diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index b6f746269a6f2..9b6672981edcc 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -212,6 +212,8 @@ export function makeAntigravityAcpAdapterFlavor( supportsNativeGoals: options.supportsNativeGoals ?? Effect.succeed(false), // Agents that advertise HTTP MCP skip the stdio bridge process; others keep stdio. mcpOverHttp: true, + // Keep initial tools/list under Antigravity ACP's ~40 KB eager schema cap via tool_search. + deferMcpTools: true, sessionCarriesPullRequestLinking: antigravityAppendsSystemPrompt, makeRuntime, buildAttachmentPrompt: ({ @@ -281,6 +283,7 @@ export function makeAntigravityAcpAdapterFlavor( // 1.4.5 returns the root trajectory's Gemini usageMetadata delta; 1.4.1 returns none. reportsPerTurnPromptUsage: true, geminiPromptUsage: true, + enablePostSettleContinuation: true, ...(profileDirectory === undefined ? {} : { diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts index 447745fc673a0..e131b4d62a6a1 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts @@ -3,6 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it } from "@effect/vitest"; import { ANTIGRAVITY_DEFAULT_MODEL, + EnvironmentId, ProviderInstanceId, ProviderSessionId, ThreadId, @@ -82,6 +83,7 @@ const makeHarness = Effect.fn("makeAntigravityDriverHarness")(function* ( /** `data` of the agent's "Internal error" response to `session/new`. */ readonly newSessionErrorData?: unknown; readonly initialMode?: string; + readonly httpMcp?: boolean; } = {}, ) { const directory = path.join(root, name); @@ -105,6 +107,7 @@ const makeHarness = Effect.fn("makeAntigravityDriverHarness")(function* ( ...(options.initialMode === undefined ? [] : [`export T3_ACP_INITIAL_MODE=${shellQuote(options.initialMode)}`]), + ...(options.httpMcp ? ["export T3_ACP_MCP_HTTP=1"] : []), `exec ${shellQuote(nodePath)} ${shellQuote(mockAgentPath)} "$@"`, "", ].join("\n"), @@ -142,6 +145,10 @@ const makeHarness = Effect.fn("makeAntigravityDriverHarness")(function* ( credentialKeys: ReadonlyArray; geminiApiKey: string | undefined; tempDirectory: string | undefined; + threadId: string | undefined; + mcpEndpoint: string | undefined; + mcpAuthorization: string | undefined; + mcpNode: string | undefined; handle: ChildProcessSpawner.ChildProcessHandle; }> = []; @@ -200,6 +207,10 @@ const makeHarness = Effect.fn("makeAntigravityDriverHarness")(function* ( geminiApiKey: env("GEMINI_API_KEY"), tempDirectory: environment.ANTIGRAVITY_HARNESS_PATH === undefined ? undefined : env("TMPDIR"), + threadId: env("T3CODE_THREAD_ID"), + mcpEndpoint: env("T3_ACP_MCP_ENDPOINT"), + mcpAuthorization: env("T3_ACP_MCP_AUTHORIZATION"), + mcpNode: env("T3_ACP_MCP_NODE"), handle, }); return handle; @@ -579,4 +590,62 @@ it.layer(layerTest)("AntigravityDriver", (it) => { expect(yield* fs.exists(legacyRoot)).toBe(false); }), ); + + it.effect.skipIf(windowsHost)( + "forwards thread MCP environment and defers MCP tools for Antigravity sessions", + () => + Effect.gen(function* () { + const h = yield* makeHarness(); + h.controls.selected = yield* h.makeExecutable("runtime http mcp", { httpMcp: true }); + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const workspace = yield* h.fs.makeTempDirectoryScoped({ prefix: "t3-ag-mcp-" }); + const threadId = ThreadId.make("thread-antigravity-mcp-env"); + const providerSessionId = ProviderSessionId.make("provider-session-antigravity-mcp-env"); + const endpoint = "http://127.0.0.1:43210/mcp"; + const authorizationHeader = "Bearer test-mcp-token"; + yield* mcpSessions.set({ + environmentId: EnvironmentId.make("env-test"), + threadId, + providerSessionId, + providerInstanceId: h.instance.instanceId, + endpoint, + authorizationHeader, + browserToolsAvailable: false, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "approval-required", + interactionMode: "default", + cwd: workspace, + }); + const modelSelection = { instanceId: h.instance.instanceId, model: "gemini-test-low" }; + const session = yield* h.instance.orchestrationAdapter.openSession({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + yield* session.ensureThread({ threadId, modelSelection, runtimePolicy }); + + const launch = h.launches.at(-1); + expect(launch?.threadId).toBe(threadId); + expect(launch?.mcpEndpoint).toBe(endpoint); + expect(launch?.mcpAuthorization).toBe(authorizationHeader); + expect(launch?.mcpNode).toBeTruthy(); + + const newSessionRequest = (yield* h.readRequests).findLast( + (request) => request.method === "session/new", + ); + expect(newSessionRequest?.params?.mcpServers).toEqual([ + { + type: "http", + name: "t3-code", + url: endpoint, + headers: [ + { name: "Authorization", value: authorizationHeader }, + { name: "t3-tool-exposure", value: "deferred" }, + ], + }, + ]); + }), + ); }); diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index 75bca5acc87be..d2804d74e27d8 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -276,7 +276,12 @@ export const AntigravityDriver: ProviderDriver< installation: executable, profile, cwd: input.cwd, - baseEnv: processEnvironment, + baseEnv: input.processEnvironment + ? { + ...processEnvironment, + ...input.processEnvironment, + } + : processEnvironment, auth, runtimeTempDirectory, }), diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 7fd64e2534fa7..e042d07e96276 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -50,6 +50,7 @@ export interface AntigravityAcpRuntimeInput extends Omit< /** Conversational sessions only; helpers and probes leave the system prompt untouched. */ readonly sessionSystemPromptAppend?: string; readonly authMethod?: AntigravityAuthMethod; + readonly processEnvironment?: NodeJS.ProcessEnv | undefined; } function parseAntigravityVersion(version: string | null | undefined) { diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts index 52e96caa08aea..79f2718d0289b 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts @@ -208,4 +208,67 @@ describe("watchAntigravityPromptOutcome", () => { }); }).pipe(Effect.provide(NodeServices.layer)), ); + + it.effect("detects corrupted checkpoint errors and quarantines the database", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profileDirectory = yield* fs.makeTempDirectoryScoped(); + const sessionId = "a1b2c3d4-e5f6-4a1b-8c2d-3e4f5a6b7c8d"; + const conversations = path.join(profileDirectory, "antigravity-acp", "conversations"); + yield* fs.makeDirectory(conversations, { recursive: true }); + const dbPath = path.join(conversations, `${sessionId}.db`); + + const database = new NodeSqlite.DatabaseSync(dbPath); + try { + database.exec( + "CREATE TABLE IF NOT EXISTS steps (idx INTEGER PRIMARY KEY, step_type INTEGER, step_payload BLOB)", + ); + } finally { + database.close(); + } + + const check = yield* watchAntigravityPromptOutcome(profileDirectory, sessionId); + + const checkpointCorruptPayload = errorPayload( + "agent executor error: could not find doneCh for checkpoint", + ); + const corruptDb = new NodeSqlite.DatabaseSync(dbPath); + try { + corruptDb + .prepare("INSERT INTO steps (idx, step_type, step_payload) VALUES (?, ?, ?)") + .run(0, ERROR_MESSAGE, checkpointCorruptPayload); + } finally { + corruptDb.close(); + } + + const blocked = `${dbPath}.corrupt-0`; + yield* fs.makeDirectory(blocked); + const walPath = `${dbPath}-wal`; + yield* fs.writeFileString(walPath, "fixture wal"); + const failed = yield* check({ stopReason: "end_turn" }); + assert.equal(failed?.retryable, false); + assert.isTrue(yield* fs.exists(dbPath)); + assert.isTrue(yield* fs.exists(walPath)); + yield* fs.remove(blocked, { recursive: true }); + yield* fs.remove(walPath); + + const failure = yield* check({ stopReason: "end_turn" }); + assert.deepEqual(failure, { + class: "provider_error", + message: + "Antigravity session checkpoint was corrupted and has been quarantined. The session will restart.", + code: "SESSION_CORRUPTED", + retryable: true, + }); + + // The original .db file should be quarantined (moved) + const originalExists = yield* fs.exists(dbPath); + assert.isFalse(originalExists); + + const files = yield* fs.readDirectory(conversations); + const quarantined = files.find((f) => f.startsWith(`${sessionId}.db.corrupt-`)); + assert.isDefined(quarantined); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + ); }); diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts index 41e25f2e417e1..9ae58ead715ab 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts @@ -20,6 +20,12 @@ const MAX_ERROR_PAYLOAD_BYTES = 16_384; // The Go harness's rendering of a Google API error, as the agent's api_errors.py reads it. const API_ERROR = /Error (\d{3}), Message: (.+?), Status: ([A-Z_]+)/s; const QUOTA_EXHAUSTED = /\breason:QUOTA_EXHAUSTED\b/; +const CHECKPOINT_CORRUPTED = /could not find doneCh for checkpoint/i; + +function isAntigravityCheckpointCorrupted(text: string): boolean { + return CHECKPOINT_CORRUPTED.test(text); +} + const RESET_TIMESTAMP = /\bquotaResetTimeStamp:([^\s\]]+)/; const RESET_DELAY = /\bquotaResetDelay:((?:\d+(?:\.\d+)?(?:ns|us|µs|μs|ms|h|m|s))+)(?=[\s\]])/; // google.rpc.RetryInfo, which plain rate limits carry instead of a quota reset. @@ -53,6 +59,15 @@ class AntigravitySessionLogError extends Schema.TaggedError new AntigravitySessionLogError({ cause }); +class AntigravitySessionQuarantineError extends Schema.TaggedError()( + "AntigravitySessionQuarantineError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not quarantine the Antigravity session database."; + } +} + const readSteps = (file: string, read: (database: NodeSqlite.DatabaseSync) => A) => Effect.try({ try: () => { @@ -124,6 +139,15 @@ function turnFailure( resetAt: resetAtFrom(text, now) ?? null, }); } + if (isAntigravityCheckpointCorrupted(text)) { + return makeProviderFailure({ + class: "provider_error", + message: + "Antigravity session checkpoint was corrupted and has been quarantined. The session will restart.", + code: "SESSION_CORRUPTED", + retryable: true, + }); + } if (apiError === null) { return makeProviderFailure({ class: "provider_error", @@ -141,6 +165,33 @@ function turnFailure( }); } +async function quarantineAntigravitySessionDatabase( + databasePath: string, + timestamp: number, +): Promise { + const quarantinePath = `${databasePath}.corrupt-${timestamp}`; + const moved: Array = []; + try { + for (const suffix of ["-wal", "-shm", ""]) { + const source = `${databasePath}${suffix}`; + const destination = `${quarantinePath}${suffix}`; + try { + await NodeFSP.rename(source, destination); + moved.push([source, destination]); + } catch (error) { + if (suffix !== "" && (error as NodeJS.ErrnoException).code === "ENOENT") continue; + throw error; + } + } + } catch (error) { + for (const [source, destination] of moved.reverse()) { + await NodeFSP.rename(destination, source); + } + throw error; + } + return quarantinePath; +} + const conversationSegments = ["antigravity-acp", "conversations"]; /** @@ -211,6 +262,34 @@ export const watchAntigravityPromptOutcome = Effect.fn("AntigravityTurnOutcome.w Effect.orElseSucceed(() => undefined), ) : undefined; - return turnFailure(result.stopReason, step, yield* DateTime.now); + const now = yield* DateTime.now; + const failure = turnFailure(result.stopReason, step, now); + if (failure?.code === "SESSION_CORRUPTED" && after !== undefined) { + const timestamp = DateTime.toEpochMillis(now); + const quarantined = yield* Effect.tryPromise({ + try: () => quarantineAntigravitySessionDatabase(after.path, timestamp), + catch: (cause) => new AntigravitySessionQuarantineError({ cause }), + }).pipe( + Effect.tap(() => + Effect.logWarning("Quarantined corrupted Antigravity session database", { + path: after.path, + }), + ), + Effect.as(true), + Effect.tapError((error) => + Effect.logWarning("Could not quarantine Antigravity session database", { error }), + ), + Effect.orElseSucceed(() => false), + ); + if (!quarantined) { + return makeProviderFailure({ + class: "provider_error", + message: "Antigravity session checkpoint is corrupted and could not be quarantined.", + code: "SESSION_QUARANTINE_FAILED", + retryable: false, + }); + } + } + return failure; }); });