The best way to control Claude Code, Codex and more from any computer or phone

main
ts 329 lines 13 KB
Raw
1 import {
2 ANTIGRAVITY_DEFAULT_MODEL,
3 ProviderDriverKind,
4 ProviderInstanceId,
5 type OrchestrationV2ProviderCapabilities,
6 type ProviderSetupError,
7 } from "@t3tools/contracts";
8 import type { SelfInvocation } from "@t3tools/shared/nodeRuntime";
9 import * as SecureRandom from "effect/crypto/SecureRandom";
10 import * as Effect from "effect/Effect";
11 import * as FileSystem from "effect/FileSystem";
12 import * as Path from "effect/Path";
13 import * as Exit from "effect/Exit";
14 import * as Semaphore from "effect/Semaphore";
15 import * as Scope from "effect/Scope";
16 import * as EffectAcpErrors from "effect-acp/errors";
17
18 import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
19 import { PULL_REQUEST_LINKING_INSTRUCTIONS } from "@t3tools/provider-core/server/runtimeInstructions";
20 import type { AntigravityAuth } from "../../provider/AntigravityAuth.ts";
21 import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
22 import {
23 antigravityAppendsSystemPrompt,
24 antigravityPermissionDisposition,
25 antigravityPermissionMode,
26 antigravityRuntimeModeForSessionMode,
27 antigravitySteersWithPrompt,
28 applyAntigravityAcpModelSelection,
29 buildAntigravityPrompt,
30 type AntigravityAcpRuntimeInput,
31 } from "../../provider/acp/AntigravityAcpSupport.ts";
32 import {
33 ANTIGRAVITY_SUBAGENT_BATCH_TITLE,
34 antigravitySubagentLaunches,
35 describeAntigravitySubagentLaunches,
36 readAntigravityChildrenAtWork,
37 } from "../../provider/acp/AntigravityChildWork.ts";
38 import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityClientFiles.ts";
39 import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts";
40 import {
41 antigravityApprovalOptions,
42 antigravityToolOutlivesPrompt,
43 antigravitySubagentOutput,
44 classifyAntigravitySubagentToolCall,
45 extractAntigravityUserInputQuestion,
46 makeAntigravityReadRepair,
47 makeAntigravityUserInputResponse,
48 normalizeAntigravityToolCall,
49 } from "../../provider/acp/AntigravityProtocol.ts";
50 import { isAntigravitySignInRequiredError } from "../../provider/antigravityAuthSupport.ts";
51 import {
52 AcpProviderCapabilitiesV2,
53 makeAcpAdapterV2,
54 type AcpAdapterV2Flavor,
55 type AcpAdapterV2RuntimeInput,
56 } from "@t3tools/provider-acp/server/adapter";
57
58 const ANTIGRAVITY_PROVIDER = ProviderDriverKind.make("antigravity");
59
60 const AntigravityProviderCapabilitiesV2 = {
61 ...AcpProviderCapabilitiesV2,
62 sessions: {
63 ...AcpProviderCapabilitiesV2.sessions,
64 supportsModelSwitchInSession: true,
65 supportsRuntimeModeSwitchInSession: true,
66 },
67 tools: {
68 ...AcpProviderCapabilitiesV2.tools,
69 supportsMcpTools: true,
70 },
71 subagents: {
72 ...AcpProviderCapabilitiesV2.subagents,
73 supportsSubagents: true,
74 },
75 } satisfies OrchestrationV2ProviderCapabilities;
76
77 /** Thread variables reach the driver here; `makeAntigravityAcpRuntime` never reads them. */
78 export type AntigravityAdapterV2RuntimeInput = Omit<
79 AntigravityAcpRuntimeInput,
80 "spawn" | "childProcessSpawner"
81 > & { readonly processEnvironment?: NodeJS.ProcessEnv };
82
83 export interface AntigravityAdapterV2Options {
84 readonly instanceId: ProviderInstanceId;
85 readonly selfInvocation: SelfInvocation;
86 readonly makeRuntime: (
87 input: AntigravityAdapterV2RuntimeInput,
88 ) => Effect.Effect<
89 AcpSessionRuntime.AcpSessionRuntime["Service"],
90 EffectAcpErrors.AcpError | ProviderSetupError,
91 Scope.Scope
92 >;
93 readonly withProcess: AntigravityAuth["withProcess"];
94 readonly defaultModel: Effect.Effect<string | undefined>;
95 readonly supportsNativeGoals?: Effect.Effect<boolean>;
96 readonly onSessionStarted?: (
97 started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
98 cwd: string,
99 ) => Effect.Effect<void>;
100 readonly onSessionEvent?: AcpAdapterV2Flavor["onSessionEvent"];
101 readonly nativeLogging?: Parameters<typeof makeAcpAdapterV2>[0]["nativeLogging"];
102 readonly continuationRequests?: Parameters<typeof makeAcpAdapterV2>[0]["continuationRequests"];
103 /** The agent's GEMINI_HOME. Its session logs show turns that ended on an upstream error. */
104 readonly profileDirectory?: string;
105 }
106
107 /**
108 * Native subagent tools report no child session ids, so children stay read-only.
109 * Only permission prompts carry the launch; NativeChildWorkQuery matches their ids by this text.
110 */
111 const extractAntigravitySubagentUpdate: NonNullable<AcpAdapterV2Flavor["extractSubagentUpdate"]> = (
112 toolCall,
113 ) => {
114 if (classifyAntigravitySubagentToolCall(toolCall) !== "subagent") {
115 return undefined;
116 }
117 const status =
118 toolCall.status === "failed" ? "failed" : toolCall.status === "pending" ? "pending" : "running";
119 const launches = antigravitySubagentLaunches(toolCall.data.rawInput);
120 const launch = launches === undefined ? undefined : describeAntigravitySubagentLaunches(launches);
121 return {
122 nativeTaskId: toolCall.toolCallId,
123 prompt:
124 launch?.prompt ??
125 antigravitySubagentOutput(toolCall) ??
126 toolCall.detail ??
127 toolCall.title ??
128 ANTIGRAVITY_SUBAGENT_BATCH_TITLE,
129 title: launch?.title ?? ANTIGRAVITY_SUBAGENT_BATCH_TITLE,
130 model: null,
131 status,
132 childSessionId: null,
133 result: status === "failed" ? (antigravitySubagentOutput(toolCall) ?? null) : null,
134 };
135 };
136
137 interface AntigravityFlavorServices {
138 readonly random: SecureRandom.SecureRandom["Service"];
139 readonly fileSystem: FileSystem.FileSystem;
140 readonly path: Path.Path;
141 readonly host: ProviderHost.ProviderHost["Service"];
142 }
143
144 export function makeAntigravityAcpAdapterFlavor(
145 options: AntigravityAdapterV2Options & AntigravityFlavorServices,
146 ): AcpAdapterV2Flavor {
147 const { profileDirectory } = options;
148 const antigravityClientFileRoots = (cwd: string | null) =>
149 cwd === null ? [options.host.paths.attachmentsDir] : [cwd, options.host.paths.attachmentsDir];
150 const makeRuntime = Effect.fn("AntigravityAdapterV2.makeRuntime")(
151 function* (input: AcpAdapterV2RuntimeInput) {
152 const scope = yield* Scope.fork(yield* Effect.scope);
153 const runtime = yield* options
154 .withProcess(
155 Scope.close(scope, Exit.void),
156 options.makeRuntime({
157 ...input,
158 clientFileReads: true,
159 sessionSystemPromptAppend: PULL_REQUEST_LINKING_INSTRUCTIONS,
160 }),
161 )
162 .pipe(Effect.provideService(Scope.Scope, scope));
163 // Repair keeps state across updates, so each runtime must have one session-update handler.
164 const reads = makeAntigravityReadRepair();
165 // Served reads are reported from the read handler, so they take turns with agent updates.
166 const updates = yield* Semaphore.make(1);
167 let projectUpdate: Parameters<typeof runtime.handleSessionUpdate>[0] | undefined;
168 return {
169 ...runtime,
170 handleReadTextFile: (handler) =>
171 runtime.handleReadTextFile((request, context) =>
172 handler(request, context).pipe(
173 Effect.onExit((exit) => {
174 const served = reads.attempted(request.path, Exit.isSuccess(exit));
175 if (served === undefined || projectUpdate === undefined) return Effect.void;
176 return updates
177 .withPermit(
178 projectUpdate({
179 sessionId: served.sessionId,
180 update: {
181 sessionUpdate: "tool_call_update",
182 toolCallId: served.toolCallId,
183 status: "completed",
184 },
185 }),
186 )
187 .pipe(Effect.ignore);
188 }),
189 ),
190 ),
191 prompt: (payload, promptOptions) =>
192 Effect.sync(reads.reset).pipe(Effect.andThen(runtime.prompt(payload, promptOptions))),
193 handleSessionUpdate: (handler) => {
194 projectUpdate = handler;
195 return runtime.handleSessionUpdate((notification) =>
196 updates.withPermit(handler(reads.repair(notification))),
197 );
198 },
199 start: () =>
200 runtime
201 .start()
202 .pipe(
203 Effect.tap(
204 (started) => options.onSessionStarted?.(started, input.cwd) ?? Effect.void,
205 ),
206 ),
207 } satisfies typeof runtime;
208 },
209 Effect.provideService(SecureRandom.SecureRandom, options.random),
210 Effect.mapError((cause): EffectAcpErrors.AcpError =>
211 cause._tag === "ProviderSetupError"
212 ? new EffectAcpErrors.AcpTransportError({ detail: cause.detail, cause })
213 : cause,
214 ),
215 );
216
217 return {
218 driver: ANTIGRAVITY_PROVIDER,
219 runtimeHarness: "Antigravity",
220 capabilities: AntigravityProviderCapabilitiesV2,
221 supportsNativeGoals: options.supportsNativeGoals ?? Effect.succeed(false),
222 // Agents that advertise HTTP MCP skip the stdio bridge process; others keep stdio.
223 mcpOverHttp: true,
224 sessionCarriesPullRequestLinking: antigravityAppendsSystemPrompt,
225 makeRuntime,
226 buildAttachmentPrompt: ({ text, attachments, resolveAttachmentPath, promptCapabilities }) =>
227 buildAntigravityPrompt({
228 input: text,
229 attachments,
230 resolveAttachmentPath,
231 promptCapabilities,
232 }).pipe(
233 Effect.map((blocks) => (text.trim() ? blocks.slice(1) : blocks)),
234 Effect.provideService(FileSystem.FileSystem, options.fileSystem),
235 Effect.provideService(Path.Path, options.path),
236 ),
237 // Loading history replays tool calls; resume avoids replay.
238 subagentsIdleOnTurnCompletion: true,
239 // A finished background command or timer wakes the agent with no prompt open: it streams a
240 // reply and asks for permissions, and no prompt response ever ends that reply.
241 enablePostSettleContinuation: true,
242 deferFinalizeForBackgroundWork: true,
243 wakeOnDetachedRequest: true,
244 replyEndsWithUsageUpdate: true,
245 toolOutlivesPrompt: antigravityToolOutlivesPrompt,
246 // session/cancel ends the agent's running commands, so only Stop sends it once the prompt
247 // has ended. A message sent while a command runs leaves the command alone.
248 preserveRuntimeOnSettledInterrupt: true,
249 // `agy acp` reads a prompt sent mid-turn as a steer; cancel-and-restart killed its subagents.
250 steersWithPrompt: antigravitySteersWithPrompt,
251 ...(options.onSessionEvent === undefined ? {} : { onSessionEvent: options.onSessionEvent }),
252 applyModelSelection: Effect.fn("AntigravityAdapterV2.applyModelSelection")(function* ({
253 runtime,
254 modelSelection,
255 }) {
256 const defaultModel = yield* options.defaultModel;
257 return yield* applyAntigravityAcpModelSelection({
258 runtime,
259 model:
260 modelSelection.model === ANTIGRAVITY_DEFAULT_MODEL ? undefined : modelSelection.model,
261 defaultModel,
262 mapError: (cause) => cause,
263 });
264 }),
265 sessionModeForPolicy: (policy) => antigravityPermissionMode(policy.runtimeMode),
266 runtimeModeForSessionMode: antigravityRuntimeModeForSessionMode,
267 clientFileSystem: {
268 readTextFile: (request, cwd) =>
269 readAntigravityClientTextFile({
270 fileSystem: options.fileSystem,
271 path: options.path,
272 allowedRoots: antigravityClientFileRoots(cwd),
273 request,
274 }),
275 },
276 permissionDisposition: antigravityPermissionDisposition,
277 approvalOptions: antigravityApprovalOptions,
278 extractPermissionQuestion: (request) => {
279 const question = extractAntigravityUserInputQuestion(request);
280 if (question === undefined) return undefined;
281 return {
282 question,
283 respond: (answers) => makeAntigravityUserInputResponse(request, answers),
284 };
285 },
286 normalizeToolCall: normalizeAntigravityToolCall,
287 extractSubagentUpdate: extractAntigravitySubagentUpdate,
288 supportsImagePrompts: true,
289 compactViaAdvertisedCommand: true,
290 requiresSignIn: isAntigravitySignInRequiredError,
291 checksVersionAtHandshake: true,
292 // Antigravity can leave a prompt open without updates; long tools and approvals pause this.
293 promptInactivityTimeout: "15 minutes",
294 reportsPerTurnPromptUsage: true,
295 geminiPromptUsage: true,
296 ...(profileDirectory === undefined
297 ? {}
298 : {
299 watchPromptOutcome: (sessionId: string) =>
300 watchAntigravityPromptOutcome(profileDirectory, sessionId),
301 subagentsOutlivingPrompt: ({ sessionId, nativeTaskIds }) =>
302 readAntigravityChildrenAtWork({
303 profileDirectory,
304 rootSessionId: sessionId,
305 toolCallIds: nativeTaskIds,
306 }),
307 }),
308 };
309 }
310
311 export const makeAntigravityAdapterV2 = Effect.fn("makeAntigravityAdapterV2")(function* (
312 options: AntigravityAdapterV2Options,
313 ) {
314 const services: AntigravityFlavorServices = {
315 random: yield* SecureRandom.SecureRandom,
316 fileSystem: yield* FileSystem.FileSystem,
317 path: yield* Path.Path,
318 host: yield* ProviderHost.ProviderHost,
319 };
320 return yield* makeAcpAdapterV2({
321 instanceId: options.instanceId,
322 flavor: makeAntigravityAcpAdapterFlavor({ ...options, ...services }),
323 selfInvocation: options.selfInvocation,
324 ...(options.nativeLogging === undefined ? {} : { nativeLogging: options.nativeLogging }),
325 ...(options.continuationRequests === undefined
326 ? {}
327 : { continuationRequests: options.continuationRequests }),
328 });
329 });