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

AntigravityAdapter.ts

1,279 lines48.3 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 { 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);
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;
148​
149interface PendingApproval {
150 readonly request: NativePermission;
151 readonly response: Deferred.Deferred<{
152 readonly decision: ProviderApprovalDecision;
153 readonly result: NativePermissionResponse;
154 }>;
156​
157interface PendingQuestion {
158 readonly request: NativePermission;
159 readonly response: Deferred.Deferred<{
160 readonly answers: ProviderUserInputAnswers;
161 readonly result: NativePermissionResponse;
162 }>;
164​
165interface OpenCommand {
166 readonly toolCall: AcpToolCallState;
167 readonly turnId: TurnId | undefined;
168 readonly promoted: boolean;
170​
171interface OpenSubagent {
172 readonly turnId: TurnId | undefined;
173 readonly status: "pending" | "running" | undefined;
174 readonly description?: string;
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 };
185​
186interface TurnIntent {
187 readonly turnId: TurnId;
188 readonly generation: number;
189 settled: boolean;
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;
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));
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 ...(mcp?.agentDeviceEnvironment
797 ? { agentDeviceEnvironment: mcp.agentDeviceEnvironment }
798 : {}),
799 additionalDirectories: [serverConfig.attachmentsDir],
800 ...(Option.isSome(cursor) ? { resumeSessionId: cursor.value.sessionId } : {}),
801 mcpServers: mcp
802 ? [
803 {
804 type: "http",
805 name: "t3-code",
806 url: mcp.endpoint,
807 headers: [{ name: "Authorization", value: mcp.authorizationHeader }],
808 },
809 ]
810 : [],
811 ...makeNativeLoggers({
812 nativeEventLogger: options.nativeEventLogger,
813 provider: PROVIDER,
814 threadId: input.threadId,
815 }),
816 });
817 // Workspace file access requested through the client fs
818 // capability. The agent gates each write behind
819 // `session/request_permission`, so only path containment is
820 // checked here.
821 const allowedRoots = [cwd, serverConfig.attachmentsDir];
822 yield* runtime.handleReadTextFile((request) =>
823 readClientTextFile({ fileSystem, path, allowedRoots, request }),
824 );
825 yield* runtime.handleWriteTextFile((request) =>
826 writeClientTextFile({ fileSystem, path, allowedRoots, request }),
827 );
828 yield* runtime.handleRequestPermission((request) =>
829 context
830 ? handlePermission(context, request).pipe(
831 Effect.mapError((cause) =>
832 EffectAcpErrors.AcpRequestError.internalError(
833 "Could not process an Antigravity permission request.",
834 undefined,
835 { cause },
836 ),
837 ),
838 )
839 : Effect.succeed({
840 outcome: { outcome: "cancelled" },
841 } satisfies NativePermissionResponse),
842 );
843 const started = yield* runtime.start();
844 const model = yield* applyAntigravityAcpModelSelection({
845 runtime,
846 model: input.modelSelection?.model,
847 defaultModel: yield* options.defaultModel ?? Effect.succeed(undefined),
848 mapError: (cause) => cause,
849 });
850 yield* runtime.setMode(antigravityPermissionMode(input.runtimeMode));
851 yield* options.onSessionStarted?.(started, cwd) ?? Effect.void;
852 const createdAt = yield* nowIso;
853 const session: ProviderSession = {
854 provider: PROVIDER,
855 providerInstanceId: options.instanceId,
856 threadId: input.threadId,
857 cwd,
858 status: "ready",
859 runtimeMode: input.runtimeMode,
860 ...(model ? { model } : {}),
861 resumeCursor: { schemaVersion: 1, sessionId: started.sessionId },
862 createdAt,
863 updatedAt: createdAt,
864 };
865 context = {
866 threadId: input.threadId,
867 cwd,
868 nativeSessionId: started.sessionId,
869 scope: sessionScope,
870 runtime,
871 promptLock: yield* Semaphore.make(1),
872 stopLock: yield* Semaphore.make(1),
873 commandLock: yield* Semaphore.make(1),
874 approvals: new Map(),
875 questions: new Map(),
876 commands: new Map(),
877 subagents: new Map(),
878 turns: [],
879 session,
880 activeTurnId: undefined,
881 promptFiber: undefined,
882 generation: 0,
883 stopped: false,
884 closed: false,
885 disconnected: false,
886 };
887 const running = context;
888 sessions.set(input.threadId, running);
889 yield* Stream.runForEach(runtime.getEvents(), (event) =>
890 handleEvent(running, event),
891 ).pipe(
892 Effect.catchCause(() =>
893 Effect.logError("Could not process an Antigravity runtime event."),
894 ),
895 Effect.forkIn(sessionScope),
896 );
897 yield* emit({
898 type: "session.started",
899 ...(yield* stamp),
900 provider: PROVIDER,
901 threadId: input.threadId,
902 payload: { resume: started.initializeResult },
903 });
904 yield* emit({
905 type: "session.state.changed",
906 ...(yield* stamp),
907 provider: PROVIDER,
908 threadId: input.threadId,
909 payload: { state: "ready", reason: "Antigravity ACP session ready" },
910 });
911 yield* emit({
912 type: "thread.started",
913 ...(yield* stamp),
914 provider: PROVIDER,
915 threadId: input.threadId,
916 payload: { providerThreadId: started.sessionId },
917 });
918 yield* runtime.drainEvents;
919 if (running.stopped) {
920 return yield* new ProviderAdapterSessionClosedError({
921 provider: PROVIDER,
922 threadId: input.threadId,
923 });
924 }
925 transferred = true;
926 return session;
927 }),
928 )
929 .pipe(
930 Effect.provideService(Scope.Scope, sessionScope),
931 Effect.tapError((cause) =>
932 isAntigravitySignInRequiredError(cause)
933 ? (options.onAuthRequired ?? Effect.void)
934 : Effect.void,
935 ),
936 Effect.mapError((cause) =>
937 isAcpError(cause)
938 ? mapAntigravityError(input.threadId, "session/start", cause)
939 : new ProviderAdapterRequestError({
940 provider: PROVIDER,
941 method: "session/start",
942 detail: "Could not start Antigravity. Check the provider setup status.",
943 cause,
944 }),
945 ),
946 );
947 }).pipe(Effect.scoped),
948 );
949​
950 const promoteBackgroundCommands = (context: SessionContext) =>
951 context.commandLock.withPermit(
952 Effect.gen(function* () {
953 for (const [id, command] of context.commands) {
954 if (command.promoted) continue;
955 yield* emit({
956 type: "task.started",
957 ...(yield* stamp),
958 provider: PROVIDER,
959 threadId: context.threadId,
960 turnId: command.turnId,
961 payload: {
962 taskId: RuntimeTaskId.make(id),
963 taskType: "local_bash",
964 toolUseId: id,
965 description:
966 command.toolCall.command ?? command.toolCall.title ?? "Antigravity command",
967 },
968 });
969 context.commands.set(id, { ...command, promoted: true });
970 }
971 }),
972 );
973​
974 const sendTurn: Adapter["sendTurn"] = Effect.fn("AntigravityAdapter.sendTurn")(function* (input) {
975 const context = yield* requireSession(input.threadId);
976 if (input.modelSelection && input.modelSelection.instanceId !== options.instanceId) {
977 return yield* new ProviderAdapterValidationError({
978 provider: PROVIDER,
979 operation: "sendTurn",
980 issue: "The selected model belongs to another provider instance.",
981 });
982 }
983 const prompt = yield* buildAntigravityPrompt({
984 input: input.input,
985 attachments: input.attachments,
986 attachmentsDir: serverConfig.attachmentsDir,
987 }).pipe(
988 Effect.provideService(FileSystem.FileSystem, fileSystem),
989 Effect.provideService(Path.Path, path),
990 Effect.mapError((cause) => mapAntigravityError(input.threadId, "session/prompt", cause)),
991 );
992 let intent: TurnIntent | undefined;
993 // The caller holds promptLock while it changes or settles the active turn.
994 const finishTurn = (turn: TurnIntent, payload: TurnCompletedPayload) =>
995 Effect.gen(function* () {
996 if (turn.settled || context.stopped || context.generation !== turn.generation) return;
997 turn.settled = true;
998 yield* promoteBackgroundCommands(context);
999 yield* finishSubagents(
1000 context,
1001 payload.state === "cancelled"
1002 ? "cancelled"
1003 : payload.state === "failed"
1004 ? "failed"
1005 : "idle",
1006 payload.errorMessage,
1007 );
1008 context.activeTurnId = undefined;
1009 context.promptFiber = undefined;
1010 context.session = {
1011 ...context.session,
1012 status: payload.state === "failed" ? "error" : "ready",
1013 activeTurnId: undefined,
1014 updatedAt: yield* nowIso,
1015 ...(payload.errorMessage
1016 ? { lastError: payload.errorMessage }
1017 : { lastError: undefined }),
1018 };
1019 yield* emit({
1020 type: "turn.completed",
1021 ...(yield* stamp),
1022 provider: PROVIDER,
1023 threadId: input.threadId,
1024 turnId: turn.turnId,
1025 payload,
1026 });
1027 }).pipe(Effect.uninterruptible);
1028​
1029 return yield* Effect.gen(function* () {
1030 const launch = yield* context.promptLock.withPermit(
1031 Effect.gen(function* () {
1032 yield* requireSession(input.threadId);
1033 const requestedModel = input.modelSelection?.model ?? context.session.model;
1034 const configOptions = yield* context.runtime.getConfigOptions;
1035 const model = resolveAntigravityModel({
1036 configOptions,
1037 model: requestedModel,
1038 defaultModel: yield* options.defaultModel ?? Effect.succeed(undefined),
1039 });
1040 const availableModels = antigravityModelOptions(configOptions);
1041 if (model && !availableModels.some((option) => option.value === model)) {
1042 return yield* EffectAcpErrors.AcpRequestError.invalidParams(
1043 `Antigravity model '${model}' is unavailable for this Google account. Select an available model.`,
1044 );
1046 const turnId = context.activeTurnId ?? TurnId.make(yield* randomId);
1047 const steering = context.activeTurnId !== undefined;
1048 const turn: TurnIntent = { turnId, generation: ++context.generation, settled: false };
1049 intent = turn;
1050 context.activeTurnId = turnId;
1051 if (!steering) {
1052 yield* emit({
1053 type: "turn.started",
1054 ...(yield* stamp),
1055 provider: PROVIDER,
1056 threadId: input.threadId,
1057 turnId,
1058 payload: model ? { model } : {},
1059 });
1061 if (context.promptFiber) {
1062 yield* cancelRequests(context);
1063 yield* context.runtime.cancel;
1064 yield* Fiber.await(context.promptFiber);
1065 yield* finishSubagents(context, "cancelled");
1067 yield* applyAntigravityAcpModelSelection({
1068 runtime: context.runtime,
1069 model,
1070 mapError: (cause) => cause,
1071 });
1072 yield* context.runtime.setMode(antigravityPermissionMode(context.session.runtimeMode));
1073 context.session = {
1074 ...context.session,
1075 status: "running",
1076 activeTurnId: turnId,
1077 ...(model ? { model } : {}),
1078 updatedAt: yield* nowIso,
1079 };
1080 const dispatched = yield* Deferred.make<void>();
1081 const fiber = yield* context.runtime
1082 .prompt(
1084 prompt: [
1085 ...prompt,
1087 type: "text",
1088 text: buildRuntimeInstructions({ harness: "Antigravity", model }),
1089 },
1090 ],
1091 },
1092 { dispatched },
1094 .pipe(Effect.forkIn(context.scope));
1095 context.promptFiber = fiber;
1096 // Fiber.join can skip a scope-close waiter when the child is interrupted.
1097 // Unwrap the Exit after Fiber.await returns.
1098 yield* Effect.raceFirst(
1099 Deferred.await(dispatched),
1100 Fiber.await(fiber).pipe(
1101 Effect.flatMap((exit) => exit),
1102 Effect.asVoid,
1103 ),
1104 );
1105 return { turn, fiber };
1106 }),
1107 );
1108 const result = yield* Fiber.await(launch.fiber).pipe(Effect.flatMap((exit) => exit));
1109 yield* context.runtime.drainEvents;
1110 if (context.stopped) {
1111 return yield* new ProviderAdapterSessionClosedError({
1112 provider: PROVIDER,
1113 threadId: input.threadId,
1114 });
1116 const record = context.turns.find((turn) => turn.id === launch.turn.turnId);
1117 if (record) record.items.push(result);
1118 else context.turns.push({ id: launch.turn.turnId, items: [result] });
1119 yield* context.promptLock.withPermit(
1120 finishTurn(launch.turn, {
1121 state: result.stopReason === "cancelled" ? "cancelled" : "completed",
1122 stopReason: result.stopReason,
1123 }),
1124 );
1125 return {
1126 threadId: input.threadId,
1127 turnId: launch.turn.turnId,
1128 resumeCursor: context.session.resumeCursor,
1129 };
1130 }).pipe(
1131 Effect.tapError((cause) =>
1132 isAntigravitySignInRequiredError(cause)
1133 ? (options.onAuthRequired ?? Effect.void)
1134 : Effect.void,
1135 ),
1136 Effect.mapError((cause) =>
1137 isAcpError(cause) ? mapAntigravityError(input.threadId, "session/prompt", cause) : cause,
1138 ),
1139 Effect.tapError((cause) =>
1140 Effect.suspend(() =>
1141 intent
1142 ? context.promptLock.withPermit(
1143 finishTurn(intent, { state: "failed", errorMessage: cause.message }),
1145 : Effect.void,
1146 ),
1147 ),
1148 Effect.onInterrupt(() =>
1149 context.promptLock.withPermit(
1150 Effect.gen(function* () {
1151 const turn = intent;
1152 if (!turn || turn.settled || context.stopped || context.generation !== turn.generation)
1153 return;
1154 const promptFiber = context.promptFiber;
1155 yield* cancelRequests(context);
1156 yield* Effect.ignore(context.runtime.cancel);
1157 if (promptFiber) yield* Fiber.interrupt(promptFiber);
1158 yield* finishTurn(turn, { state: "cancelled", stopReason: "cancelled" });
1159 }),
1160 ),
1161 ),
1162 );
1163 });
1164​
1165 const interruptTurn: Adapter["interruptTurn"] = (threadId) =>
1166 Effect.gen(function* () {
1167 const context = yield* requireSession(threadId);
1168 yield* context.promptLock
1169 .withPermit(
1170 Effect.gen(function* () {
1171 yield* cancelRequests(context);
1172 yield* context.runtime.cancel;
1173 }),
1175 .pipe(Effect.mapError((cause) => mapAntigravityError(threadId, "session/cancel", cause)));
1176 });
1177​
1178 const respondToRequest: Adapter["respondToRequest"] = (threadId, requestId, decision) =>
1179 Effect.gen(function* () {
1180 const context = yield* requireSession(threadId);
1181 const pending = context.approvals.get(requestId);
1182 if (!pending) {
1183 return yield* new ProviderAdapterRequestError({
1184 provider: PROVIDER,
1185 method: "session/request_permission",
1186 detail: "This approval request is no longer pending.",
1187 });
1189 const optionId =
1190 decision === "cancel"
1191 ? undefined
1192 : selectAntigravityPermissionOptionId(pending.request, decision);
1193 if (decision !== "cancel" && optionId === undefined) {
1194 return yield* new ProviderAdapterValidationError({
1195 provider: PROVIDER,
1196 operation: "respondToRequest",
1197 issue:
1198 "Antigravity did not offer this permission choice. Select one of the available choices.",
1199 });
1201 yield* Deferred.succeed(pending.response, {
1202 decision,
1203 result: {
1204 outcome:
1205 optionId === undefined ? { outcome: "cancelled" } : { outcome: "selected", optionId },
1206 },
1207 });
1208 });
1209​
1210 const respondToUserInput: Adapter["respondToUserInput"] = (threadId, requestId, answers) =>
1211 Effect.gen(function* () {
1212 const context = yield* requireSession(threadId);
1213 const pending = context.questions.get(requestId);
1214 if (!pending) {
1215 return yield* new ProviderAdapterRequestError({
1216 provider: PROVIDER,
1217 method: "session/request_permission",
1218 detail: "This question is no longer pending.",
1219 });
1221 const result = makeAntigravityUserInputResponse(pending.request, answers);
1222 if (!result) {
1223 return yield* new ProviderAdapterValidationError({
1224 provider: PROVIDER,
1225 operation: "respondToUserInput",
1226 issue:
1227 "Select one of Antigravity's offered answers. Custom answers are not supported for this question.",
1228 });
1230 yield* Deferred.succeed(pending.response, { answers, result });
1231 });
1232​
1233 const stopSession: Adapter["stopSession"] = (threadId) =>
1234 withThreadLock(threadId, Effect.flatMap(requireSession(threadId), stopContext));
1235 const stopAll: Adapter["stopAll"] = () =>
1236 Effect.forEach([...sessions.values()], stopContext, { discard: true });
1237 yield* Effect.addFinalizer(() =>
1238 stopAll().pipe(
1239 Effect.catchCause((cause) =>
1240 Cause.hasInterrupts(cause)
1241 ? Effect.void
1242 : Effect.logError("Could not stop an Antigravity session."),
1243 ),
1244 Effect.ensuring(PubSub.shutdown(events)),
1245 ),
1246 );
1247​
1248 return {
1249 provider: PROVIDER,
1250 capabilities: { sessionModelSwitch: "in-session", supportsConversationRollback: false },
1251 compaction: { type: "slash-command", command: "/compact" },
1252 startSession,
1253 sendTurn,
1254 interruptTurn,
1255 respondToRequest,
1256 respondToUserInput,
1257 stopSession,
1258 stopAll,
1259 listSessions: () =>
1260 Effect.sync(() =>
1261 [...sessions.values()]
1262 .filter((context) => !context.stopped)
1263 .map((context) => ({ ...context.session })),
1264 ),
1265 hasSession: (threadId) =>
1266 Effect.sync(() => sessions.has(threadId) && !sessions.get(threadId)?.stopped),
1267 readThread: (threadId) =>
1268 Effect.map(requireSession(threadId), (context) => ({ threadId, turns: context.turns })),
1269 rollbackThread: (_threadId: ThreadId, _numTurns: number) =>
1270 Effect.fail(
1271 new ProviderAdapterValidationError({
1272 provider: PROVIDER,
1273 operation: "rollbackThread",
1274 issue: "Antigravity does not support conversation rewind. Start a new thread instead.",
1275 }),
1276 ),
1277 streamEvents: Stream.fromPubSub(events),
1278 } satisfies Adapter;
1279});