Open History to see the last commit
1import {
2 ApprovalRequestId,
3 EventId,
4 ProviderDriverKind,
5 ProviderInstanceId,
6 RuntimeRequestId,
7 RuntimeTaskId,
8 TurnId,
9 type AntigravitySettings,
10 type ProviderApprovalDecision,
11 type ProviderRuntimeEvent,
12 type ProviderSession,
13 type ProviderSetupError,
14 type ProviderUserInputAnswers,
15 type RuntimeTaskStatus,
16 type ThreadId,
17 type TurnCompletedPayload,
18} from "@t3tools/contracts";
19import * as Cause from "effect/Cause";
20import * as Crypto from "effect/Crypto";
21import * as DateTime from "effect/DateTime";
22import * as Deferred from "effect/Deferred";
23import * as Effect from "effect/Effect";
24import * as Exit from "effect/Exit";
25import * as Fiber from "effect/Fiber";
26import * as FileSystem from "effect/FileSystem";
27import * as Option from "effect/Option";
28import * as Path from "effect/Path";
29import * as PubSub from "effect/PubSub";
30import * as Schema from "effect/Schema";
31import * as Scope from "effect/Scope";
32import * as Semaphore from "effect/Semaphore";
33import * as Stream from "effect/Stream";
34import * as SynchronizedRef from "effect/SynchronizedRef";
35import * as EffectAcpErrors from "effect-acp/errors";
36import type * as EffectAcpSchema from "effect-acp/schema";
37
38import { ServerConfig } from "../../config.ts";
39import { buildRuntimeInstructions } from "../RuntimeInstructions.ts";
40import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
41import type { AntigravityAuth } from "../AntigravityAuth.ts";
42import {
43 ProviderAdapterRequestError,
44 ProviderAdapterSessionClosedError,
45 ProviderAdapterSessionNotFoundError,
46 ProviderAdapterValidationError,
47 type ProviderAdapterError,
48} from "../Errors.ts";
49import {
50 ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE,
51 isAntigravitySignInRequiredError,
52} from "../antigravityAuthSupport.ts";
53import { mapAcpToAdapterError } from "../acp/AcpAdapterSupport.ts";
54import {
55 makeAcpAssistantItemEvent,
56 makeAcpContentDeltaEvent,
57 makeAcpPlanUpdatedEvent,
58 makeAcpRequestOpenedEvent,
59 makeAcpRequestResolvedEvent,
60 makeAcpToolCallEvent,
61} from "../acp/AcpCoreRuntimeEvents.ts";
62import { makeAcpNativeLoggerFactory } from "../acp/AcpNativeLogging.ts";
63import { parsePermissionRequest, type AcpToolCallState } from "../acp/AcpRuntimeModel.ts";
64import type * as AcpSessionRuntime from "../acp/AcpSessionRuntime.ts";
65import {
66 antigravityPermissionMode,
67 antigravityModelOptions,
68 applyAntigravityAcpModelSelection,
69 buildAntigravityPrompt,
70 type AntigravityAcpRuntimeInput,
71 resolveAntigravityModel,
72} from "../acp/AntigravityAcpSupport.ts";
73import {
74 antigravityApprovalOptions,
75 antigravitySubagentOutput,
76 classifyAntigravitySubagentToolCall,
77 extractAntigravityUserInputQuestion,
78 isAntigravityOpenCommand,
79 isAntigravitySubagentReplayStart,
80 isAntigravityUserInputRequest,
81 makeAntigravityUserInputResponse,
82 normalizeAntigravityToolCall,
83 sanitizeAntigravityToolPayload,
84 selectAntigravityPermissionOptionId,
85} from "../acp/AntigravityProtocol.ts";
86import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
87import type { EventNdjsonLogger } from "./EventNdjsonLogger.ts";
88
89const PROVIDER = ProviderDriverKind.make("antigravity");
90const ResumeCursor = Schema.Struct({
91 schemaVersion: Schema.Literal(1),
92 sessionId: Schema.NonEmptyString,
93});
94const decodeResumeCursor = Schema.decodeUnknownOption(ResumeCursor);
95const isAcpError = Schema.is(EffectAcpErrors.AcpError);
96
97type Adapter = ProviderAdapterShape<ProviderAdapterError>;
98type Runtime = Pick<
99 AcpSessionRuntime.AcpSessionRuntime["Service"],
100 | "handleRequestPermission"
101 | "handleReadTextFile"
102 | "handleWriteTextFile"
103 | "start"
104 | "setMode"
105 | "setModel"
106 | "getConfigOptions"
107 | "getEvents"
108 | "drainEvents"
109 | "prompt"
110 | "cancel"
111>;
112type NativePermission = EffectAcpSchema.RequestPermissionRequest;
113type NativePermissionResponse = EffectAcpSchema.RequestPermissionResponse;
114
115function mapAntigravityError(threadId: ThreadId, method: string, cause: EffectAcpErrors.AcpError) {
116 return isAntigravitySignInRequiredError(cause)
117 ? new ProviderAdapterRequestError({
118 provider: PROVIDER,
119 method,
120 detail: ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE,
121 cause,
122 })
123 : mapAcpToAdapterError(PROVIDER, threadId, method, cause);
124}
125
126export interface AntigravityAdapterOptions {
127 readonly instanceId: ProviderInstanceId;
128 readonly makeRuntime: (
129 input: Omit<AntigravityAcpRuntimeInput, "spawn" | "childProcessSpawner" | "onAuthorizationUrl">,
130 ) => Effect.Effect<Runtime, EffectAcpErrors.AcpError | ProviderSetupError, Scope.Scope>;
131 readonly withProcess: AntigravityAuth["withProcess"];
132 readonly onSessionStarted?: (
133 started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
134 cwd: string,
135 ) => Effect.Effect<void>;
136 readonly onAvailableCommands?: (
137 commands: ReadonlyArray<EffectAcpSchema.AvailableCommand>,
138 cwd: string,
139 ) => Effect.Effect<void>;
140 readonly onConfigOptionsUpdated?: (
141 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
142 ) => Effect.Effect<void>;
143 readonly onAuthRequired?: Effect.Effect<void>;
144 /** Model the provider default alias selects, when the account offers it. */
145 readonly defaultModel?: Effect.Effect<string | undefined>;
146 readonly nativeEventLogger?: EventNdjsonLogger;
147}
148
149interface PendingApproval {
150 readonly request: NativePermission;
151 readonly response: Deferred.Deferred<{
152 readonly decision: ProviderApprovalDecision;
153 readonly result: NativePermissionResponse;
154 }>;
155}
156
157interface PendingQuestion {
158 readonly request: NativePermission;
159 readonly response: Deferred.Deferred<{
160 readonly answers: ProviderUserInputAnswers;
161 readonly result: NativePermissionResponse;
162 }>;
163}
164
165interface OpenCommand {
166 readonly toolCall: AcpToolCallState;
167 readonly turnId: TurnId | undefined;
168 readonly promoted: boolean;
169}
170
171interface OpenSubagent {
172 readonly turnId: TurnId | undefined;
173 readonly status: "pending" | "running" | undefined;
174 readonly description?: string;
175}
176
177function subagentLinkage(toolCallId: string) {
178 return {
179 taskId: RuntimeTaskId.make(toolCallId),
180 taskType: "subagent_batch",
181 toolUseId: toolCallId,
182 title: "Antigravity subagent batch",
183 };
184}
185
186interface TurnIntent {
187 readonly turnId: TurnId;
188 readonly generation: number;
189 settled: boolean;
190}
191
192interface SessionContext {
193 readonly threadId: ThreadId;
194 readonly cwd: string;
195 readonly nativeSessionId: string;
196 readonly scope: Scope.Closeable;
197 readonly runtime: Runtime;
198 readonly promptLock: Semaphore.Semaphore;
199 readonly stopLock: Semaphore.Semaphore;
200 readonly commandLock: Semaphore.Semaphore;
201 readonly approvals: Map<ApprovalRequestId, PendingApproval>;
202 readonly questions: Map<ApprovalRequestId, PendingQuestion>;
203 readonly commands: Map<string, OpenCommand>;
204 /** Keep only IDs after settlement or MCP exclusion so merged late updates cannot change identity. */
205 readonly subagents: Map<string, OpenSubagent | "finished" | "mcp">;
206 readonly turns: Array<{ id: TurnId; items: Array<unknown> }>;
207 session: ProviderSession;
208 activeTurnId: TurnId | undefined;
209 promptFiber: Fiber.Fiber<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError> | undefined;
210 generation: number;
211 stopped: boolean;
212 closed: boolean;
213 disconnected: boolean;
214}
215
216const CLIENT_FILE_MAX_BYTES = 8 * 1024 * 1024;
217
218function isInsideRoot(path: Path.Path, root: string, candidate: string): boolean {
219 const relative = path.relative(root, candidate);
220 return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
221}
222
223/** Resolves an agent-supplied path and rejects anything outside the session roots. */
224const resolveClientFilePath = Effect.fn("AntigravityAdapter.resolveClientFilePath")(
225 function* (input: {
226 readonly fileSystem: FileSystem.FileSystem;
227 readonly path: Path.Path;
228 readonly allowedRoots: ReadonlyArray<string>;
229 readonly requestPath: string;
230 }) {
231 const { path } = input;
232 const resolved = path.resolve(input.requestPath);
233 // Follow symlinks on the parent so a link out of the workspace cannot escape it.
234 const parent = yield* input.fileSystem
235 .realPath(path.dirname(resolved))
236 .pipe(Effect.orElseSucceed(() => path.dirname(resolved)));
237 const real = path.join(parent, path.basename(resolved));
238 const roots = yield* Effect.forEach(input.allowedRoots, (root) =>
239 input.fileSystem.realPath(root).pipe(Effect.orElseSucceed(() => root)),
240 );
241 if (!roots.some((root) => isInsideRoot(path, root, real))) {
242 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
243 `Path '${input.requestPath}' is outside the session workspace.`,
244 );
245 }
246 return real;
247 },
248);
249
250const readClientTextFile = Effect.fn("AntigravityAdapter.readClientTextFile")(function* (input: {
251 readonly fileSystem: FileSystem.FileSystem;
252 readonly path: Path.Path;
253 readonly allowedRoots: ReadonlyArray<string>;
254 readonly request: EffectAcpSchema.ReadTextFileRequest;
255}): Effect.fn.Return<EffectAcpSchema.ReadTextFileResponse, EffectAcpErrors.AcpError> {
256 const filePath = yield* resolveClientFilePath({ ...input, requestPath: input.request.path });
257 const info = yield* input.fileSystem
258 .stat(filePath)
259 .pipe(
260 Effect.mapError(() =>
261 EffectAcpErrors.AcpRequestError.resourceNotFound(`File '${input.request.path}' not found.`),
262 ),
263 );
264 if (info.type !== "File" || Number(info.size) > CLIENT_FILE_MAX_BYTES) {
265 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
266 `File '${input.request.path}' is not a readable text file under ${CLIENT_FILE_MAX_BYTES} bytes.`,
267 );
268 }
269 const text = yield* input.fileSystem
270 .readFileString(filePath)
271 .pipe(
272 Effect.mapError(() =>
273 EffectAcpErrors.AcpRequestError.internalError(`Could not read '${input.request.path}'.`),
274 ),
275 );
276 const line = input.request.line ?? undefined;
277 const limit = input.request.limit ?? undefined;
278 if (line === undefined && limit === undefined) {
279 return { content: text };
280 }
281 // ACP lines are 1-indexed. `limit` is a line count.
282 const lines = text.split("\n");
283 const start = Math.max(0, (line ?? 1) - 1);
284 const end = limit === undefined ? lines.length : Math.min(lines.length, start + limit);
285 return { content: lines.slice(start, end).join("\n") };
286});
287
288const writeClientTextFile = Effect.fn("AntigravityAdapter.writeClientTextFile")(function* (input: {
289 readonly fileSystem: FileSystem.FileSystem;
290 readonly path: Path.Path;
291 readonly allowedRoots: ReadonlyArray<string>;
292 readonly request: EffectAcpSchema.WriteTextFileRequest;
293}): Effect.fn.Return<EffectAcpSchema.WriteTextFileResponse, EffectAcpErrors.AcpError> {
294 const filePath = yield* resolveClientFilePath({ ...input, requestPath: input.request.path });
295 yield* input.fileSystem.makeDirectory(input.path.dirname(filePath), { recursive: true }).pipe(
296 Effect.andThen(input.fileSystem.writeFileString(filePath, input.request.content)),
297 Effect.mapError(() =>
298 EffectAcpErrors.AcpRequestError.internalError(`Could not write '${input.request.path}'.`),
299 ),
300 );
301 return {};
302});
303
304/** Keeps one official ACP process per thread and drains a cancelled prompt before steering. */
305export const makeAntigravityAdapter = Effect.fn("makeAntigravityAdapter")(function* (
306 settings: AntigravitySettings,
307 options: AntigravityAdapterOptions,
308) {
309 const crypto = yield* Crypto.Crypto;
310 const fileSystem = yield* FileSystem.FileSystem;
311 const path = yield* Path.Path;
312 const serverConfig = yield* ServerConfig;
313 const ownerScope = yield* Effect.scope;
314 const makeNativeLoggers = yield* makeAcpNativeLoggerFactory();
315 const sessions = new Map<ThreadId, SessionContext>();
316 const locks = yield* SynchronizedRef.make(new Map<ThreadId, Semaphore.Semaphore>());
317 const events = yield* PubSub.unbounded<ProviderRuntimeEvent>();
318 const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
319 const randomId = crypto.randomUUIDv4.pipe(
320 Effect.mapError(
321 (cause) =>
322 new ProviderAdapterRequestError({
323 provider: PROVIDER,
324 method: "crypto/randomUUIDv4",
325 detail: "Could not create an Antigravity event ID.",
326 cause,
327 }),
328 ),
329 );
330 const stamp = Effect.all({
331 eventId: Effect.map(randomId, EventId.make),
332 createdAt: nowIso,
333 });
334 const emit = (event: ProviderRuntimeEvent) => PubSub.publish(events, event).pipe(Effect.asVoid);
335
336 const withThreadLock = <A, E, R>(threadId: ThreadId, task: Effect.Effect<A, E, R>) =>
337 SynchronizedRef.modifyEffect(locks, (current) => {
338 const existing = current.get(threadId);
339 if (existing) return Effect.succeed([existing, current] as const);
340 return Semaphore.make(1).pipe(
341 Effect.map((lock) => [lock, new Map(current).set(threadId, lock)] as const),
342 );
343 }).pipe(Effect.flatMap((lock) => lock.withPermit(task)));
344
345 const requireSession = (threadId: ThreadId) => {
346 const context = sessions.get(threadId);
347 return context && !context.stopped
348 ? Effect.succeed(context)
349 : Effect.fail(new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }));
350 };
351
352 const cancelRequests = Effect.fn("AntigravityAdapter.cancelRequests")(function* (
353 context: SessionContext,
354 ) {
355 for (const pending of context.approvals.values()) {
356 yield* Deferred.succeed(pending.response, {
357 decision: "cancel",
358 result: { outcome: { outcome: "cancelled" } },
359 });
360 }
361 for (const pending of context.questions.values()) {
362 yield* Deferred.succeed(pending.response, {
363 answers: {},
364 result: { outcome: { outcome: "cancelled" } },
365 });
366 }
367 });
368
369 const finishBackgroundCommands = (context: SessionContext) =>
370 context.commandLock.withPermit(
371 Effect.gen(function* () {
372 for (const [id, command] of context.commands) {
373 if (!command.promoted) continue;
374 yield* emit({
375 type: "task.completed",
376 ...(yield* stamp),
377 provider: PROVIDER,
378 threadId: context.threadId,
379 turnId: command.turnId,
380 payload: {
381 taskId: RuntimeTaskId.make(id),
382 taskType: "local_bash",
383 toolUseId: id,
384 status: "stopped",
385 },
386 });
387 }
388 context.commands.clear();
389 }),
390 );
391
392 const finishSubagents = (
393 context: SessionContext,
394 status: Extract<RuntimeTaskStatus, "cancelled" | "failed" | "idle">,
395 error?: string,
396 ) =>
397 context.commandLock.withPermit(
398 Effect.gen(function* () {
399 for (const [id, subagent] of context.subagents) {
400 if (subagent === "finished" || subagent === "mcp") continue;
401 yield* emit({
402 type: "task.updated",
403 ...(yield* stamp),
404 provider: PROVIDER,
405 threadId: context.threadId,
406 turnId: subagent.turnId,
407 payload: {
408 ...subagentLinkage(id),
409 status,
410 ...(status === "idle"
411 ? {
412 description: "Turn ended. Individual agent status is unavailable.",
413 timelineBypass: true,
414 }
415 : {}),
416 ...(error ? { error } : {}),
417 },
418 });
419 context.subagents.set(id, "finished");
420 }
421 }),
422 );
423
424 const stopContext = (context: SessionContext) =>
425 context.stopLock
426 .withPermit(
427 Effect.gen(function* () {
428 if (context.closed) return;
429 context.stopped = true;
430 yield* Effect.gen(function* () {
431 yield* cancelRequests(context);
432 if (context.promptFiber && !context.disconnected) {
433 yield* Effect.ignore(context.runtime.cancel);
434 }
435 }).pipe(Effect.ensuring(Scope.close(context.scope, Exit.void)));
436 context.closed = true;
437 if (sessions.get(context.threadId) === context) sessions.delete(context.threadId);
438 yield* finishBackgroundCommands(context);
439 yield* finishSubagents(
440 context,
441 context.disconnected ? "failed" : "cancelled",
442 context.disconnected ? "Antigravity process stopped." : undefined,
443 );
444 context.subagents.clear();
445 yield* emit({
446 type: "session.exited",
447 ...(yield* stamp),
448 provider: PROVIDER,
449 threadId: context.threadId,
450 payload: {
451 exitKind: context.disconnected ? "error" : "graceful",
452 ...(context.disconnected ? { reason: "Antigravity process stopped." } : {}),
453 },
454 });
455 }),
456 )
457 .pipe(Effect.uninterruptible);
458
459 const handlePermission = Effect.fn("AntigravityAdapter.handlePermission")(function* (
460 context: SessionContext,
461 request: NativePermission,
462 ): Effect.fn.Return<NativePermissionResponse, ProviderAdapterError> {
463 if (context.stopped || request.sessionId !== context.nativeSessionId) {
464 return { outcome: { outcome: "cancelled" } };
465 }
466 const requestId = ApprovalRequestId.make(yield* randomId);
467 const runtimeRequestId = RuntimeRequestId.make(requestId);
468 const turnId = context.activeTurnId;
469 const rawPayload = sanitizeAntigravityToolPayload(request);
470
471 if (isAntigravityUserInputRequest(request)) {
472 const question = extractAntigravityUserInputQuestion(request);
473 if (!question) return { outcome: { outcome: "cancelled" } };
474 const response = yield* Deferred.make<{
475 answers: ProviderUserInputAnswers;
476 result: NativePermissionResponse;
477 }>();
478 context.questions.set(requestId, { request, response });
479 return yield* Effect.gen(function* () {
480 yield* emit({
481 type: "user-input.requested",
482 ...(yield* stamp),
483 provider: PROVIDER,
484 threadId: context.threadId,
485 turnId,
486 requestId: runtimeRequestId,
487 payload: { questions: [question] },
488 raw: { source: "acp.jsonrpc", method: "session/request_permission", payload: rawPayload },
489 });
490 const answer = yield* Deferred.await(response);
491 yield* emit({
492 type: "user-input.resolved",
493 ...(yield* stamp),
494 provider: PROVIDER,
495 threadId: context.threadId,
496 turnId,
497 requestId: runtimeRequestId,
498 payload: { answers: answer.answers },
499 });
500 return answer.result;
501 }).pipe(Effect.ensuring(Effect.sync(() => context.questions.delete(requestId))));
502 }
503
504 const response = yield* Deferred.make<{
505 decision: ProviderApprovalDecision;
506 result: NativePermissionResponse;
507 }>();
508 context.approvals.set(requestId, { request, response });
509 const parsed = parsePermissionRequest(request);
510 const toolCall = parsed.toolCall ? normalizeAntigravityToolCall(parsed.toolCall) : undefined;
511 const permissionRequest = {
512 ...parsed,
513 ...(toolCall ? { toolCall } : {}),
514 detail:
515 toolCall?.command ??
516 toolCall?.detail ??
517 toolCall?.title ??
518 "Antigravity requests permission.",
519 };
520 return yield* Effect.gen(function* () {
521 yield* emit(
522 makeAcpRequestOpenedEvent({
523 stamp: yield* stamp,
524 provider: PROVIDER,
525 threadId: context.threadId,
526 turnId,
527 requestId: runtimeRequestId,
528 permissionRequest,
529 approvalOptions: antigravityApprovalOptions(request),
530 detail: permissionRequest.detail ?? "Antigravity requests permission.",
531 args: rawPayload,
532 source: "acp.jsonrpc",
533 method: "session/request_permission",
534 rawPayload,
535 }),
536 );
537 const answer = yield* Deferred.await(response);
538 yield* emit(
539 makeAcpRequestResolvedEvent({
540 stamp: yield* stamp,
541 provider: PROVIDER,
542 threadId: context.threadId,
543 turnId,
544 requestId: runtimeRequestId,
545 permissionRequest,
546 decision: answer.decision,
547 }),
548 );
549 return answer.result;
550 }).pipe(Effect.ensuring(Effect.sync(() => context.approvals.delete(requestId))));
551 });
552
553 const handleEvent = Effect.fn("AntigravityAdapter.handleEvent")(function* (
554 context: SessionContext,
555 event: AcpSessionRuntime.AcpSessionRuntimeEvent,
556 ) {
557 if (event._tag === "EventStreamBarrier") {
558 yield* Deferred.succeed(event.acknowledge, undefined);
559 return;
560 }
561 if (context.stopped) return;
562 switch (event._tag) {
563 case "ModeChanged":
564 return;
565 case "AvailableCommandsUpdated":
566 yield* options.onAvailableCommands?.(event.availableCommands, context.cwd) ?? Effect.void;
567 return;
568 case "ConfigOptionsUpdated":
569 yield* options.onConfigOptionsUpdated?.(event.configOptions) ?? Effect.void;
570 return;
571 case "ConnectionTerminated":
572 context.stopped = true;
573 context.disconnected = true;
574 yield* stopContext(context).pipe(Effect.forkIn(ownerScope));
575 return;
576 case "AssistantItemStarted":
577 case "AssistantItemCompleted":
578 yield* emit(
579 makeAcpAssistantItemEvent({
580 stamp: yield* stamp,
581 provider: PROVIDER,
582 threadId: context.threadId,
583 turnId: context.activeTurnId,
584 itemId: event.itemId,
585 lifecycle: event._tag === "AssistantItemStarted" ? "item.started" : "item.completed",
586 }),
587 );
588 return;
589 case "ThoughtDelta":
590 case "ContentDelta":
591 yield* emit(
592 makeAcpContentDeltaEvent({
593 stamp: yield* stamp,
594 provider: PROVIDER,
595 threadId: context.threadId,
596 turnId: context.activeTurnId,
597 ...(event._tag === "ContentDelta" && event.itemId ? { itemId: event.itemId } : {}),
598 ...(event._tag === "ThoughtDelta" ? { streamKind: "reasoning_text" } : {}),
599 text: event.text,
600 rawPayload: sanitizeAntigravityToolPayload(event.rawPayload),
601 }),
602 );
603 return;
604 case "PlanUpdated":
605 yield* emit(
606 makeAcpPlanUpdatedEvent({
607 stamp: yield* stamp,
608 provider: PROVIDER,
609 threadId: context.threadId,
610 turnId: context.activeTurnId,
611 payload: event.payload,
612 source: "acp.jsonrpc",
613 method: "session/update",
614 rawPayload: sanitizeAntigravityToolPayload(event.rawPayload),
615 }),
616 );
617 return;
618 case "ToolCallUpdated":
619 yield* context.commandLock.withPermit(
620 Effect.gen(function* () {
621 const toolCall = normalizeAntigravityToolCall(event.toolCall);
622 const tracked = context.subagents.get(toolCall.toolCallId);
623 if (tracked === "finished") return;
624 const kind = classifyAntigravitySubagentToolCall(toolCall, event.rawPayload);
625 const isMcp = tracked === "mcp" || kind === "mcp";
626 if (isMcp) context.subagents.set(toolCall.toolCallId, "mcp");
627 const subagent = tracked === "mcp" ? undefined : tracked;
628 if (!isMcp && (subagent || kind === "subagent")) {
629 const turnId = subagent?.turnId ?? context.activeTurnId;
630 const linkage = subagentLinkage(toolCall.toolCallId);
631 // Replay starts claim completion before the result says whether the call failed.
632 if (
633 context.activeTurnId === undefined &&
634 isAntigravitySubagentReplayStart(event.rawPayload)
635 ) {
636 context.subagents.set(toolCall.toolCallId, { turnId, status: undefined });
637 return;
638 }
639 if (toolCall.status === "failed") {
640 const summary = antigravitySubagentOutput(toolCall);
641 yield* emit({
642 type: "task.completed",
643 ...(yield* stamp),
644 provider: PROVIDER,
645 threadId: context.threadId,
646 turnId,
647 payload: {
648 ...linkage,
649 status: toolCall.status,
650 ...(summary ? { summary } : {}),
651 },
652 });
653 context.subagents.set(toolCall.toolCallId, "finished");
654 } else if (context.activeTurnId === undefined && toolCall.status === "completed") {
655 yield* emit({
656 type: "task.updated",
657 ...(yield* stamp),
658 provider: PROVIDER,
659 threadId: context.threadId,
660 turnId,
661 payload: {
662 ...linkage,
663 status: "idle",
664 description: "Individual agent status is unavailable for this earlier batch.",
665 timelineBypass: true,
666 },
667 });
668 context.subagents.set(toolCall.toolCallId, "finished");
669 } else {
670 // start_subagent returns after launching a batch. Its output is
671 // the launch description, not a child result or completion.
672 const status = toolCall.status === "pending" ? "pending" : "running";
673 const description =
674 antigravitySubagentOutput(toolCall) ?? subagent?.description ?? linkage.title;
675 if (subagent?.status !== status || subagent?.description !== description) {
676 yield* emit({
677 type: "task.progress",
678 ...(yield* stamp),
679 provider: PROVIDER,
680 threadId: context.threadId,
681 turnId,
682 payload: { ...linkage, description, summary: description, status },
683 });
684 }
685 context.subagents.set(toolCall.toolCallId, { turnId, status, description });
686 }
687 return;
688 }
689 const existing = context.commands.get(toolCall.toolCallId);
690 yield* emit(
691 makeAcpToolCallEvent({
692 stamp: yield* stamp,
693 provider: PROVIDER,
694 threadId: context.threadId,
695 turnId: existing?.turnId ?? context.activeTurnId,
696 toolCall,
697 rawPayload: sanitizeAntigravityToolPayload(event.rawPayload),
698 }),
699 );
700 if (isAntigravityOpenCommand(toolCall)) {
701 context.commands.set(toolCall.toolCallId, {
702 toolCall,
703 turnId: existing?.turnId ?? context.activeTurnId,
704 promoted: existing?.promoted ?? false,
705 });
706 } else if (toolCall.status === "completed" || toolCall.status === "failed") {
707 context.commands.delete(toolCall.toolCallId);
708 if (existing?.promoted) {
709 yield* emit({
710 type: "task.completed",
711 ...(yield* stamp),
712 provider: PROVIDER,
713 threadId: context.threadId,
714 turnId: existing.turnId,
715 payload: {
716 taskId: RuntimeTaskId.make(toolCall.toolCallId),
717 taskType: "local_bash",
718 toolUseId: toolCall.toolCallId,
719 status: toolCall.status === "failed" ? "failed" : "completed",
720 },
721 });
722 }
723 }
724 }),
725 );
726 return;
727 }
728 });
729
730 const startSession: Adapter["startSession"] = (input) =>
731 withThreadLock(
732 input.threadId,
733 Effect.gen(function* () {
734 if (!settings.enabled) {
735 return yield* new ProviderAdapterValidationError({
736 provider: PROVIDER,
737 operation: "startSession",
738 issue: "Enable Antigravity in provider settings before starting a thread.",
739 });
740 }
741 if (
742 (input.provider !== undefined && input.provider !== PROVIDER) ||
743 (input.providerInstanceId !== undefined &&
744 input.providerInstanceId !== options.instanceId) ||
745 (input.modelSelection !== undefined &&
746 input.modelSelection.instanceId !== options.instanceId)
747 ) {
748 return yield* new ProviderAdapterValidationError({
749 provider: PROVIDER,
750 operation: "startSession",
751 issue: "The Antigravity provider instance does not match the requested session.",
752 });
753 }
754 if (!input.cwd?.trim()) {
755 return yield* new ProviderAdapterValidationError({
756 provider: PROVIDER,
757 operation: "startSession",
758 issue: "The session requires a workspace directory.",
759 });
760 }
761 const cursor = decodeResumeCursor(input.resumeCursor);
762 if (input.resumeCursor !== undefined && Option.isNone(cursor)) {
763 return yield* new ProviderAdapterValidationError({
764 provider: PROVIDER,
765 operation: "startSession",
766 issue: "The saved Antigravity session is invalid. Start a new thread.",
767 });
768 }
769 const previous = sessions.get(input.threadId);
770 if (previous) yield* stopContext(previous);
771 const cwd = path.resolve(input.cwd);
772 const sessionScope = yield* Scope.make("sequential");
773 let transferred = false;
774 let context: SessionContext | undefined;
775 yield* Effect.addFinalizer(() => {
776 if (transferred) return Effect.void;
777 sessions.delete(input.threadId);
778 return Scope.close(sessionScope, Exit.void);
779 });
780 const stopOwned = Effect.suspend(() =>
781 context ? stopContext(context).pipe(Effect.ignore) : Scope.close(sessionScope, Exit.void),
782 );
783
784 return yield* options
785 .withProcess(
786 stopOwned,
787 Effect.gen(function* () {
788 const mcp = McpProviderSession.readMcpProviderSession(input.threadId);
789 // The attachments dir grant lets the agent read pasted files at
790 // the paths ProviderService injects into the turn text. It is a
791 // leaf directory holding only uploads.
792 const runtime = yield* options.makeRuntime({
793 cwd,
794 clientInfo: { name: "t3-code", version: "0.0.0" },
795 clientFileSystem: true,
796 additionalDirectories: [serverConfig.attachmentsDir],
797 ...(Option.isSome(cursor) ? { resumeSessionId: cursor.value.sessionId } : {}),
798 mcpServers: mcp
799 ? [
800 {
801 type: "http",
802 name: "t3-code",
803 url: mcp.endpoint,
804 headers: [{ name: "Authorization", value: mcp.authorizationHeader }],
805 },
806 ]
807 : [],
808 ...makeNativeLoggers({
809 nativeEventLogger: options.nativeEventLogger,
810 provider: PROVIDER,
811 threadId: input.threadId,
812 }),
813 });
814 // Workspace file access requested through the client fs
815 // capability. The agent gates each write behind
816 // `session/request_permission`, so only path containment is
817 // checked here.
818 const allowedRoots = [cwd, serverConfig.attachmentsDir];
819 yield* runtime.handleReadTextFile((request) =>
820 readClientTextFile({ fileSystem, path, allowedRoots, request }),
821 );
822 yield* runtime.handleWriteTextFile((request) =>
823 writeClientTextFile({ fileSystem, path, allowedRoots, request }),
824 );
825 yield* runtime.handleRequestPermission((request) =>
826 context
827 ? handlePermission(context, request).pipe(
828 Effect.mapError((cause) =>
829 EffectAcpErrors.AcpRequestError.internalError(
830 "Could not process an Antigravity permission request.",
831 undefined,
832 { cause },
833 ),
834 ),
835 )
836 : Effect.succeed({
837 outcome: { outcome: "cancelled" },
838 } satisfies NativePermissionResponse),
839 );
840 const started = yield* runtime.start();
841 const model = yield* applyAntigravityAcpModelSelection({
842 runtime,
843 model: input.modelSelection?.model,
844 defaultModel: yield* options.defaultModel ?? Effect.succeed(undefined),
845 mapError: (cause) => cause,
846 });
847 yield* runtime.setMode(antigravityPermissionMode(input.runtimeMode));
848 yield* options.onSessionStarted?.(started, cwd) ?? Effect.void;
849 const createdAt = yield* nowIso;
850 const session: ProviderSession = {
851 provider: PROVIDER,
852 providerInstanceId: options.instanceId,
853 threadId: input.threadId,
854 cwd,
855 status: "ready",
856 runtimeMode: input.runtimeMode,
857 ...(model ? { model } : {}),
858 resumeCursor: { schemaVersion: 1, sessionId: started.sessionId },
859 createdAt,
860 updatedAt: createdAt,
861 };
862 context = {
863 threadId: input.threadId,
864 cwd,
865 nativeSessionId: started.sessionId,
866 scope: sessionScope,
867 runtime,
868 promptLock: yield* Semaphore.make(1),
869 stopLock: yield* Semaphore.make(1),
870 commandLock: yield* Semaphore.make(1),
871 approvals: new Map(),
872 questions: new Map(),
873 commands: new Map(),
874 subagents: new Map(),
875 turns: [],
876 session,
877 activeTurnId: undefined,
878 promptFiber: undefined,
879 generation: 0,
880 stopped: false,
881 closed: false,
882 disconnected: false,
883 };
884 const running = context;
885 sessions.set(input.threadId, running);
886 yield* Stream.runForEach(runtime.getEvents(), (event) =>
887 handleEvent(running, event),
888 ).pipe(
889 Effect.catchCause(() =>
890 Effect.logError("Could not process an Antigravity runtime event."),
891 ),
892 Effect.forkIn(sessionScope),
893 );
894 yield* emit({
895 type: "session.started",
896 ...(yield* stamp),
897 provider: PROVIDER,
898 threadId: input.threadId,
899 payload: { resume: started.initializeResult },
900 });
901 yield* emit({
902 type: "session.state.changed",
903 ...(yield* stamp),
904 provider: PROVIDER,
905 threadId: input.threadId,
906 payload: { state: "ready", reason: "Antigravity ACP session ready" },
907 });
908 yield* emit({
909 type: "thread.started",
910 ...(yield* stamp),
911 provider: PROVIDER,
912 threadId: input.threadId,
913 payload: { providerThreadId: started.sessionId },
914 });
915 yield* runtime.drainEvents;
916 if (running.stopped) {
917 return yield* new ProviderAdapterSessionClosedError({
918 provider: PROVIDER,
919 threadId: input.threadId,
920 });
921 }
922 transferred = true;
923 return session;
924 }),
925 )
926 .pipe(
927 Effect.provideService(Scope.Scope, sessionScope),
928 Effect.tapError((cause) =>
929 isAntigravitySignInRequiredError(cause)
930 ? (options.onAuthRequired ?? Effect.void)
931 : Effect.void,
932 ),
933 Effect.mapError((cause) =>
934 isAcpError(cause)
935 ? mapAntigravityError(input.threadId, "session/start", cause)
936 : new ProviderAdapterRequestError({
937 provider: PROVIDER,
938 method: "session/start",
939 detail: "Could not start Antigravity. Check the provider setup status.",
940 cause,
941 }),
942 ),
943 );
944 }).pipe(Effect.scoped),
945 );
946
947 const promoteBackgroundCommands = (context: SessionContext) =>
948 context.commandLock.withPermit(
949 Effect.gen(function* () {
950 for (const [id, command] of context.commands) {
951 if (command.promoted) continue;
952 yield* emit({
953 type: "task.started",
954 ...(yield* stamp),
955 provider: PROVIDER,
956 threadId: context.threadId,
957 turnId: command.turnId,
958 payload: {
959 taskId: RuntimeTaskId.make(id),
960 taskType: "local_bash",
961 toolUseId: id,
962 description:
963 command.toolCall.command ?? command.toolCall.title ?? "Antigravity command",
964 },
965 });
966 context.commands.set(id, { ...command, promoted: true });
967 }
968 }),
969 );
970
971 const sendTurn: Adapter["sendTurn"] = Effect.fn("AntigravityAdapter.sendTurn")(function* (input) {
972 const context = yield* requireSession(input.threadId);
973 if (input.modelSelection && input.modelSelection.instanceId !== options.instanceId) {
974 return yield* new ProviderAdapterValidationError({
975 provider: PROVIDER,
976 operation: "sendTurn",
977 issue: "The selected model belongs to another provider instance.",
978 });
979 }
980 const prompt = yield* buildAntigravityPrompt({
981 input: input.input,
982 attachments: input.attachments,
983 attachmentsDir: serverConfig.attachmentsDir,
984 }).pipe(
985 Effect.provideService(FileSystem.FileSystem, fileSystem),
986 Effect.provideService(Path.Path, path),
987 Effect.mapError((cause) => mapAntigravityError(input.threadId, "session/prompt", cause)),
988 );
989 let intent: TurnIntent | undefined;
990 // The caller holds promptLock while it changes or settles the active turn.
991 const finishTurn = (turn: TurnIntent, payload: TurnCompletedPayload) =>
992 Effect.gen(function* () {
993 if (turn.settled || context.stopped || context.generation !== turn.generation) return;
994 turn.settled = true;
995 yield* promoteBackgroundCommands(context);
996 yield* finishSubagents(
997 context,
998 payload.state === "cancelled"
999 ? "cancelled"
1000 : payload.state === "failed"
1001 ? "failed"
1002 : "idle",
1003 payload.errorMessage,
1004 );
1005 context.activeTurnId = undefined;
1006 context.promptFiber = undefined;
1007 context.session = {
1008 ...context.session,
1009 status: payload.state === "failed" ? "error" : "ready",
1010 activeTurnId: undefined,
1011 updatedAt: yield* nowIso,
1012 ...(payload.errorMessage
1013 ? { lastError: payload.errorMessage }
1014 : { lastError: undefined }),
1015 };
1016 yield* emit({
1017 type: "turn.completed",
1018 ...(yield* stamp),
1019 provider: PROVIDER,
1020 threadId: input.threadId,
1021 turnId: turn.turnId,
1022 payload,
1023 });
1024 }).pipe(Effect.uninterruptible);
1025
1026 return yield* Effect.gen(function* () {
1027 const launch = yield* context.promptLock.withPermit(
1028 Effect.gen(function* () {
1029 yield* requireSession(input.threadId);
1030 const requestedModel = input.modelSelection?.model ?? context.session.model;
1031 const configOptions = yield* context.runtime.getConfigOptions;
1032 const model = resolveAntigravityModel({
1033 configOptions,
1034 model: requestedModel,
1035 defaultModel: yield* options.defaultModel ?? Effect.succeed(undefined),
1036 });
1037 const availableModels = antigravityModelOptions(configOptions);
1038 if (model && !availableModels.some((option) => option.value === model)) {
1039 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
1040 `Antigravity model '${model}' is unavailable for this Google account. Select an available model.`,
1041 );
1042 }
1043 const turnId = context.activeTurnId ?? TurnId.make(yield* randomId);
1044 const steering = context.activeTurnId !== undefined;
1045 const turn: TurnIntent = { turnId, generation: ++context.generation, settled: false };
1046 intent = turn;
1047 context.activeTurnId = turnId;
1048 if (!steering) {
1049 yield* emit({
1050 type: "turn.started",
1051 ...(yield* stamp),
1052 provider: PROVIDER,
1053 threadId: input.threadId,
1054 turnId,
1055 payload: model ? { model } : {},
1056 });
1057 }
1058 if (context.promptFiber) {
1059 yield* cancelRequests(context);
1060 yield* context.runtime.cancel;
1061 yield* Fiber.await(context.promptFiber);
1062 yield* finishSubagents(context, "cancelled");
1063 }
1064 yield* applyAntigravityAcpModelSelection({
1065 runtime: context.runtime,
1066 model,
1067 mapError: (cause) => cause,
1068 });
1069 yield* context.runtime.setMode(antigravityPermissionMode(context.session.runtimeMode));
1070 context.session = {
1071 ...context.session,
1072 status: "running",
1073 activeTurnId: turnId,
1074 ...(model ? { model } : {}),
1075 updatedAt: yield* nowIso,
1076 };
1077 const dispatched = yield* Deferred.make<void>();
1078 const fiber = yield* context.runtime
1079 .prompt(
1080 {
1081 prompt: [
1082 ...prompt,
1083 {
1084 type: "text",
1085 text: buildRuntimeInstructions({ harness: "Antigravity", model }),
1086 },
1087 ],
1088 },
1089 { dispatched },
1090 )
1091 .pipe(Effect.forkIn(context.scope));
1092 context.promptFiber = fiber;
1093 // Fiber.join can skip a scope-close waiter when the child is interrupted.
1094 // Unwrap the Exit after Fiber.await returns.
1095 yield* Effect.raceFirst(
1096 Deferred.await(dispatched),
1097 Fiber.await(fiber).pipe(
1098 Effect.flatMap((exit) => exit),
1099 Effect.asVoid,
1100 ),
1101 );
1102 return { turn, fiber };
1103 }),
1104 );
1105 const result = yield* Fiber.await(launch.fiber).pipe(Effect.flatMap((exit) => exit));
1106 yield* context.runtime.drainEvents;
1107 if (context.stopped) {
1108 return yield* new ProviderAdapterSessionClosedError({
1109 provider: PROVIDER,
1110 threadId: input.threadId,
1111 });
1112 }
1113 const record = context.turns.find((turn) => turn.id === launch.turn.turnId);
1114 if (record) record.items.push(result);
1115 else context.turns.push({ id: launch.turn.turnId, items: [result] });
1116 yield* context.promptLock.withPermit(
1117 finishTurn(launch.turn, {
1118 state: result.stopReason === "cancelled" ? "cancelled" : "completed",
1119 stopReason: result.stopReason,
1120 }),
1121 );
1122 return {
1123 threadId: input.threadId,
1124 turnId: launch.turn.turnId,
1125 resumeCursor: context.session.resumeCursor,
1126 };
1127 }).pipe(
1128 Effect.tapError((cause) =>
1129 isAntigravitySignInRequiredError(cause)
1130 ? (options.onAuthRequired ?? Effect.void)
1131 : Effect.void,
1132 ),
1133 Effect.mapError((cause) =>
1134 isAcpError(cause) ? mapAntigravityError(input.threadId, "session/prompt", cause) : cause,
1135 ),
1136 Effect.tapError((cause) =>
1137 Effect.suspend(() =>
1138 intent
1139 ? context.promptLock.withPermit(
1140 finishTurn(intent, { state: "failed", errorMessage: cause.message }),
1141 )
1142 : Effect.void,
1143 ),
1144 ),
1145 Effect.onInterrupt(() =>
1146 context.promptLock.withPermit(
1147 Effect.gen(function* () {
1148 const turn = intent;
1149 if (!turn || turn.settled || context.stopped || context.generation !== turn.generation)
1150 return;
1151 const promptFiber = context.promptFiber;
1152 yield* cancelRequests(context);
1153 yield* Effect.ignore(context.runtime.cancel);
1154 if (promptFiber) yield* Fiber.interrupt(promptFiber);
1155 yield* finishTurn(turn, { state: "cancelled", stopReason: "cancelled" });
1156 }),
1157 ),
1158 ),
1159 );
1160 });
1161
1162 const interruptTurn: Adapter["interruptTurn"] = (threadId) =>
1163 Effect.gen(function* () {
1164 const context = yield* requireSession(threadId);
1165 yield* context.promptLock
1166 .withPermit(
1167 Effect.gen(function* () {
1168 yield* cancelRequests(context);
1169 yield* context.runtime.cancel;
1170 }),
1171 )
1172 .pipe(Effect.mapError((cause) => mapAntigravityError(threadId, "session/cancel", cause)));
1173 });
1174
1175 const respondToRequest: Adapter["respondToRequest"] = (threadId, requestId, decision) =>
1176 Effect.gen(function* () {
1177 const context = yield* requireSession(threadId);
1178 const pending = context.approvals.get(requestId);
1179 if (!pending) {
1180 return yield* new ProviderAdapterRequestError({
1181 provider: PROVIDER,
1182 method: "session/request_permission",
1183 detail: "This approval request is no longer pending.",
1184 });
1185 }
1186 const optionId =
1187 decision === "cancel"
1188 ? undefined
1189 : selectAntigravityPermissionOptionId(pending.request, decision);
1190 if (decision !== "cancel" && optionId === undefined) {
1191 return yield* new ProviderAdapterValidationError({
1192 provider: PROVIDER,
1193 operation: "respondToRequest",
1194 issue:
1195 "Antigravity did not offer this permission choice. Select one of the available choices.",
1196 });
1197 }
1198 yield* Deferred.succeed(pending.response, {
1199 decision,
1200 result: {
1201 outcome:
1202 optionId === undefined ? { outcome: "cancelled" } : { outcome: "selected", optionId },
1203 },
1204 });
1205 });
1206
1207 const respondToUserInput: Adapter["respondToUserInput"] = (threadId, requestId, answers) =>
1208 Effect.gen(function* () {
1209 const context = yield* requireSession(threadId);
1210 const pending = context.questions.get(requestId);
1211 if (!pending) {
1212 return yield* new ProviderAdapterRequestError({
1213 provider: PROVIDER,
1214 method: "session/request_permission",
1215 detail: "This question is no longer pending.",
1216 });
1217 }
1218 const result = makeAntigravityUserInputResponse(pending.request, answers);
1219 if (!result) {
1220 return yield* new ProviderAdapterValidationError({
1221 provider: PROVIDER,
1222 operation: "respondToUserInput",
1223 issue:
1224 "Select one of Antigravity's offered answers. Custom answers are not supported for this question.",
1225 });
1226 }
1227 yield* Deferred.succeed(pending.response, { answers, result });
1228 });
1229
1230 const stopSession: Adapter["stopSession"] = (threadId) =>
1231 withThreadLock(threadId, Effect.flatMap(requireSession(threadId), stopContext));
1232 const stopAll: Adapter["stopAll"] = () =>
1233 Effect.forEach([...sessions.values()], stopContext, { discard: true });
1234 yield* Effect.addFinalizer(() =>
1235 stopAll().pipe(
1236 Effect.catchCause((cause) =>
1237 Cause.hasInterrupts(cause)
1238 ? Effect.void
1239 : Effect.logError("Could not stop an Antigravity session."),
1240 ),
1241 Effect.ensuring(PubSub.shutdown(events)),
1242 ),
1243 );
1244
1245 return {
1246 provider: PROVIDER,
1247 capabilities: { sessionModelSwitch: "in-session", supportsConversationRollback: false },
1248 compaction: { type: "slash-command", command: "/compact" },
1249 startSession,
1250 sendTurn,
1251 interruptTurn,
1252 respondToRequest,
1253 respondToUserInput,
1254 stopSession,
1255 stopAll,
1256 listSessions: () =>
1257 Effect.sync(() =>
1258 [...sessions.values()]
1259 .filter((context) => !context.stopped)
1260 .map((context) => ({ ...context.session })),
1261 ),
1262 hasSession: (threadId) =>
1263 Effect.sync(() => sessions.has(threadId) && !sessions.get(threadId)?.stopped),
1264 readThread: (threadId) =>
1265 Effect.map(requireSession(threadId), (context) => ({ threadId, turns: context.turns })),
1266 rollbackThread: (_threadId: ThreadId, _numTurns: number) =>
1267 Effect.fail(
1268 new ProviderAdapterValidationError({
1269 provider: PROVIDER,
1270 operation: "rollbackThread",
1271 issue: "Antigravity does not support conversation rewind. Start a new thread instead.",
1272 }),
1273 ),
1274 streamEvents: Stream.fromPubSub(events),
1275 } satisfies Adapter;
1276});