diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 5cbb4975e5e57..7c1805180f870 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1,3 +1,6 @@ +// @effect-diagnostics nodeBuiltinImport:off -- fixtures write a native session database. +import * as NodeSqlite from "node:sqlite"; + import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; @@ -2129,6 +2132,116 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { assert.equal(opened.cancels(), cancels); }).pipe(Effect.provide(layerSession)), ); + + // When manage_task(kill) cancels a background run_command, agy transitions its RUN_COMMAND step + // to CANCELED (6) in conversations/.db without emitting a terminal tool_call_update. + it.effect( + "finalizes the turn when a background command was canceled in the session database without a tool_call_update", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profile = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-agy-cmd-cancel-" }); + const conversations = path.join(profile, "antigravity-acp", "conversations"); + yield* fileSystem.makeDirectory(conversations, { recursive: true }); + const db = new NodeSqlite.DatabaseSync(path.join(conversations, "mock-session-1.db")); + try { + db.exec( + "CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER NOT NULL, status INTEGER NOT NULL, metadata BLOB, step_payload BLOB)", + ); + db.prepare("INSERT INTO steps VALUES (14, 21, 6, NULL, NULL)").run(); + } finally { + db.close(); + } + const { command, startTurn, throughTerminal } = yield* openSessionWithRunningCommand( + { WaitMsBeforeAsync: 10000 }, + undefined, + undefined, + { profileDirectory: profile }, + ); + yield* startTurn(1, false); + const run = yield* throughTerminal; + const terminal = run.at(-1); + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed"); + const reconciled = run.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === command.toolCallId, + ); + assert.equal( + reconciled?.type === "turn_item.updated" && reconciled.turnItem.status, + "failed", + ); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect( + "keeps the run open when the session database confirms the background command is still running", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profile = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-agy-cmd-live-" }); + const conversations = path.join(profile, "antigravity-acp", "conversations"); + yield* fileSystem.makeDirectory(conversations, { recursive: true }); + const encoder = new TextEncoder(); + const varint = (value: number): number[] => { + const bytes: number[] = []; + while (value >= 0x80) { + bytes.push((value & 0x7f) | 0x80); + value = Math.floor(value / 0x80); + } + return [...bytes, value]; + }; + const field = (number: number, value: string | Uint8Array) => { + const bytes = typeof value === "string" ? encoder.encode(value) : value; + return [...varint(number * 8 + 2), ...varint(bytes.length), ...bytes]; + }; + const proto = (...parts: number[][]) => Uint8Array.from(parts.flat()); + const metadata = proto( + field( + 4, + proto( + field(1, "call_native_999"), + field(2, "run_command"), + field(3, JSON.stringify({ CommandLine: "node fetch_throughput.mjs" })), + ), + ), + ); + const db = new NodeSqlite.DatabaseSync(path.join(conversations, "mock-session-1.db")); + try { + db.exec( + "CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER NOT NULL, status INTEGER NOT NULL, metadata BLOB, step_payload BLOB)", + ); + db.prepare("INSERT INTO steps VALUES (14, 21, 2, ?, NULL)").run(metadata); + } finally { + db.close(); + } + const { command, usage, send, startTurn, until, throughPromptSettled } = + yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }, undefined, undefined, { + profileDirectory: profile, + }); + yield* startTurn(1, false); + yield* throughPromptSettled; + yield* TestClock.adjust("10 minutes"); + yield* send({ + sessionUpdate: "tool_call_update", + ...command, + status: "completed", + rawOutput: { output: "Command exited with code 0.", exit_code: 0 }, + }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Command finished." }, + }); + yield* send(usage); + yield* TestClock.adjust("3 seconds"); + const run = yield* until((event) => event.type === "turn.terminal"); + const terminal = run.at(-1); + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed"); + assert.include(JSON.stringify(run), "Command finished."); + }).pipe(Effect.provide(layerSession)), + ); }); describe("AntigravityAdapterV2 subagent reads", () => { diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index c20afa04e31b8..08a30414cd2f5 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -36,6 +36,7 @@ import { readAntigravityChildrenAtWork, readAntigravityPendingReply, } from "../../provider/acp/AntigravityChildWork.ts"; +import { readAntigravityRunningCommands } from "../../provider/acp/AntigravityBackgroundCommands.ts"; import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityClientFiles.ts"; import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts"; import { @@ -312,6 +313,12 @@ export function makeAntigravityAcpAdapterFlavor( rootSessionId: sessionId, toolCallIds: nativeTaskIds, }), + toolsOutlivingPrompt: ({ sessionId, tools }) => + readAntigravityRunningCommands({ + profileDirectory, + sessionId, + tools, + }), hasPendingReply: (sessionId: string) => readAntigravityPendingReply({ profileDirectory, diff --git a/apps/server/src/provider/acp/AntigravityBackgroundCommands.test.ts b/apps/server/src/provider/acp/AntigravityBackgroundCommands.test.ts new file mode 100644 index 0000000000000..f9fc245018a8e --- /dev/null +++ b/apps/server/src/provider/acp/AntigravityBackgroundCommands.test.ts @@ -0,0 +1,569 @@ +// @effect-diagnostics nodeBuiltinImport:off -- fixtures write a native session database. +import * as NodeSqlite from "node:sqlite"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; + +import { readAntigravityRunningCommands } from "./AntigravityBackgroundCommands.ts"; +import { normalizeAntigravityToolCall } from "./AntigravityProtocol.ts"; + +const SESSION_ID = "bd48a7d6-ee8d-4386-91ae-4c4b53248b72"; +const RUN_COMMAND_STEP_TYPE = 21; +const STATUS_RUNNING = 2; +const STATUS_DONE = 3; +const STATUS_CANCELED = 6; + +const varint = (value: number): number[] => { + const bytes: number[] = []; + while (value >= 0x80) { + bytes.push((value & 0x7f) | 0x80); + value = Math.floor(value / 0x80); + } + return [...bytes, value]; +}; +const field = (number: number, value: string | Uint8Array) => { + const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value; + return [...varint(number * 8 + 2), ...varint(bytes.length), ...bytes]; +}; +const proto = (...parts: number[][]) => Uint8Array.from(parts.flat()); + +const commandStepMetadata = (input: { + readonly callId: string; + readonly args: Record; +}) => + proto( + field( + 4, + proto(field(1, input.callId), field(2, "run_command"), field(3, JSON.stringify(input.args))), + ), + ); + +const commandStepPayload = (input: { + readonly metadata: Uint8Array; + readonly commandLine: string; + readonly cwd?: string; +}) => + proto( + field(5, input.metadata), + field( + 28, + proto( + ...(input.cwd === undefined ? [] : [field(2, input.cwd)]), + field(23, input.commandLine), + ), + ), + ); + +const makeToolCall = (input: { + readonly toolCallId: string; + readonly commandLine: string; + readonly cwd?: string; +}): AcpToolCallState => + normalizeAntigravityToolCall({ + toolCallId: input.toolCallId, + kind: "execute", + title: "Ran command", + status: "inProgress", + data: { + rawInput: { + CommandLine: input.commandLine, + ...(input.cwd === undefined ? {} : { Cwd: input.cwd }), + WaitMsBeforeAsync: 10000, + }, + }, + }); + +const writeSessionDb = Effect.fn("writeSessionDb")(function* (input: { + readonly profileDirectory: string; + readonly sessionId?: string; + readonly rows: ReadonlyArray<{ + readonly idx: number; + readonly stepType: number; + readonly status: number; + readonly metadata: Uint8Array | null; + readonly payload: Uint8Array | null; + }>; +}) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const conversations = path.join(input.profileDirectory, "antigravity-acp", "conversations"); + yield* fs.makeDirectory(conversations, { recursive: true }); + const dbPath = path.join(conversations, `${input.sessionId ?? SESSION_ID}.db`); + const database = new NodeSqlite.DatabaseSync(dbPath); + try { + database.exec( + "CREATE TABLE IF NOT EXISTS steps (idx INTEGER PRIMARY KEY, step_type INTEGER NOT NULL, status INTEGER NOT NULL, metadata BLOB, step_payload BLOB)", + ); + const insert = database.prepare("INSERT INTO steps VALUES (?, ?, ?, ?, ?)"); + for (const row of input.rows) { + insert.run(row.idx, row.stepType, row.status, row.metadata, row.payload); + } + } finally { + database.close(); + } + return dbPath; +}); + +describe("readAntigravityRunningCommands", () => { + it.effect("returns empty when all RUN_COMMAND steps were canceled or finished", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const profileDirectory = yield* fs.makeTempDirectoryScoped(); + const meta = commandStepMetadata({ + callId: "call_4689361663381181880", + args: { CommandLine: "pytest -q tests/", Cwd: "/repo" }, + }); + yield* writeSessionDb({ + profileDirectory, + rows: [ + { + idx: 14, + stepType: RUN_COMMAND_STEP_TYPE, + status: STATUS_CANCELED, + metadata: meta, + payload: commandStepPayload({ + metadata: meta, + commandLine: "pytest -q tests/", + cwd: "/repo", + }), + }, + { + idx: 18, + stepType: RUN_COMMAND_STEP_TYPE, + status: STATUS_DONE, + metadata: meta, + payload: commandStepPayload({ + metadata: meta, + commandLine: "echo done", + cwd: "/repo", + }), + }, + ], + }); + const result = yield* readAntigravityRunningCommands({ + profileDirectory, + sessionId: SESSION_ID, + tools: [ + makeToolCall({ + toolCallId: `${SESSION_ID}:13`, + commandLine: "pytest -q tests/", + cwd: "/repo", + }), + ], + }); + assert.deepEqual(result, []); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("keeps only tools that still have an active RUN_COMMAND step in the database", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const profileDirectory = yield* fs.makeTempDirectoryScoped(); + const canceledMeta = commandStepMetadata({ + callId: "call_canceled", + args: { CommandLine: "pytest -q tests/", Cwd: "/repo" }, + }); + const runningMeta = commandStepMetadata({ + callId: "call_running", + args: { CommandLine: "node fetch_throughput.mjs", Cwd: "/repo" }, + }); + yield* writeSessionDb({ + profileDirectory, + rows: [ + { + idx: 14, + stepType: RUN_COMMAND_STEP_TYPE, + status: STATUS_CANCELED, + metadata: canceledMeta, + payload: commandStepPayload({ + metadata: canceledMeta, + commandLine: "pytest -q tests/", + cwd: "/repo", + }), + }, + { + idx: 22, + stepType: RUN_COMMAND_STEP_TYPE, + status: STATUS_RUNNING, + metadata: runningMeta, + payload: commandStepPayload({ + metadata: runningMeta, + commandLine: "node fetch_throughput.mjs", + cwd: "/repo", + }), + }, + ], + }); + const result = yield* readAntigravityRunningCommands({ + profileDirectory, + sessionId: SESSION_ID, + tools: [ + makeToolCall({ + toolCallId: `${SESSION_ID}:13`, + commandLine: "pytest -q tests/", + cwd: "/repo", + }), + makeToolCall({ + toolCallId: `${SESSION_ID}:19`, + commandLine: "node fetch_throughput.mjs", + cwd: "/repo", + }), + ], + }); + assert.deepEqual(result, [`${SESSION_ID}:19`]); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect( + "preserves long truncated commands and distinguishes duplicates by cwd or exact callId", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const profileDirectory = yield* fs.makeTempDirectoryScoped(); + const longCommand = `python3 -c "${"x".repeat(9_000)}"`; + const meta = commandStepMetadata({ + callId: "call_native_20", + args: { CommandLine: longCommand, Cwd: "/repo-b" }, + }); + yield* writeSessionDb({ + profileDirectory, + rows: [ + { + idx: 10, + stepType: RUN_COMMAND_STEP_TYPE, + status: STATUS_CANCELED, + metadata: commandStepMetadata({ + callId: "call_native_10", + args: { CommandLine: longCommand, Cwd: "/repo-a" }, + }), + payload: null, + }, + { + idx: 20, + stepType: RUN_COMMAND_STEP_TYPE, + status: STATUS_RUNNING, + metadata: meta, + payload: commandStepPayload({ + metadata: meta, + commandLine: longCommand, + cwd: "/repo-b", + }), + }, + ], + }); + const result = yield* readAntigravityRunningCommands({ + profileDirectory, + sessionId: SESSION_ID, + tools: [ + makeToolCall({ + toolCallId: `${SESSION_ID}:10`, + commandLine: longCommand, + cwd: "/repo-a", + }), + makeToolCall({ + toolCallId: `${SESSION_ID}:20`, + commandLine: longCommand, + cwd: "/repo-b", + }), + ], + }); + assert.deepEqual(result, [`${SESSION_ID}:20`]); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect( + "returns undefined instead of guessing when identical commands cannot be distinguished", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const profileDirectory = yield* fs.makeTempDirectoryScoped(); + const runningMeta = commandStepMetadata({ + callId: "call_native_older", + args: { CommandLine: "pytest -q tests/", Cwd: "/repo" }, + }); + yield* writeSessionDb({ + profileDirectory, + rows: [ + { + idx: 10, + stepType: RUN_COMMAND_STEP_TYPE, + status: STATUS_RUNNING, + metadata: runningMeta, + payload: commandStepPayload({ + metadata: runningMeta, + commandLine: "pytest -q tests/", + cwd: "/repo", + }), + }, + { + idx: 20, + stepType: RUN_COMMAND_STEP_TYPE, + status: STATUS_CANCELED, + metadata: commandStepMetadata({ + callId: "call_native_newer", + args: { CommandLine: "pytest -q tests/", Cwd: "/repo" }, + }), + payload: null, + }, + ], + }); + const result = yield* readAntigravityRunningCommands({ + profileDirectory, + sessionId: SESSION_ID, + tools: [ + makeToolCall({ + toolCallId: `${SESSION_ID}:10`, + commandLine: "pytest -q tests/", + cwd: "/repo", + }), + makeToolCall({ + toolCallId: `${SESSION_ID}:20`, + commandLine: "pytest -q tests/", + cwd: "/repo", + }), + ], + }); + assert.isUndefined(result); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect( + "returns undefined for an active row lacking command text unless callId matches exactly", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const profileDirectory = yield* fs.makeTempDirectoryScoped(); + const idOnlyMeta = proto( + field(4, proto(field(1, "call_native_only"), field(2, "run_command"))), + ); + yield* writeSessionDb({ + profileDirectory, + rows: [ + { + idx: 10, + stepType: RUN_COMMAND_STEP_TYPE, + status: STATUS_RUNNING, + metadata: idOnlyMeta, + payload: null, + }, + ], + }); + // Different ACP id + active row without command text -> inconclusive (do not kill live tool). + assert.isUndefined( + yield* readAntigravityRunningCommands({ + profileDirectory, + sessionId: SESSION_ID, + tools: [ + makeToolCall({ + toolCallId: `${SESSION_ID}:10`, + commandLine: "node fetch_throughput.mjs", + cwd: "/repo", + }), + ], + }), + ); + // Exact callId match still succeeds even without command text on the DB row. + assert.deepEqual( + yield* readAntigravityRunningCommands({ + profileDirectory, + sessionId: SESSION_ID, + tools: [ + makeToolCall({ + toolCallId: "call_native_only", + commandLine: "node fetch_throughput.mjs", + cwd: "/repo", + }), + ], + }), + ["call_native_only"], + ); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("ignores active daemon commands when reconciling non-daemon commands", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const profileDirectory = yield* fs.makeTempDirectoryScoped(); + const daemonMeta = commandStepMetadata({ + callId: "call_daemon", + args: { CommandLine: "vite dev", Cwd: "/repo", IsDaemon: true }, + }); + yield* writeSessionDb({ + profileDirectory, + rows: [ + { + idx: 10, + stepType: RUN_COMMAND_STEP_TYPE, + status: STATUS_CANCELED, + metadata: commandStepMetadata({ + callId: "call_short", + args: { CommandLine: "vite dev", Cwd: "/repo" }, + }), + payload: null, + }, + { + idx: 12, + stepType: RUN_COMMAND_STEP_TYPE, + status: STATUS_RUNNING, + metadata: daemonMeta, + payload: commandStepPayload({ + metadata: daemonMeta, + commandLine: "vite dev", + cwd: "/repo", + }), + }, + ], + }); + const result = yield* readAntigravityRunningCommands({ + profileDirectory, + sessionId: SESSION_ID, + tools: [ + makeToolCall({ toolCallId: `${SESSION_ID}:9`, commandLine: "vite dev", cwd: "/repo" }), + ], + }); + assert.deepEqual(result, []); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("returns undefined when the session database is missing, empty, or symlinked", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profileDirectory = yield* fs.makeTempDirectoryScoped(); + const tool = makeToolCall({ + toolCallId: `${SESSION_ID}:1`, + commandLine: "node fetch_throughput.mjs", + }); + + // Missing database + assert.isUndefined( + yield* readAntigravityRunningCommands({ + profileDirectory, + sessionId: SESSION_ID, + tools: [tool], + }), + ); + + // Database with no RUN_COMMAND rows yet + const emptySessionId = "11111111-1111-1111-1111-111111111111"; + const realDb = yield* writeSessionDb({ + profileDirectory, + sessionId: emptySessionId, + rows: [], + }); + assert.isUndefined( + yield* readAntigravityRunningCommands({ + profileDirectory, + sessionId: emptySessionId, + tools: [tool], + }), + ); + + // Symlinked database must be refused by antigravityManagedPath + const linkSessionId = "22222222-2222-2222-2222-222222222222"; + const linkPath = path.join( + profileDirectory, + "antigravity-acp", + "conversations", + `${linkSessionId}.db`, + ); + yield* fs.symlink(realDb, linkPath); + assert.isUndefined( + yield* readAntigravityRunningCommands({ + profileDirectory, + sessionId: linkSessionId, + tools: [tool], + }), + ); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect( + "preserves non-execute outliving tools such as schedule alongside canceled commands", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const profileDirectory = yield* fs.makeTempDirectoryScoped(); + yield* writeSessionDb({ + profileDirectory, + rows: [ + { + idx: 14, + stepType: RUN_COMMAND_STEP_TYPE, + status: STATUS_CANCELED, + metadata: commandStepMetadata({ + callId: "call_canceled", + args: { CommandLine: "pytest -q tests/", Cwd: "/repo" }, + }), + payload: null, + }, + ], + }); + const scheduleTool: AcpToolCallState = { + toolCallId: `${SESSION_ID}:20`, + kind: "other", + title: "Running schedule", + status: "inProgress", + data: { rawInput: { DurationSeconds: 300, Prompt: "Check status" } }, + }; + const result = yield* readAntigravityRunningCommands({ + profileDirectory, + sessionId: SESSION_ID, + tools: [ + makeToolCall({ + toolCallId: `${SESSION_ID}:13`, + commandLine: "pytest -q tests/", + cwd: "/repo", + }), + scheduleTool, + ], + }); + assert.deepEqual(result, [scheduleTool.toolCallId]); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("returns undefined when an active row has oversized metadata", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const profileDirectory = yield* fs.makeTempDirectoryScoped(); + // Valid, matching metadata padded past MAX_METADATA_BYTES so removing the size guard would match. + const validMatchingMeta = commandStepMetadata({ + callId: `${SESSION_ID}:13`, + args: { CommandLine: "pytest -q tests/", Cwd: "/repo" }, + }); + const oversizedValidMeta = Uint8Array.from([ + ...validMatchingMeta, + ...field(30, "x".repeat(256 * 1024)), + ]); + yield* writeSessionDb({ + profileDirectory, + rows: [ + { + idx: 14, + stepType: RUN_COMMAND_STEP_TYPE, + status: STATUS_RUNNING, + metadata: oversizedValidMeta, + payload: null, + }, + ], + }); + assert.isUndefined( + yield* readAntigravityRunningCommands({ + profileDirectory, + sessionId: SESSION_ID, + tools: [ + makeToolCall({ + toolCallId: `${SESSION_ID}:13`, + commandLine: "pytest -q tests/", + cwd: "/repo", + }), + ], + }), + ); + }).pipe(Effect.provide(NodeServices.layer)), + ); +}); diff --git a/apps/server/src/provider/acp/AntigravityBackgroundCommands.ts b/apps/server/src/provider/acp/AntigravityBackgroundCommands.ts new file mode 100644 index 0000000000000..75ba68701cec0 --- /dev/null +++ b/apps/server/src/provider/acp/AntigravityBackgroundCommands.ts @@ -0,0 +1,290 @@ +// @effect-diagnostics nodeBuiltinImport:off -- node:sqlite reads the native session database read-only. +import * as NodeSqlite from "node:sqlite"; + +import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { protoFields } from "./AntigravityChildWork.ts"; +import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts"; +import { + antigravityCommandOutlivesPrompt, + boundAntigravityCommandLine, + boundAntigravityToolText, +} from "./AntigravityProtocol.ts"; + +// CORTEX_STEP_TYPE_RUN_COMMAND in exa.cortex_pb. +const RUN_COMMAND_STEP_TYPE = 21; +// Active (non-terminal) CortexStepStatus values: PENDING, RUNNING, WAITING, QUEUED. +const ACTIVE_STEP_STATUSES = [1, 2, 9, 11] as const; +// Field numbers in exa.cortex_pb.CortexStep / CortexStepMetadata / ToolCall / RunCommandStep. +const STEP_METADATA = 5; +const METADATA_TOOL_CALL = 4; +const TOOL_CALL_ID = 1; +const TOOL_CALL_ARGS_JSON = 3; +const STEP_RUN_COMMAND = 28; +const RUN_COMMAND_CWD = 2; +const RUN_COMMAND_LINE = 23; +const RUN_COMMAND_PROPOSED_LINE = 25; + +// Bound reads so a huge step payload or corrupted database never stalls settlement. +const MAX_ACTIVE_COMMANDS = 64; +const MAX_METADATA_BYTES = 256 * 1024; +const MAX_PAYLOAD_BYTES = 512 * 1024; +const NATIVE_SESSION_ID = /^[\w-]{1,64}$/; +const CONVERSATION_SEGMENTS = ["antigravity-acp", "conversations"] as const; + +const textDecoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); + +const fieldBytes = (bytes: Uint8Array | undefined, fieldNumber: number): Uint8Array | undefined => { + if (bytes === undefined) return undefined; + for (const [number, value] of protoFields(bytes)) { + if (number === fieldNumber) return value; + } + return undefined; +}; + +const fieldText = (bytes: Uint8Array | undefined, fieldNumber: number): string | undefined => { + const value = fieldBytes(bytes, fieldNumber); + return value === undefined ? undefined : textDecoder.decode(value); +}; + +const CommandArgs = Schema.Struct({ + command: Schema.optional(Schema.String), + CommandLine: Schema.optional(Schema.String), + command_line: Schema.optional(Schema.String), + commandLine: Schema.optional(Schema.String), + cwd: Schema.optional(Schema.String), + Cwd: Schema.optional(Schema.String), + WorkingDirectory: Schema.optional(Schema.String), + working_dir: Schema.optional(Schema.String), + workingDir: Schema.optional(Schema.String), + IsDaemon: Schema.optional(Schema.Boolean), +}); + +const decodeCommandArgsObject = Schema.decodeUnknownOption(CommandArgs); +const decodeCommandArgsJson = Schema.decodeUnknownOption(Schema.fromJsonString(CommandArgs)); + +const normalizeCommand = (value: string | undefined): string | undefined => { + const trimmed = value?.trim(); + return trimmed ? boundAntigravityCommandLine(trimmed) : undefined; +}; + +const normalizeCwd = (value: string | undefined): string | undefined => { + const trimmed = value?.trim(); + return trimmed ? boundAntigravityToolText(trimmed) : undefined; +}; + +interface ActiveNativeCommand { + readonly callId: string | undefined; + readonly command: string | undefined; + readonly cwd: string | undefined; + readonly isDaemon: boolean; +} + +function decodeActiveCommand( + metadata: Uint8Array | null, + payload: Uint8Array | null, +): ActiveNativeCommand | undefined { + try { + const metaBytes = + metadata ?? (payload === null ? undefined : fieldBytes(payload, STEP_METADATA)); + const toolCall = fieldBytes(metaBytes, METADATA_TOOL_CALL); + const callId = fieldText(toolCall, TOOL_CALL_ID); + const argsJson = fieldText(toolCall, TOOL_CALL_ARGS_JSON); + const args = + argsJson === undefined ? undefined : Option.getOrUndefined(decodeCommandArgsJson(argsJson)); + const runCommand = payload === null ? undefined : fieldBytes(payload, STEP_RUN_COMMAND); + const rawCommand = + args?.CommandLine ?? + args?.command_line ?? + args?.commandLine ?? + args?.command ?? + fieldText(runCommand, RUN_COMMAND_LINE) ?? + fieldText(runCommand, RUN_COMMAND_PROPOSED_LINE); + const rawCwd = + args?.Cwd ?? + args?.WorkingDirectory ?? + args?.working_dir ?? + args?.workingDir ?? + args?.cwd ?? + fieldText(runCommand, RUN_COMMAND_CWD); + return { + callId, + command: normalizeCommand(rawCommand), + cwd: normalizeCwd(rawCwd), + isDaemon: args?.IsDaemon === true, + }; + } catch { + return undefined; + } +} + +function toolCommandIdentity(tool: AcpToolCallState): { + readonly command: string | undefined; + readonly cwd: string | undefined; +} { + const rawArgs = Option.getOrUndefined(decodeCommandArgsObject(tool.data.rawInput)); + const rawCommand = + tool.command ?? + (typeof tool.data.command === "string" ? tool.data.command : undefined) ?? + rawArgs?.CommandLine ?? + rawArgs?.command_line ?? + rawArgs?.commandLine ?? + rawArgs?.command; + const rawCwd = + (typeof tool.data.cwd === "string" ? tool.data.cwd : undefined) ?? + rawArgs?.Cwd ?? + rawArgs?.WorkingDirectory ?? + rawArgs?.working_dir ?? + rawArgs?.workingDir ?? + rawArgs?.cwd; + return { + command: normalizeCommand(rawCommand), + cwd: normalizeCwd(rawCwd), + }; +} + +class AntigravityBackgroundCommandsReadError extends Schema.TaggedError()( + "AntigravityBackgroundCommandsReadError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not read running commands from the Antigravity session database."; + } +} + +/** + * Canceled background `run_command` steps (`manage_task(kill)`) get no terminal `tool_call_update`. + * Returns `tools` still active in `conversations/.db`, or `undefined` if unproven. + */ +export const readAntigravityRunningCommands = Effect.fn("readAntigravityRunningCommands")( + function* (input: { + readonly profileDirectory: string; + readonly sessionId: string; + readonly tools: ReadonlyArray; + }) { + const nonExecuteIds: Array = []; + const executeTools: Array = []; + for (const tool of input.tools) { + if (antigravityCommandOutlivesPrompt(tool)) executeTools.push(tool); + else nonExecuteIds.push(tool.toolCallId); + } + if (executeTools.length === 0) return nonExecuteIds as ReadonlyArray; + if (!NATIVE_SESSION_ID.test(input.sessionId)) return undefined; + const read = async (): Promise | undefined> => { + const profileRoot = await antigravityProfileRoot(input.profileDirectory); + if (profileRoot === undefined) return undefined; + const databaseFile = await antigravityManagedPath( + profileRoot, + [...CONVERSATION_SEGMENTS, `${input.sessionId}.db`], + "file", + ); + if (databaseFile === undefined) return undefined; + const database = new NodeSqlite.DatabaseSync(databaseFile.path, { readOnly: true }); + try { + database.exec("PRAGMA busy_timeout = 100"); + const hasSteps = + database + .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'steps'") + .get() !== undefined; + if (!hasSteps) return undefined; + const rows = database + .prepare( + `SELECT + CASE WHEN length(metadata) <= ? THEN metadata ELSE NULL END AS metadata, + length(metadata) AS metadataBytes, + CASE WHEN length(step_payload) <= ? THEN step_payload ELSE NULL END AS payload + FROM steps + WHERE step_type = ? AND status IN (${ACTIVE_STEP_STATUSES.join(", ")}) + ORDER BY idx DESC + LIMIT ?`, + ) + .all( + MAX_METADATA_BYTES, + MAX_PAYLOAD_BYTES, + RUN_COMMAND_STEP_TYPE, + MAX_ACTIVE_COMMANDS + 1, + ); + if (rows.length > MAX_ACTIVE_COMMANDS) return undefined; + if (rows.length === 0) { + const hasAnyCommand = + database + .prepare("SELECT 1 FROM steps WHERE step_type = ? LIMIT 1") + .get(RUN_COMMAND_STEP_TYPE) !== undefined; + return hasAnyCommand ? nonExecuteIds : undefined; + } + const active: Array = []; + for (const row of rows) { + if (typeof row.metadataBytes === "number" && row.metadataBytes > MAX_METADATA_BYTES) { + return undefined; + } + const metadata = row.metadata instanceof Uint8Array ? row.metadata : null; + const payload = row.payload instanceof Uint8Array ? row.payload : null; + const decoded = decodeActiveCommand(metadata, payload); + if (decoded === undefined) return undefined; + if (decoded.isDaemon) continue; + if (decoded.callId === undefined && decoded.command === undefined) return undefined; + active.push(decoded); + } + if (active.length === 0) return nonExecuteIds; + const remainingActive = [...active]; + const stillRunning: Array = [...nonExecuteIds]; + const unmatchedTools: Array<{ + readonly tool: AcpToolCallState; + readonly identity: ReturnType; + }> = []; + // Pass 1: exact callId matches are unambiguous even when command text is absent. + for (const tool of executeTools) { + const exactIndex = remainingActive.findIndex( + (entry) => entry.callId !== undefined && entry.callId === tool.toolCallId, + ); + if (exactIndex !== -1) { + remainingActive.splice(exactIndex, 1); + stillRunning.push(tool.toolCallId); + } else { + unmatchedTools.push({ tool, identity: toolCommandIdentity(tool) }); + } + } + if (unmatchedTools.length === 0 || remainingActive.length === 0) { + return stillRunning; + } + // Any remaining active row or open tool without command text cannot be attributed safely. + if ( + remainingActive.some((entry) => entry.command === undefined) || + unmatchedTools.some((entry) => entry.identity.command === undefined) + ) { + return undefined; + } + const matchesCommand = ( + entry: ActiveNativeCommand, + identity: ReturnType, + ) => + entry.command === identity.command && + (identity.cwd === undefined || entry.cwd === undefined || entry.cwd === identity.cwd); + for (const candidate of unmatchedTools) { + const matchingActive = remainingActive.filter((entry) => + matchesCommand(entry, candidate.identity), + ); + if (matchingActive.length === 0) continue; + const competingTools = unmatchedTools.filter((other) => + matchingActive.some((entry) => matchesCommand(entry, other.identity)), + ); + // Do not guess which duplicate command is live when fewer active rows exist than tools. + if (competingTools.length > matchingActive.length) { + return undefined; + } + stillRunning.push(candidate.tool.toolCallId); + } + return stillRunning; + } finally { + database.close(); + } + }; + return yield* Effect.tryPromise({ + try: read, + catch: (cause) => new AntigravityBackgroundCommandsReadError({ cause }), + }).pipe(Effect.orElseSucceed(() => undefined)); + }, +); diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index 2e59a78e376b4..df9268d41e3a7 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -224,7 +224,7 @@ const COMMAND_TEXT_FIELDS = new Set([ ]); /** Keeps the tail of long tool text, as every bounded tool payload does. */ -export { boundText as boundAntigravityToolText }; +export { boundCommandLine as boundAntigravityCommandLine, boundText as boundAntigravityToolText }; /** True when bounding cut some of this text. */ export const isCutAntigravityToolText = (text: string) => text.includes(TOOL_TEXT_TRUNCATED); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 908c99e4eaeb3..e51cf76fcb35b 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -637,6 +637,14 @@ export interface AcpAdapterV2Flavor { * tool ends. With `deferFinalizeForBackgroundWork`, the turn stays open until then. */ readonly toolOutlivesPrompt?: (toolCall: AcpToolCallState) => boolean; + /** + * Asked when the prompt or a post-settle reply ends to reconcile running `toolOutlivesPrompt` + * tools; ids absent from a defined result are marked failed, `undefined` keeps them open. + */ + readonly toolsOutlivingPrompt?: (input: { + readonly sessionId: string; + readonly tools: ReadonlyArray; + }) => Effect.Effect | undefined>; /** * Finalize a settled turn held only by running commands once the session has been silent for * `timeout`, so a command that never reports back cannot leave the thread in Working forever. @@ -4359,6 +4367,29 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } }); + const reconcileOutlivingTools = Effect.fn("AcpAdapterV2.reconcileOutlivingTools")( + function* (context: ActiveAcpTurn) { + const outlives = flavor.toolOutlivesPrompt; + if (outlives === undefined || flavor.toolsOutlivingPrompt === undefined) return; + const running = [...context.tools.values()].filter( + (tool) => toolStatus(tool.status) === "running" && outlives(tool), + ); + if (running.length === 0) return; + const stillRunning = yield* flavor.toolsOutlivingPrompt({ + sessionId: context.nativeThreadId, + tools: running, + }); + if (context.finalized || stillRunning === undefined) return; + const stillRunningIds = new Set(stillRunning); + for (const tool of running) { + if (stillRunningIds.has(tool.toolCallId)) continue; + const current = context.tools.get(tool.toolCallId); + if (current === undefined || toolStatus(current.status) !== "running") continue; + yield* emitTool(context, { ...current, status: "failed" }); + } + }, + ); + const hasSurvivingBackgroundWork = (context: ActiveAcpTurn): boolean => [...context.toolCallIdsByBackgroundTaskId.values()].some((toolCallId) => { const tool = context.tools.get(toolCallId); @@ -5787,7 +5818,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } else if (context.nativeThreadId === notification.sessionId) { if (update.sessionUpdate === "usage_update") { context.replyOpen = false; - if (context.promptSettled) yield* idleReportedSubagents(context); + if (context.promptSettled) { + yield* idleReportedSubagents(context); + yield* reconcileOutlivingTools(context); + } yield* rearmDeferredFinalize(context); } else if (acpRootSessionUpdateIngestsOutput(notification)) { context.replyOpen = true; @@ -9300,6 +9334,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return; } yield* idleReportedSubagents(context); + yield* reconcileOutlivingTools(context); if (context.finalized) return; const deferredBackgroundWork = defersFinalizeForBackgroundWork && @@ -9704,6 +9739,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context.promptSettledStatus = "completed"; // The replayed reply ended before the prompt counted as settled. yield* idleReportedSubagents(context); + yield* reconcileOutlivingTools(context); if (drainedWakeCount === 0) { if (continuationWasRequested && defersFinalizeForBackgroundWork) { if (hasDeferredBackgroundWork(context)) {