Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AntigravityAdapter.ts

1,240 lines46.7 KB

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