diff --git a/apps/server/src/provider/acp/AntigravityChildWork.test.ts b/apps/server/src/provider/acp/AntigravityChildWork.test.ts index ed0397da32bb7..e1bfe3aa504e8 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.test.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.test.ts @@ -318,6 +318,160 @@ it.layer(NodeServices.layer)("readAntigravityChildWork", (it) => { }), ); + it.effect("follows a detached 1.5 launch id through the child's inbox to its transcript", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profile = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-detached-" }); + const sibling = "b468c0e1-d2f3-4a5b-6c7d-8e9f0a1b2c3d"; + const writeJson = (segments: ReadonlyArray, value: unknown) => { + const file = path.join(profile, "antigravity-acp", "brain", ...segments); + return fs + .makeDirectory(path.dirname(file), { recursive: true }) + .pipe(Effect.andThen(fs.writeFileString(file, JSON.stringify(value)))); + }; + const writeTranscript = ( + conversationId: string, + lines: ReadonlyArray>, + ) => { + const file = path.join( + profile, + "antigravity-acp", + "brain", + conversationId, + ".system_generated", + "logs", + "transcript.jsonl", + ); + return fs + .makeDirectory(path.dirname(file), { recursive: true }) + .pipe( + Effect.andThen( + fs.writeFileString(file, lines.map((line) => JSON.stringify(line)).join("\n") + "\n"), + ), + ); + }; + + // Matches real agy 1.5.12 records (no legacy step_type=127 database row). + yield* writeJson([ROOT, ".system_generated", "subagents", `${CHILD}.json`], { + conversationId: CHILD, + subagentDescriptor: { typeName: "research", role: LAUNCH.role }, + state: "SUBAGENT_STATE_ALIVE", + }); + yield* writeJson([CHILD, ".system_generated", "messages", "launch.json"], { + sender: ROOT, + content: LAUNCH.prompt, + sourceMetadata: { + tool: { + conversationId: ROOT, + stepIndex: 2, + toolCall: { + id: "call_11340266277043349041", + name: "invoke_subagent", + argumentsJson: JSON.stringify({ + TypeName: "research", + Role: LAUNCH.role, + Prompt: LAUNCH.prompt, + }), + }, + }, + }, + }); + yield* writeJson([CHILD, ".system_generated", "messages", "read.json"], { launch: true }); + yield* writeTranscript(CHILD, [ + { + step_index: 0, + type: "SYSTEM_MESSAGE", + status: "DONE", + content: `\n[Message] sender=${ROOT} content=${LAUNCH.prompt}\n`, + }, + { + step_index: 1, + type: "PLANNER_RESPONSE", + status: "DONE", + tool_calls: [{ name: "read_file", args: { Path: '"/project/README.md"' } }], + }, + { + step_index: 2, + type: "GENERIC", + status: "DONE", + content: "2: MAGIC_TOKEN=probe-38478-ok", + }, + ]); + + // A second detached child without argumentsJson falls back to descriptor role + message content. + yield* writeJson([ROOT, ".system_generated", "subagents", `${sibling}.json`], { + conversationId: sibling, + subagentDescriptor: { typeName: "research", role: "Line Counter" }, + }); + yield* writeJson([sibling, ".system_generated", "messages", "launch.json"], { + sender: ROOT, + content: "Count lines in README.md", + sourceMetadata: { + tool: { + toolCall: { id: "call_22340266277043349042", name: "invoke_subagent" }, + }, + }, + }); + // A follow-up send_message must not be treated as a launch. + yield* writeJson([sibling, ".system_generated", "messages", "followup.json"], { + sender: ROOT, + content: "Also check LICENSE", + sourceMetadata: { + tool: { + toolCall: { id: "call_followup", name: "send_message" }, + }, + }, + }); + + const [first, ...firstRest] = yield* read(profile, "call_11340266277043349041", { + title: LAUNCH.role, + prompt: LAUNCH.prompt, + }); + expect(firstRest).toEqual([]); + expect(first).toMatchObject({ + conversationId: CHILD, + role: LAUNCH.role, + prompt: LAUNCH.prompt, + truncated: false, + }); + expect(first?.steps?.map((step) => step.text ?? step.toolCalls[0]?.name)).toEqual([ + "read_file", + "2: MAGIC_TOKEN=probe-38478-ok", + ]); + expect(first?.steps?.[0]?.toolCalls[0]?.input).toBe('{"Path":"/project/README.md"}'); + + // Missing transcript still returns the proven child with steps: null. + const [second] = yield* read(profile, "call_22340266277043349042", { + title: "Line Counter", + prompt: "Count lines in README.md", + }); + expect(second).toEqual({ + conversationId: sibling, + role: "Line Counter", + prompt: "Count lines in README.md", + steps: null, + truncated: false, + }); + + // Unknown id and send_message id return nothing. + expect(yield* read(profile, "call_unknown")).toEqual([]); + expect(yield* read(profile, "call_followup")).toEqual([]); + + // Another child claiming the same toolCall id makes ownership ambiguous. + yield* writeJson([sibling, ".system_generated", "messages", "dup.json"], { + sender: ROOT, + content: LAUNCH.prompt, + sourceMetadata: { + tool: { + toolCall: { id: "call_11340266277043349041", name: "invoke_subagent" }, + }, + }, + }); + expect(yield* read(profile, "call_11340266277043349041")).toEqual([]); + }), + ); + 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 17d3ba3de18f2..554e419421f6c 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.ts @@ -125,7 +125,10 @@ const text = (bytes: Uint8Array | undefined, field: number) => { interface InvokeRecord { readonly toolCallId: string | undefined; readonly launches: ReadonlyArray; - readonly children: ReadonlyArray<{ readonly conversationId: string; readonly logUri: string }>; + readonly children: ReadonlyArray<{ + readonly conversationId: string; + readonly logUri?: string | undefined; + }>; } const NATIVE_ID = /^[A-Za-z0-9-]{1,64}$/; @@ -386,13 +389,15 @@ async function readChildTranscript( ) )?.path; if (expected === undefined) return undefined; - let named: string; - try { - named = NodeURL.fileURLToPath(child.logUri); - } catch { - return undefined; + if (child.logUri !== undefined) { + let named: string; + try { + named = NodeURL.fileURLToPath(child.logUri); + } catch { + return undefined; + } + if ((await NodeFSP.realpath(named).catch(() => undefined)) !== expected) return undefined; } - if ((await NodeFSP.realpath(named).catch(() => undefined)) !== expected) return undefined; const handle = await NodeFSP.open( expected, NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NOFOLLOW ?? 0), @@ -435,23 +440,27 @@ export const readAntigravityChildWork = Effect.fn("readAntigravityChildWork")(fu return yield* Effect.tryPromise({ try: async (): Promise> => { const profileRoot = await antigravityProfileRoot(input.profileDirectory); - const databasePath = - profileRoot === undefined - ? undefined - : ( - await antigravityManagedPath( - profileRoot, - ["antigravity-acp", "conversations", `${input.rootSessionId}.db`], - "file", - ) - )?.path; - if (profileRoot === undefined || databasePath === undefined) return []; - const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true }); - let record: InvokeRecord | undefined; - try { - record = findInvokeRecord(database, input); - } finally { - database.close(); + if (profileRoot === undefined) return []; + let record = await findDetachedInvokeRecord( + profileRoot, + input.rootSessionId, + input.nativeTaskId, + ); + if (record === undefined) { + const databasePath = ( + await antigravityManagedPath( + profileRoot, + ["antigravity-acp", "conversations", `${input.rootSessionId}.db`], + "file", + ) + )?.path; + if (databasePath === undefined) return []; + const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true }); + try { + record = findInvokeRecord(database, input); + } finally { + database.close(); + } } if (record === undefined) return []; const { launches, children } = record; @@ -486,11 +495,19 @@ const decodeChildMessage = Schema.decodeUnknownOption( Schema.fromJsonString( Schema.Struct({ sender: Schema.String, + content: Schema.optional(Schema.String), sourceMetadata: Schema.optional( Schema.Struct({ tool: Schema.optional( Schema.Struct({ - toolCall: Schema.optional(Schema.Struct({ id: Schema.String, name: Schema.String })), + conversationId: Schema.optional(Schema.String), + toolCall: Schema.optional( + Schema.Struct({ + id: Schema.String, + name: Schema.String, + argumentsJson: Schema.optional(Schema.String), + }), + ), }), ), }), @@ -499,6 +516,19 @@ const decodeChildMessage = Schema.decodeUnknownOption( ), ); +const decodeDetachedSubagent = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + conversationId: Schema.optional(Schema.String), + subagentDescriptor: Schema.optional( + Schema.Struct({ + role: Schema.optional(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"]; @@ -518,6 +548,102 @@ async function readInbox(profileRoot: string, conversationId: string) { ); } +type ChildMessage = Awaited>[number]; + +async function listDetachedChildIds( + profileRoot: string, + rootSessionId: string, +): Promise | undefined> { + const children = await antigravityManagedPath( + profileRoot, + ["antigravity-acp", "brain", rootSessionId, ".system_generated", "subagents"], + "directory", + ); + if (children === undefined) return undefined; + const entries = await NodeFSP.readdir(children.path).catch(() => undefined); + if (entries === undefined) return undefined; + const childIds = entries.flatMap((name) => + name.endsWith(".json") && NATIVE_ID.test(name.slice(0, -5)) ? [name.slice(0, -5)] : [], + ); + return childIds.length > MAX_DETACHED_CHILDREN ? undefined : childIds; +} + +function detachedLaunchCall(message: ChildMessage, rootSessionId: string) { + const tool = message.sourceMetadata?.tool; + const call = tool?.toolCall; + return message.sender === rootSessionId && + (tool?.conversationId === undefined || tool.conversationId === rootSessionId) && + call?.name === "invoke_subagent" + ? call + : undefined; +} + +async function readDetachedSubagent(profileRoot: string, rootSessionId: string, childId: string) { + const file = await antigravityManagedPath( + profileRoot, + [ + "antigravity-acp", + "brain", + rootSessionId, + ".system_generated", + "subagents", + `${childId}.json`, + ], + "file", + ); + if (file === undefined || file.info.size > MAX_STEP_BYTES) return undefined; + const contents = await NodeFSP.readFile(file.path, "utf8").catch(() => undefined); + if (contents === undefined) return undefined; + const record = Option.getOrUndefined(decodeDetachedSubagent(contents)); + return record !== undefined && + (record.conversationId === undefined || record.conversationId === childId) + ? record + : undefined; +} + +/** + * agy 1.5 records detached children under `subagents/` instead of a SQLite `INVOKE_SUBAGENT` step; + * the child's own inbox carries the parent's launching `invoke_subagent` tool call id. + */ +async function findDetachedInvokeRecord( + profileRoot: string, + rootSessionId: string, + nativeTaskId: string, +): Promise { + const childIds = await listDetachedChildIds(profileRoot, rootSessionId); + if (childIds === undefined || childIds.length === 0) return undefined; + const matches: Array = []; + for (const childId of childIds) { + const messages = await readInbox(profileRoot, childId).catch(() => undefined); + // An unreadable or oversized sibling inbox could also claim this id, so uniqueness is unproven. + if (messages === undefined) return undefined; + const launchMessage = messages.find( + (message) => detachedLaunchCall(message, rootSessionId)?.id === nativeTaskId, + ); + if (launchMessage === undefined) continue; + const subagent = await readDetachedSubagent(profileRoot, rootSessionId, childId); + if (subagent === undefined) return undefined; + const argumentsJson = launchMessage.sourceMetadata?.tool?.toolCall?.argumentsJson; + const parsedArgs = + argumentsJson === undefined + ? undefined + : Option.getOrUndefined(decodeArgument(argumentsJson)); + const [fromArgs] = antigravitySubagentLaunches(parsedArgs) ?? []; + matches.push({ + toolCallId: nativeTaskId, + launches: [ + fromArgs ?? { + role: subagent.subagentDescriptor?.role ?? "", + prompt: launchMessage.content ?? "", + }, + ], + children: [{ conversationId: childId }], + }); + } + const [match] = matches; + return matches.length === 1 ? match : undefined; +} + /** * 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 @@ -532,19 +658,11 @@ export const readAntigravityChildrenAtWork = Effect.fn("readAntigravityChildrenA if (!NATIVE_ID.test(input.rootSessionId)) return []; const read = async (): Promise> => { const profileRoot = await antigravityProfileRoot(input.profileDirectory); - const children = + const childIds = 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 []; + : await listDetachedChildIds(profileRoot, input.rootSessionId); + if (profileRoot === undefined || childIds === undefined) return []; const reported = new Set( (await readInbox(profileRoot, input.rootSessionId)).map((message) => message.sender), ); @@ -552,12 +670,8 @@ export const readAntigravityChildrenAtWork = Effect.fn("readAntigravityChildrenA 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) - ) { + const launch = detachedLaunchCall(message, input.rootSessionId); + if (launch !== undefined && input.toolCallIds.includes(launch.id)) { atWork.push(launch.id); } }