The best way to control Claude Code, Codex and more from any computer or phone
| 1 | // @effect-diagnostics nodeBuiltinImport:off -- node:sqlite reads the native session database read-only. |
| 2 | import * as NodeFS from "node:fs"; |
| 3 | import * as NodeFSP from "node:fs/promises"; |
| 4 | import * as NodeSqlite from "node:sqlite"; |
| 5 | import * as NodeURL from "node:url"; |
| 6 | |
| 7 | import type { |
| 8 | OrchestrationV2NativeChildStep, |
| 9 | OrchestrationV2NativeChildWork, |
| 10 | } from "@t3tools/contracts"; |
| 11 | import * as Effect from "effect/Effect"; |
| 12 | import * as Option from "effect/Option"; |
| 13 | import * as Predicate from "effect/Predicate"; |
| 14 | import * as Schema from "effect/Schema"; |
| 15 | |
| 16 | import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts"; |
| 17 | import { boundAntigravityToolText, isCutAntigravityToolText } from "./AntigravityProtocol.ts"; |
| 18 | |
| 19 | // Field numbers from the runtime's trajectory protos (exa.cortex_pb). |
| 20 | const STEP_METADATA = 5; |
| 21 | const METADATA_TOOL_CALL = 4; |
| 22 | const STEP_PLANNER_RESPONSE = 20; |
| 23 | const PLANNER_TOOL_CALLS = 7; |
| 24 | const STEP_INVOKE_SUBAGENT = 143; |
| 25 | const INVOKE_SPECS = 9; |
| 26 | const INVOKE_RESULTS = 10; |
| 27 | const INVOKE_SUBAGENT_STEP_TYPE = 127; |
| 28 | |
| 29 | // One open reads at most this much; past any bound the batch view stays as it was. |
| 30 | const MAX_STEP_BYTES = 1024 * 1024; |
| 31 | const MAX_INVOKE_ROWS = 200; |
| 32 | const MAX_SCAN_BYTES = 8 * 1024 * 1024; |
| 33 | const MAX_CHILDREN = 16; |
| 34 | const TRANSCRIPT_BYTE_CAP = 256 * 1024; |
| 35 | const BATCH_TRANSCRIPT_BYTES = 512 * 1024; |
| 36 | const STEP_TEXT_CAP = 4_000; |
| 37 | const TOOL_INPUT_CAP = 1_000; |
| 38 | const MAX_MESSAGE_FILES = 256; |
| 39 | const MAX_DETACHED_CHILDREN = 64; |
| 40 | |
| 41 | /** T3's title for a batch whose launch text it never saw. */ |
| 42 | export const ANTIGRAVITY_SUBAGENT_BATCH_TITLE = "Antigravity subagent batch"; |
| 43 | |
| 44 | interface AntigravityChildLaunch { |
| 45 | readonly role: string; |
| 46 | readonly prompt: string; |
| 47 | } |
| 48 | |
| 49 | const 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. |
| 51 | const 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. */ |
| 56 | export 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 | ); |
| 67 | } |
| 68 | |
| 69 | /** Batch title and prompt; reads match permission-prompt tool call ids against this exact text. */ |
| 70 | export 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 | }; |
| 80 | } |
| 81 | |
| 82 | /** Length-delimited fields only; varints and fixed values are skipped. */ |
| 83 | export function 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; |
| 112 | } |
| 113 | |
| 114 | // Keep a leading byte order mark: T3 stores launch text with it. |
| 115 | const textDecoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); |
| 116 | const messages = (bytes: Uint8Array, field: number) => |
| 117 | protoFields(bytes).flatMap(([number, value]) => (number === field ? [value] : [])); |
| 118 | const message = (bytes: Uint8Array | undefined, field: number) => |
| 119 | bytes === undefined ? undefined : messages(bytes, field)[0]; |
| 120 | const text = (bytes: Uint8Array | undefined, field: number) => { |
| 121 | const value = message(bytes, field); |
| 122 | return value === undefined ? undefined : textDecoder.decode(value); |
| 123 | }; |
| 124 | |
| 125 | interface 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 | }>; |
| 132 | } |
| 133 | |
| 134 | const NATIVE_ID = /^[A-Za-z0-9-]{1,64}$/; |
| 135 | |
| 136 | /** Undefined for steps this reader cannot decode, so they never count as proof. */ |
| 137 | const 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 | |
| 147 | const 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 | |
| 165 | const 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 | |
| 174 | const 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 | |
| 182 | interface BatchLaunch { |
| 183 | readonly title: string | null; |
| 184 | readonly prompt: string; |
| 185 | } |
| 186 | |
| 187 | const 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 | */ |
| 203 | function 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; |
| 302 | } |
| 303 | |
| 304 | const complete = (record: InvokeRecord) => |
| 305 | record.launches.length === record.children.length && record.children.length <= MAX_CHILDREN |
| 306 | ? record |
| 307 | : undefined; |
| 308 | |
| 309 | const 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 | }); |
| 319 | const decodeTranscriptLine = Schema.decodeUnknownOption(Schema.fromJsonString(TranscriptLine)); |
| 320 | |
| 321 | // The runtime records each tool argument value as JSON text. |
| 322 | const decodeArgument = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)); |
| 323 | const 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 | |
| 333 | const 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. */ |
| 337 | function 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 | ); |
| 368 | } |
| 369 | |
| 370 | /** Reads the tail of the transcript at the named child's own unlinked profile path. */ |
| 371 | async 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 tailStart = Math.max(0, stat.size - byteCap); |
| 409 | // One extra byte tells whether the retained tail starts on a line boundary. |
| 410 | const readStart = Math.max(0, tailStart - 1); |
| 411 | const buffer = Buffer.alloc(stat.size - readStart); |
| 412 | const { bytesRead } = await handle.read(buffer, 0, buffer.length, readStart); |
| 413 | const bytes = buffer.subarray(0, bytesRead); |
| 414 | let lineStart = 0; |
| 415 | if (tailStart > 0) { |
| 416 | const newline = bytes.indexOf(0x0a); |
| 417 | if (newline === -1) return { steps: [], truncated: true }; |
| 418 | lineStart = newline + 1; |
| 419 | } |
| 420 | const contents = bytes.toString("utf8", lineStart); |
| 421 | return { steps: transcriptSteps(contents, prompt), truncated: tailStart > 0 }; |
| 422 | } finally { |
| 423 | await handle.close(); |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | class AntigravityChildWorkReadError extends Schema.TaggedError<AntigravityChildWorkReadError>()( |
| 428 | "AntigravityChildWorkReadError", |
| 429 | { cause: Schema.Defect() }, |
| 430 | ) { |
| 431 | override get message(): string { |
| 432 | return "Could not read Antigravity subagent records."; |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | /** Children a subagent tool call launched, proven by the parent's own session record. */ |
| 437 | export const readAntigravityChildWork = Effect.fn("readAntigravityChildWork")(function* (input: { |
| 438 | readonly profileDirectory: string; |
| 439 | readonly rootSessionId: string; |
| 440 | readonly nativeTaskId: string; |
| 441 | readonly launch: BatchLaunch; |
| 442 | /** The thread's other Antigravity batches from this instance. */ |
| 443 | readonly siblings: ReadonlyArray<BatchLaunch & { readonly nativeTaskId: string }>; |
| 444 | }) { |
| 445 | if (!NATIVE_ID.test(input.rootSessionId)) return []; |
| 446 | return yield* Effect.tryPromise({ |
| 447 | try: async (): Promise<ReadonlyArray<OrchestrationV2NativeChildWork>> => { |
| 448 | const profileRoot = await antigravityProfileRoot(input.profileDirectory); |
| 449 | if (profileRoot === undefined) return []; |
| 450 | let record = await findDetachedInvokeRecord( |
| 451 | profileRoot, |
| 452 | input.rootSessionId, |
| 453 | input.nativeTaskId, |
| 454 | ); |
| 455 | if (record === undefined) { |
| 456 | const databasePath = ( |
| 457 | await antigravityManagedPath( |
| 458 | profileRoot, |
| 459 | ["antigravity-acp", "conversations", `${input.rootSessionId}.db`], |
| 460 | "file", |
| 461 | ) |
| 462 | )?.path; |
| 463 | if (databasePath === undefined) return []; |
| 464 | const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true }); |
| 465 | try { |
| 466 | record = findInvokeRecord(database, input); |
| 467 | } finally { |
| 468 | database.close(); |
| 469 | } |
| 470 | } |
| 471 | if (record === undefined) return []; |
| 472 | const { launches, children } = record; |
| 473 | // One budget for the whole batch, so the response stays small however many children ran. |
| 474 | const byteCap = Math.min( |
| 475 | TRANSCRIPT_BYTE_CAP, |
| 476 | Math.floor(BATCH_TRANSCRIPT_BYTES / Math.max(1, children.length)), |
| 477 | ); |
| 478 | return Promise.all( |
| 479 | children.map(async (child, index) => { |
| 480 | const transcript = await readChildTranscript( |
| 481 | profileRoot, |
| 482 | child, |
| 483 | launches[index]?.prompt ?? "", |
| 484 | byteCap, |
| 485 | ).catch(() => undefined); |
| 486 | return { |
| 487 | conversationId: child.conversationId, |
| 488 | role: launches[index]?.role ?? "", |
| 489 | prompt: launches[index]?.prompt ?? "", |
| 490 | steps: transcript?.steps ?? null, |
| 491 | truncated: transcript?.truncated ?? false, |
| 492 | }; |
| 493 | }), |
| 494 | ); |
| 495 | }, |
| 496 | catch: (cause) => new AntigravityChildWorkReadError({ cause }), |
| 497 | }); |
| 498 | }); |
| 499 | |
| 500 | const decodeChildMessage = Schema.decodeUnknownOption( |
| 501 | Schema.fromJsonString( |
| 502 | Schema.Struct({ |
| 503 | sender: Schema.String, |
| 504 | content: Schema.optional(Schema.String), |
| 505 | sourceMetadata: Schema.optional( |
| 506 | Schema.Struct({ |
| 507 | tool: Schema.optional( |
| 508 | Schema.Struct({ |
| 509 | conversationId: Schema.optional(Schema.String), |
| 510 | toolCall: Schema.optional( |
| 511 | Schema.Struct({ |
| 512 | id: Schema.String, |
| 513 | name: Schema.String, |
| 514 | argumentsJson: Schema.optional(Schema.String), |
| 515 | }), |
| 516 | ), |
| 517 | }), |
| 518 | ), |
| 519 | }), |
| 520 | ), |
| 521 | }), |
| 522 | ), |
| 523 | ); |
| 524 | |
| 525 | const decodeDetachedSubagent = Schema.decodeUnknownOption( |
| 526 | Schema.fromJsonString( |
| 527 | Schema.Struct({ |
| 528 | conversationId: Schema.optional(Schema.String), |
| 529 | state: Schema.optional(Schema.String), |
| 530 | subagentDescriptor: Schema.optional( |
| 531 | Schema.Struct({ |
| 532 | role: Schema.optional(Schema.String), |
| 533 | }), |
| 534 | ), |
| 535 | }), |
| 536 | ), |
| 537 | ); |
| 538 | |
| 539 | /** A conversation's inbox. Throws past a bound or on a file it cannot read, so nothing is proven. */ |
| 540 | async function readInbox(profileRoot: string, conversationId: string) { |
| 541 | const directory = ["antigravity-acp", "brain", conversationId, ".system_generated", "messages"]; |
| 542 | const inbox = await antigravityManagedPath(profileRoot, directory, "directory"); |
| 543 | if (inbox === undefined) return []; |
| 544 | // `read.json` is the runtime's read receipts, not a message. |
| 545 | const names = (await NodeFSP.readdir(inbox.path)).filter( |
| 546 | (name) => name.endsWith(".json") && name !== "read.json", |
| 547 | ); |
| 548 | if (names.length > MAX_MESSAGE_FILES) throw new Error("Too many messages"); |
| 549 | return Promise.all( |
| 550 | names.map(async (name) => { |
| 551 | const file = await antigravityManagedPath(profileRoot, [...directory, name], "file"); |
| 552 | if (file === undefined || file.info.size > MAX_STEP_BYTES) throw new Error("Unreadable"); |
| 553 | return Option.getOrThrow(decodeChildMessage(await NodeFSP.readFile(file.path, "utf8"))); |
| 554 | }), |
| 555 | ); |
| 556 | } |
| 557 | |
| 558 | type ChildMessage = Awaited<ReturnType<typeof readInbox>>[number]; |
| 559 | |
| 560 | async function listDetachedChildIds( |
| 561 | profileRoot: string, |
| 562 | rootSessionId: string, |
| 563 | ): Promise<ReadonlyArray<string> | undefined> { |
| 564 | const children = await antigravityManagedPath( |
| 565 | profileRoot, |
| 566 | ["antigravity-acp", "brain", rootSessionId, ".system_generated", "subagents"], |
| 567 | "directory", |
| 568 | ); |
| 569 | if (children === undefined) return undefined; |
| 570 | const entries = await NodeFSP.readdir(children.path).catch(() => undefined); |
| 571 | if (entries === undefined) return undefined; |
| 572 | const childIds = entries.flatMap((name) => |
| 573 | name.endsWith(".json") && NATIVE_ID.test(name.slice(0, -5)) ? [name.slice(0, -5)] : [], |
| 574 | ); |
| 575 | return childIds.length > MAX_DETACHED_CHILDREN ? undefined : childIds; |
| 576 | } |
| 577 | |
| 578 | function detachedLaunchCall(message: ChildMessage, rootSessionId: string) { |
| 579 | const tool = message.sourceMetadata?.tool; |
| 580 | const call = tool?.toolCall; |
| 581 | return message.sender === rootSessionId && |
| 582 | (tool?.conversationId === undefined || tool.conversationId === rootSessionId) && |
| 583 | call?.name === "invoke_subagent" |
| 584 | ? call |
| 585 | : undefined; |
| 586 | } |
| 587 | |
| 588 | async function readDetachedSubagent(profileRoot: string, rootSessionId: string, childId: string) { |
| 589 | const file = await antigravityManagedPath( |
| 590 | profileRoot, |
| 591 | [ |
| 592 | "antigravity-acp", |
| 593 | "brain", |
| 594 | rootSessionId, |
| 595 | ".system_generated", |
| 596 | "subagents", |
| 597 | `${childId}.json`, |
| 598 | ], |
| 599 | "file", |
| 600 | ); |
| 601 | if (file === undefined || file.info.size > MAX_STEP_BYTES) return undefined; |
| 602 | const contents = await NodeFSP.readFile(file.path, "utf8").catch(() => undefined); |
| 603 | if (contents === undefined) return undefined; |
| 604 | const record = Option.getOrUndefined(decodeDetachedSubagent(contents)); |
| 605 | return record !== undefined && |
| 606 | (record.conversationId === undefined || record.conversationId === childId) |
| 607 | ? record |
| 608 | : undefined; |
| 609 | } |
| 610 | |
| 611 | /** |
| 612 | * agy 1.5 records detached children under `subagents/` instead of a SQLite `INVOKE_SUBAGENT` step; |
| 613 | * the child's own inbox carries the parent's launching `invoke_subagent` tool call id. |
| 614 | */ |
| 615 | async function findDetachedInvokeRecord( |
| 616 | profileRoot: string, |
| 617 | rootSessionId: string, |
| 618 | nativeTaskId: string, |
| 619 | ): Promise<InvokeRecord | undefined> { |
| 620 | const childIds = await listDetachedChildIds(profileRoot, rootSessionId); |
| 621 | if (childIds === undefined || childIds.length === 0) return undefined; |
| 622 | const matches: Array<InvokeRecord> = []; |
| 623 | for (const childId of childIds) { |
| 624 | const messages = await readInbox(profileRoot, childId).catch(() => undefined); |
| 625 | // An unreadable or oversized sibling inbox could also claim this id, so uniqueness is unproven. |
| 626 | if (messages === undefined) return undefined; |
| 627 | const launchMessage = messages.find( |
| 628 | (message) => detachedLaunchCall(message, rootSessionId)?.id === nativeTaskId, |
| 629 | ); |
| 630 | if (launchMessage === undefined) continue; |
| 631 | const subagent = await readDetachedSubagent(profileRoot, rootSessionId, childId); |
| 632 | if (subagent === undefined) return undefined; |
| 633 | const argumentsJson = launchMessage.sourceMetadata?.tool?.toolCall?.argumentsJson; |
| 634 | const parsedArgs = |
| 635 | argumentsJson === undefined |
| 636 | ? undefined |
| 637 | : Option.getOrUndefined(decodeArgument(argumentsJson)); |
| 638 | const [fromArgs] = antigravitySubagentLaunches(parsedArgs) ?? []; |
| 639 | matches.push({ |
| 640 | toolCallId: nativeTaskId, |
| 641 | launches: [ |
| 642 | fromArgs ?? { |
| 643 | role: subagent.subagentDescriptor?.role ?? "", |
| 644 | prompt: launchMessage.content ?? "", |
| 645 | }, |
| 646 | ], |
| 647 | children: [{ conversationId: childId }], |
| 648 | }); |
| 649 | } |
| 650 | const [match] = matches; |
| 651 | return matches.length === 1 ? match : undefined; |
| 652 | } |
| 653 | |
| 654 | /** |
| 655 | * agy 1.5 children outlive their `invoke_subagent` call and the agent reports no end for them: |
| 656 | * a child is done, or waits for guidance, once its message is in the parent's inbox or its record |
| 657 | * says it was killed. Returns the launching tool call ids of children with neither; none when the |
| 658 | * records prove nothing. |
| 659 | */ |
| 660 | export const readAntigravityChildrenAtWork = Effect.fn("readAntigravityChildrenAtWork")( |
| 661 | function* (input: { |
| 662 | readonly profileDirectory: string; |
| 663 | readonly rootSessionId: string; |
| 664 | readonly toolCallIds: ReadonlyArray<string>; |
| 665 | }) { |
| 666 | if (!NATIVE_ID.test(input.rootSessionId)) return []; |
| 667 | const read = async (): Promise<ReadonlyArray<string>> => { |
| 668 | const profileRoot = await antigravityProfileRoot(input.profileDirectory); |
| 669 | const childIds = |
| 670 | profileRoot === undefined |
| 671 | ? undefined |
| 672 | : await listDetachedChildIds(profileRoot, input.rootSessionId); |
| 673 | if (profileRoot === undefined || childIds === undefined) return []; |
| 674 | const reported = new Set( |
| 675 | (await readInbox(profileRoot, input.rootSessionId)).map((message) => message.sender), |
| 676 | ); |
| 677 | const atWork: Array<string> = []; |
| 678 | for (const childId of childIds) { |
| 679 | if (reported.has(childId)) continue; |
| 680 | // `manage_subagents` kill only marks the record; a killed child never reports. |
| 681 | const subagent = await readDetachedSubagent(profileRoot, input.rootSessionId, childId); |
| 682 | if (subagent?.state === "SUBAGENT_STATE_KILLED") continue; |
| 683 | for (const message of await readInbox(profileRoot, childId)) { |
| 684 | const launch = detachedLaunchCall(message, input.rootSessionId); |
| 685 | if (launch !== undefined && input.toolCallIds.includes(launch.id)) { |
| 686 | atWork.push(launch.id); |
| 687 | } |
| 688 | } |
| 689 | } |
| 690 | return atWork; |
| 691 | }; |
| 692 | return yield* Effect.tryPromise({ |
| 693 | try: read, |
| 694 | catch: (cause) => new AntigravityChildWorkReadError({ cause }), |
| 695 | }).pipe(Effect.orElseSucceed((): ReadonlyArray<string> => [])); |
| 696 | }, |
| 697 | ); |