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

AntigravityChildWork.ts

966 lines36.3 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 });
50const SwarmAddInput = Schema.Struct({
51 action: Schema.String,
52 name: Schema.optional(Schema.String),
53 role: Schema.optional(Schema.String),
54 brief: Schema.optional(Schema.String),
55 n: Schema.optional(Schema.Number),
56 tasks: Schema.optional(Schema.Array(Schema.String)),
57});
58// agy 1.5 launches one child per call with a flat input; earlier releases send a batch.
59const decodeLaunchInput = Schema.decodeUnknownOption(
60 Schema.Union([Schema.Struct({ Subagents: Schema.NonEmptyArray(LaunchInput) }), LaunchInput]),
61);
62const decodeSwarmAddInput = Schema.decodeUnknownOption(SwarmAddInput);
63​
64// The tool input is untrusted; a huge `n` must not allocate a launch per requested worker.
65const MAX_SWARM_ADD_LAUNCHES = 64;
66​
67function swarmAddLaunches(input: unknown): ReadonlyArray<AntigravityChildLaunch> | undefined {
68 const decoded = Option.getOrUndefined(decodeSwarmAddInput(input));
69 if (decoded === undefined || decoded.action.trim().toLowerCase() !== "add") return undefined;
70 const baseName = decoded.name?.trim().replace(/^@/, "") ?? "";
71 const brief = decoded.brief?.trim() ?? "";
72 const tasks = decoded.tasks ?? [];
73 const requestedCount =
74 decoded.n !== undefined && Number.isFinite(decoded.n) ? Math.trunc(decoded.n) : 0;
75 const count = Math.min(Math.max(tasks.length, requestedCount, 1), MAX_SWARM_ADD_LAUNCHES);
76 const roleSuffix =
77 decoded.role !== undefined && decoded.role.trim().length > 0 && decoded.role !== "worker"
78 ? ` (${decoded.role.trim()})`
79 : "";
80​
81 if (count === 1) {
82 const task = tasks[0]?.trim() ?? "";
83 const prompt = brief.length > 0 && task.length > 0 ? `${brief}\n\n${task}` : brief || task;
84 return [
85 {
86 role: baseName.length > 0 ? `@${baseName}${roleSuffix}` : `Swarm worker${roleSuffix}`,
87 prompt,
88 },
89 ];
90 }
91​
92 return Array.from({ length: count }, (_, index) => {
93 const task = tasks[index]?.trim() ?? "";
94 const prompt = brief.length > 0 && task.length > 0 ? `${brief}\n\n${task}` : task || brief;
95 const role =
96 baseName.length > 0
97 ? `@${baseName}-${index + 1}${roleSuffix}`
98 : `Swarm worker ${index + 1}${roleSuffix}`;
99 return { role, prompt };
100 });
102​
103/** `invoke_subagent` or native `swarm` (`action: "add"`) arguments. */
104export function antigravitySubagentLaunches(
105 input: unknown,
106): ReadonlyArray<AntigravityChildLaunch> | undefined {
107 const classic = Option.getOrUndefined(
108 Option.map(decodeLaunchInput(input), (decoded) =>
109 ("Subagents" in decoded ? decoded.Subagents : [decoded]).map((entry) => ({
110 role: entry.Role,
111 prompt: entry.Prompt,
112 })),
113 ),
114 );
115 return classic ?? swarmAddLaunches(input);
117​
118/** Batch title and prompt; reads match permission-prompt tool call ids against this exact text. */
119export function describeAntigravitySubagentLaunches(
120 launches: ReadonlyArray<AntigravityChildLaunch>,
121) {
122 const [only] = launches;
123 return launches.length === 1 && only !== undefined
124 ? { title: only.role, prompt: only.prompt }
125 : {
126 title: launches.map((launch) => launch.role).join(", "),
127 prompt: launches.map((launch) => `${launch.role}\n${launch.prompt}`).join("\n\n"),
128 };
130​
131/** Length-delimited fields only; varints and fixed values are skipped. */
132export function protoFields(bytes: Uint8Array): ReadonlyArray<readonly [number, Uint8Array]> {
133 const fields: Array<readonly [number, Uint8Array]> = [];
134 let offset = 0;
135 const varint = () => {
136 let value = 0;
137 for (let shift = 0; shift < 64; shift += 7) {
138 const byte = bytes[offset++];
139 if (byte === undefined) throw new Error("Truncated varint");
140 value += (byte & 0x7f) * 2 ** shift;
141 if (byte < 0x80) return value;
142 }
143 throw new Error("Overlong varint");
144 };
145 while (offset < bytes.length) {
146 const key = varint();
147 const wire = key % 8;
148 const field = Math.floor(key / 8);
149 if (wire === 0) varint();
150 else if (wire === 1) offset += 8;
151 else if (wire === 5) offset += 4;
152 else if (wire === 2) {
153 const length = varint();
154 if (offset + length > bytes.length) throw new Error("Truncated field");
155 fields.push([field, bytes.subarray(offset, offset + length)]);
156 offset += length;
157 } else throw new Error("Unsupported wire type");
158 }
159 if (offset > bytes.length) throw new Error("Truncated field");
160 return fields;
162​
163// Keep a leading byte order mark: T3 stores launch text with it.
164const textDecoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
165const messages = (bytes: Uint8Array, field: number) =>
166 protoFields(bytes).flatMap(([number, value]) => (number === field ? [value] : []));
167const message = (bytes: Uint8Array | undefined, field: number) =>
168 bytes === undefined ? undefined : messages(bytes, field)[0];
169const text = (bytes: Uint8Array | undefined, field: number) => {
170 const value = message(bytes, field);
171 return value === undefined ? undefined : textDecoder.decode(value);
172};
173​
174interface InvokeRecord {
175 readonly toolCallId: string | undefined;
176 readonly launches: ReadonlyArray<AntigravityChildLaunch>;
177 readonly children: ReadonlyArray<{
178 readonly conversationId: string;
179 readonly logUri?: string | undefined;
180 }>;
182​
183const NATIVE_ID = /^[A-Za-z0-9-]{1,64}$/;
184​
185/** Undefined for steps this reader cannot decode, so they never count as proof. */
186const safely =
187 <A>(decode: (payload: Uint8Array) => A) =>
188 (payload: Uint8Array): A | undefined => {
189 try {
190 return decode(payload);
191 } catch {
192 return undefined;
193 }
194 };
195​
196const decodeInvokeRecord = safely((payload): InvokeRecord | undefined => {
197 const invoke = message(payload, STEP_INVOKE_SUBAGENT);
198 if (invoke === undefined) return undefined;
199 const children = messages(invoke, INVOKE_RESULTS).map((result) => ({
200 conversationId: text(result, 1) ?? "",
201 logUri: text(result, 2) ?? "",
202 }));
203 if (!children.every((child) => NATIVE_ID.test(child.conversationId))) return undefined;
204 return {
205 toolCallId: text(message(message(payload, STEP_METADATA), METADATA_TOOL_CALL), 1),
206 launches: messages(invoke, INVOKE_SPECS).map((spec) => ({
207 role: text(spec, 2) ?? "",
208 prompt: text(spec, 3) ?? "",
209 })),
210 children,
211 };
212});
213​
214const plannerInvokeCallIds = safely((payload): ReadonlyArray<string> => {
215 const planner = message(payload, STEP_PLANNER_RESPONSE);
216 if (planner === undefined) return [];
217 return messages(planner, PLANNER_TOOL_CALLS).flatMap((call) => {
218 const id = text(call, 1);
219 return text(call, 2) === "invoke_subagent" && id !== undefined ? [id] : [];
220 });
221});
222​
223const payloadOf = (row: unknown) =>
224 row !== null &&
225 typeof row === "object" &&
226 "step_payload" in row &&
227 row.step_payload instanceof Uint8Array
228 ? row.step_payload
229 : undefined;
230​
231interface BatchLaunch {
232 readonly title: string | null;
233 readonly prompt: string;
235​
236const plannerCallIdsAt = (database: NodeSqlite.DatabaseSync, plannerIdx: number) => {
237 const planner = payloadOf(
238 database
239 .prepare(
240 "SELECT step_payload FROM steps WHERE idx = ? AND step_format = 0 AND length(step_payload) <= ?",
241 )
242 .get(plannerIdx, MAX_STEP_BYTES),
243 );
244 return planner === undefined ? undefined : plannerInvokeCallIds(planner);
245};
246​
247/**
248 * Auto-approved calls carry `<sessionId>:<plannerStep>`; the record with that planner call's id
249 * is the proof. Permission prompts carry a random id, so the launch text must match one record
250 * no auto-approved sibling claims, and no sibling may share the text.
251 */
252function findInvokeRecord(
253 database: NodeSqlite.DatabaseSync,
254 input: {
255 readonly rootSessionId: string;
256 readonly nativeTaskId: string;
257 readonly launch: BatchLaunch;
258 readonly siblings: ReadonlyArray<BatchLaunch & { readonly nativeTaskId: string }>;
259 },
260): InvokeRecord | undefined {
261 const plannerIdxOf = (nativeTaskId: string) => {
262 const stepId = /^(.+):(\d+)$/.exec(nativeTaskId);
263 return stepId === null ? undefined : stepId[1] === input.rootSessionId ? Number(stepId[2]) : -1;
264 };
265 const plannerIdx = plannerIdxOf(input.nativeTaskId);
266 if (plannerIdx !== undefined) {
267 if (plannerIdx < 0) return undefined;
268 const callIds = plannerCallIdsAt(database, plannerIdx) ?? [];
269 const [callId] = callIds;
270 if (callIds.length !== 1) return undefined;
271 // The record follows the planner step that issued the call.
272 let rows = 0;
273 let bytes = 0;
274 for (const row of database
275 .prepare(
276 // SQLite returns only in-bound payloads, so an oversized row never reaches this process.
277 "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",
278 )
279 .iterate(MAX_STEP_BYTES, INVOKE_SUBAGENT_STEP_TYPE, plannerIdx)) {
280 const size = row !== null && typeof row === "object" && "size" in row ? Number(row.size) : 0;
281 rows += 1;
282 bytes += size;
283 if (rows > MAX_INVOKE_ROWS || size > MAX_STEP_BYTES || bytes > MAX_SCAN_BYTES)
284 return undefined;
285 const payload = payloadOf(row);
286 const record = payload === undefined ? undefined : decodeInvokeRecord(payload);
287 if (record !== undefined && record.toolCallId === callId) return complete(record);
288 }
289 return undefined;
290 }
291 const totals = database
292 .prepare(
293 "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 = ?",
294 )
295 .get(INVOKE_SUBAGENT_STEP_TYPE);
296 const total = (key: string) =>
297 totals !== undefined && key in totals ? Number(totals[key as keyof typeof totals] ?? 0) : 0;
298 const sameText = (launch: BatchLaunch) =>
299 launch.title === input.launch.title && launch.prompt === input.launch.prompt;
300 if (
301 input.siblings.some(sameText) ||
302 total("rows") > MAX_INVOKE_ROWS ||
303 total("bytes") > MAX_SCAN_BYTES ||
304 total("largest") > MAX_STEP_BYTES ||
305 total("other") > 0
306 ) {
307 return undefined;
308 }
309 const claimed = new Set<string>();
310 for (const sibling of input.siblings) {
311 const idx = plannerIdxOf(sibling.nativeTaskId);
312 // A sibling whose launch text is missing, or cut under the same roles, or whose planner step
313 // is unreadable, cannot be ruled out.
314 if (idx === undefined) {
315 if (
316 sibling.title === ANTIGRAVITY_SUBAGENT_BATCH_TITLE ||
317 (sibling.title !== null && isCutAntigravityToolText(sibling.title)) ||
318 (isCutAntigravityToolText(sibling.prompt) &&
319 (sibling.title === null || sibling.title === input.launch.title))
320 )
321 return undefined;
322 continue;
323 }
324 if (idx < 0) continue;
325 const callIds = plannerCallIdsAt(database, idx);
326 if (callIds === undefined || callIds.length === 0) return undefined;
327 for (const callId of callIds) claimed.add(callId);
328 }
329 const matches: Array<InvokeRecord> = [];
330 for (const row of database
331 .prepare("SELECT step_payload FROM steps WHERE step_type = ? ORDER BY idx")
332 .iterate(INVOKE_SUBAGENT_STEP_TYPE)) {
333 const payload = payloadOf(row);
334 const record = payload === undefined ? undefined : decodeInvokeRecord(payload);
335 // An unreadable record could be an identical launch, so uniqueness is unproven.
336 if (record === undefined) return undefined;
337 if (record.toolCallId !== undefined && claimed.has(record.toolCallId)) continue;
338 // T3 stored the launch from the bounded tool payload, so bound the record the same way.
339 const described = describeAntigravitySubagentLaunches(
340 record.launches.map((launch) => ({
341 role: boundAntigravityToolText(launch.role),
342 prompt: boundAntigravityToolText(launch.prompt),
343 })),
344 );
345 if (sameText(described)) {
346 matches.push(record);
347 }
348 }
349 const [match] = matches;
350 return matches.length === 1 && match !== undefined ? complete(match) : undefined;
352​
353const complete = (record: InvokeRecord) =>
354 record.launches.length === record.children.length && record.children.length <= MAX_CHILDREN
355 ? record
356 : undefined;
357​
358const TranscriptLine = Schema.Struct({
359 step_index: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
360 type: Schema.String,
361 status: Schema.optional(Schema.String),
362 content: Schema.optional(Schema.String),
363 error: Schema.optional(Schema.String),
364 tool_calls: Schema.optional(
365 Schema.Array(Schema.Struct({ name: Schema.String, args: Schema.optional(Schema.Unknown) })),
366 ),
367});
368const decodeTranscriptLine = Schema.decodeUnknownOption(Schema.fromJsonString(TranscriptLine));
369​
370// The runtime records each tool argument value as JSON text.
371const decodeArgument = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
372const toolArguments = (args: unknown) =>
373 Predicate.isObject(args)
374 ? Object.fromEntries(
375 Object.entries(args).map(([key, value]) => [
376 key,
377 typeof value === "string" ? Option.getOrElse(decodeArgument(value), () => value) : value,
378 ]),
379 )
380 : (args ?? {});
381​
382const capText = (value: string, limit: number) =>
383 value.length <= limit ? value : `${value.slice(0, limit)}…`;
384​
385/** Skips the runtime's opening envelope around the launch prompt the view already shows. */
386function transcriptSteps(
387 contents: string,
388 prompt: string,
389): ReadonlyArray<OrchestrationV2NativeChildStep> {
390 const launchPrompt = prompt.trim();
391 return contents.split("\n").flatMap((line) =>
392 Option.match(decodeTranscriptLine(line), {
393 onNone: () => [],
394 onSome: (step) =>
395 step.step_index === 0 &&
396 step.type === "SYSTEM_MESSAGE" &&
397 launchPrompt !== "" &&
398 step.content?.includes(launchPrompt) === true
399 ? []
400 : [
401 {
402 index: step.step_index,
403 type: step.type,
404 status: step.status ?? null,
405 text:
406 step.content !== undefined || step.error !== undefined
407 ? capText(step.content ?? step.error ?? "", STEP_TEXT_CAP)
408 : null,
409 toolCalls: (step.tool_calls ?? []).map((call) => ({
410 name: call.name,
411 input: capText(JSON.stringify(toolArguments(call.args)), TOOL_INPUT_CAP),
412 })),
413 },
414 ],
415 }),
416 );
418​
419/** Reads the tail of the transcript at the named child's own unlinked profile path. */
420async function readChildTranscript(
421 profileRoot: string,
422 child: InvokeRecord["children"][number],
423 prompt: string,
424 byteCap: number,
425) {
426 const expected = (
427 await antigravityManagedPath(
428 profileRoot,
429 [
430 "antigravity-acp",
431 "brain",
432 child.conversationId,
433 ".system_generated",
434 "logs",
435 "transcript.jsonl",
436 ],
437 "file",
438 )
439 )?.path;
440 if (expected === undefined) return undefined;
441 if (child.logUri !== undefined) {
442 let named: string;
443 try {
444 named = NodeURL.fileURLToPath(child.logUri);
445 } catch {
446 return undefined;
447 }
448 if ((await NodeFSP.realpath(named).catch(() => undefined)) !== expected) return undefined;
449 }
450 const handle = await NodeFSP.open(
451 expected,
452 NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NOFOLLOW ?? 0),
453 );
454 try {
455 const stat = await handle.stat();
456 if (!stat.isFile()) return undefined;
457 const tailStart = Math.max(0, stat.size - byteCap);
458 // One extra byte tells whether the retained tail starts on a line boundary.
459 const readStart = Math.max(0, tailStart - 1);
460 const buffer = Buffer.alloc(stat.size - readStart);
461 const { bytesRead } = await handle.read(buffer, 0, buffer.length, readStart);
462 const bytes = buffer.subarray(0, bytesRead);
463 let lineStart = 0;
464 if (tailStart > 0) {
465 const newline = bytes.indexOf(0x0a);
466 if (newline === -1) return { steps: [], truncated: true };
467 lineStart = newline + 1;
468 }
469 const contents = bytes.toString("utf8", lineStart);
470 return { steps: transcriptSteps(contents, prompt), truncated: tailStart > 0 };
471 } finally {
472 await handle.close();
473 }
475​
476class AntigravityChildWorkReadError extends Schema.TaggedError<AntigravityChildWorkReadError>()(
477 "AntigravityChildWorkReadError",
478 { cause: Schema.Defect() },
479) {
480 override get message(): string {
481 return "Could not read Antigravity subagent records.";
482 }
484​
485/** Children a subagent tool call launched, proven by the parent's own session record. */
486export const readAntigravityChildWork = Effect.fn("readAntigravityChildWork")(function* (input: {
487 readonly profileDirectory: string;
488 readonly rootSessionId: string;
489 readonly nativeTaskId: string;
490 readonly launch: BatchLaunch;
491 /** The thread's other Antigravity batches from this instance. */
492 readonly siblings: ReadonlyArray<BatchLaunch & { readonly nativeTaskId: string }>;
493}) {
494 if (!NATIVE_ID.test(input.rootSessionId)) return [];
495 return yield* Effect.tryPromise({
496 try: async (): Promise<ReadonlyArray<OrchestrationV2NativeChildWork>> => {
497 const profileRoot = await antigravityProfileRoot(input.profileDirectory);
498 if (profileRoot === undefined) return [];
499 let record = await findDetachedInvokeRecord(
500 profileRoot,
501 input.rootSessionId,
502 input.nativeTaskId,
503 );
504 if (record === undefined) {
505 const databasePath = (
506 await antigravityManagedPath(
507 profileRoot,
508 ["antigravity-acp", "conversations", `${input.rootSessionId}.db`],
509 "file",
510 )
511 )?.path;
512 if (databasePath === undefined) return [];
513 const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });
514 try {
515 record = findInvokeRecord(database, input);
516 } finally {
517 database.close();
518 }
519 }
520 if (record === undefined) return [];
521 const { launches, children } = record;
522 // One budget for the whole batch, so the response stays small however many children ran.
523 const byteCap = Math.min(
524 TRANSCRIPT_BYTE_CAP,
525 Math.floor(BATCH_TRANSCRIPT_BYTES / Math.max(1, children.length)),
526 );
527 return Promise.all(
528 children.map(async (child, index) => {
529 const transcript = await readChildTranscript(
530 profileRoot,
531 child,
532 launches[index]?.prompt ?? "",
533 byteCap,
534 ).catch(() => undefined);
535 return {
536 conversationId: child.conversationId,
537 role: launches[index]?.role ?? "",
538 prompt: launches[index]?.prompt ?? "",
539 steps: transcript?.steps ?? null,
540 truncated: transcript?.truncated ?? false,
541 };
542 }),
543 );
544 },
545 catch: (cause) => new AntigravityChildWorkReadError({ cause }),
546 });
547});
548​
549const decodeChildMessage = Schema.decodeUnknownOption(
550 Schema.fromJsonString(
551 Schema.Struct({
552 sender: Schema.String,
553 content: Schema.optional(Schema.String),
554 sourceMetadata: Schema.optional(
555 Schema.Struct({
556 tool: Schema.optional(
557 Schema.Struct({
558 conversationId: Schema.optional(Schema.String),
559 toolCall: Schema.optional(
560 Schema.Struct({
561 id: Schema.String,
562 name: Schema.String,
563 argumentsJson: Schema.optional(Schema.String),
564 }),
565 ),
566 }),
567 ),
568 }),
569 ),
570 }),
571 ),
572);
573​
574const decodeDetachedSubagent = Schema.decodeUnknownOption(
575 Schema.fromJsonString(
576 Schema.Struct({
577 conversationId: Schema.optional(Schema.String),
578 state: Schema.optional(Schema.String),
579 subagentDescriptor: Schema.optional(
580 Schema.Struct({
581 role: Schema.optional(Schema.String),
582 }),
583 ),
584 }),
585 ),
586);
587​
588/** A conversation's inbox. Throws past a bound or on a file it cannot read, so nothing is proven. */
589async function readInbox(profileRoot: string, conversationId: string) {
590 const directory = ["antigravity-acp", "brain", conversationId, ".system_generated", "messages"];
591 const inbox = await antigravityManagedPath(profileRoot, directory, "directory");
592 if (inbox === undefined) return [];
593 // `read.json` is the runtime's read receipts, not a message.
594 const names = (await NodeFSP.readdir(inbox.path)).filter(
595 (name) => name.endsWith(".json") && name !== "read.json",
596 );
597 if (names.length > MAX_MESSAGE_FILES) throw new Error("Too many messages");
598 return Promise.all(
599 names.map(async (name) => {
600 const file = await antigravityManagedPath(profileRoot, [...directory, name], "file");
601 if (file === undefined || file.info.size > MAX_STEP_BYTES) throw new Error("Unreadable");
602 return Option.getOrThrow(decodeChildMessage(await NodeFSP.readFile(file.path, "utf8")));
603 }),
604 );
606​
607type ChildMessage = Awaited<ReturnType<typeof readInbox>>[number];
608​
609async function listDetachedChildIds(
610 profileRoot: string,
611 rootSessionId: string,
612): Promise<ReadonlyArray<string> | undefined> {
613 const children = await antigravityManagedPath(
614 profileRoot,
615 ["antigravity-acp", "brain", rootSessionId, ".system_generated", "subagents"],
616 "directory",
617 );
618 if (children === undefined) return undefined;
619 const entries = await NodeFSP.readdir(children.path).catch(() => undefined);
620 if (entries === undefined) return undefined;
621 const childIds = entries.flatMap((name) =>
622 name.endsWith(".json") && NATIVE_ID.test(name.slice(0, -5)) ? [name.slice(0, -5)] : [],
623 );
624 return childIds.length > MAX_DETACHED_CHILDREN ? undefined : childIds;
626​
627function detachedLaunchCall(message: ChildMessage, rootSessionId: string) {
628 const tool = message.sourceMetadata?.tool;
629 const call = tool?.toolCall;
630 return message.sender === rootSessionId &&
631 (tool?.conversationId === undefined || tool.conversationId === rootSessionId) &&
632 (call?.name === "invoke_subagent" || call?.name === "swarm")
633 ? call
634 : undefined;
636​
637function swarmRoleLabel(descriptorRole: string | undefined): string | undefined {
638 const trimmed = descriptorRole?.trim() ?? "";
639 const match = /^Swarm Worker \((.+)\)$/.exec(trimmed);
640 return match?.[1] !== undefined ? `@${match[1].trim()}` : undefined;
642​
643const decodeSwarmRoster = Schema.decodeUnknownOption(
644 Schema.fromJsonString(
645 Schema.Struct({
646 members: Schema.optional(
647 Schema.Record(
648 Schema.String,
649 Schema.Struct({
650 conversation_id: Schema.optional(Schema.String),
651 role: Schema.optional(Schema.String),
652 desired_state: Schema.optional(Schema.String),
653 phase: Schema.optional(Schema.String),
654 wake_mode: Schema.optional(Schema.String),
655 }),
656 ),
657 ),
658 }),
659 ),
660);
661​
662interface DiskSwarmMember {
663 readonly name: string;
664 readonly role: string;
665 readonly killed: boolean;
666 readonly parked: boolean;
668​
669async function readDiskSwarmMembersByConversationId(
670 profileRoot: string,
671 rootSessionId: string,
672): Promise<ReadonlyMap<string, DiskSwarmMember>> {
673 const file = await antigravityManagedPath(
674 profileRoot,
675 ["antigravity-acp", "brain", rootSessionId, ".system_generated", "swarm", "members.json"],
676 "file",
677 );
678 if (file === undefined || file.info.size > MAX_STEP_BYTES) return new Map();
679 const raw = await NodeFSP.readFile(file.path, "utf8").catch(() => undefined);
680 if (raw === undefined) return new Map();
681 const decoded = Option.getOrUndefined(decodeSwarmRoster(raw));
682 const members = decoded?.members;
683 if (members === undefined) return new Map();
684 const byConversation = new Map<string, DiskSwarmMember>();
685 for (const [name, member] of Object.entries(members)) {
686 const convId = member.conversation_id;
687 if (convId === undefined || !NATIVE_ID.test(convId)) continue;
688 const role = member.role ?? "worker";
689 if (role === "coordinator") continue;
690 const killed = member.desired_state === "KILLED" || member.phase === "KILLED";
691 const parked = member.wake_mode === "mentions" || member.wake_mode === "anything";
692 byConversation.set(convId, { name, role, killed, parked });
693 }
694 return byConversation;
696​
697async function readDetachedSubagent(profileRoot: string, rootSessionId: string, childId: string) {
698 const file = await antigravityManagedPath(
699 profileRoot,
700 [
701 "antigravity-acp",
702 "brain",
703 rootSessionId,
704 ".system_generated",
705 "subagents",
706 `${childId}.json`,
707 ],
708 "file",
709 );
710 if (file === undefined || file.info.size > MAX_STEP_BYTES) return undefined;
711 const contents = await NodeFSP.readFile(file.path, "utf8").catch(() => undefined);
712 if (contents === undefined) return undefined;
713 const record = Option.getOrUndefined(decodeDetachedSubagent(contents));
714 return record !== undefined &&
715 (record.conversationId === undefined || record.conversationId === childId)
716 ? record
717 : undefined;
719​
720/**
721 * agy 1.5 records detached children under `subagents/` instead of a SQLite `INVOKE_SUBAGENT` step;
722 * the child's own inbox carries the parent's launching `invoke_subagent` tool call id.
723 */
724async function findDetachedInvokeRecord(
725 profileRoot: string,
726 rootSessionId: string,
727 nativeTaskId: string,
728): Promise<InvokeRecord | undefined> {
729 const childIds = await listDetachedChildIds(profileRoot, rootSessionId);
730 if (childIds === undefined || childIds.length === 0) return undefined;
731 const matches: Array<InvokeRecord & { readonly isSwarm: boolean }> = [];
732 for (const childId of childIds) {
733 const messages = await readInbox(profileRoot, childId).catch(() => undefined);
734 // An unreadable or oversized sibling inbox could also claim this id, so uniqueness is unproven.
735 if (messages === undefined) return undefined;
736 const launchMessage = messages.find(
737 (message) => detachedLaunchCall(message, rootSessionId)?.id === nativeTaskId,
738 );
739 if (launchMessage === undefined) continue;
740 const subagent = await readDetachedSubagent(profileRoot, rootSessionId, childId);
741 if (subagent === undefined) return undefined;
742 const call = launchMessage.sourceMetadata?.tool?.toolCall;
743 const isSwarm = call?.name === "swarm";
744 const argumentsJson = call?.argumentsJson;
745 const parsedArgs =
746 argumentsJson === undefined
747 ? undefined
748 : Option.getOrUndefined(decodeArgument(argumentsJson));
749 const argLaunches = antigravitySubagentLaunches(parsedArgs);
750 const descriptorLabel = swarmRoleLabel(subagent.subagentDescriptor?.role);
751 const matchedLaunch =
752 isSwarm && descriptorLabel !== undefined
753 ? (argLaunches?.find((entry) => entry.role.startsWith(descriptorLabel)) ?? {
754 role: descriptorLabel,
755 prompt: launchMessage.content ?? argLaunches?.[0]?.prompt ?? "",
756 })
757 : argLaunches?.[0];
758 matches.push({
759 isSwarm,
760 toolCallId: nativeTaskId,
761 launches: [
762 matchedLaunch ?? {
763 role: descriptorLabel ?? subagent.subagentDescriptor?.role ?? "",
764 prompt: launchMessage.content ?? "",
765 },
766 ],
767 children: [{ conversationId: childId }],
768 });
769 }
770 if (matches.length === 1) {
771 return matches[0];
772 }
773 if (matches.length > 1 && matches.every((entry) => entry.isSwarm)) {
774 const ordered = [...matches].sort((left, right) =>
775 (left.launches[0]?.role ?? "").localeCompare(right.launches[0]?.role ?? "", undefined, {
776 numeric: true,
777 }),
778 );
779 return {
780 toolCallId: nativeTaskId,
781 launches: ordered.flatMap((entry) => entry.launches),
782 children: ordered.flatMap((entry) => entry.children),
783 };
784 }
785 return undefined;
787​
788const PENDING_REPLY_TAIL_BYTES = 64 * 1024;
789const HIGH_PRIORITY_MESSAGE = "MESSAGE_PRIORITY_HIGH";
790const LOW_PRIORITY_MESSAGE = "MESSAGE_PRIORITY_LOW";
791​
792const decodeReadReceipts = Schema.decodeUnknownOption(
793 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Boolean)),
794);
795​
796const decodeInboxPriorityMessage = Schema.decodeUnknownOption(
797 Schema.fromJsonString(
798 Schema.Struct({
799 id: Schema.optional(Schema.String),
800 priority: Schema.optional(Schema.String),
801 }),
802 ),
803);
804​
805async function hasUnreadWakingInboxMessage(
806 profileRoot: string,
807 sessionId: string,
808): Promise<boolean> {
809 const directory = ["antigravity-acp", "brain", sessionId, ".system_generated", "messages"];
810 const inbox = await antigravityManagedPath(profileRoot, directory, "directory");
811 if (inbox === undefined) return false;
812 const entries = await NodeFSP.readdir(inbox.path).catch(() => undefined);
813 if (entries === undefined) return false;
814 const messageNames = entries.filter((name) => name.endsWith(".json") && name !== "read.json");
815 if (messageNames.length === 0 || messageNames.length > MAX_MESSAGE_FILES) return false;
816 let readReceipts: Readonly<Record<string, boolean>> = {};
817 if (entries.includes("read.json")) {
818 const receiptFile = await antigravityManagedPath(
819 profileRoot,
820 [...directory, "read.json"],
821 "file",
822 );
823 if (receiptFile === undefined || receiptFile.info.size > MAX_STEP_BYTES) return false;
824 const rawReceipts = await NodeFSP.readFile(receiptFile.path, "utf8").catch(() => undefined);
825 if (rawReceipts === undefined) return false;
826 const decodedReceipts = decodeReadReceipts(rawReceipts);
827 if (Option.isNone(decodedReceipts)) return false;
828 readReceipts = decodedReceipts.value;
829 }
830 for (const name of messageNames) {
831 const fileId = name.slice(0, -5);
832 if (readReceipts[fileId] === true) continue;
833 const file = await antigravityManagedPath(profileRoot, [...directory, name], "file");
834 if (file === undefined || file.info.size > MAX_STEP_BYTES) continue;
835 const raw = await NodeFSP.readFile(file.path, "utf8").catch(() => undefined);
836 if (raw === undefined) continue;
837 const decoded = decodeInboxPriorityMessage(raw);
838 if (Option.isNone(decoded)) continue;
839 if (decoded.value.id !== undefined && readReceipts[decoded.value.id] === true) continue;
840 if (decoded.value.priority === HIGH_PRIORITY_MESSAGE) return true;
841 }
842 return false;
844​
845async function readLastTranscriptLine(
846 profileRoot: string,
847 sessionId: string,
848): Promise<Schema.Schema.Type<typeof TranscriptLine> | undefined> {
849 const transcript = await antigravityManagedPath(
850 profileRoot,
851 ["antigravity-acp", "brain", sessionId, ".system_generated", "logs", "transcript.jsonl"],
852 "file",
853 );
854 if (transcript === undefined) return undefined;
855 const handle = await NodeFSP.open(
856 transcript.path,
857 NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NOFOLLOW ?? 0),
858 );
859 try {
860 const stat = await handle.stat();
861 if (!stat.isFile() || stat.size === 0) return undefined;
862 for (const byteCap of [PENDING_REPLY_TAIL_BYTES, TRANSCRIPT_BYTE_CAP]) {
863 const start = Math.max(0, stat.size - byteCap);
864 const buffer = Buffer.alloc(stat.size - start);
865 const { bytesRead } = await handle.read(buffer, 0, buffer.length, start);
866 let end = bytesRead;
867 while (end > 0 && (buffer[end - 1] === 0x0a || buffer[end - 1] === 0x0d)) {
868 end -= 1;
869 }
870 if (end === 0) {
871 if (start === 0) return undefined;
872 continue;
873 }
874 const trimmed = buffer.subarray(0, end);
875 const lastNewline = trimmed.lastIndexOf(0x0a);
876 if (lastNewline === -1 && start > 0) continue;
877 const line = trimmed.toString("utf8", lastNewline + 1);
878 return Option.getOrUndefined(decodeTranscriptLine(line));
879 }
880 return undefined;
881 } finally {
882 await handle.close();
883 }
885​
886/**
887 * True when `agy` has a high-priority wake queued in the session's inbox or already dequeued as
888 * the trailing `SYSTEM_MESSAGE` step in `transcript.jsonl` with no `PLANNER_RESPONSE` yet.
889 * Fails closed when records are missing, linked, or unreadable.
890 */
891export const readAntigravityPendingReply = Effect.fn("readAntigravityPendingReply")(
892 function* (input: { readonly profileDirectory: string; readonly sessionId: string }) {
893 if (!NATIVE_ID.test(input.sessionId)) return false;
894 const read = async (): Promise<boolean> => {
895 const profileRoot = await antigravityProfileRoot(input.profileDirectory);
896 if (profileRoot === undefined) return false;
897 if (await hasUnreadWakingInboxMessage(profileRoot, input.sessionId)) return true;
898 const lastStep = await readLastTranscriptLine(profileRoot, input.sessionId);
899 if (lastStep === undefined || lastStep.type !== "SYSTEM_MESSAGE") return false;
900 return (
901 lastStep.content === undefined ||
902 lastStep.content.includes(`priority=${HIGH_PRIORITY_MESSAGE}`) ||
903 !lastStep.content.includes(`priority=${LOW_PRIORITY_MESSAGE}`)
904 );
905 };
906 return yield* Effect.tryPromise({
907 try: read,
908 catch: (cause) => new AntigravityChildWorkReadError({ cause }),
909 }).pipe(Effect.orElseSucceed(() => false));
910 },
911);
912​
913/**
914 * agy 1.5 children outlive their `invoke_subagent` call and the agent reports no end for them:
915 * a child is done, or waits for guidance, once its message is in the parent's inbox or its record
916 * says it was killed. Returns the launching tool call ids of children with neither; none when the
917 * records prove nothing.
918 */
919export const readAntigravityChildrenAtWork = Effect.fn("readAntigravityChildrenAtWork")(
920 function* (input: {
921 readonly profileDirectory: string;
922 readonly rootSessionId: string;
923 readonly toolCallIds: ReadonlyArray<string>;
924 }) {
925 if (!NATIVE_ID.test(input.rootSessionId)) return [];
926 const read = async (): Promise<ReadonlyArray<string>> => {
927 const profileRoot = await antigravityProfileRoot(input.profileDirectory);
928 const childIds =
929 profileRoot === undefined
930 ? undefined
931 : await listDetachedChildIds(profileRoot, input.rootSessionId);
932 if (profileRoot === undefined || childIds === undefined) return [];
933 const reported = new Set(
934 (await readInbox(profileRoot, input.rootSessionId)).map((message) => message.sender),
935 );
936 const swarmMembers = await readDiskSwarmMembersByConversationId(
937 profileRoot,
938 input.rootSessionId,
939 );
940 const atWork = new Set<string>();
941 for (const childId of childIds) {
942 if (reported.has(childId)) continue;
943 const swarmMember = swarmMembers.get(childId);
944 if (swarmMember?.killed === true || swarmMember?.parked === true) continue;
945 // `manage_subagents` kill only marks the record; a killed child never reports.
946 const subagent = await readDetachedSubagent(profileRoot, input.rootSessionId, childId);
947 if (subagent?.state === "SUBAGENT_STATE_KILLED") continue;
948 const directTaskId = `swarm:${childId}`;
949 if (input.toolCallIds.includes(directTaskId)) {
950 atWork.add(directTaskId);
951 }
952 for (const message of await readInbox(profileRoot, childId)) {
953 const launch = detachedLaunchCall(message, input.rootSessionId);
954 if (launch !== undefined && input.toolCallIds.includes(launch.id)) {
955 atWork.add(launch.id);
956 }
957 }
958 }
959 return [...atWork];
960 };
961 return yield* Effect.tryPromise({
962 try: read,
963 catch: (cause) => new AntigravityChildWorkReadError({ cause }),
964 }).pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
965 },
966);