Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AntigravityChildWork.ts

686 lines25.2 KB

1// @effect-diagnostics nodeBuiltinImport:off -- node:sqlite reads the native session database read-only.
2import * as NodeFS from "node:fs";
3import * as NodeFSP from "node:fs/promises";
4import * as NodeSqlite from "node:sqlite";
5import * as NodeURL from "node:url";
6​
7import type {
8 OrchestrationV2NativeChildStep,
9 OrchestrationV2NativeChildWork,
10} from "@t3tools/contracts";
11import * as Effect from "effect/Effect";
12import * as Option from "effect/Option";
13import * as Predicate from "effect/Predicate";
14import * as Schema from "effect/Schema";
15​
16import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts";
17import { boundAntigravityToolText, isCutAntigravityToolText } from "./AntigravityProtocol.ts";
18​
19// Field numbers from the runtime's trajectory protos (exa.cortex_pb).
20const STEP_METADATA = 5;
21const METADATA_TOOL_CALL = 4;
22const STEP_PLANNER_RESPONSE = 20;
23const PLANNER_TOOL_CALLS = 7;
24const STEP_INVOKE_SUBAGENT = 143;
25const INVOKE_SPECS = 9;
26const INVOKE_RESULTS = 10;
27const INVOKE_SUBAGENT_STEP_TYPE = 127;
28​
29// One open reads at most this much; past any bound the batch view stays as it was.
30const MAX_STEP_BYTES = 1024 * 1024;
31const MAX_INVOKE_ROWS = 200;
32const MAX_SCAN_BYTES = 8 * 1024 * 1024;
33const MAX_CHILDREN = 16;
34const TRANSCRIPT_BYTE_CAP = 256 * 1024;
35const BATCH_TRANSCRIPT_BYTES = 512 * 1024;
36const STEP_TEXT_CAP = 4_000;
37const TOOL_INPUT_CAP = 1_000;
38const MAX_MESSAGE_FILES = 256;
39const MAX_DETACHED_CHILDREN = 64;
40​
41/** T3's title for a batch whose launch text it never saw. */
42export const ANTIGRAVITY_SUBAGENT_BATCH_TITLE = "Antigravity subagent batch";
43​
44interface AntigravityChildLaunch {
45 readonly role: string;
46 readonly prompt: string;
48​
49const LaunchInput = Schema.Struct({ Role: Schema.String, Prompt: Schema.String });
50// agy 1.5 launches one child per call with a flat input; earlier releases send a batch.
51const decodeLaunchInput = Schema.decodeUnknownOption(
52 Schema.Union([Schema.Struct({ Subagents: Schema.NonEmptyArray(LaunchInput) }), LaunchInput]),
53);
54​
55/** `invoke_subagent` arguments, from the permission prompt or the persisted record. */
56export function antigravitySubagentLaunches(
57 input: unknown,
58): ReadonlyArray<AntigravityChildLaunch> | undefined {
59 return Option.getOrUndefined(
60 Option.map(decodeLaunchInput(input), (decoded) =>
61 ("Subagents" in decoded ? decoded.Subagents : [decoded]).map((entry) => ({
62 role: entry.Role,
63 prompt: entry.Prompt,
64 })),
65 ),
66 );
68​
69/** Batch title and prompt; reads match permission-prompt tool call ids against this exact text. */
70export function describeAntigravitySubagentLaunches(
71 launches: ReadonlyArray<AntigravityChildLaunch>,
72) {
73 const [only] = launches;
74 return launches.length === 1 && only !== undefined
75 ? { title: only.role, prompt: only.prompt }
76 : {
77 title: launches.map((launch) => launch.role).join(", "),
78 prompt: launches.map((launch) => `${launch.role}\n${launch.prompt}`).join("\n\n"),
79 };
81​
82/** Length-delimited fields only; varints and fixed values are skipped. */
83function protoFields(bytes: Uint8Array): ReadonlyArray<readonly [number, Uint8Array]> {
84 const fields: Array<readonly [number, Uint8Array]> = [];
85 let offset = 0;
86 const varint = () => {
87 let value = 0;
88 for (let shift = 0; shift < 64; shift += 7) {
89 const byte = bytes[offset++];
90 if (byte === undefined) throw new Error("Truncated varint");
91 value += (byte & 0x7f) * 2 ** shift;
92 if (byte < 0x80) return value;
93 }
94 throw new Error("Overlong varint");
95 };
96 while (offset < bytes.length) {
97 const key = varint();
98 const wire = key % 8;
99 const field = Math.floor(key / 8);
100 if (wire === 0) varint();
101 else if (wire === 1) offset += 8;
102 else if (wire === 5) offset += 4;
103 else if (wire === 2) {
104 const length = varint();
105 if (offset + length > bytes.length) throw new Error("Truncated field");
106 fields.push([field, bytes.subarray(offset, offset + length)]);
107 offset += length;
108 } else throw new Error("Unsupported wire type");
109 }
110 if (offset > bytes.length) throw new Error("Truncated field");
111 return fields;
113​
114// Keep a leading byte order mark: T3 stores launch text with it.
115const textDecoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
116const messages = (bytes: Uint8Array, field: number) =>
117 protoFields(bytes).flatMap(([number, value]) => (number === field ? [value] : []));
118const message = (bytes: Uint8Array | undefined, field: number) =>
119 bytes === undefined ? undefined : messages(bytes, field)[0];
120const text = (bytes: Uint8Array | undefined, field: number) => {
121 const value = message(bytes, field);
122 return value === undefined ? undefined : textDecoder.decode(value);
123};
124​
125interface InvokeRecord {
126 readonly toolCallId: string | undefined;
127 readonly launches: ReadonlyArray<AntigravityChildLaunch>;
128 readonly children: ReadonlyArray<{
129 readonly conversationId: string;
130 readonly logUri?: string | undefined;
131 }>;
133​
134const NATIVE_ID = /^[A-Za-z0-9-]{1,64}$/;
135​
136/** Undefined for steps this reader cannot decode, so they never count as proof. */
137const safely =
138 <A>(decode: (payload: Uint8Array) => A) =>
139 (payload: Uint8Array): A | undefined => {
140 try {
141 return decode(payload);
142 } catch {
143 return undefined;
144 }
145 };
146​
147const decodeInvokeRecord = safely((payload): InvokeRecord | undefined => {
148 const invoke = message(payload, STEP_INVOKE_SUBAGENT);
149 if (invoke === undefined) return undefined;
150 const children = messages(invoke, INVOKE_RESULTS).map((result) => ({
151 conversationId: text(result, 1) ?? "",
152 logUri: text(result, 2) ?? "",
153 }));
154 if (!children.every((child) => NATIVE_ID.test(child.conversationId))) return undefined;
155 return {
156 toolCallId: text(message(message(payload, STEP_METADATA), METADATA_TOOL_CALL), 1),
157 launches: messages(invoke, INVOKE_SPECS).map((spec) => ({
158 role: text(spec, 2) ?? "",
159 prompt: text(spec, 3) ?? "",
160 })),
161 children,
162 };
163});
164​
165const plannerInvokeCallIds = safely((payload): ReadonlyArray<string> => {
166 const planner = message(payload, STEP_PLANNER_RESPONSE);
167 if (planner === undefined) return [];
168 return messages(planner, PLANNER_TOOL_CALLS).flatMap((call) => {
169 const id = text(call, 1);
170 return text(call, 2) === "invoke_subagent" && id !== undefined ? [id] : [];
171 });
172});
173​
174const payloadOf = (row: unknown) =>
175 row !== null &&
176 typeof row === "object" &&
177 "step_payload" in row &&
178 row.step_payload instanceof Uint8Array
179 ? row.step_payload
180 : undefined;
181​
182interface BatchLaunch {
183 readonly title: string | null;
184 readonly prompt: string;
186​
187const plannerCallIdsAt = (database: NodeSqlite.DatabaseSync, plannerIdx: number) => {
188 const planner = payloadOf(
189 database
190 .prepare(
191 "SELECT step_payload FROM steps WHERE idx = ? AND step_format = 0 AND length(step_payload) <= ?",
192 )
193 .get(plannerIdx, MAX_STEP_BYTES),
194 );
195 return planner === undefined ? undefined : plannerInvokeCallIds(planner);
196};
197​
198/**
199 * Auto-approved calls carry `<sessionId>:<plannerStep>`; the record with that planner call's id
200 * is the proof. Permission prompts carry a random id, so the launch text must match one record
201 * no auto-approved sibling claims, and no sibling may share the text.
202 */
203function findInvokeRecord(
204 database: NodeSqlite.DatabaseSync,
205 input: {
206 readonly rootSessionId: string;
207 readonly nativeTaskId: string;
208 readonly launch: BatchLaunch;
209 readonly siblings: ReadonlyArray<BatchLaunch & { readonly nativeTaskId: string }>;
210 },
211): InvokeRecord | undefined {
212 const plannerIdxOf = (nativeTaskId: string) => {
213 const stepId = /^(.+):(\d+)$/.exec(nativeTaskId);
214 return stepId === null ? undefined : stepId[1] === input.rootSessionId ? Number(stepId[2]) : -1;
215 };
216 const plannerIdx = plannerIdxOf(input.nativeTaskId);
217 if (plannerIdx !== undefined) {
218 if (plannerIdx < 0) return undefined;
219 const callIds = plannerCallIdsAt(database, plannerIdx) ?? [];
220 const [callId] = callIds;
221 if (callIds.length !== 1) return undefined;
222 // The record follows the planner step that issued the call.
223 let rows = 0;
224 let bytes = 0;
225 for (const row of database
226 .prepare(
227 // SQLite returns only in-bound payloads, so an oversized row never reaches this process.
228 "SELECT length(step_payload) AS size, CASE WHEN length(step_payload) <= ? THEN step_payload END AS step_payload FROM steps WHERE step_type = ? AND step_format = 0 AND idx > ? ORDER BY idx",
229 )
230 .iterate(MAX_STEP_BYTES, INVOKE_SUBAGENT_STEP_TYPE, plannerIdx)) {
231 const size = row !== null && typeof row === "object" && "size" in row ? Number(row.size) : 0;
232 rows += 1;
233 bytes += size;
234 if (rows > MAX_INVOKE_ROWS || size > MAX_STEP_BYTES || bytes > MAX_SCAN_BYTES)
235 return undefined;
236 const payload = payloadOf(row);
237 const record = payload === undefined ? undefined : decodeInvokeRecord(payload);
238 if (record !== undefined && record.toolCallId === callId) return complete(record);
239 }
240 return undefined;
241 }
242 const totals = database
243 .prepare(
244 "SELECT count(*) AS rows, coalesce(sum(length(step_payload)), 0) AS bytes, coalesce(max(length(step_payload)), 0) AS largest, sum(step_format != 0) AS other FROM steps WHERE step_type = ?",
245 )
246 .get(INVOKE_SUBAGENT_STEP_TYPE);
247 const total = (key: string) =>
248 totals !== undefined && key in totals ? Number(totals[key as keyof typeof totals] ?? 0) : 0;
249 const sameText = (launch: BatchLaunch) =>
250 launch.title === input.launch.title && launch.prompt === input.launch.prompt;
251 if (
252 input.siblings.some(sameText) ||
253 total("rows") > MAX_INVOKE_ROWS ||
254 total("bytes") > MAX_SCAN_BYTES ||
255 total("largest") > MAX_STEP_BYTES ||
256 total("other") > 0
257 ) {
258 return undefined;
259 }
260 const claimed = new Set<string>();
261 for (const sibling of input.siblings) {
262 const idx = plannerIdxOf(sibling.nativeTaskId);
263 // A sibling whose launch text is missing, or cut under the same roles, or whose planner step
264 // is unreadable, cannot be ruled out.
265 if (idx === undefined) {
266 if (
267 sibling.title === ANTIGRAVITY_SUBAGENT_BATCH_TITLE ||
268 (sibling.title !== null && isCutAntigravityToolText(sibling.title)) ||
269 (isCutAntigravityToolText(sibling.prompt) &&
270 (sibling.title === null || sibling.title === input.launch.title))
271 )
272 return undefined;
273 continue;
274 }
275 if (idx < 0) continue;
276 const callIds = plannerCallIdsAt(database, idx);
277 if (callIds === undefined || callIds.length === 0) return undefined;
278 for (const callId of callIds) claimed.add(callId);
279 }
280 const matches: Array<InvokeRecord> = [];
281 for (const row of database
282 .prepare("SELECT step_payload FROM steps WHERE step_type = ? ORDER BY idx")
283 .iterate(INVOKE_SUBAGENT_STEP_TYPE)) {
284 const payload = payloadOf(row);
285 const record = payload === undefined ? undefined : decodeInvokeRecord(payload);
286 // An unreadable record could be an identical launch, so uniqueness is unproven.
287 if (record === undefined) return undefined;
288 if (record.toolCallId !== undefined && claimed.has(record.toolCallId)) continue;
289 // T3 stored the launch from the bounded tool payload, so bound the record the same way.
290 const described = describeAntigravitySubagentLaunches(
291 record.launches.map((launch) => ({
292 role: boundAntigravityToolText(launch.role),
293 prompt: boundAntigravityToolText(launch.prompt),
294 })),
295 );
296 if (sameText(described)) {
297 matches.push(record);
298 }
299 }
300 const [match] = matches;
301 return matches.length === 1 && match !== undefined ? complete(match) : undefined;
303​
304const complete = (record: InvokeRecord) =>
305 record.launches.length === record.children.length && record.children.length <= MAX_CHILDREN
306 ? record
307 : undefined;
308​
309const TranscriptLine = Schema.Struct({
310 step_index: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
311 type: Schema.String,
312 status: Schema.optional(Schema.String),
313 content: Schema.optional(Schema.String),
314 error: Schema.optional(Schema.String),
315 tool_calls: Schema.optional(
316 Schema.Array(Schema.Struct({ name: Schema.String, args: Schema.optional(Schema.Unknown) })),
317 ),
318});
319const decodeTranscriptLine = Schema.decodeUnknownOption(Schema.fromJsonString(TranscriptLine));
320​
321// The runtime records each tool argument value as JSON text.
322const decodeArgument = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
323const toolArguments = (args: unknown) =>
324 Predicate.isObject(args)
325 ? Object.fromEntries(
326 Object.entries(args).map(([key, value]) => [
327 key,
328 typeof value === "string" ? Option.getOrElse(decodeArgument(value), () => value) : value,
329 ]),
330 )
331 : (args ?? {});
332​
333const capText = (value: string, limit: number) =>
334 value.length <= limit ? value : `${value.slice(0, limit)}…`;
335​
336/** Skips the runtime's opening envelope around the launch prompt the view already shows. */
337function transcriptSteps(
338 contents: string,
339 prompt: string,
340): ReadonlyArray<OrchestrationV2NativeChildStep> {
341 const launchPrompt = prompt.trim();
342 return contents.split("\n").flatMap((line) =>
343 Option.match(decodeTranscriptLine(line), {
344 onNone: () => [],
345 onSome: (step) =>
346 step.step_index === 0 &&
347 step.type === "SYSTEM_MESSAGE" &&
348 launchPrompt !== "" &&
349 step.content?.includes(launchPrompt) === true
350 ? []
351 : [
352 {
353 index: step.step_index,
354 type: step.type,
355 status: step.status ?? null,
356 text:
357 step.content !== undefined || step.error !== undefined
358 ? capText(step.content ?? step.error ?? "", STEP_TEXT_CAP)
359 : null,
360 toolCalls: (step.tool_calls ?? []).map((call) => ({
361 name: call.name,
362 input: capText(JSON.stringify(toolArguments(call.args)), TOOL_INPUT_CAP),
363 })),
364 },
365 ],
366 }),
367 );
369​
370/** Reads the tail of the transcript at the named child's own unlinked profile path. */
371async function readChildTranscript(
372 profileRoot: string,
373 child: InvokeRecord["children"][number],
374 prompt: string,
375 byteCap: number,
376) {
377 const expected = (
378 await antigravityManagedPath(
379 profileRoot,
380 [
381 "antigravity-acp",
382 "brain",
383 child.conversationId,
384 ".system_generated",
385 "logs",
386 "transcript.jsonl",
387 ],
388 "file",
389 )
390 )?.path;
391 if (expected === undefined) return undefined;
392 if (child.logUri !== undefined) {
393 let named: string;
394 try {
395 named = NodeURL.fileURLToPath(child.logUri);
396 } catch {
397 return undefined;
398 }
399 if ((await NodeFSP.realpath(named).catch(() => undefined)) !== expected) return undefined;
400 }
401 const handle = await NodeFSP.open(
402 expected,
403 NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NOFOLLOW ?? 0),
404 );
405 try {
406 const stat = await handle.stat();
407 if (!stat.isFile()) return undefined;
408 const length = Math.min(stat.size, byteCap);
409 const buffer = Buffer.alloc(length);
410 const { bytesRead } = await handle.read(buffer, 0, length, stat.size - length);
411 const truncated = stat.size > length;
412 let contents = buffer.subarray(0, bytesRead).toString("utf8");
413 // A tail read starts mid-line.
414 if (truncated) contents = contents.slice(contents.indexOf("\n") + 1);
415 return { steps: transcriptSteps(contents, prompt), truncated };
416 } finally {
417 await handle.close();
418 }
420​
421class AntigravityChildWorkReadError extends Schema.TaggedError<AntigravityChildWorkReadError>()(
422 "AntigravityChildWorkReadError",
423 { cause: Schema.Defect() },
424) {
425 override get message(): string {
426 return "Could not read Antigravity subagent records.";
427 }
429​
430/** Children a subagent tool call launched, proven by the parent's own session record. */
431export const readAntigravityChildWork = Effect.fn("readAntigravityChildWork")(function* (input: {
432 readonly profileDirectory: string;
433 readonly rootSessionId: string;
434 readonly nativeTaskId: string;
435 readonly launch: BatchLaunch;
436 /** The thread's other Antigravity batches from this instance. */
437 readonly siblings: ReadonlyArray<BatchLaunch & { readonly nativeTaskId: string }>;
438}) {
439 if (!NATIVE_ID.test(input.rootSessionId)) return [];
440 return yield* Effect.tryPromise({
441 try: async (): Promise<ReadonlyArray<OrchestrationV2NativeChildWork>> => {
442 const profileRoot = await antigravityProfileRoot(input.profileDirectory);
443 if (profileRoot === undefined) return [];
444 let record = await findDetachedInvokeRecord(
445 profileRoot,
446 input.rootSessionId,
447 input.nativeTaskId,
448 );
449 if (record === undefined) {
450 const databasePath = (
451 await antigravityManagedPath(
452 profileRoot,
453 ["antigravity-acp", "conversations", `${input.rootSessionId}.db`],
454 "file",
455 )
456 )?.path;
457 if (databasePath === undefined) return [];
458 const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });
459 try {
460 record = findInvokeRecord(database, input);
461 } finally {
462 database.close();
463 }
464 }
465 if (record === undefined) return [];
466 const { launches, children } = record;
467 // One budget for the whole batch, so the response stays small however many children ran.
468 const byteCap = Math.min(
469 TRANSCRIPT_BYTE_CAP,
470 Math.floor(BATCH_TRANSCRIPT_BYTES / Math.max(1, children.length)),
471 );
472 return Promise.all(
473 children.map(async (child, index) => {
474 const transcript = await readChildTranscript(
475 profileRoot,
476 child,
477 launches[index]?.prompt ?? "",
478 byteCap,
479 ).catch(() => undefined);
480 return {
481 conversationId: child.conversationId,
482 role: launches[index]?.role ?? "",
483 prompt: launches[index]?.prompt ?? "",
484 steps: transcript?.steps ?? null,
485 truncated: transcript?.truncated ?? false,
486 };
487 }),
488 );
489 },
490 catch: (cause) => new AntigravityChildWorkReadError({ cause }),
491 });
492});
493​
494const decodeChildMessage = Schema.decodeUnknownOption(
495 Schema.fromJsonString(
496 Schema.Struct({
497 sender: Schema.String,
498 content: Schema.optional(Schema.String),
499 sourceMetadata: Schema.optional(
500 Schema.Struct({
501 tool: Schema.optional(
502 Schema.Struct({
503 conversationId: Schema.optional(Schema.String),
504 toolCall: Schema.optional(
505 Schema.Struct({
506 id: Schema.String,
507 name: Schema.String,
508 argumentsJson: Schema.optional(Schema.String),
509 }),
510 ),
511 }),
512 ),
513 }),
514 ),
515 }),
516 ),
517);
518​
519const decodeDetachedSubagent = Schema.decodeUnknownOption(
520 Schema.fromJsonString(
521 Schema.Struct({
522 conversationId: Schema.optional(Schema.String),
523 subagentDescriptor: Schema.optional(
524 Schema.Struct({
525 role: Schema.optional(Schema.String),
526 }),
527 ),
528 }),
529 ),
530);
531​
532/** A conversation's inbox. Throws past a bound or on a file it cannot read, so nothing is proven. */
533async function readInbox(profileRoot: string, conversationId: string) {
534 const directory = ["antigravity-acp", "brain", conversationId, ".system_generated", "messages"];
535 const inbox = await antigravityManagedPath(profileRoot, directory, "directory");
536 if (inbox === undefined) return [];
537 // `read.json` is the runtime's read receipts, not a message.
538 const names = (await NodeFSP.readdir(inbox.path)).filter(
539 (name) => name.endsWith(".json") && name !== "read.json",
540 );
541 if (names.length > MAX_MESSAGE_FILES) throw new Error("Too many messages");
542 return Promise.all(
543 names.map(async (name) => {
544 const file = await antigravityManagedPath(profileRoot, [...directory, name], "file");
545 if (file === undefined || file.info.size > MAX_STEP_BYTES) throw new Error("Unreadable");
546 return Option.getOrThrow(decodeChildMessage(await NodeFSP.readFile(file.path, "utf8")));
547 }),
548 );
550​
551type ChildMessage = Awaited<ReturnType<typeof readInbox>>[number];
552​
553async function listDetachedChildIds(
554 profileRoot: string,
555 rootSessionId: string,
556): Promise<ReadonlyArray<string> | undefined> {
557 const children = await antigravityManagedPath(
558 profileRoot,
559 ["antigravity-acp", "brain", rootSessionId, ".system_generated", "subagents"],
560 "directory",
561 );
562 if (children === undefined) return undefined;
563 const entries = await NodeFSP.readdir(children.path).catch(() => undefined);
564 if (entries === undefined) return undefined;
565 const childIds = entries.flatMap((name) =>
566 name.endsWith(".json") && NATIVE_ID.test(name.slice(0, -5)) ? [name.slice(0, -5)] : [],
567 );
568 return childIds.length > MAX_DETACHED_CHILDREN ? undefined : childIds;
570​
571function detachedLaunchCall(message: ChildMessage, rootSessionId: string) {
572 const tool = message.sourceMetadata?.tool;
573 const call = tool?.toolCall;
574 return message.sender === rootSessionId &&
575 (tool?.conversationId === undefined || tool.conversationId === rootSessionId) &&
576 call?.name === "invoke_subagent"
577 ? call
578 : undefined;
580​
581async function readDetachedSubagent(profileRoot: string, rootSessionId: string, childId: string) {
582 const file = await antigravityManagedPath(
583 profileRoot,
584 [
585 "antigravity-acp",
586 "brain",
587 rootSessionId,
588 ".system_generated",
589 "subagents",
590 `${childId}.json`,
591 ],
592 "file",
593 );
594 if (file === undefined || file.info.size > MAX_STEP_BYTES) return undefined;
595 const contents = await NodeFSP.readFile(file.path, "utf8").catch(() => undefined);
596 if (contents === undefined) return undefined;
597 const record = Option.getOrUndefined(decodeDetachedSubagent(contents));
598 return record !== undefined &&
599 (record.conversationId === undefined || record.conversationId === childId)
600 ? record
601 : undefined;
603​
604/**
605 * agy 1.5 records detached children under `subagents/` instead of a SQLite `INVOKE_SUBAGENT` step;
606 * the child's own inbox carries the parent's launching `invoke_subagent` tool call id.
607 */
608async function findDetachedInvokeRecord(
609 profileRoot: string,
610 rootSessionId: string,
611 nativeTaskId: string,
612): Promise<InvokeRecord | undefined> {
613 const childIds = await listDetachedChildIds(profileRoot, rootSessionId);
614 if (childIds === undefined || childIds.length === 0) return undefined;
615 const matches: Array<InvokeRecord> = [];
616 for (const childId of childIds) {
617 const messages = await readInbox(profileRoot, childId).catch(() => undefined);
618 // An unreadable or oversized sibling inbox could also claim this id, so uniqueness is unproven.
619 if (messages === undefined) return undefined;
620 const launchMessage = messages.find(
621 (message) => detachedLaunchCall(message, rootSessionId)?.id === nativeTaskId,
622 );
623 if (launchMessage === undefined) continue;
624 const subagent = await readDetachedSubagent(profileRoot, rootSessionId, childId);
625 if (subagent === undefined) return undefined;
626 const argumentsJson = launchMessage.sourceMetadata?.tool?.toolCall?.argumentsJson;
627 const parsedArgs =
628 argumentsJson === undefined
629 ? undefined
630 : Option.getOrUndefined(decodeArgument(argumentsJson));
631 const [fromArgs] = antigravitySubagentLaunches(parsedArgs) ?? [];
632 matches.push({
633 toolCallId: nativeTaskId,
634 launches: [
635 fromArgs ?? {
636 role: subagent.subagentDescriptor?.role ?? "",
637 prompt: launchMessage.content ?? "",
638 },
639 ],
640 children: [{ conversationId: childId }],
641 });
642 }
643 const [match] = matches;
644 return matches.length === 1 ? match : undefined;
646​
647/**
648 * agy 1.5 children outlive their `invoke_subagent` call and the agent reports no end for them:
649 * a child is done, or waits for guidance, once its message is in the parent's inbox. Returns the
650 * launching tool call ids of children with no message yet; none when the records prove nothing.
651 */
652export const readAntigravityChildrenAtWork = Effect.fn("readAntigravityChildrenAtWork")(
653 function* (input: {
654 readonly profileDirectory: string;
655 readonly rootSessionId: string;
656 readonly toolCallIds: ReadonlyArray<string>;
657 }) {
658 if (!NATIVE_ID.test(input.rootSessionId)) return [];
659 const read = async (): Promise<ReadonlyArray<string>> => {
660 const profileRoot = await antigravityProfileRoot(input.profileDirectory);
661 const childIds =
662 profileRoot === undefined
663 ? undefined
664 : await listDetachedChildIds(profileRoot, input.rootSessionId);
665 if (profileRoot === undefined || childIds === undefined) return [];
666 const reported = new Set(
667 (await readInbox(profileRoot, input.rootSessionId)).map((message) => message.sender),
668 );
669 const atWork: Array<string> = [];
670 for (const childId of childIds) {
671 if (reported.has(childId)) continue;
672 for (const message of await readInbox(profileRoot, childId)) {
673 const launch = detachedLaunchCall(message, input.rootSessionId);
674 if (launch !== undefined && input.toolCallIds.includes(launch.id)) {
675 atWork.push(launch.id);
676 }
677 }
678 }
679 return atWork;
680 };
681 return yield* Effect.tryPromise({
682 try: read,
683 catch: (cause) => new AntigravityChildWorkReadError({ cause }),
684 }).pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
685 },
686);