Open History to see the last commit
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;
38
39/** T3's title for a batch whose launch text it never saw. */
40export const ANTIGRAVITY_SUBAGENT_BATCH_TITLE = "Antigravity subagent batch";
41
42interface AntigravityChildLaunch {
43 readonly role: string;
44 readonly prompt: string;
45}
46
47const decodeLaunchInput = Schema.decodeUnknownOption(
48 Schema.Struct({
49 Subagents: Schema.NonEmptyArray(Schema.Struct({ Role: Schema.String, Prompt: Schema.String })),
50 }),
51);
52
53/** `invoke_subagent` arguments, from the permission prompt or the persisted record. */
54export function antigravitySubagentLaunches(
55 input: unknown,
56): ReadonlyArray<AntigravityChildLaunch> | undefined {
57 return Option.getOrUndefined(
58 Option.map(decodeLaunchInput(input), (decoded) =>
59 decoded.Subagents.map((entry) => ({ role: entry.Role, prompt: entry.Prompt })),
60 ),
61 );
62}
63
64/** Batch title and prompt; reads match permission-prompt tool call ids against this exact text. */
65export function describeAntigravitySubagentLaunches(
66 launches: ReadonlyArray<AntigravityChildLaunch>,
67) {
68 const [only] = launches;
69 return launches.length === 1 && only !== undefined
70 ? { title: only.role, prompt: only.prompt }
71 : {
72 title: launches.map((launch) => launch.role).join(", "),
73 prompt: launches.map((launch) => `${launch.role}\n${launch.prompt}`).join("\n\n"),
74 };
75}
76
77/** Length-delimited fields only; varints and fixed values are skipped. */
78function protoFields(bytes: Uint8Array): ReadonlyArray<readonly [number, Uint8Array]> {
79 const fields: Array<readonly [number, Uint8Array]> = [];
80 let offset = 0;
81 const varint = () => {
82 let value = 0;
83 for (let shift = 0; shift < 64; shift += 7) {
84 const byte = bytes[offset++];
85 if (byte === undefined) throw new Error("Truncated varint");
86 value += (byte & 0x7f) * 2 ** shift;
87 if (byte < 0x80) return value;
88 }
89 throw new Error("Overlong varint");
90 };
91 while (offset < bytes.length) {
92 const key = varint();
93 const wire = key % 8;
94 const field = Math.floor(key / 8);
95 if (wire === 0) varint();
96 else if (wire === 1) offset += 8;
97 else if (wire === 5) offset += 4;
98 else if (wire === 2) {
99 const length = varint();
100 if (offset + length > bytes.length) throw new Error("Truncated field");
101 fields.push([field, bytes.subarray(offset, offset + length)]);
102 offset += length;
103 } else throw new Error("Unsupported wire type");
104 }
105 if (offset > bytes.length) throw new Error("Truncated field");
106 return fields;
107}
108
109// Keep a leading byte order mark: T3 stores launch text with it.
110const textDecoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
111const messages = (bytes: Uint8Array, field: number) =>
112 protoFields(bytes).flatMap(([number, value]) => (number === field ? [value] : []));
113const message = (bytes: Uint8Array | undefined, field: number) =>
114 bytes === undefined ? undefined : messages(bytes, field)[0];
115const text = (bytes: Uint8Array | undefined, field: number) => {
116 const value = message(bytes, field);
117 return value === undefined ? undefined : textDecoder.decode(value);
118};
119
120interface InvokeRecord {
121 readonly toolCallId: string | undefined;
122 readonly launches: ReadonlyArray<AntigravityChildLaunch>;
123 readonly children: ReadonlyArray<{ readonly conversationId: string; readonly logUri: string }>;
124}
125
126const NATIVE_ID = /^[A-Za-z0-9-]{1,64}$/;
127
128/** Undefined for steps this reader cannot decode, so they never count as proof. */
129const safely =
130 <A>(decode: (payload: Uint8Array) => A) =>
131 (payload: Uint8Array): A | undefined => {
132 try {
133 return decode(payload);
134 } catch {
135 return undefined;
136 }
137 };
138
139const decodeInvokeRecord = safely((payload): InvokeRecord | undefined => {
140 const invoke = message(payload, STEP_INVOKE_SUBAGENT);
141 if (invoke === undefined) return undefined;
142 const children = messages(invoke, INVOKE_RESULTS).map((result) => ({
143 conversationId: text(result, 1) ?? "",
144 logUri: text(result, 2) ?? "",
145 }));
146 if (!children.every((child) => NATIVE_ID.test(child.conversationId))) return undefined;
147 return {
148 toolCallId: text(message(message(payload, STEP_METADATA), METADATA_TOOL_CALL), 1),
149 launches: messages(invoke, INVOKE_SPECS).map((spec) => ({
150 role: text(spec, 2) ?? "",
151 prompt: text(spec, 3) ?? "",
152 })),
153 children,
154 };
155});
156
157const plannerInvokeCallIds = safely((payload): ReadonlyArray<string> => {
158 const planner = message(payload, STEP_PLANNER_RESPONSE);
159 if (planner === undefined) return [];
160 return messages(planner, PLANNER_TOOL_CALLS).flatMap((call) => {
161 const id = text(call, 1);
162 return text(call, 2) === "invoke_subagent" && id !== undefined ? [id] : [];
163 });
164});
165
166const payloadOf = (row: unknown) =>
167 row !== null &&
168 typeof row === "object" &&
169 "step_payload" in row &&
170 row.step_payload instanceof Uint8Array
171 ? row.step_payload
172 : undefined;
173
174interface BatchLaunch {
175 readonly title: string | null;
176 readonly prompt: string;
177}
178
179const plannerCallIdsAt = (database: NodeSqlite.DatabaseSync, plannerIdx: number) => {
180 const planner = payloadOf(
181 database
182 .prepare(
183 "SELECT step_payload FROM steps WHERE idx = ? AND step_format = 0 AND length(step_payload) <= ?",
184 )
185 .get(plannerIdx, MAX_STEP_BYTES),
186 );
187 return planner === undefined ? undefined : plannerInvokeCallIds(planner);
188};
189
190/**
191 * Auto-approved calls carry `<sessionId>:<plannerStep>`; the record with that planner call's id
192 * is the proof. Permission prompts carry a random id, so the launch text must match one record
193 * no auto-approved sibling claims, and no sibling may share the text.
194 */
195function findInvokeRecord(
196 database: NodeSqlite.DatabaseSync,
197 input: {
198 readonly rootSessionId: string;
199 readonly nativeTaskId: string;
200 readonly launch: BatchLaunch;
201 readonly siblings: ReadonlyArray<BatchLaunch & { readonly nativeTaskId: string }>;
202 },
203): InvokeRecord | undefined {
204 const plannerIdxOf = (nativeTaskId: string) => {
205 const stepId = /^(.+):(\d+)$/.exec(nativeTaskId);
206 return stepId === null ? undefined : stepId[1] === input.rootSessionId ? Number(stepId[2]) : -1;
207 };
208 const plannerIdx = plannerIdxOf(input.nativeTaskId);
209 if (plannerIdx !== undefined) {
210 if (plannerIdx < 0) return undefined;
211 const callIds = plannerCallIdsAt(database, plannerIdx) ?? [];
212 const [callId] = callIds;
213 if (callIds.length !== 1) return undefined;
214 // The record follows the planner step that issued the call.
215 let rows = 0;
216 let bytes = 0;
217 for (const row of database
218 .prepare(
219 // SQLite returns only in-bound payloads, so an oversized row never reaches this process.
220 "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",
221 )
222 .iterate(MAX_STEP_BYTES, INVOKE_SUBAGENT_STEP_TYPE, plannerIdx)) {
223 const size = row !== null && typeof row === "object" && "size" in row ? Number(row.size) : 0;
224 rows += 1;
225 bytes += size;
226 if (rows > MAX_INVOKE_ROWS || size > MAX_STEP_BYTES || bytes > MAX_SCAN_BYTES)
227 return undefined;
228 const payload = payloadOf(row);
229 const record = payload === undefined ? undefined : decodeInvokeRecord(payload);
230 if (record !== undefined && record.toolCallId === callId) return complete(record);
231 }
232 return undefined;
233 }
234 const totals = database
235 .prepare(
236 "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 = ?",
237 )
238 .get(INVOKE_SUBAGENT_STEP_TYPE);
239 const total = (key: string) =>
240 totals !== undefined && key in totals ? Number(totals[key as keyof typeof totals] ?? 0) : 0;
241 const sameText = (launch: BatchLaunch) =>
242 launch.title === input.launch.title && launch.prompt === input.launch.prompt;
243 if (
244 input.siblings.some(sameText) ||
245 total("rows") > MAX_INVOKE_ROWS ||
246 total("bytes") > MAX_SCAN_BYTES ||
247 total("largest") > MAX_STEP_BYTES ||
248 total("other") > 0
249 ) {
250 return undefined;
251 }
252 const claimed = new Set<string>();
253 for (const sibling of input.siblings) {
254 const idx = plannerIdxOf(sibling.nativeTaskId);
255 // A sibling whose launch text is missing, or cut under the same roles, or whose planner step
256 // is unreadable, cannot be ruled out.
257 if (idx === undefined) {
258 if (
259 sibling.title === ANTIGRAVITY_SUBAGENT_BATCH_TITLE ||
260 (sibling.title !== null && isCutAntigravityToolText(sibling.title)) ||
261 (isCutAntigravityToolText(sibling.prompt) &&
262 (sibling.title === null || sibling.title === input.launch.title))
263 )
264 return undefined;
265 continue;
266 }
267 if (idx < 0) continue;
268 const callIds = plannerCallIdsAt(database, idx);
269 if (callIds === undefined || callIds.length === 0) return undefined;
270 for (const callId of callIds) claimed.add(callId);
271 }
272 const matches: Array<InvokeRecord> = [];
273 for (const row of database
274 .prepare("SELECT step_payload FROM steps WHERE step_type = ? ORDER BY idx")
275 .iterate(INVOKE_SUBAGENT_STEP_TYPE)) {
276 const payload = payloadOf(row);
277 const record = payload === undefined ? undefined : decodeInvokeRecord(payload);
278 // An unreadable record could be an identical launch, so uniqueness is unproven.
279 if (record === undefined) return undefined;
280 if (record.toolCallId !== undefined && claimed.has(record.toolCallId)) continue;
281 // T3 stored the launch from the bounded tool payload, so bound the record the same way.
282 const described = describeAntigravitySubagentLaunches(
283 record.launches.map((launch) => ({
284 role: boundAntigravityToolText(launch.role),
285 prompt: boundAntigravityToolText(launch.prompt),
286 })),
287 );
288 if (sameText(described)) {
289 matches.push(record);
290 }
291 }
292 const [match] = matches;
293 return matches.length === 1 && match !== undefined ? complete(match) : undefined;
294}
295
296const complete = (record: InvokeRecord) =>
297 record.launches.length === record.children.length && record.children.length <= MAX_CHILDREN
298 ? record
299 : undefined;
300
301const TranscriptLine = Schema.Struct({
302 step_index: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
303 type: Schema.String,
304 status: Schema.optional(Schema.String),
305 content: Schema.optional(Schema.String),
306 error: Schema.optional(Schema.String),
307 tool_calls: Schema.optional(
308 Schema.Array(Schema.Struct({ name: Schema.String, args: Schema.optional(Schema.Unknown) })),
309 ),
310});
311const decodeTranscriptLine = Schema.decodeUnknownOption(Schema.fromJsonString(TranscriptLine));
312
313// The runtime records each tool argument value as JSON text.
314const decodeArgument = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
315const toolArguments = (args: unknown) =>
316 Predicate.isObject(args)
317 ? Object.fromEntries(
318 Object.entries(args).map(([key, value]) => [
319 key,
320 typeof value === "string" ? Option.getOrElse(decodeArgument(value), () => value) : value,
321 ]),
322 )
323 : (args ?? {});
324
325const capText = (value: string, limit: number) =>
326 value.length <= limit ? value : `${value.slice(0, limit)}…`;
327
328/** Skips the runtime's opening envelope around the launch prompt the view already shows. */
329function transcriptSteps(
330 contents: string,
331 prompt: string,
332): ReadonlyArray<OrchestrationV2NativeChildStep> {
333 const launchPrompt = prompt.trim();
334 return contents.split("\n").flatMap((line) =>
335 Option.match(decodeTranscriptLine(line), {
336 onNone: () => [],
337 onSome: (step) =>
338 step.step_index === 0 &&
339 step.type === "SYSTEM_MESSAGE" &&
340 launchPrompt !== "" &&
341 step.content?.includes(launchPrompt) === true
342 ? []
343 : [
344 {
345 index: step.step_index,
346 type: step.type,
347 status: step.status ?? null,
348 text:
349 step.content !== undefined || step.error !== undefined
350 ? capText(step.content ?? step.error ?? "", STEP_TEXT_CAP)
351 : null,
352 toolCalls: (step.tool_calls ?? []).map((call) => ({
353 name: call.name,
354 input: capText(JSON.stringify(toolArguments(call.args)), TOOL_INPUT_CAP),
355 })),
356 },
357 ],
358 }),
359 );
360}
361
362/** Reads the tail of the transcript at the named child's own unlinked profile path. */
363async function readChildTranscript(
364 profileRoot: string,
365 child: InvokeRecord["children"][number],
366 prompt: string,
367 byteCap: number,
368) {
369 const expected = (
370 await antigravityManagedPath(
371 profileRoot,
372 [
373 "antigravity-acp",
374 "brain",
375 child.conversationId,
376 ".system_generated",
377 "logs",
378 "transcript.jsonl",
379 ],
380 "file",
381 )
382 )?.path;
383 if (expected === undefined) return undefined;
384 let named: string;
385 try {
386 named = NodeURL.fileURLToPath(child.logUri);
387 } catch {
388 return undefined;
389 }
390 if ((await NodeFSP.realpath(named).catch(() => undefined)) !== expected) return undefined;
391 const handle = await NodeFSP.open(
392 expected,
393 NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NOFOLLOW ?? 0),
394 );
395 try {
396 const stat = await handle.stat();
397 if (!stat.isFile()) return undefined;
398 const length = Math.min(stat.size, byteCap);
399 const buffer = Buffer.alloc(length);
400 const { bytesRead } = await handle.read(buffer, 0, length, stat.size - length);
401 const truncated = stat.size > length;
402 let contents = buffer.subarray(0, bytesRead).toString("utf8");
403 // A tail read starts mid-line.
404 if (truncated) contents = contents.slice(contents.indexOf("\n") + 1);
405 return { steps: transcriptSteps(contents, prompt), truncated };
406 } finally {
407 await handle.close();
408 }
409}
410
411class AntigravityChildWorkReadError extends Schema.TaggedError<AntigravityChildWorkReadError>()(
412 "AntigravityChildWorkReadError",
413 { cause: Schema.Defect() },
414) {
415 override get message(): string {
416 return "Could not read Antigravity subagent records.";
417 }
418}
419
420/** Children a subagent tool call launched, proven by the parent's own session record. */
421export const readAntigravityChildWork = Effect.fn("readAntigravityChildWork")(function* (input: {
422 readonly profileDirectory: string;
423 readonly rootSessionId: string;
424 readonly nativeTaskId: string;
425 readonly launch: BatchLaunch;
426 /** The thread's other Antigravity batches from this instance. */
427 readonly siblings: ReadonlyArray<BatchLaunch & { readonly nativeTaskId: string }>;
428}) {
429 if (!NATIVE_ID.test(input.rootSessionId)) return [];
430 return yield* Effect.tryPromise({
431 try: async (): Promise<ReadonlyArray<OrchestrationV2NativeChildWork>> => {
432 const profileRoot = await antigravityProfileRoot(input.profileDirectory);
433 const databasePath =
434 profileRoot === undefined
435 ? undefined
436 : (
437 await antigravityManagedPath(
438 profileRoot,
439 ["antigravity-acp", "conversations", `${input.rootSessionId}.db`],
440 "file",
441 )
442 )?.path;
443 if (profileRoot === undefined || databasePath === undefined) return [];
444 const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });
445 let record: InvokeRecord | undefined;
446 try {
447 record = findInvokeRecord(database, input);
448 } finally {
449 database.close();
450 }
451 if (record === undefined) return [];
452 const { launches, children } = record;
453 // One budget for the whole batch, so the response stays small however many children ran.
454 const byteCap = Math.min(
455 TRANSCRIPT_BYTE_CAP,
456 Math.floor(BATCH_TRANSCRIPT_BYTES / Math.max(1, children.length)),
457 );
458 return Promise.all(
459 children.map(async (child, index) => {
460 const transcript = await readChildTranscript(
461 profileRoot,
462 child,
463 launches[index]?.prompt ?? "",
464 byteCap,
465 ).catch(() => undefined);
466 return {
467 conversationId: child.conversationId,
468 role: launches[index]?.role ?? "",
469 prompt: launches[index]?.prompt ?? "",
470 steps: transcript?.steps ?? null,
471 truncated: transcript?.truncated ?? false,
472 };
473 }),
474 );
475 },
476 catch: (cause) => new AntigravityChildWorkReadError({ cause }),
477 });
478});