diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 8a7e4ff193be0..0bedbebc90c72 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -98,6 +98,20 @@ describe("AntigravityAdapterV2 flavor", () => { }); assert.equal(launch?.title, "Readme Reader"); assert.equal(launch?.prompt, "Read README.md"); + + // agy 1.5.x auto-approves one subagent per call with a flat input. + const single = flavor.extractSubagentUpdate?.({ + toolCallId: "call_16976942396429577770", + title: "Run invoke_subagent", + kind: "other", + status: "completed", + data: { + rawInput: { TypeName: "research", Role: "Codebase Researcher", Prompt: "Read README.md" }, + }, + }); + assert.equal(single?.status, "running"); + assert.equal(single?.title, "Codebase Researcher"); + assert.equal(single?.prompt, "Read README.md"); }); it("routes interaction_* permission requests to the question card", () => { @@ -901,6 +915,8 @@ describe("AntigravityAdapterV2 html_render pages", () => { */ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand")(function* ( commandInput: Record, + /** The prompt launches one agy 1.5 subagent instead; its records live below this profile. */ + detachedChildProfile?: string, ) { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const path = yield* Path.Path; @@ -959,7 +975,18 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") }).pipe(Effect.andThen(runtime.handleRequestPermission(handler))), prompt: () => Effect.gen(function* () { - yield* send({ sessionUpdate: "tool_call", ...command, status: "in_progress" }); + yield* send( + detachedChildProfile === undefined + ? { sessionUpdate: "tool_call", ...command, status: "in_progress" } + : { + sessionUpdate: "tool_call", + toolCallId: "call_research", + kind: "other", + title: "Run invoke_subagent", + status: "completed", + rawInput: { TypeName: "research", Role: "Researcher", Prompt: "Read it" }, + }, + ); yield* send({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "I'll render once the fetch finishes." }, @@ -972,6 +999,7 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") }, withProcess: (_stop, task) => task, defaultModel: Effect.undefined, + ...(detachedChildProfile === undefined ? {} : { profileDirectory: detachedChildProfile }), }); const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode: "full-access", @@ -1182,6 +1210,99 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); + // Files as agy 1.5.12 wrote them: the launch sits in the child's inbox, and the child's report + // lands in the parent's inbox with no session update. Only the agent's own reply follows. + it.effect.each([ + { reports: "after the prompt ends", duringPrompt: false }, + { reports: "while the prompt runs", duringPrompt: true }, + ])("keeps a detached subagent running until it reports $reports", ({ duringPrompt }) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profile = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-antigravity-kids-" }); + const records = (conversationId: string, kind: string) => + path.join(profile, "antigravity-acp", "brain", conversationId, ".system_generated", kind); + const write = (directory: string, name: string, value: unknown) => + fileSystem + .makeDirectory(directory, { recursive: true }) + .pipe( + Effect.andThen( + fileSystem.writeFileString(path.join(directory, name), JSON.stringify(value)), + ), + ); + yield* write(records("mock-session-1", "subagents"), "child-1.json", {}); + yield* write(records("child-1", "messages"), "launch.json", { + sender: "mock-session-1", + sourceMetadata: { tool: { toolCall: { id: "call_research", name: "invoke_subagent" } } }, + }); + const report = write(records("mock-session-1", "messages"), "report.json", { + sender: "child-1", + }); + if (duringPrompt) yield* report; + + const { usage, offers, send, startTurn, until, throughPromptSettled } = + yield* openSessionWithRunningCommand({}, profile); + yield* startTurn(1, false); + const statuses = (events: ReadonlyArray) => + events.flatMap((event) => + event.type === "subagent.updated" ? [event.subagent.status] : [], + ); + const prompt = yield* throughPromptSettled; + assert.equal(statuses(prompt).at(-1), duringPrompt ? "idle" : "running"); + if (!duringPrompt) { + yield* TestClock.adjust("10 minutes"); + yield* report; + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "The researcher found it." }, + }); + 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.equal(statuses([...prompt, ...run]).at(-1), "idle"); + assert.equal( + JSON.stringify(run).includes("The researcher found it."), + !duringPrompt, + "the reply about the report is part of the run", + ); + assert.lengthOf(offers, 0, "the open run needs no continuation"); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("ends a continuation run whose replayed reply launched a subagent", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + // No records: nothing proves a child is at work, so none may hold a run open. + const profile = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-antigravity-kids-" }); + const { usage, offers, send, startTurn, throughTerminal } = + yield* openSessionWithRunningCommand({}, profile); + yield* startTurn(1, false); + yield* throughTerminal; + yield* send({ + sessionUpdate: "tool_call", + toolCallId: "call_follow_up", + kind: "other", + title: "Run invoke_subagent", + status: "completed", + rawInput: { TypeName: "research", Role: "Checker", Prompt: "Check it" }, + }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Started a checker." }, + }); + yield* send(usage); + assert.lengthOf(offers, 1, "the agent's own reply must wake the thread"); + yield* offers[0]!.dispatchIfCurrent!(Effect.void); + yield* startTurn(2, true); + yield* TestClock.adjust("3 seconds"); + const terminal = (yield* throughTerminal).at(-1); + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed"); + }).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" }, diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index b8fd0bb98ecd4..0307c4ba18822 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -31,6 +31,7 @@ import { ANTIGRAVITY_SUBAGENT_BATCH_TITLE, antigravitySubagentLaunches, describeAntigravitySubagentLaunches, + readAntigravityChildrenAtWork, } from "../../provider/acp/AntigravityChildWork.ts"; import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityClientFiles.ts"; import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts"; @@ -303,6 +304,12 @@ export function makeAntigravityAcpAdapterFlavor( : { watchPromptOutcome: (sessionId: string) => watchAntigravityPromptOutcome(profileDirectory, sessionId), + subagentsOutlivingPrompt: ({ sessionId, nativeTaskIds }) => + readAntigravityChildrenAtWork({ + profileDirectory, + rootSessionId: sessionId, + toolCallIds: nativeTaskIds, + }), }), }; } diff --git a/apps/server/src/provider/acp/AntigravityChildWork.ts b/apps/server/src/provider/acp/AntigravityChildWork.ts index ea12e0e2b20de..17d3ba3de18f2 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.ts @@ -35,6 +35,8 @@ const TRANSCRIPT_BYTE_CAP = 256 * 1024; const BATCH_TRANSCRIPT_BYTES = 512 * 1024; const STEP_TEXT_CAP = 4_000; const TOOL_INPUT_CAP = 1_000; +const MAX_MESSAGE_FILES = 256; +const MAX_DETACHED_CHILDREN = 64; /** T3's title for a batch whose launch text it never saw. */ export const ANTIGRAVITY_SUBAGENT_BATCH_TITLE = "Antigravity subagent batch"; @@ -44,10 +46,10 @@ interface AntigravityChildLaunch { readonly prompt: string; } +const LaunchInput = Schema.Struct({ Role: Schema.String, Prompt: Schema.String }); +// agy 1.5 launches one child per call with a flat input; earlier releases send a batch. const decodeLaunchInput = Schema.decodeUnknownOption( - Schema.Struct({ - Subagents: Schema.NonEmptyArray(Schema.Struct({ Role: Schema.String, Prompt: Schema.String })), - }), + Schema.Union([Schema.Struct({ Subagents: Schema.NonEmptyArray(LaunchInput) }), LaunchInput]), ); /** `invoke_subagent` arguments, from the permission prompt or the persisted record. */ @@ -56,7 +58,10 @@ export function antigravitySubagentLaunches( ): ReadonlyArray | undefined { return Option.getOrUndefined( Option.map(decodeLaunchInput(input), (decoded) => - decoded.Subagents.map((entry) => ({ role: entry.Role, prompt: entry.Prompt })), + ("Subagents" in decoded ? decoded.Subagents : [decoded]).map((entry) => ({ + role: entry.Role, + prompt: entry.Prompt, + })), ), ); } @@ -476,3 +481,92 @@ export const readAntigravityChildWork = Effect.fn("readAntigravityChildWork")(fu catch: (cause) => new AntigravityChildWorkReadError({ cause }), }); }); + +const decodeChildMessage = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + sender: Schema.String, + sourceMetadata: Schema.optional( + Schema.Struct({ + tool: Schema.optional( + Schema.Struct({ + toolCall: Schema.optional(Schema.Struct({ id: Schema.String, name: Schema.String })), + }), + ), + }), + ), + }), + ), +); + +/** A conversation's inbox. Throws past a bound or on a file it cannot read, so nothing is proven. */ +async function readInbox(profileRoot: string, conversationId: string) { + const directory = ["antigravity-acp", "brain", conversationId, ".system_generated", "messages"]; + const inbox = await antigravityManagedPath(profileRoot, directory, "directory"); + if (inbox === undefined) return []; + // `read.json` is the runtime's read receipts, not a message. + const names = (await NodeFSP.readdir(inbox.path)).filter( + (name) => name.endsWith(".json") && name !== "read.json", + ); + if (names.length > MAX_MESSAGE_FILES) throw new Error("Too many messages"); + return Promise.all( + names.map(async (name) => { + const file = await antigravityManagedPath(profileRoot, [...directory, name], "file"); + if (file === undefined || file.info.size > MAX_STEP_BYTES) throw new Error("Unreadable"); + return Option.getOrThrow(decodeChildMessage(await NodeFSP.readFile(file.path, "utf8"))); + }), + ); +} + +/** + * agy 1.5 children outlive their `invoke_subagent` call and the agent reports no end for them: + * a child is done, or waits for guidance, once its message is in the parent's inbox. Returns the + * launching tool call ids of children with no message yet; none when the records prove nothing. + */ +export const readAntigravityChildrenAtWork = Effect.fn("readAntigravityChildrenAtWork")( + function* (input: { + readonly profileDirectory: string; + readonly rootSessionId: string; + readonly toolCallIds: ReadonlyArray; + }) { + if (!NATIVE_ID.test(input.rootSessionId)) return []; + const read = async (): Promise> => { + const profileRoot = await antigravityProfileRoot(input.profileDirectory); + const children = + profileRoot === undefined + ? undefined + : await antigravityManagedPath( + profileRoot, + ["antigravity-acp", "brain", input.rootSessionId, ".system_generated", "subagents"], + "directory", + ); + if (profileRoot === undefined || children === undefined) return []; + const childIds = (await NodeFSP.readdir(children.path)).flatMap((name) => + name.endsWith(".json") && NATIVE_ID.test(name.slice(0, -5)) ? [name.slice(0, -5)] : [], + ); + if (childIds.length > MAX_DETACHED_CHILDREN) return []; + const reported = new Set( + (await readInbox(profileRoot, input.rootSessionId)).map((message) => message.sender), + ); + const atWork: Array = []; + for (const childId of childIds) { + if (reported.has(childId)) continue; + for (const message of await readInbox(profileRoot, childId)) { + const launch = message.sourceMetadata?.tool?.toolCall; + if ( + message.sender === input.rootSessionId && + launch?.name === "invoke_subagent" && + input.toolCallIds.includes(launch.id) + ) { + atWork.push(launch.id); + } + } + } + return atWork; + }; + return yield* Effect.tryPromise({ + try: read, + catch: (cause) => new AntigravityChildWorkReadError({ cause }), + }).pipe(Effect.orElseSucceed((): ReadonlyArray => [])); + }, +); diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index ef087c2e7665d..73e383552651f 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -494,6 +494,8 @@ const ANTIGRAVITY_SUBAGENT_TITLES = new Set([ "Run start_subagent?", "Running invoke_subagent", "Run invoke_subagent?", + // agy 1.5 auto-approved calls. + "Run invoke_subagent", ]); /** The ACP agent reports subagent calls as ordinary tools without child IDs or models. */ diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 33bc49ff8927a..db495c441e331 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -502,6 +502,15 @@ export interface AcpAdapterV2Flavor { event: AcpSessionRuntime.AcpSessionRuntimeEvent, ) => Effect.Effect; readonly subagentsIdleOnTurnCompletion?: boolean; + /** + * 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 + * it returns hold the turn open and the rest become idle. + */ + readonly subagentsOutlivingPrompt?: (input: { + readonly sessionId: string; + readonly nativeTaskIds: ReadonlyArray; + }) => Effect.Effect>; readonly supportsCompaction?: boolean; /** Sends `/compact` as a prompt, only to sessions whose advertised commands include `compact`. */ readonly compactViaAdvertisedCommand?: boolean; @@ -4101,7 +4110,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (status === "pending" || status === "running") return true; } // finalizeTurn idles these subagents, so waiting on them would never settle. - if (flavor.subagentsIdleOnTurnCompletion === true) return false; + if ( + flavor.subagentsIdleOnTurnCompletion === true && + flavor.subagentsOutlivingPrompt === undefined + ) + return false; for (const subagent of context.subagents.values()) { if (acpSubagentStatusBlocksTurnSettlement(subagent.task.status)) { return true; @@ -4110,6 +4123,39 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return false; }; + const idleReportedSubagents = Effect.fn("AcpAdapterV2.idleReportedSubagents")(function* ( + context: ActiveAcpTurn, + ) { + if (flavor.subagentsOutlivingPrompt === undefined) return; + const nativeTaskId = (subagent: ActiveAcpSubagent) => + subagent.task.nativeTaskRef?.nativeId ?? String(subagent.task.id); + const running = [...context.subagents.values()].filter((subagent) => + acpSubagentStatusBlocksTurnSettlement(subagent.task.status), + ); + if (running.length === 0) return; + const atWork = yield* flavor.subagentsOutlivingPrompt({ + sessionId: context.nativeThreadId, + nativeTaskIds: running.map(nativeTaskId), + }); + if (context.finalized) return; + for (const subagent of running) { + if ( + atWork.includes(nativeTaskId(subagent)) || + !acpSubagentStatusBlocksTurnSettlement(subagent.task.status) + ) + continue; + yield* emitSubagent(context, { + nativeTaskId: nativeTaskId(subagent), + prompt: subagent.task.prompt, + title: subagent.task.title, + model: subagent.task.model, + status: "idle", + childSessionId: subagent.childSessionId, + result: null, + }); + } + }); + const hasSurvivingBackgroundWork = (context: ActiveAcpTurn): boolean => [...context.toolCallIdsByBackgroundTaskId.values()].some((toolCallId) => { const tool = context.tools.get(toolCallId); @@ -5451,6 +5497,7 @@ 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); yield* rearmDeferredFinalize(context); } else if (acpRootSessionUpdateIngestsOutput(notification)) { context.replyOpen = true; @@ -8985,6 +9032,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } context.promptSettled = true; context.promptSettledStatus = "completed"; + // The replayed reply ended before the prompt counted as settled. + yield* idleReportedSubagents(context); if (drainedWakeCount === 0) { if (continuationWasRequested && defersFinalizeForBackgroundWork) { if (hasDeferredBackgroundWork(context)) { @@ -9135,6 +9184,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); return; } + yield* idleReportedSubagents(context); + if (context.finalized) return; if ( defersFinalizeForBackgroundWork && !context.interrupted &&