diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 5e3a971dba1c9..8a7e4ff193be0 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -42,6 +42,7 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import { + type AntigravityAdapterV2RuntimeInput, makeAntigravityAcpAdapterFlavor, makeAntigravityAdapterV2, } from "./AntigravityAdapterV2.ts"; @@ -894,152 +895,198 @@ describe("AntigravityAdapterV2 html_render pages", () => { ); }); -describe("AntigravityAdapterV2 work after the prompt ends", () => { - // Frames as agy 1.5.11 sent them for `run_command` with `WaitMsBeforeAsync`: the prompt returns - // end_turn, the command finishes later, and the agent replies with no prompt open. - it.effect("continues in one run when a finished background command wakes the agent", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const path = yield* Path.Path; - const crypto = yield* SecureRandom.SecureRandom; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), +/** + * A session whose prompt reports one running command and returns end_turn, as agy 1.5.11 does + * for `run_command` once `WaitMsBeforeAsync` passes. The test sends every later frame. + */ +const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand")(function* ( + commandInput: Record, +) { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdate: Parameters[0] | undefined; + let requestPermission: Parameters[0] | undefined; + const send = (update: EffectAcpSchema.SessionUpdate) => + sessionUpdate === undefined + ? Effect.die("the adapter must handle session updates") + : sessionUpdate(normalizeAntigravitySessionUpdate({ sessionId: "mock-session-1", update })); + const command = { + toolCallId: "call_fetch", + kind: "execute", + title: "node fetch_throughput.mjs", + rawInput: { CommandLine: "node fetch_throughput.mjs", ...commandInput }, + } as const; + let cancels = 0; + let terminate: AntigravityAdapterV2RuntimeInput["onTermination"]; + const usage = { sessionUpdate: "usage_update", used: 9000, size: 1048576 } as const; + const offers: Array = []; + const instanceId = ProviderInstanceId.make("antigravity-wake-test"); + const threadId = ThreadId.make("thread-antigravity-wake"); + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + continuationRequests: { offer: (request) => Effect.sync(() => void offers.push(request)) }, + makeRuntime: (input) => { + terminate = input.onTermination; + return makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { T3_ACP_ANTIGRAVITY: "1" }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + cancel: Effect.sync(() => { + cancels += 1; + }), + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + handleRequestPermission: (handler) => + Effect.sync(() => { + requestPermission = handler; + }).pipe(Effect.andThen(runtime.handleRequestPermission(handler))), + prompt: () => + Effect.gen(function* () { + yield* send({ sessionUpdate: "tool_call", ...command, status: "in_progress" }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "I'll render once the fetch finishes." }, + }); + yield* send(usage); + return { stopReason: "end_turn" as const }; + }), + })), ); - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdate: Parameters[0] | undefined; - let requestPermission: Parameters[0] | undefined; - const send = (update: EffectAcpSchema.SessionUpdate) => - sessionUpdate === undefined - ? Effect.die("the adapter must handle session updates") - : sessionUpdate( - normalizeAntigravitySessionUpdate({ sessionId: "mock-session-1", update }), - ); - const command = { - toolCallId: "call_fetch", - kind: "execute", - title: "node fetch_throughput.mjs", - rawInput: { CommandLine: "node fetch_throughput.mjs", WaitMsBeforeAsync: 10000 }, - } as const; - const usage = { sessionUpdate: "usage_update", used: 9000, size: 1048576 } as const; - const offers: Array = []; - const instanceId = ProviderInstanceId.make("antigravity-wake-test"); - const threadId = ThreadId.make("thread-antigravity-wake"); - const adapter = yield* makeAntigravityAdapterV2({ - instanceId, - selfInvocation: yield* resolveSelfInvocation(), - continuationRequests: { offer: (request) => Effect.sync(() => void offers.push(request)) }, - makeRuntime: (input) => - makeAntigravityAcpRuntime({ - ...input, - childProcessSpawner, - spawn: { - command: process.execPath, - args: [mockAgentPath], - cwd: input.cwd, - env: { T3_ACP_ANTIGRAVITY: "1" }, - }, - }).pipe( - Effect.provideService(SecureRandom.SecureRandom, crypto), - Effect.map((runtime): RuntimeService => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdate = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - handleRequestPermission: (handler) => - Effect.sync(() => { - requestPermission = handler; - }).pipe(Effect.andThen(runtime.handleRequestPermission(handler))), - prompt: () => - Effect.gen(function* () { - yield* send({ sessionUpdate: "tool_call", ...command, status: "in_progress" }); - yield* send({ - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "I'll render once the fetch finishes." }, - }); - yield* send(usage); - return { stopReason: "end_turn" as const }; - }), - })), - ), - withProcess: (_stop, task) => task, - defaultModel: Effect.undefined, - }); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + }, + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-wake"), + modelSelection, + runtimePolicy, + }); + const events = yield* Queue.unbounded(); + yield* session.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + const until = (done: (event: ProviderAdapter.ProviderAdapterV2Event) => boolean) => + Effect.gen(function* () { + const seen: Array = []; + while (true) { + const event = yield* Queue.take(events); + seen.push(event); + if (done(event)) return seen; + } + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + const startTurn = (ordinal: number, continuation: boolean) => + session.startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-antigravity-wake"), + title: "Antigravity wake", + providerInstanceId: instanceId, + modelSelection, runtimeMode: "full-access", interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "gemini-test-low" } as const; - const session = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-antigravity-wake"), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* session.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const throughTerminal = Effect.gen(function* () { - const seen: Array = []; - while (true) { - const event = yield* Queue.take(events); - seen.push(event); - if (event.type === "turn.terminal") return seen; - } - }); - const providerThread = yield* session.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - const startTurn = (ordinal: number, continuation: boolean) => - session.startTurn({ - appThread: { - createdBy: "user", - creationSource: "web", - id: threadId, - projectId: ProjectId.make("project-antigravity-wake"), - title: "Antigravity wake", - providerInstanceId: instanceId, - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: process.cwd(), - activeProviderThreadId: providerThread.id, - lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, - forkedFrom: null, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - lastVisitedAt: null, - deletedAt: null, - }, - threadId, - runId: RunId.make(`run-antigravity-wake-${ordinal}`), - runOrdinal: ordinal, - providerTurnOrdinal: ordinal, - attemptId: RunAttemptId.make(`attempt-antigravity-wake-${ordinal}`), - rootNodeId: NodeId.make(`node-antigravity-wake-${ordinal}`), - providerThread, - message: { - ...(continuation - ? { createdBy: "agent" as const, creationSource: "provider" as const } - : { createdBy: "user" as const, creationSource: "web" as const }), - messageId: MessageId.make(`message-antigravity-wake-${ordinal}`), - text: "chart the throughput", - attachments: [], - }, - modelSelection, - runtimePolicy, - }); + branch: null, + worktreePath: process.cwd(), + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + threadId, + runId: RunId.make(`run-antigravity-wake-${ordinal}`), + runOrdinal: ordinal, + providerTurnOrdinal: ordinal, + attemptId: RunAttemptId.make(`attempt-antigravity-wake-${ordinal}`), + rootNodeId: NodeId.make(`node-antigravity-wake-${ordinal}`), + providerThread, + message: { + ...(continuation + ? { createdBy: "agent" as const, creationSource: "provider" as const } + : { createdBy: "user" as const, creationSource: "web" as const }), + messageId: MessageId.make(`message-antigravity-wake-${ordinal}`), + text: "chart the throughput", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + return { + session, + providerThread, + command, + usage, + offers, + send, + startTurn, + until, + throughTerminal: until((event) => event.type === "turn.terminal"), + // The reply before end_turn closes when the prompt settles, held open or not. + throughPromptSettled: until( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "assistant_message" && + event.turnItem.status === "completed", + ), + requestPermission: (...args: Parameters>) => + requestPermission === undefined + ? Effect.die("the adapter must handle permission requests") + : requestPermission(...args), + cancels: () => cancels, + runtimeDies: Effect.suspend( + () => + terminate?.( + new EffectAcpErrors.AcpTransportError({ detail: "agent exited", cause: "exit" }), + ) ?? Effect.die("the adapter must watch its runtime"), + ), + }; +}); + +describe("AntigravityAdapterV2 work after the prompt ends", () => { + // agy sets `IsDaemon` on a command it does not wait for. When it exits, the agent replies + // with no prompt open. + it.effect("continues in one run when a finished daemon wakes the agent", () => + Effect.gen(function* () { + const { command, usage, offers, send, startTurn, throughTerminal, requestPermission } = + yield* openSessionWithRunningCommand({ IsDaemon: true, WaitMsBeforeAsync: 500 }); yield* startTurn(1, false); const promptTerminal = (yield* throughTerminal).at(-1); assert.equal(promptTerminal?.type === "turn.terminal" && promptTerminal.status, "completed"); @@ -1050,23 +1097,19 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { status: "completed", rawOutput: { output: "Command exited with code 0.", exit_code: 0 }, }); - assert.lengthOf(offers, 1, "the finished command must wake the thread"); + assert.lengthOf(offers, 1, "the finished daemon must wake the thread"); // The agent can ask before the app has started the continuation run. const followUp = { toolCallId: "call_analyze", kind: "execute", title: "node analyze.mjs" }; - const permission = yield* Effect.suspend(() => - requestPermission === undefined - ? Effect.die("the adapter must handle permission requests") - : requestPermission( - { - sessionId: "mock-session-1", - toolCall: { ...followUp, status: "pending" }, - options: [ - { optionId: "allow", name: "Allow", kind: "allow_once" }, - { optionId: "deny", name: "Deny", kind: "reject_once" }, - ], - }, - { requestId: "permission-1", method: "session/request_permission" }, - ), + const permission = yield* requestPermission( + { + sessionId: "mock-session-1", + toolCall: { ...followUp, status: "pending" }, + options: [ + { optionId: "allow", name: "Allow", kind: "allow_once" }, + { optionId: "deny", name: "Deny", kind: "reject_once" }, + ], + }, + { requestId: "permission-1", method: "session/request_permission" }, ).pipe(Effect.forkScoped({ startImmediately: true })); yield* offers[0]!.dispatchIfCurrent!(Effect.void); yield* startTurn(2, true); @@ -1108,6 +1151,65 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { assert.lengthOf(offers, 1, "one wake is one run"); }).pipe(Effect.provide(layerSession)), ); + + // Frames as agy 1.5.11 sent them for `run_command` with `WaitMsBeforeAsync`: the prompt returns + // end_turn while the command runs, and the agent replies when the command finishes. + it.effect("keeps the run open while a command the agent waits for still runs", () => + Effect.gen(function* () { + const { command, usage, offers, send, startTurn, until, throughPromptSettled } = + yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); + 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* TestClock.adjust("10 seconds"); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Here is the chart." }, + }); + 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), "Here is the chart.", "the reply is part of the run"); + assert.lengthOf(offers, 0, "the open run needs no continuation"); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect.each([ + // session/cancel ends the agent's commands, so only Stop may send it. + { ending: "Stop", cancels: 1, status: "interrupted" }, + { ending: "a new message", cancels: 0, status: "interrupted" }, + { ending: "the agent exiting", cancels: 0, status: "failed" }, + ] as const)( + "ends a run held open by a running command on $ending", + ({ ending, cancels, status }) => + Effect.gen(function* () { + const opened = yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); + yield* opened.startTurn(1, false); + const started = yield* opened.throughPromptSettled; + const turn = started.find((event) => event.type === "provider_turn.updated"); + if (turn?.type !== "provider_turn.updated") return assert.fail("the turn must start"); + if (ending === "the agent exiting") { + yield* opened.runtimeDies; + } else { + yield* opened.session.interruptTurn({ + providerThread: opened.providerThread, + providerTurnId: turn.providerTurn.id, + ...(ending === "Stop" ? { requestRuntimeRestart: true } : {}), + }); + } + const terminal = (yield* opened.throughTerminal).at(-1); + assert.equal(terminal?.type === "turn.terminal" && terminal.status, status); + assert.equal(opened.cancels(), cancels); + }).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 b91f1a452679d..b8fd0bb98ecd4 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -36,6 +36,7 @@ import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityCli import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts"; import { antigravityApprovalOptions, + antigravityCommandOutlivesPrompt, antigravitySubagentOutput, classifyAntigravitySubagentToolCall, extractAntigravityUserInputQuestion, @@ -248,6 +249,10 @@ export function makeAntigravityAcpAdapterFlavor( deferFinalizeForBackgroundWork: true, wakeOnDetachedRequest: true, replyEndsWithUsageUpdate: true, + toolOutlivesPrompt: antigravityCommandOutlivesPrompt, + // session/cancel ends the agent's running commands, so only Stop sends it once the prompt + // has ended. A message sent while a command runs leaves the command alone. + preserveRuntimeOnSettledInterrupt: true, ...(options.onSessionEvent === undefined ? {} : { onSessionEvent: options.onSessionEvent }), applyModelSelection: Effect.fn("AntigravityAdapterV2.applyModelSelection")(function* ({ runtime, diff --git a/apps/server/src/preview/PortScanner.test.ts b/apps/server/src/preview/PortScanner.test.ts index d9b226e21f4fe..13ff5ad75c5c8 100644 --- a/apps/server/src/preview/PortScanner.test.ts +++ b/apps/server/src/preview/PortScanner.test.ts @@ -842,7 +842,9 @@ effectIt.effect.each(["linux", "darwin"] as const)( (platform) => { const agentPort = 43_124; const otherPort = 43_125; - const agentListener = `p4242\ncnode\nn127.0.0.1:${agentPort}\n`; + // The agent CLI has the thread in its environment too; its own port is not a server. + const agentListener = + `p4242\ncnode\nn127.0.0.1:${agentPort}\n` + `p4300\ncagy\nn127.0.0.1:43126\n`; const otherListener = `p5000\ncpostgres\nn127.0.0.1:${otherPort}\n`; let lsofStdout = otherListener; let lsofFails = false; @@ -855,11 +857,18 @@ effectIt.effect.each(["linux", "darwin"] as const)( "/proc/4242/environ": `PATH=/usr/bin\0${PortScanner.AGENT_THREAD_ENV}=thread-agent\0`, "/proc/5000/environ": "PATH=/usr/bin\0", }; + const procAgent: Record = { + "/proc/4242/stat": "4242 (node) S 4300 4300 4300 0", + "/proc/4300/environ": `${PortScanner.AGENT_THREAD_ENV}=thread-agent\0`, + "/proc/4300/stat": `4300 (agy acp) S ${process.pid} 4300 4300 0`, + }; const layer = layerScanner.pipe( Layer.provide( Layer.mergeAll( FileSystem.layerNoop({ readFileString: (path) => { + const agent = procAgent[path]; + if (agent !== undefined) return Effect.succeed(agent); const content = procEnviron[path]; if (content === undefined) return missing.readFileString(path); environmentReads += 1; @@ -881,9 +890,9 @@ effectIt.effect.each(["linux", "darwin"] as const)( ) : Effect.succeed(processOutput(lsofStdout)); } - // A direct child of this process, so stop refuses it without signaling anything. + // In its agent CLI's process group, so stop refuses it without signaling anything. if (input.args[0] === "-A") { - return Effect.succeed(processOutput(`4242 ${process.pid} 4242\n`)); + return Effect.succeed(processOutput(`4242 4300 4300\n4300 ${process.pid} 4300\n`)); } if (environmentFails) { return Effect.fail( @@ -897,8 +906,9 @@ effectIt.effect.each(["linux", "darwin"] as const)( environmentReads += 1; return Effect.succeed( processOutput( - ` 4242 node server.js PATH=/usr/bin ${PortScanner.AGENT_THREAD_ENV}=thread-agent HOME=/Users/dev\n` + - " 5000 postgres -D /data PATH=/usr/bin\n", + ` 4242 4300 node server.js PATH=/usr/bin ${PortScanner.AGENT_THREAD_ENV}=thread-agent HOME=/Users/dev\n` + + ` 4300 ${process.pid} agy acp ${PortScanner.AGENT_THREAD_ENV}=thread-agent\n` + + " 5000 1 postgres -D /data PATH=/usr/bin\n", ), ); }, diff --git a/apps/server/src/preview/PortScanner.ts b/apps/server/src/preview/PortScanner.ts index d950cd636f4f5..abe3603f44fbc 100644 --- a/apps/server/src/preview/PortScanner.ts +++ b/apps/server/src/preview/PortScanner.ts @@ -384,16 +384,42 @@ const parseProcEnvironThread = (raw: string): ThreadId | null => { }; /** - * Reads macOS `ps -E -o pid=,command=`, which appends each process's launch environment to its - * argv with spaces, so an argument that spells the assignment out also matches. + * A listener with an agent thread in its environment. An agent CLI is a direct child of this + * server and has that environment too, but its own ports are not servers it started. */ -const parsePsEnvironmentThreads = (raw: string): ReadonlyMap => { - const threads = new Map(); +interface AgentListener { + readonly threadId: ThreadId; + readonly isAgentCli: boolean; +} + +/** Reads the parent pid from `/proc//stat`, whose command field can hold spaces. */ +const parseProcStatParent = (raw: string): number | null => { + const parent = Number( + raw + .slice(raw.lastIndexOf(")") + 1) + .trim() + .split(" ")[1], + ); + return Number.isInteger(parent) ? parent : null; +}; + +/** + * Reads macOS `ps -E -o pid=,ppid=,command=`, which appends each process's launch environment + * to its argv with spaces, so an argument that spells the assignment out also matches. + */ +const parsePsEnvironmentThreads = ( + raw: string, + serverPid: number, +): ReadonlyMap => { + const threads = new Map(); for (const line of raw.split("\n")) { - const match = /^\s*(\d+)\s(.*)$/.exec(line); + const match = /^\s*(\d+)\s+(\d+)\s(.*)$/.exec(line); if (!match) continue; - const value = AGENT_THREAD_ASSIGNMENT.exec(match[2]!)?.[1]; - threads.set(Number(match[1]), value ? ThreadId.make(value) : null); + const value = AGENT_THREAD_ASSIGNMENT.exec(match[3]!)?.[1]; + threads.set( + Number(match[1]), + value ? { threadId: ThreadId.make(value), isAgentCli: Number(match[2]) === serverPid } : null, + ); } return threads; }; @@ -528,7 +554,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() { // Each current listener pid's agent thread, or null without one. A process keeps its launch // environment, so a pid is read once while it listens. Cleared while no client retains the // scanner, since unscanned pids can be reused. - const agentThreadsRef = yield* Ref.make>(new Map()); + const agentThreadsRef = yield* Ref.make>(new Map()); const agentCommandStopWatchers = new Set(); let runningAgents = 0; // An agent that exited, or a cache cleared with a marked listener, owes one listener read: the @@ -540,40 +566,41 @@ export const make = Effect.gen(function* PortDiscoveryMake() { ) { const cached = yield* Ref.get(agentThreadsRef); const unread = pids.filter((pid) => !cached.has(pid)); - const read: ReadonlyMap = + const readProcListener = Effect.fnUntraced(function* (pid: number) { + const threadId = yield* fileSystem.readFileString(`/proc/${pid}/environ`).pipe( + Effect.map(parseProcEnvironThread), + Effect.orElseSucceed(() => null), + ); + if (threadId === null) return [pid, null] as const; + const parent = yield* fileSystem.readFileString(`/proc/${pid}/stat`).pipe( + Effect.map(parseProcStatParent), + Effect.orElseSucceed(() => null), + ); + return [pid, { threadId, isAgentCli: parent === process.pid }] as const; + }); + const read: ReadonlyMap = unread.length === 0 ? new Map() : hostPlatform === "linux" - ? new Map( - yield* Effect.forEach( - unread, - (pid) => - fileSystem.readFileString(`/proc/${pid}/environ`).pipe( - Effect.map(parseProcEnvironThread), - Effect.orElseSucceed(() => null), - Effect.map((threadId) => [pid, threadId] as const), - ), - { concurrency: 16 }, - ), - ) + ? new Map(yield* Effect.forEach(unread, readProcListener, { concurrency: 16 })) : yield* processRunner .run({ command: "ps", - args: ["-E", "-ww", "-o", "pid=,command=", "-p", unread.join(",")], + args: ["-E", "-ww", "-o", "pid=,ppid=,command=", "-p", unread.join(",")], timeout: Duration.millis(PS_TIMEOUT_MS), maxOutputBytes: PS_MAX_OUTPUT_BYTES, }) .pipe( - Effect.map((result) => parsePsEnvironmentThreads(result.stdout)), + Effect.map((result) => parsePsEnvironmentThreads(result.stdout, process.pid)), Effect.orElseSucceed(() => { agentScanPending = true; return new Map(); }), ); - const next = new Map(); + const next = new Map(); for (const pid of pids) { - const threadId = cached.has(pid) ? cached.get(pid) : read.get(pid); - if (threadId !== undefined) next.set(pid, threadId); + const listener = cached.has(pid) ? cached.get(pid) : read.get(pid); + if (listener !== undefined) next.set(pid, listener); } yield* Ref.set(agentThreadsRef, next); return next; @@ -587,8 +614,10 @@ export const make = Effect.gen(function* PortDiscoveryMake() { agentScanPending = false; const threads = yield* readAgentThreads(pids.filter((pid) => !terminalOwners.has(pid))); const owners = new Map(terminalOwners); - for (const [pid, threadId] of threads) { - if (threadId !== null) owners.set(pid, { terminal: null, agent: { threadId } }); + for (const [pid, listener] of threads) { + if (listener !== null && !listener.isAgentCli) { + owners.set(pid, { terminal: null, agent: { threadId: listener.threadId } }); + } } return owners; }); diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index 5b74756a1de11..ef087c2e7665d 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -45,6 +45,15 @@ const decodeSingleAnswer = Schema.decodeUnknownOption( ); const decodeToolCallContent = Schema.decodeUnknownOption(AcpWireSchema.ToolCallContent); +/** + * The agent goes on running a command after its prompt ends, and replies by itself when the + * command finishes. A daemon may never finish. + */ +export function antigravityCommandOutlivesPrompt(toolCall: AcpToolCallState): boolean { + const input = toolCall.data.rawInput; + return toolCall.kind === "execute" && !(Predicate.isObject(input) && input.IsDaemon === true); +} + /** Native questions share the permission method, but their choices are not approvals. */ export function isAntigravityUserInputRequest( request: EffectAcpSchema.RequestPermissionRequest, diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 7402b5ec9b0eb..33bc49ff8927a 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -584,6 +584,11 @@ export interface AcpAdapterV2Flavor { readonly appendOutput: string; }>; readonly isPersistentBackgroundTool?: (toolCall: AcpToolCallState) => boolean; + /** + * A tool the agent goes on running after its prompt ends, and reports on by itself when the + * tool ends. With `deferFinalizeForBackgroundWork`, the turn stays open until then. + */ + readonly toolOutlivesPrompt?: (toolCall: AcpToolCallState) => boolean; readonly isProviderWakeNotification?: ( notification: EffectAcpSchema.SessionNotification, ) => boolean; @@ -2575,7 +2580,31 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( runtimeGeneration, Effect.gen(function* () { yield* Ref.set(runtimeRestartRequired, true); - if (!followsAgentWorkState) return; + if (!followsAgentWorkState) { + // An open prompt fails with its transport. A turn held open for a running tool + // has no prompt, so nothing else ends it. + const held = yield* Ref.get(activeTurn); + if ( + flavor.toolOutlivesPrompt === undefined || + held === null || + !held.promptSettled || + held.finalized || + !hasDeferredBackgroundWork(held) + ) + return; + for (const tool of held.tools.values()) { + const status = toolStatus(tool.status); + if (status === "pending" || status === "running" || status === "waiting") { + yield* emitTool(held, tool, "failed"); + } + } + yield* finalizeTurn( + held, + "failed", + makeProviderFailure({ class: "transport_error" }), + ); + return; + } agentWork = { sessionUpdate: "state_update", state: "idle", stopReason: "error" }; for (const child of nativeChildren.values()) { if (child.status !== "running") continue; @@ -4053,6 +4082,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const hasDeferredBackgroundWork = (context: ActiveAcpTurn): boolean => { if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true; + if (flavor.toolOutlivesPrompt !== undefined) { + // A tool that never started has nothing to report later. + for (const tool of context.tools.values()) { + if (toolStatus(tool.status) === "running" && flavor.toolOutlivesPrompt(tool)) + return true; + } + } if (context.awaitingBackgroundHydration.size > 0) return true; if (context.pendingInjectedReport.size > 0) return true; for (const [taskId, toolCallId] of context.toolCallIdsByBackgroundTaskId) {