diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index fca472c6c433e..10e2617f1c3fc 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1248,6 +1248,75 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") }); describe("AntigravityAdapterV2 work after the prompt ends", () => { + // A swarm launch completes at once; only the board and the worker's transcript show the work. + it.effect("keeps the run open for swarm workers after the launch tool completes", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profile = yield* fs.makeTempDirectoryScoped({ prefix: "t3-antigravity-swarm-" }); + const brain = path.join(profile, "antigravity-acp", "brain"); + const swarm = path.join(brain, "mock-session-1", ".system_generated", "swarm"); + const logs = path.join(brain, "worker-1", ".system_generated", "logs"); + const transcript = path.join(logs, "transcript.jsonl"); + yield* fs.makeDirectory(swarm, { recursive: true }); + yield* fs.makeDirectory(logs, { recursive: true }); + yield* fs.writeFileString( + path.join(swarm, "members.json"), + JSON.stringify({ + members: { + coordinator: { conversation_id: "mock-session-1", wake_mode: "working" }, + worker: { conversation_id: "worker-1", wake_mode: "working" }, + }, + }), + ); + yield* fs.writeFileString( + transcript, + JSON.stringify({ step_index: 0, type: "SYSTEM_MESSAGE", status: "DONE" }) + "\n", + ); + const { offers, send, startTurn, throughPromptSettled, throughTerminal, usage } = + yield* openSessionWithRunningCommand({}, profile, undefined, { + initialToolCalls: [ + { + sessionUpdate: "tool_call", + toolCallId: "call_swarm", + kind: "other", + title: "Run swarm", + status: "completed", + rawInput: { action: "add", name: "worker", brief: "Check the chart" }, + }, + ], + }); + + yield* startTurn(1, false); + yield* throughPromptSettled; + yield* TestClock.adjust("10 minutes"); + yield* fs.writeFileString( + transcript, + [ + { + step_index: 1, + type: "PLANNER_RESPONSE", + status: "DONE", + tool_calls: [{ name: "post_message" }, { name: "swarm_wait" }], + }, + { step_index: 2, type: "GENERIC", status: "DONE" }, + { step_index: 3, type: "GENERIC", status: "DONE" }, + ] + .map((step) => JSON.stringify(step)) + .join("\n") + "\n", + ); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "The swarm checked the chart." }, + }); + yield* send(usage); + yield* TestClock.adjust("3 seconds"); + const events = yield* throughTerminal; + assert.include(JSON.stringify(events), "The swarm checked the chart."); + assert.lengthOf(offers, 0, "the worker report stays in the original run"); + }).pipe(Effect.provide(layerSession)), + ); + // 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", () => diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 3f629c813b615..bf631e8d8a1f4 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -32,6 +32,7 @@ import { import { ANTIGRAVITY_SUBAGENT_BATCH_TITLE, antigravitySubagentLaunches, + antigravitySwarmAtWork, describeAntigravitySubagentLaunches, readAntigravityChildrenAtWork, readAntigravityPendingReply, @@ -299,6 +300,8 @@ export function makeAntigravityAcpAdapterFlavor( : { watchPromptOutcome: (sessionId: string) => watchAntigravityPromptOutcome(profileDirectory, sessionId), + detachedWorkOutlivingPrompt: (sessionId: string) => + antigravitySwarmAtWork(profileDirectory, sessionId), subagentsOutlivingPrompt: ({ sessionId, nativeTaskIds }) => readAntigravityChildrenAtWork({ profileDirectory, diff --git a/apps/server/src/provider/acp/AntigravityChildWork.test.ts b/apps/server/src/provider/acp/AntigravityChildWork.test.ts index e0336da84ac64..b576f9c2acedc 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.test.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.test.ts @@ -10,6 +10,7 @@ import * as Path from "effect/Path"; import { ANTIGRAVITY_SUBAGENT_BATCH_TITLE, antigravitySubagentLaunches, + antigravitySwarmAtWork, describeAntigravitySubagentLaunches, readAntigravityChildrenAtWork, readAntigravityChildWork, @@ -541,6 +542,76 @@ it.layer(NodeServices.layer)("readAntigravityChildWork", (it) => { }), ); + it.effect("counts a parked swarm worker at work only while its calls or tasks run", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profile = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-swarm-" }); + const brain = path.join(profile, "antigravity-acp", "brain"); + const swarm = path.join(brain, ROOT, ".system_generated", "swarm"); + const logs = path.join(brain, CHILD, ".system_generated", "logs"); + yield* fs.makeDirectory(swarm, { recursive: true }); + yield* fs.makeDirectory(logs, { recursive: true }); + yield* fs.writeFileString( + path.join(swarm, "members.json"), + JSON.stringify({ + members: { + coordinator: { conversation_id: ROOT, wake_mode: "mentions" }, + writer: { conversation_id: CHILD, wake_mode: "mentions" }, + }, + }), + ); + const writeSteps = (steps: ReadonlyArray) => + fs.writeFileString( + path.join(logs, "transcript.jsonl"), + [{ step_index: 0, type: "SYSTEM_MESSAGE", status: "DONE" }, ...steps] + .map((step, index) => JSON.stringify({ ...step, step_index: index })) + .join("\n") + "\n", + ); + // agy 1.5.13 parks a worker with swarm_wait after the call it ran beside it. + const parked = (sibling: string, siblingStatus: string) => [ + { + type: "PLANNER_RESPONSE", + status: "DONE", + tool_calls: [{ name: sibling }, { name: "swarm_wait" }], + }, + { type: "GENERIC", status: siblingStatus }, + { type: "GENERIC", status: "DONE" }, + ]; + // A long command moves to a background task and the worker's reply ends without a call. + const task = `${CHILD}/task-2`; + const backgrounded = [ + { type: "PLANNER_RESPONSE", status: "DONE", tool_calls: [{ name: "run_command" }] }, + { + type: "GENERIC", + status: "RUNNING", + content: `Tool is running as a background task with task id: ${task}\nTask Description: sleep 120`, + }, + { type: "PLANNER_RESPONSE", status: "DONE", content: "Waiting for sleep 120." }, + ]; + const finished = { + type: "SYSTEM_MESSAGE", + status: "DONE", + content: `[Message] sender=${task} content=Task id "${task}" finished with result:\nCommand exited with code 0.`, + }; + + for (const [label, steps, atWork] of [ + ["post_message DONE", parked("post_message", "DONE"), false], + ["run_command ERROR", parked("run_command", "ERROR"), false], + ["run_command RUNNING", parked("run_command", "RUNNING"), true], + ["background task running", backgrounded, true], + [ + "background task finished", + [...backgrounded, finished, ...parked("post_message", "DONE")], + false, + ], + ] as const) { + yield* writeSteps(steps); + expect(yield* antigravitySwarmAtWork(profile, ROOT), label).toBe(atWork); + } + }), + ); + it.effect("shares one transcript budget across the batch", () => Effect.gen(function* () { const filler = JSON.stringify({ diff --git a/apps/server/src/provider/acp/AntigravityChildWork.ts b/apps/server/src/provider/acp/AntigravityChildWork.ts index aa0932cf0f41a..c8d4bd2a7cc73 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.ts @@ -367,32 +367,24 @@ function transcriptSteps( ); } -/** Reads the tail of the transcript at the named child's own unlinked profile path. */ -async function readChildTranscript( +async function readTranscriptTail( profileRoot: string, - child: InvokeRecord["children"][number], - prompt: string, + conversationId: string, + logUri: string | undefined, byteCap: number, ) { const expected = ( await antigravityManagedPath( profileRoot, - [ - "antigravity-acp", - "brain", - child.conversationId, - ".system_generated", - "logs", - "transcript.jsonl", - ], + ["antigravity-acp", "brain", conversationId, ".system_generated", "logs", "transcript.jsonl"], "file", ) )?.path; if (expected === undefined) return undefined; - if (child.logUri !== undefined) { + if (logUri !== undefined) { let named: string; try { - named = NodeURL.fileURLToPath(child.logUri); + named = NodeURL.fileURLToPath(logUri); } catch { return undefined; } @@ -414,16 +406,75 @@ async function readChildTranscript( let lineStart = 0; if (tailStart > 0) { const newline = bytes.indexOf(0x0a); - if (newline === -1) return { steps: [], truncated: true }; + if (newline === -1) return { contents: "", truncated: true }; lineStart = newline + 1; } const contents = bytes.toString("utf8", lineStart); - return { steps: transcriptSteps(contents, prompt), truncated: tailStart > 0 }; + return { contents, truncated: tailStart > 0 }; } finally { await handle.close(); } } +const decodeSwarmRoster = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + members: Schema.Record( + Schema.String, + Schema.Struct({ + conversation_id: Schema.String, + killed: Schema.optional(Schema.Boolean), + wake_mode: Schema.optional(Schema.String), + }), + ), + }), + ), +); + +const BACKGROUND_TASK = /running as a background task with task id: (\S+)/; + +/** agy parks a worker whose command went to a background task until the task's finish message. */ +function backgroundTaskRunning(lines: ReadonlyArray): boolean { + const running = new Set(); + for (const line of lines) { + const step = Option.getOrUndefined(decodeTranscriptLine(line)); + const content = step?.content ?? ""; + const started = step?.type === "GENERIC" ? BACKGROUND_TASK.exec(content)?.[1] : undefined; + if (started !== undefined) running.add(started); + if (step?.type !== "SYSTEM_MESSAGE") continue; + for (const id of running) if (content.includes(`Task id "${id}"`)) running.delete(id); + } + return running.size > 0; +} + +function swarmWorkerAtWork(transcript: string): boolean { + const lines = transcript.split("\n"); + const results: Array = []; + if (Option.getOrUndefined(decodeTranscriptLine(lines.at(-1)))?.type === "ERROR_MESSAGE") { + return false; + } + if (backgroundTaskRunning(lines)) return true; + for (let index = lines.length - 1; index >= 0; index -= 1) { + const step = Option.getOrUndefined(decodeTranscriptLine(lines[index])); + if (step?.type === "GENERIC") { + results.push(step.status); + continue; + } + if (step?.type !== "PLANNER_RESPONSE" || step.status !== "DONE") return true; + const calls = step.tool_calls ?? []; + if (calls.length === 0) return results.length > 0; + const wait = calls.findIndex((call) => call.name === "swarm_wait"); + // A sibling call that failed has ended; one still running keeps the worker at work. + return ( + wait < 0 || + results.length < calls.length || + results[results.length - 1 - wait] !== "DONE" || + results.some((status) => status !== "DONE" && status !== "ERROR") + ); + } + return true; +} + class AntigravityChildWorkReadError extends Schema.TaggedError()( "AntigravityChildWorkReadError", { cause: Schema.Defect() }, @@ -433,6 +484,42 @@ class AntigravityChildWorkReadError extends Schema.TaggedError { + const root = await antigravityProfileRoot(profileDirectory); + if (root === undefined) return false; + const file = await antigravityManagedPath( + root, + ["antigravity-acp", "brain", sessionId, ".system_generated", "swarm", "members.json"], + "file", + ); + if (file === undefined || file.info.size > MAX_STEP_BYTES) return false; + const roster = Option.getOrUndefined( + decodeSwarmRoster(await NodeFSP.readFile(file.path, "utf8")), + ); + if (roster === undefined) return false; + const workers = Object.values(roster.members); + if (workers.length > MAX_DETACHED_CHILDREN) return false; + for (const worker of workers) { + const id = worker.conversation_id; + if (worker.killed || id === sessionId || !NATIVE_ID.test(id)) continue; + const tail = await readTranscriptTail(root, id, undefined, MAX_STEP_BYTES); + const contents = tail?.contents.trimEnd(); + if (contents ? swarmWorkerAtWork(contents) : worker.wake_mode === "working") return true; + } + return false; + }; + return yield* Effect.tryPromise({ + try: read, + catch: (cause) => new AntigravityChildWorkReadError({ cause }), + }).pipe(Effect.orElseSucceed(() => false)); +}); + /** Children a subagent tool call launched, proven by the parent's own session record. */ export const readAntigravityChildWork = Effect.fn("readAntigravityChildWork")(function* (input: { readonly profileDirectory: string; @@ -477,17 +564,20 @@ export const readAntigravityChildWork = Effect.fn("readAntigravityChildWork")(fu ); return Promise.all( children.map(async (child, index) => { - const transcript = await readChildTranscript( + const transcript = await readTranscriptTail( profileRoot, - child, - launches[index]?.prompt ?? "", + child.conversationId, + child.logUri, byteCap, ).catch(() => undefined); return { conversationId: child.conversationId, role: launches[index]?.role ?? "", prompt: launches[index]?.prompt ?? "", - steps: transcript?.steps ?? null, + steps: + transcript === undefined + ? null + : transcriptSteps(transcript.contents, launches[index]?.prompt ?? ""), truncated: transcript?.truncated ?? false, }; }), diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 8c5de2578b9c7..d8912c91542f3 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -532,6 +532,8 @@ export interface AcpAdapterV2Flavor { cwd: string, ) => Effect.Effect; readonly subagentsIdleOnTurnCompletion?: boolean; + /** Checks native work that has no running ACP tool or subagent item. */ + readonly detachedWorkOutlivingPrompt?: (sessionId: string) => Effect.Effect; /** * Subagents the agent goes on running after its prompt, with no update when one ends. Asked * when the prompt ends and when a reply the agent started by itself ends; the native task ids @@ -1726,6 +1728,7 @@ interface ActiveAcpTurn { readonly promptStarted: Deferred.Deferred; promptUsage: EffectAcpSchema.Usage | undefined; backgroundFinalizeGeneration: number; + detachedWorkPending: boolean; /** `replyEndsWithUsageUpdate`: output arrived and its closing `usage_update` has not. */ replyOpen: boolean; /** The agent's own id for this turn's prompt, from `forkFromTurn.nativeTurnId`. */ @@ -2756,11 +2759,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // has no prompt, so nothing else ends it. const held = yield* Ref.get(activeTurn); if ( - flavor.toolOutlivesPrompt === undefined || + (flavor.toolOutlivesPrompt === undefined && + flavor.detachedWorkOutlivingPrompt === undefined) || held === null || !held.promptSettled || held.finalized || - !hasDeferredBackgroundWork(held) + !(held.detachedWorkPending || hasDeferredBackgroundWork(held)) ) return; for (const tool of held.tools.values()) { @@ -8729,19 +8733,34 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const generation = context.backgroundFinalizeGeneration; const replyOpen = context.replyOpen; const debounce = replyOpen ? ACP_OPEN_REPLY_QUIET_LIMIT : ACP_DEFERRED_FINALIZE_DEBOUNCE; + const canFinalize = () => + context.promptSettled && + !context.finalized && + !context.interrupted && + context.backgroundFinalizeGeneration === generation && + !hasDeferredBackgroundWork(context); + const readDetachedWork = Effect.fn("AcpAdapterV2.readDetachedWork")(function* () { + if (flavor.detachedWorkOutlivingPrompt === undefined) return true; + const pending = yield* flavor.detachedWorkOutlivingPrompt(context.nativeThreadId); + if (!canFinalize()) return false; + context.detachedWorkPending = pending; + return true; + }); + if (!(yield* readDetachedWork())) return; yield* Effect.gen(function* () { - yield* Effect.sleep(debounce); - const stillCurrent = () => - !context.finalized && - !context.interrupted && - context.backgroundFinalizeGeneration === generation && - !hasDeferredBackgroundWork(context); - if (!stillCurrent()) return; + while (true) { + yield* Effect.sleep(debounce); + if (!canFinalize()) return; + // Finalize only on two idle reads in a row, so the last worker's wake can arrive. + const wasPending = context.detachedWorkPending; + if (!(yield* readDetachedWork())) return; + if (!context.detachedWorkPending && !wasPending) break; + } const pendingReply = !replyOpen && flavor.hasPendingReply !== undefined ? yield* flavor.hasPendingReply(context.nativeThreadId) : false; - if (!stillCurrent()) return; + if (!canFinalize()) return; if (pendingReply) { context.replyOpen = true; yield* scheduleDeferredFinalize(context); @@ -9167,10 +9186,22 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } yield* idleReportedSubagents(context); if (context.finalized) return; + let detachedWorkSeen = false; + if ( + defersFinalizeForBackgroundWork && + status === "completed" && + flavor.detachedWorkOutlivingPrompt !== undefined + ) { + detachedWorkSeen = yield* flavor.detachedWorkOutlivingPrompt( + context.nativeThreadId, + ); + context.detachedWorkPending = detachedWorkSeen; + if (detachedWorkSeen) yield* scheduleDeferredFinalize(context); + } const deferredBackgroundWork = defersFinalizeForBackgroundWork && !context.interrupted && - hasDeferredBackgroundWork(context); + (detachedWorkSeen || hasDeferredBackgroundWork(context)); const pendingReply = !deferredBackgroundWork && defersFinalizeForBackgroundWork && @@ -9439,6 +9470,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( promptStarted, promptUsage: undefined, backgroundFinalizeGeneration: 0, + detachedWorkPending: false, replyOpen: false, nativePromptId: undefined, lastProgressAt: 0,