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gCAAgC,CAC/C,OAAO,EAAE,aAAa,CAAC,oBAAoB,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,GACnF,IAAI,CAIN;AAED,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,gBAAgB,EAAE,GAAG,SAAS,GAAG,OAAO,CAQ1F;AAED,wBAAgB,4BAA4B,CAC3C,MAAM,EAAE,WAAW,EACnB,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE;IACT,EAAE,EAAE,MAAM,CAAC;IACX,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,KAAK,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACpE,IAAI,CAAC,EAAE,eAAe,CAAC;IACvB,EAAE,EAAE,MAAM,CAAC;CACX,GACC,gBAAgB,CA0GlB;AAED,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAKhG;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAK5D;AAED,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,CAIvE","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { writeAtomicJson } from \"../../shared/atomic-json.ts\";\nimport { THINKING_LEVELS } from \"../../shared/model-info.ts\";\nimport {\n\ttype AsyncJobState,\n\ttype AsyncStatus,\n\tDIRS,\n\ttype LaunchResolvedChildExtensionsV1,\n\ttype NestedRouteInfo,\n\ttype NestedRunState,\n\ttype NestedRunSummary,\n\ttype NestedStepSummary,\n\ttype RuntimeAcknowledgedChildExtensionsV1,\n\ttype SubagentRunMode,\n\ttype SubagentState,\n\tTEMP_ROOT_DIR,\n\ttype TurnBudgetState,\n} from \"../../shared/types.ts\";\nimport { sanitizeProcessTerminal } from \"../background/process-terminal.ts\";\nimport { isSafeNestedPathId, type NestedPathEntry, parseNestedPathEnv, sanitizeNestedPath } from \"./nested-path.ts\";\nimport {\n\tSUBAGENT_PARENT_CAPABILITY_TOKEN_ENV,\n\tSUBAGENT_PARENT_CHILD_INDEX_ENV,\n\tSUBAGENT_PARENT_CONTROL_INBOX_ENV,\n\tSUBAGENT_PARENT_DEPTH_ENV,\n\tSUBAGENT_PARENT_EVENT_SINK_ENV,\n\tSUBAGENT_PARENT_PATH_ENV,\n\tSUBAGENT_PARENT_ROOT_RUN_ID_ENV,\n\tSUBAGENT_PARENT_RUN_ID_ENV,\n} from \"./pi-args.ts\";\n\nexport const NESTED_EVENTS_DIR = path.join(TEMP_ROOT_DIR, \"nested-subagent-events\");\nconst ROUTE_FILE = \"route.json\";\nconst REGISTRY_FILE = \"registry.json\";\nconst MAX_EVENT_BYTES = 64 * 1024;\nconst MAX_STEPS = 12;\nconst MAX_CHILDREN = 16;\nconst MAX_DEPTH = 3;\n\ntype NestedStatusEventType = \"subagent.nested.started\" | \"subagent.nested.updated\" | \"subagent.nested.completed\";\ntype NestedControlResultEventType = \"subagent.nested.control-result\";\n\nexport type NestedRoute = NestedRouteInfo;\n\nexport interface NestedEventRecord {\n\ttype: NestedStatusEventType;\n\tts: number;\n\trootRunId: string;\n\tparentRunId: string;\n\tparentStepIndex?: number;\n\tcapabilityToken: string;\n\tchild: NestedRunSummary;\n}\n\nexport interface NestedControlResultRecord {\n\ttype: NestedControlResultEventType;\n\tts: number;\n\trootRunId: string;\n\tcapabilityToken: string;\n\trequestId: string;\n\ttargetRunId: string;\n\tok: boolean;\n\tmessage: string;\n}\n\nexport interface NestedControlRequestRecord {\n\ttype: \"subagent.nested.control-request\";\n\tts: number;\n\trootRunId: string;\n\tcapabilityToken: string;\n\trequestId: string;\n\ttargetRunId: string;\n\taction: \"interrupt\" | \"resume\";\n\tmessage?: string;\n}\n\nexport interface NestedRegistry {\n\trootRunId: string;\n\tupdatedAt: number;\n\tchildren: NestedRunSummary[];\n\tprocessedEvents: string[];\n}\n\nexport function isSafeNestedId(value: unknown): value is string {\n\treturn isSafeNestedPathId(value);\n}\n\nexport function assertSafeNestedId(label: string, value: string): void {\n\tif (!isSafeNestedId(value)) throw new Error(`${label} must be a non-empty safe id token.`);\n}\n\nfunction assertSafeId(label: string, value: string): void {\n\tassertSafeNestedId(label, value);\n}\n\nfunction containedPath(base: string, candidate: string): boolean {\n\tconst resolvedBase = path.resolve(base);\n\tconst resolvedCandidate = path.resolve(candidate);\n\treturn resolvedCandidate === resolvedBase || resolvedCandidate.startsWith(`${resolvedBase}${path.sep}`);\n}\n\nfunction commonRouteRoot(route: Pick<NestedRoute, \"eventSink\" | \"controlInbox\">): string {\n\treturn path.dirname(path.resolve(route.eventSink));\n}\n\nfunction validateRouteShape(route: NestedRoute): void {\n\tassertSafeId(\"rootRunId\", route.rootRunId);\n\tassertSafeId(\"capabilityToken\", route.capabilityToken);\n\tif (!containedPath(NESTED_EVENTS_DIR, route.eventSink))\n\t\tthrow new Error(\"Nested event sink is outside the subagent nested event root.\");\n\tif (!containedPath(NESTED_EVENTS_DIR, route.controlInbox))\n\t\tthrow new Error(\"Nested control inbox is outside the subagent nested event root.\");\n\tif (commonRouteRoot(route) !== path.dirname(path.resolve(route.controlInbox)))\n\t\tthrow new Error(\"Nested event sink and control inbox must share one route root.\");\n}\n\nexport function createNestedRoute(rootRunId: string): NestedRoute {\n\tassertSafeId(\"rootRunId\", rootRunId);\n\tconst capabilityToken = randomUUID();\n\tconst routeRoot = path.join(NESTED_EVENTS_DIR, `${rootRunId}-${capabilityToken}`);\n\tconst eventSink = path.join(routeRoot, \"events\");\n\tconst controlInbox = path.join(routeRoot, \"controls\");\n\tfs.mkdirSync(eventSink, { recursive: true, mode: 0o700 });\n\tfs.mkdirSync(controlInbox, { recursive: true, mode: 0o700 });\n\tfs.writeFileSync(\n\t\tpath.join(routeRoot, ROUTE_FILE),\n\t\t`${JSON.stringify({ rootRunId, capabilityToken, createdAt: Date.now() })}\\n`,\n\t\t{ mode: 0o600 },\n\t);\n\treturn { rootRunId, eventSink, controlInbox, capabilityToken };\n}\n\nexport function resolveNestedRouteFromEnv(env: NodeJS.ProcessEnv = process.env): NestedRoute | undefined {\n\tconst rootRunId = env[SUBAGENT_PARENT_ROOT_RUN_ID_ENV];\n\tconst eventSink = env[SUBAGENT_PARENT_EVENT_SINK_ENV];\n\tconst controlInbox = env[SUBAGENT_PARENT_CONTROL_INBOX_ENV];\n\tconst capabilityToken = env[SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV];\n\tif (!rootRunId || !eventSink || !controlInbox || !capabilityToken) return undefined;\n\tconst route = { rootRunId, eventSink, controlInbox, capabilityToken };\n\tvalidateRouteShape(route);\n\tconst routeFile = path.join(commonRouteRoot(route), ROUTE_FILE);\n\tconst metadata = JSON.parse(fs.readFileSync(routeFile, \"utf-8\")) as {\n\t\trootRunId?: unknown;\n\t\tcapabilityToken?: unknown;\n\t};\n\tif (metadata.rootRunId !== rootRunId || metadata.capabilityToken !== capabilityToken) {\n\t\tthrow new Error(\"Nested event route metadata does not match the provided root id and capability token.\");\n\t}\n\treturn route;\n}\n\nexport function resolveInheritedNestedRouteFromEnv(env: NodeJS.ProcessEnv = process.env): NestedRoute | undefined {\n\ttry {\n\t\treturn resolveNestedRouteFromEnv(env);\n\t} catch (error) {\n\t\tconsole.error(\"Ignoring invalid nested subagent event route:\", error);\n\t\treturn undefined;\n\t}\n}\n\nexport function resolveNestedParentAddressFromEnv(\n\tenv: NodeJS.ProcessEnv = process.env,\n): { parentRunId: string; parentStepIndex?: number; depth: number; path: NestedPathEntry[] } | undefined {\n\tconst parentRunId = env[SUBAGENT_PARENT_RUN_ID_ENV];\n\tif (!isSafeNestedId(parentRunId)) return undefined;\n\tconst rawIndex = env[SUBAGENT_PARENT_CHILD_INDEX_ENV];\n\tconst parentStepIndex = rawIndex && /^\\d+$/.test(rawIndex) ? Number(rawIndex) : undefined;\n\tconst depth = Math.min(Math.max(1, clampNumber(Number(env[SUBAGENT_PARENT_DEPTH_ENV])) ?? 1), MAX_DEPTH);\n\tconst parsedPath = parseNestedPathEnv(env[SUBAGENT_PARENT_PATH_ENV]);\n\tconst nestedPath = parsedPath.length\n\t\t? parsedPath\n\t\t: [{ runId: parentRunId, ...(parentStepIndex !== undefined ? { stepIndex: parentStepIndex } : {}) }];\n\treturn { parentRunId, ...(parentStepIndex !== undefined ? { parentStepIndex } : {}), depth, path: nestedPath };\n}\n\nexport function resolveNestedAsyncDir(rootRunId: string, run: NestedRunSummary): string | undefined {\n\tif (!run.asyncDir) return undefined;\n\tconst resolved = path.resolve(run.asyncDir);\n\tconst nestedRoot = path.resolve(TEMP_ROOT_DIR, \"nested-subagent-runs\", rootRunId, run.id);\n\tconst relative = path.relative(nestedRoot, resolved);\n\treturn resolved === nestedRoot || (!relative.startsWith(\"..\") && !path.isAbsolute(relative)) ? resolved : undefined;\n}\n\nfunction clampNumber(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction stringValue(value: unknown, max = 512): string | undefined {\n\treturn typeof value === \"string\" && value.length > 0 ? value.slice(0, max) : undefined;\n}\n\nfunction sanitizeTokenUsage(value: unknown): NestedRunSummary[\"totalTokens\"] | undefined {\n\tif (!value || typeof value !== \"object\") return undefined;\n\tconst raw = value as Record<string, unknown>;\n\tconst input = clampNumber(raw.input);\n\tconst output = clampNumber(raw.output);\n\tconst total = clampNumber(raw.total);\n\treturn input !== undefined && output !== undefined && total !== undefined ? { input, output, total } : undefined;\n}\n\nfunction sanitizeCost(value: unknown): NestedRunSummary[\"totalCost\"] | undefined {\n\tif (!value || typeof value !== \"object\") return undefined;\n\tconst raw = value as Record<string, unknown>;\n\tconst inputTokens = clampNumber(raw.inputTokens);\n\tconst outputTokens = clampNumber(raw.outputTokens);\n\tconst costUsd = clampNumber(raw.costUsd);\n\treturn inputTokens !== undefined && outputTokens !== undefined && costUsd !== undefined\n\t\t? { inputTokens, outputTokens, costUsd }\n\t\t: undefined;\n}\n\nfunction sanitizeLaunchResolvedExtensions(value: unknown): LaunchResolvedChildExtensionsV1 | undefined {\n\tif (!value || typeof value !== \"object\") return undefined;\n\tconst raw = value as Record<string, unknown>;\n\tif (raw.version !== 1 || raw.source !== \"launch-resolved\" || typeof raw.disableAmbientExtensions !== \"boolean\")\n\t\treturn undefined;\n\tconst stringList = (input: unknown): string[] =>\n\t\tArray.isArray(input)\n\t\t\t? input\n\t\t\t\t\t.filter((item): item is string => typeof item === \"string\" && /^sha256:[a-f0-9]{16}$/.test(item))\n\t\t\t\t\t.slice(0, 32)\n\t\t\t: [];\n\tconst omitted = raw.omitted && typeof raw.omitted === \"object\" ? (raw.omitted as Record<string, unknown>) : {};\n\tconst omittedCount = (key: string): number => Math.max(0, Math.floor(clampNumber(omitted[key]) ?? 0));\n\treturn {\n\t\tversion: 1,\n\t\tsource: \"launch-resolved\",\n\t\tdisableAmbientExtensions: raw.disableAmbientExtensions,\n\t\truntime: stringList(raw.runtime),\n\t\tconfigured: stringList(raw.configured),\n\t\teffective: stringList(raw.effective),\n\t\tomitted: {\n\t\t\truntime: omittedCount(\"runtime\"),\n\t\t\tconfigured: omittedCount(\"configured\"),\n\t\t\teffective: omittedCount(\"effective\"),\n\t\t},\n\t};\n}\n\nfunction sanitizeRuntimeAcknowledgedExtensions(value: unknown): RuntimeAcknowledgedChildExtensionsV1 | undefined {\n\tif (!value || typeof value !== \"object\") return undefined;\n\tconst raw = value as Record<string, unknown>;\n\tif (raw.version !== 1 || raw.source !== \"child-runtime\" || !Array.isArray(raw.ids)) return undefined;\n\tconst ids: string[] = [];\n\tconst seen = new Set<string>();\n\tfor (const item of raw.ids) {\n\t\tif (\n\t\t\ttypeof item !== \"string\" ||\n\t\t\titem.length === 0 ||\n\t\t\titem.length > 128 ||\n\t\t\t!/^[A-Za-z0-9._:@+-]+$/.test(item) ||\n\t\t\titem.includes(\"..\") ||\n\t\t\titem.includes(\"/\") ||\n\t\t\titem.includes(\"\\\\\") ||\n\t\t\tseen.has(item)\n\t\t)\n\t\t\tcontinue;\n\t\tseen.add(item);\n\t\tids.push(item);\n\t}\n\tif (ids.length === 0) return undefined;\n\treturn {\n\t\tversion: 1,\n\t\tsource: \"child-runtime\",\n\t\tids: ids.slice(0, 32),\n\t\tomitted: Math.max(0, ids.length - 32) + Math.max(0, Math.floor(clampNumber(raw.omitted) ?? 0)),\n\t};\n}\n\nfunction runtimeAcknowledgedEntry(\n\tvalue: unknown,\n): { runtimeAcknowledgedExtensions: RuntimeAcknowledgedChildExtensionsV1 } | Record<string, never> {\n\tconst sanitized = sanitizeRuntimeAcknowledgedExtensions(value);\n\treturn sanitized ? { runtimeAcknowledgedExtensions: sanitized } : {};\n}\n\nfunction sanitizeTurnBudget(value: unknown): TurnBudgetState | undefined {\n\tif (!value || typeof value !== \"object\") return undefined;\n\tconst raw = value as Record<string, unknown>;\n\tconst maxTurns = clampNumber(raw.maxTurns);\n\tconst graceTurns = clampNumber(raw.graceTurns);\n\tconst turnCount = clampNumber(raw.turnCount);\n\tconst outcome =\n\t\traw.outcome === \"within-budget\" ||\n\t\traw.outcome === \"wrap-up-requested\" ||\n\t\traw.outcome === \"termination-deferred\" ||\n\t\traw.outcome === \"exceeded\"\n\t\t\t? raw.outcome\n\t\t\t: undefined;\n\tif (maxTurns === undefined || graceTurns === undefined || turnCount === undefined || !outcome) return undefined;\n\treturn {\n\t\tmaxTurns,\n\t\tgraceTurns,\n\t\tturnCount,\n\t\toutcome,\n\t\t...(clampNumber(raw.wrapUpRequestedAtTurn) !== undefined\n\t\t\t? { wrapUpRequestedAtTurn: clampNumber(raw.wrapUpRequestedAtTurn) }\n\t\t\t: {}),\n\t\t...(clampNumber(raw.terminationDeferredAtTurn) !== undefined\n\t\t\t? { terminationDeferredAtTurn: clampNumber(raw.terminationDeferredAtTurn) }\n\t\t\t: {}),\n\t\t...(clampNumber(raw.exceededAtTurn) !== undefined ? { exceededAtTurn: clampNumber(raw.exceededAtTurn) } : {}),\n\t};\n}\n\nfunction sanitizeState(value: unknown, fallback: NestedRunState): NestedRunState {\n\treturn value === \"queued\" ||\n\t\tvalue === \"running\" ||\n\t\tvalue === \"complete\" ||\n\t\tvalue === \"failed\" ||\n\t\tvalue === \"paused\" ||\n\t\tvalue === \"stopped\"\n\t\t? value\n\t\t: fallback;\n}\n\nfunction sanitizeStep(input: unknown, depth: number): NestedStepSummary | undefined {\n\tif (!input || typeof input !== \"object\") return undefined;\n\tconst raw = input as Record<string, unknown>;\n\tconst agent = stringValue(raw.agent, 128);\n\tif (!agent) return undefined;\n\tconst status =\n\t\traw.status === \"pending\" ||\n\t\traw.status === \"running\" ||\n\t\traw.status === \"complete\" ||\n\t\traw.status === \"completed\" ||\n\t\traw.status === \"failed\" ||\n\t\traw.status === \"paused\" ||\n\t\traw.status === \"stopped\"\n\t\t\t? raw.status\n\t\t\t: \"pending\";\n\tconst model = stringValue(raw.model);\n\tconst thinking = THINKING_LEVELS.find((level) => level === raw.thinking);\n\treturn {\n\t\tagent,\n\t\tstatus,\n\t\t...(model ? { model } : {}),\n\t\t...(thinking ? { thinking } : {}),\n\t\t...(stringValue(raw.sessionFile, 2048) ? { sessionFile: stringValue(raw.sessionFile, 2048) } : {}),\n\t\t...(raw.activityState === \"active_long_running\" || raw.activityState === \"needs_attention\"\n\t\t\t? { activityState: raw.activityState }\n\t\t\t: {}),\n\t\t...(clampNumber(raw.lastActivityAt) !== undefined ? { lastActivityAt: clampNumber(raw.lastActivityAt) } : {}),\n\t\t...(stringValue(raw.currentTool, 128) ? { currentTool: stringValue(raw.currentTool, 128) } : {}),\n\t\t...(clampNumber(raw.currentToolStartedAt) !== undefined\n\t\t\t? { currentToolStartedAt: clampNumber(raw.currentToolStartedAt) }\n\t\t\t: {}),\n\t\t...(stringValue(raw.currentPath, 2048) ? { currentPath: stringValue(raw.currentPath, 2048) } : {}),\n\t\t...(clampNumber(raw.turnCount) !== undefined ? { turnCount: clampNumber(raw.turnCount) } : {}),\n\t\t...(clampNumber(raw.toolCount) !== undefined ? { toolCount: clampNumber(raw.toolCount) } : {}),\n\t\t...(clampNumber(raw.startedAt) !== undefined ? { startedAt: clampNumber(raw.startedAt) } : {}),\n\t\t...(clampNumber(raw.endedAt) !== undefined ? { endedAt: clampNumber(raw.endedAt) } : {}),\n\t\t...(stringValue(raw.error, 1024) ? { error: stringValue(raw.error, 1024) } : {}),\n\t\t...(raw.timedOut === true ? { timedOut: true } : {}),\n\t\t...(raw.stopped === true ? { stopped: true } : {}),\n\t\t...(sanitizeTurnBudget(raw.turnBudget) ? { turnBudget: sanitizeTurnBudget(raw.turnBudget) } : {}),\n\t\t...(raw.turnBudgetExceeded === true ? { turnBudgetExceeded: true } : {}),\n\t\t...(raw.wrapUpRequested === true ? { wrapUpRequested: true } : {}),\n\t\t...(sanitizeLaunchResolvedExtensions(raw.launchResolvedExtensions)\n\t\t\t? { launchResolvedExtensions: sanitizeLaunchResolvedExtensions(raw.launchResolvedExtensions) }\n\t\t\t: {}),\n\t\t...(sanitizeRuntimeAcknowledgedExtensions(raw.runtimeAcknowledgedExtensions)\n\t\t\t? { runtimeAcknowledgedExtensions: sanitizeRuntimeAcknowledgedExtensions(raw.runtimeAcknowledgedExtensions) }\n\t\t\t: {}),\n\t\t...(depth < MAX_DEPTH && Array.isArray(raw.children)\n\t\t\t? {\n\t\t\t\t\tchildren: raw.children\n\t\t\t\t\t\t.map((child) => sanitizeSummary(child, depth + 1))\n\t\t\t\t\t\t.filter((child): child is NestedRunSummary => Boolean(child))\n\t\t\t\t\t\t.slice(0, MAX_CHILDREN),\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\nexport function sanitizeSummary(input: unknown, depth = 0): NestedRunSummary | undefined {\n\tif (!input || typeof input !== \"object\") return undefined;\n\tconst raw = input as Record<string, unknown>;\n\tif (!isSafeNestedId(raw.id) || !isSafeNestedId(raw.parentRunId)) return undefined;\n\tconst pathParts = sanitizeNestedPath(raw.path);\n\tconst steps = Array.isArray(raw.steps)\n\t\t? raw.steps\n\t\t\t\t.map((step) => sanitizeStep(step, depth + 1))\n\t\t\t\t.filter((step): step is NestedStepSummary => Boolean(step))\n\t\t\t\t.slice(0, MAX_STEPS)\n\t\t: undefined;\n\tconst totalTokens = sanitizeTokenUsage(raw.totalTokens);\n\tconst totalCost = sanitizeCost(raw.totalCost);\n\treturn {\n\t\tid: raw.id,\n\t\tparentRunId: raw.parentRunId,\n\t\t...(clampNumber(raw.parentStepIndex) !== undefined ? { parentStepIndex: clampNumber(raw.parentStepIndex) } : {}),\n\t\t...(stringValue(raw.parentAgent, 128) ? { parentAgent: stringValue(raw.parentAgent, 128) } : {}),\n\t\tdepth: Math.min(Math.max(0, clampNumber(raw.depth) ?? 0), MAX_DEPTH),\n\t\tpath: pathParts,\n\t\tstate: sanitizeState(raw.state, \"running\"),\n\t\t...(stringValue(raw.model) ? { model: stringValue(raw.model) } : {}),\n\t\t...(THINKING_LEVELS.find((level) => level === raw.thinking)\n\t\t\t? { thinking: THINKING_LEVELS.find((level) => level === raw.thinking) }\n\t\t\t: {}),\n\t\t...(stringValue(raw.asyncDir, 2048) ? { asyncDir: stringValue(raw.asyncDir, 2048) } : {}),\n\t\t...(clampNumber(raw.pid) !== undefined && clampNumber(raw.pid)! > 0 && Number.isInteger(clampNumber(raw.pid))\n\t\t\t? { pid: clampNumber(raw.pid) }\n\t\t\t: {}),\n\t\t...(stringValue(raw.sessionId, 256) ? { sessionId: stringValue(raw.sessionId, 256) } : {}),\n\t\t...(stringValue(raw.sessionFile, 2048) ? { sessionFile: stringValue(raw.sessionFile, 2048) } : {}),\n\t\t...(stringValue(raw.intercomTarget, 256) ? { intercomTarget: stringValue(raw.intercomTarget, 256) } : {}),\n\t\t...(stringValue(raw.ownerIntercomTarget, 256)\n\t\t\t? { ownerIntercomTarget: stringValue(raw.ownerIntercomTarget, 256) }\n\t\t\t: {}),\n\t\t...(stringValue(raw.leafIntercomTarget, 256)\n\t\t\t? { leafIntercomTarget: stringValue(raw.leafIntercomTarget, 256) }\n\t\t\t: {}),\n\t\t...(raw.ownerState === \"live\" || raw.ownerState === \"gone\" || raw.ownerState === \"unknown\"\n\t\t\t? { ownerState: raw.ownerState }\n\t\t\t: {}),\n\t\t...(stringValue(raw.controlInbox, 2048) ? { controlInbox: stringValue(raw.controlInbox, 2048) } : {}),\n\t\t...(stringValue(raw.capabilityToken, 128) ? { capabilityToken: stringValue(raw.capabilityToken, 128) } : {}),\n\t\t...(raw.mode === \"single\" || raw.mode === \"parallel\" || raw.mode === \"chain\" ? { mode: raw.mode } : {}),\n\t\t...(stringValue(raw.agent, 128) ? { agent: stringValue(raw.agent, 128) } : {}),\n\t\t...(Array.isArray(raw.agents)\n\t\t\t? {\n\t\t\t\t\tagents: raw.agents\n\t\t\t\t\t\t.map((agent) => stringValue(agent, 128))\n\t\t\t\t\t\t.filter((agent): agent is string => Boolean(agent))\n\t\t\t\t\t\t.slice(0, MAX_STEPS),\n\t\t\t\t}\n\t\t\t: {}),\n\t\t...(clampNumber(raw.currentStep) !== undefined ? { currentStep: clampNumber(raw.currentStep) } : {}),\n\t\t...(clampNumber(raw.chainStepCount) !== undefined ? { chainStepCount: clampNumber(raw.chainStepCount) } : {}),\n\t\t...(raw.activityState === \"active_long_running\" || raw.activityState === \"needs_attention\"\n\t\t\t? { activityState: raw.activityState }\n\t\t\t: {}),\n\t\t...(clampNumber(raw.lastActivityAt) !== undefined ? { lastActivityAt: clampNumber(raw.lastActivityAt) } : {}),\n\t\t...(stringValue(raw.currentTool, 128) ? { currentTool: stringValue(raw.currentTool, 128) } : {}),\n\t\t...(clampNumber(raw.currentToolStartedAt) !== undefined\n\t\t\t? { currentToolStartedAt: clampNumber(raw.currentToolStartedAt) }\n\t\t\t: {}),\n\t\t...(stringValue(raw.currentPath, 2048) ? { currentPath: stringValue(raw.currentPath, 2048) } : {}),\n\t\t...(clampNumber(raw.turnCount) !== undefined ? { turnCount: clampNumber(raw.turnCount) } : {}),\n\t\t...(clampNumber(raw.toolCount) !== undefined ? { toolCount: clampNumber(raw.toolCount) } : {}),\n\t\t...(totalTokens ? { totalTokens } : {}),\n\t\t...(totalCost ? { totalCost } : {}),\n\t\t...(clampNumber(raw.startedAt) !== undefined ? { startedAt: clampNumber(raw.startedAt) } : {}),\n\t\t...(clampNumber(raw.endedAt) !== undefined ? { endedAt: clampNumber(raw.endedAt) } : {}),\n\t\t...(clampNumber(raw.lastUpdate) !== undefined ? { lastUpdate: clampNumber(raw.lastUpdate) } : {}),\n\t\t...(clampNumber(raw.timeoutMs) !== undefined ? { timeoutMs: clampNumber(raw.timeoutMs) } : {}),\n\t\t...(clampNumber(raw.deadlineAt) !== undefined ? { deadlineAt: clampNumber(raw.deadlineAt) } : {}),\n\t\t...(raw.timedOut === true ? { timedOut: true } : {}),\n\t\t...(raw.stopped === true ? { stopped: true } : {}),\n\t\t...(sanitizeTurnBudget(raw.turnBudget) ? { turnBudget: sanitizeTurnBudget(raw.turnBudget) } : {}),\n\t\t...(raw.turnBudgetExceeded === true ? { turnBudgetExceeded: true } : {}),\n\t\t...(raw.wrapUpRequested === true ? { wrapUpRequested: true } : {}),\n\t\t...(stringValue(raw.error, 1024) ? { error: stringValue(raw.error, 1024) } : {}),\n\t\t...(sanitizeLaunchResolvedExtensions(raw.launchResolvedExtensions)\n\t\t\t? { launchResolvedExtensions: sanitizeLaunchResolvedExtensions(raw.launchResolvedExtensions) }\n\t\t\t: {}),\n\t\t...(sanitizeRuntimeAcknowledgedExtensions(raw.runtimeAcknowledgedExtensions)\n\t\t\t? { runtimeAcknowledgedExtensions: sanitizeRuntimeAcknowledgedExtensions(raw.runtimeAcknowledgedExtensions) }\n\t\t\t: {}),\n\t\t...(steps && steps.length > 0 ? { steps } : {}),\n\t\t...(depth < MAX_DEPTH && Array.isArray(raw.children)\n\t\t\t? {\n\t\t\t\t\tchildren: raw.children\n\t\t\t\t\t\t.map((child) => sanitizeSummary(child, depth + 1))\n\t\t\t\t\t\t.filter((child): child is NestedRunSummary => Boolean(child))\n\t\t\t\t\t\t.slice(0, MAX_CHILDREN),\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\nfunction parseRecord(content: string, route: NestedRoute): NestedEventRecord | undefined {\n\tif (Buffer.byteLength(content, \"utf-8\") > MAX_EVENT_BYTES) return undefined;\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(content);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (!parsed || typeof parsed !== \"object\") return undefined;\n\tconst raw = parsed as Record<string, unknown>;\n\tif (\n\t\traw.type !== \"subagent.nested.started\" &&\n\t\traw.type !== \"subagent.nested.updated\" &&\n\t\traw.type !== \"subagent.nested.completed\"\n\t)\n\t\treturn undefined;\n\tif (raw.rootRunId !== route.rootRunId || raw.capabilityToken !== route.capabilityToken) return undefined;\n\tif (!isSafeNestedId(raw.parentRunId)) return undefined;\n\tconst ts = clampNumber(raw.ts);\n\tif (ts === undefined) return undefined;\n\tconst child = sanitizeSummary(raw.child);\n\tif (!child || child.id === route.rootRunId) return undefined;\n\tconst routedChild: NestedRunSummary = {\n\t\t...child,\n\t\tcontrolInbox: route.controlInbox,\n\t\tcapabilityToken: route.capabilityToken,\n\t\townerState: child.ownerState ?? \"unknown\",\n\t};\n\treturn {\n\t\ttype: raw.type,\n\t\tts,\n\t\trootRunId: route.rootRunId,\n\t\tparentRunId: raw.parentRunId,\n\t\t...(clampNumber(raw.parentStepIndex) !== undefined ? { parentStepIndex: clampNumber(raw.parentStepIndex) } : {}),\n\t\tcapabilityToken: route.capabilityToken,\n\t\tchild: routedChild,\n\t};\n}\n\nexport function parseNestedEventRecords(content: string, route: NestedRoute): NestedEventRecord[] {\n\tif (!content.includes(\"\\n\")) {\n\t\tconst record = parseRecord(content.trim(), route);\n\t\treturn record ? [record] : [];\n\t}\n\treturn content\n\t\t.split(\"\\n\")\n\t\t.slice(0, content.endsWith(\"\\n\") ? undefined : -1)\n\t\t.map((line) => (line.trim() ? parseRecord(line, route) : undefined))\n\t\t.filter((event): event is NestedEventRecord => Boolean(event));\n}\n\nfunction terminal(state: NestedRunState): boolean {\n\treturn state === \"complete\" || state === \"failed\" || state === \"paused\" || state === \"stopped\";\n}\n\nfunction mergeBoundedChildren(\n\texisting: NestedRunSummary[] | undefined,\n\tincoming: NestedRunSummary[] | undefined,\n): NestedRunSummary[] | undefined {\n\tif (incoming === undefined) return existing?.slice(0, MAX_CHILDREN);\n\tconst incomingById = new Map(incoming.map((child) => [child.id, child]));\n\tconst merged = (existing ?? []).map((child) => incomingById.get(child.id) ?? child);\n\tfor (const child of incoming) {\n\t\tif (!existing?.some((prior) => prior.id === child.id)) merged.push(child);\n\t}\n\treturn merged.slice(0, MAX_CHILDREN);\n}\n\nfunction mergeStepSummary(existing: NestedStepSummary | undefined, incoming: NestedStepSummary): NestedStepSummary {\n\tif (!existing || existing.agent !== incoming.agent)\n\t\treturn { ...incoming, ...(incoming.children ? { children: incoming.children.slice(0, MAX_CHILDREN) } : {}) };\n\tconst metadata = { ...existing } as Partial<NestedStepSummary>;\n\tdelete metadata.status;\n\tdelete metadata.activityState;\n\tdelete metadata.lastActivityAt;\n\tdelete metadata.currentTool;\n\tdelete metadata.currentToolStartedAt;\n\tdelete metadata.currentPath;\n\tdelete metadata.turnCount;\n\tdelete metadata.toolCount;\n\tdelete metadata.children;\n\tconst children = mergeBoundedChildren(existing.children, incoming.children);\n\treturn {\n\t\t...metadata,\n\t\t...incoming,\n\t\t...(children ? { children } : {}),\n\t};\n}\n\nfunction mergeSummary(existing: NestedRunSummary | undefined, event: NestedEventRecord): NestedRunSummary {\n\tconst incomingState =\n\t\tevent.type === \"subagent.nested.completed\" && event.child.state === \"running\" ? \"complete\" : event.child.state;\n\tconst incoming = { ...event.child, state: incomingState, lastUpdate: event.child.lastUpdate ?? event.ts };\n\tif (!existing) return incoming;\n\tconst existingUpdate = existing.lastUpdate ?? 0;\n\tconst incomingUpdate = incoming.lastUpdate ?? event.ts;\n\tif (incomingUpdate < existingUpdate) return existing;\n\tif (terminal(existing.state) && !terminal(incoming.state)) return existing;\n\tif (terminal(existing.state) && terminal(incoming.state) && incomingUpdate === existingUpdate) return existing;\n\tconst existingSteps = existing.steps ?? [];\n\tconst incomingSteps = incoming.steps;\n\tconst steps =\n\t\tincomingSteps === undefined\n\t\t\t? existing.steps\n\t\t\t: Array.from(\n\t\t\t\t\t{ length: Math.min(MAX_STEPS, Math.max(existingSteps.length, incomingSteps.length)) },\n\t\t\t\t\t(_, index) =>\n\t\t\t\t\t\tincomingSteps[index]\n\t\t\t\t\t\t\t? mergeStepSummary(existingSteps[index], incomingSteps[index]!)\n\t\t\t\t\t\t\t: existingSteps[index]!,\n\t\t\t\t).filter((step): step is NestedStepSummary => Boolean(step));\n\tconst children = mergeBoundedChildren(existing.children, incoming.children);\n\treturn {\n\t\t...existing,\n\t\t...incoming,\n\t\t...(steps ? { steps } : {}),\n\t\t...(children ? { children } : {}),\n\t\tstate: incoming.state,\n\t\tlastUpdate: Math.max(existingUpdate, incomingUpdate),\n\t};\n}\n\nfunction attachChild(children: NestedRunSummary[], event: NestedEventRecord): NestedRunSummary[] {\n\tlet updated = false;\n\tconst walk = (items: NestedRunSummary[]): NestedRunSummary[] =>\n\t\titems.map((item) => {\n\t\t\tif (item.id === event.parentRunId) {\n\t\t\t\tconst existingChildren = item.children ?? [];\n\t\t\t\tconst childIndex = existingChildren.findIndex((child) => child.id === event.child.id);\n\t\t\t\tconst nextChild = mergeSummary(childIndex >= 0 ? existingChildren[childIndex] : undefined, event);\n\t\t\t\tconst nextChildren =\n\t\t\t\t\tchildIndex >= 0\n\t\t\t\t\t\t? existingChildren.map((child, index) => (index === childIndex ? nextChild : child))\n\t\t\t\t\t\t: [...existingChildren, nextChild];\n\t\t\t\tupdated = true;\n\t\t\t\treturn {\n\t\t\t\t\t...item,\n\t\t\t\t\tchildren: nextChildren.slice(0, MAX_CHILDREN),\n\t\t\t\t\tlastUpdate: Math.max(item.lastUpdate ?? 0, event.ts),\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!item.children?.length) return item;\n\t\t\tconst nextChildren = walk(item.children);\n\t\t\treturn nextChildren === item.children ? item : { ...item, children: nextChildren };\n\t\t});\n\tconst next = walk(children);\n\tif (updated) return next;\n\tconst childIndex = next.findIndex((child) => child.id === event.child.id);\n\tconst nextChild = mergeSummary(childIndex >= 0 ? next[childIndex] : undefined, event);\n\treturn childIndex >= 0\n\t\t? next.map((child, index) => (index === childIndex ? nextChild : child))\n\t\t: [...next, nextChild].slice(0, MAX_CHILDREN);\n}\n\nexport function applyNestedEvent(registry: NestedRegistry, event: NestedEventRecord): NestedRegistry {\n\treturn {\n\t\t...registry,\n\t\tupdatedAt: Math.max(registry.updatedAt, event.ts),\n\t\tchildren: attachChild(registry.children, event),\n\t};\n}\n\nfunction registryPath(route: NestedRoute): string {\n\treturn path.join(commonRouteRoot(route), REGISTRY_FILE);\n}\n\nexport function findNestedRouteForRootId(rootRunId: string): NestedRoute | undefined {\n\tassertSafeId(\"rootRunId\", rootRunId);\n\tlet entries: string[];\n\ttry {\n\t\tentries = fs.readdirSync(NESTED_EVENTS_DIR);\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n\t\tthrow error;\n\t}\n\tfor (const entry of entries) {\n\t\tif (!entry.startsWith(`${rootRunId}-`)) continue;\n\t\tconst routeRoot = path.join(NESTED_EVENTS_DIR, entry);\n\t\ttry {\n\t\t\tconst metadata = JSON.parse(fs.readFileSync(path.join(routeRoot, ROUTE_FILE), \"utf-8\")) as {\n\t\t\t\trootRunId?: unknown;\n\t\t\t\tcapabilityToken?: unknown;\n\t\t\t};\n\t\t\tif (metadata.rootRunId !== rootRunId || typeof metadata.capabilityToken !== \"string\") continue;\n\t\t\tconst route = {\n\t\t\t\trootRunId,\n\t\t\t\teventSink: path.join(routeRoot, \"events\"),\n\t\t\t\tcontrolInbox: path.join(routeRoot, \"controls\"),\n\t\t\t\tcapabilityToken: metadata.capabilityToken,\n\t\t\t};\n\t\t\tvalidateRouteShape(route);\n\t\t\treturn route;\n\t\t} catch {}\n\t}\n\treturn undefined;\n}\n\n/**\n * Scan the nested-events directory once and index every route by its root run\n * id. Use this when resolving routes for many runs (e.g. listAsyncRuns) so the\n * cost is O(routes) total instead of O(runs * routes) from calling\n * findNestedRouteForRootId per run.\n */\nexport function buildNestedRouteIndex(): Map<string, NestedRoute> {\n\tlet entries: string[];\n\ttry {\n\t\tentries = fs.readdirSync(NESTED_EVENTS_DIR);\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return new Map();\n\t\tthrow error;\n\t}\n\tconst index = new Map<string, NestedRoute>();\n\tfor (const entry of entries) {\n\t\tconst routeRoot = path.join(NESTED_EVENTS_DIR, entry);\n\t\ttry {\n\t\t\tconst metadata = JSON.parse(fs.readFileSync(path.join(routeRoot, ROUTE_FILE), \"utf-8\")) as {\n\t\t\t\trootRunId?: unknown;\n\t\t\t\tcapabilityToken?: unknown;\n\t\t\t};\n\t\t\tif (typeof metadata.rootRunId !== \"string\" || typeof metadata.capabilityToken !== \"string\") continue;\n\t\t\tif (index.has(metadata.rootRunId)) continue;\n\t\t\tconst route: NestedRoute = {\n\t\t\t\trootRunId: metadata.rootRunId,\n\t\t\t\teventSink: path.join(routeRoot, \"events\"),\n\t\t\t\tcontrolInbox: path.join(routeRoot, \"controls\"),\n\t\t\t\tcapabilityToken: metadata.capabilityToken,\n\t\t\t};\n\t\t\tvalidateRouteShape(route);\n\t\t\tindex.set(metadata.rootRunId, route);\n\t\t} catch {}\n\t}\n\treturn index;\n}\n\nexport function projectNestedRegistryForRoot(rootRunId: string): NestedRegistry | undefined {\n\tconst route = findNestedRouteForRootId(rootRunId);\n\treturn route ? projectNestedEvents(route) : undefined;\n}\n\nexport function findNestedRun(children: NestedRunSummary[] | undefined, id: string): NestedRunSummary | undefined {\n\tif (!children?.length) return undefined;\n\tfor (const child of children) {\n\t\tif (child.id === id) return child;\n\t\tconst nested =\n\t\t\tfindNestedRun(child.children, id) ??\n\t\t\tfindNestedRun(\n\t\t\t\tchild.steps?.flatMap((step) => step.children ?? []),\n\t\t\t\tid,\n\t\t\t);\n\t\tif (nested) return nested;\n\t}\n\treturn undefined;\n}\n\nexport interface NestedRunMatch {\n\trootRunId: string;\n\troute: NestedRoute;\n\trun: NestedRunSummary;\n}\n\nexport interface NestedRunResolutionScope {\n\troutes: NestedRoute[];\n\tdescendantOf?: { parentRunId: string; parentStepIndex?: number };\n}\n\nfunction collectNestedRuns(\n\tchildren: NestedRunSummary[] | undefined,\n\toutput: NestedRunSummary[] = [],\n): NestedRunSummary[] {\n\tfor (const child of children ?? []) {\n\t\toutput.push(child);\n\t\tcollectNestedRuns(child.children, output);\n\t\tcollectNestedRuns(\n\t\t\tchild.steps?.flatMap((step) => step.children ?? []),\n\t\t\toutput,\n\t\t);\n\t}\n\treturn output;\n}\n\nfunction collectScopedNestedRuns(\n\tchildren: NestedRunSummary[] | undefined,\n\tscope: NestedRunResolutionScope[\"descendantOf\"],\n\toutput: NestedRunSummary[] = [],\n): NestedRunSummary[] {\n\tif (!scope) return collectNestedRuns(children, output);\n\tfor (const child of children ?? []) {\n\t\tif (\n\t\t\tchild.parentRunId === scope.parentRunId &&\n\t\t\t(scope.parentStepIndex === undefined || child.parentStepIndex === scope.parentStepIndex)\n\t\t) {\n\t\t\tcollectNestedRuns([child], output);\n\t\t\tcontinue;\n\t\t}\n\t\tcollectScopedNestedRuns(child.children, scope, output);\n\t\tcollectScopedNestedRuns(\n\t\t\tchild.steps?.flatMap((step) => step.children ?? []),\n\t\t\tscope,\n\t\t\toutput,\n\t\t);\n\t}\n\treturn output;\n}\n\nfunction listNestedRoutes(): NestedRoute[] {\n\tlet entries: string[];\n\ttry {\n\t\tentries = fs.readdirSync(NESTED_EVENTS_DIR);\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\t\tthrow error;\n\t}\n\tconst routes: NestedRoute[] = [];\n\tfor (const entry of entries) {\n\t\tconst routeRoot = path.join(NESTED_EVENTS_DIR, entry);\n\t\ttry {\n\t\t\tconst metadata = JSON.parse(fs.readFileSync(path.join(routeRoot, ROUTE_FILE), \"utf-8\")) as {\n\t\t\t\trootRunId?: unknown;\n\t\t\t\tcapabilityToken?: unknown;\n\t\t\t};\n\t\t\tif (typeof metadata.rootRunId !== \"string\" || typeof metadata.capabilityToken !== \"string\") continue;\n\t\t\tconst route = {\n\t\t\t\trootRunId: metadata.rootRunId,\n\t\t\t\teventSink: path.join(routeRoot, \"events\"),\n\t\t\t\tcontrolInbox: path.join(routeRoot, \"controls\"),\n\t\t\t\tcapabilityToken: metadata.capabilityToken,\n\t\t\t};\n\t\t\tvalidateRouteShape(route);\n\t\t\troutes.push(route);\n\t\t} catch {}\n\t}\n\treturn routes;\n}\n\nexport function findNestedRunMatchesById(\n\tid: string,\n\toptions: { prefix?: boolean; scope?: NestedRunResolutionScope } = {},\n): NestedRunMatch[] {\n\tassertSafeId(\"id\", id);\n\tconst matches: NestedRunMatch[] = [];\n\tfor (const route of options.scope?.routes ?? listNestedRoutes()) {\n\t\ttry {\n\t\t\tconst registry = projectNestedEvents(route);\n\t\t\tfor (const run of collectScopedNestedRuns(registry.children, options.scope?.descendantOf)) {\n\t\t\t\tif (options.prefix ? run.id.startsWith(id) : run.id === id)\n\t\t\t\t\tmatches.push({ rootRunId: route.rootRunId, route, run });\n\t\t\t}\n\t\t} catch {}\n\t}\n\treturn matches;\n}\n\nexport function findNestedRunById(id: string): { rootRunId: string; run: NestedRunSummary } | undefined {\n\tconst match = findNestedRunMatchesById(id)[0];\n\treturn match ? { rootRunId: match.rootRunId, run: match.run } : undefined;\n}\n\nexport function readNestedRegistry(route: NestedRoute): NestedRegistry {\n\tvalidateRouteShape(route);\n\ttry {\n\t\tconst parsed = JSON.parse(fs.readFileSync(registryPath(route), \"utf-8\")) as NestedRegistry;\n\t\treturn {\n\t\t\trootRunId: route.rootRunId,\n\t\t\tupdatedAt: typeof parsed.updatedAt === \"number\" ? parsed.updatedAt : 0,\n\t\t\tchildren: Array.isArray(parsed.children)\n\t\t\t\t? parsed.children\n\t\t\t\t\t\t.map((child) => sanitizeSummary(child))\n\t\t\t\t\t\t.filter((child): child is NestedRunSummary => Boolean(child))\n\t\t\t\t: [],\n\t\t\tprocessedEvents: Array.isArray(parsed.processedEvents)\n\t\t\t\t? parsed.processedEvents.filter((item): item is string => typeof item === \"string\")\n\t\t\t\t: [],\n\t\t};\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t\treturn { rootRunId: route.rootRunId, updatedAt: 0, children: [], processedEvents: [] };\n\t}\n}\n\nexport function projectNestedEvents(route: NestedRoute): NestedRegistry {\n\tvalidateRouteShape(route);\n\tlet registry = readNestedRegistry(route);\n\tconst seen = new Set(registry.processedEvents);\n\tlet changed = false;\n\tlet entries: string[] = [];\n\ttry {\n\t\tentries = fs\n\t\t\t.readdirSync(route.eventSink)\n\t\t\t.filter((entry) => entry.endsWith(\".json\") || entry.endsWith(\".jsonl\"))\n\t\t\t.sort();\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t}\n\tfor (const entry of entries) {\n\t\tif (seen.has(entry)) continue;\n\t\tconst eventPath = path.join(route.eventSink, entry);\n\t\tif (!containedPath(route.eventSink, eventPath)) continue;\n\t\tlet content: string;\n\t\ttry {\n\t\t\tconst stat = fs.statSync(eventPath);\n\t\t\tif (!stat.isFile() || stat.size > MAX_EVENT_BYTES) continue;\n\t\t\tcontent = fs.readFileSync(eventPath, \"utf-8\");\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tconst records = parseNestedEventRecords(content, route);\n\t\tif (records.length === 0) continue;\n\t\tfor (const event of records) {\n\t\t\tregistry = applyNestedEvent(registry, event);\n\t\t\tchanged = true;\n\t\t}\n\t\tseen.add(entry);\n\t\tchanged = true;\n\t}\n\tif (changed) {\n\t\tconst processedEvents = [...seen];\n\t\tconst retainedEvents = processedEvents.slice(-1000);\n\t\tconst evictedEvents = processedEvents.slice(0, -1000);\n\t\tregistry = { ...registry, processedEvents: retainedEvents };\n\t\t// Parent projection is the only writer to this sidecar registry. Child and\n\t\t// runner processes only create immutable event files, so parent status.json\n\t\t// remains owned by the existing runner writer and is never rewritten here.\n\t\twriteAtomicJson(registryPath(route), registry);\n\n\t\t// The registry retains only a bounded filename cursor. Remove the old\n\t\t// immutable status records after the cursor is durable; otherwise an evicted\n\t\t// filename is rediscovered on the next projection and replayed forever.\n\t\tfor (const entry of evictedEvents) {\n\t\t\tconst eventPath = path.join(route.eventSink, entry);\n\t\t\tif (!containedPath(route.eventSink, eventPath)) continue;\n\t\t\ttry {\n\t\t\t\tconst stat = fs.statSync(eventPath);\n\t\t\t\tif (!stat.isFile() || stat.size > MAX_EVENT_BYTES) continue;\n\t\t\t\tconst content = fs.readFileSync(eventPath, \"utf-8\");\n\t\t\t\tconst hasStatusRecord = parseNestedEventRecords(content, route).length > 0;\n\t\t\t\tconst hasControlResult = content\n\t\t\t\t\t.split(\"\\n\")\n\t\t\t\t\t.some((line) => line.trim() && parseControlResult(line.trim(), route));\n\t\t\t\tif (hasStatusRecord && !hasControlResult) fs.unlinkSync(eventPath);\n\t\t\t} catch {\n\t\t\t\t// A cleanup failure must not make a successfully projected status fail.\n\t\t\t}\n\t\t}\n\t}\n\treturn registry;\n}\n\nfunction writeRouteRecord(dir: string, ts: number, payload: object): string {\n\tconst content = `${JSON.stringify(payload)}\\n`;\n\tif (Buffer.byteLength(content, \"utf-8\") > MAX_EVENT_BYTES)\n\t\tthrow new Error(\"Nested route record exceeds the maximum size.\");\n\tfs.mkdirSync(dir, { recursive: true, mode: 0o700 });\n\tconst name = `${String(ts).padStart(13, \"0\")}-${randomUUID()}.json`;\n\tconst tmp = path.join(dir, `.${name}.tmp`);\n\tconst finalPath = path.join(dir, name);\n\tfs.writeFileSync(tmp, content, { mode: 0o600 });\n\tfs.renameSync(tmp, finalPath);\n\treturn finalPath;\n}\n\nexport function writeNestedEvent(\n\troute: NestedRoute,\n\tevent: Omit<NestedEventRecord, \"rootRunId\" | \"capabilityToken\">,\n): void {\n\tvalidateRouteShape(route);\n\tconst record: NestedEventRecord = {\n\t\t...event,\n\t\trootRunId: route.rootRunId,\n\t\tcapabilityToken: route.capabilityToken,\n\t};\n\tconst sanitized = parseRecord(JSON.stringify(record), route);\n\tif (!sanitized) throw new Error(\"Nested event record failed validation.\");\n\twriteRouteRecord(route.eventSink, sanitized.ts, sanitized);\n}\n\nfunction parseControlRequest(content: string, route: NestedRoute): NestedControlRequestRecord | undefined {\n\tif (Buffer.byteLength(content, \"utf-8\") > MAX_EVENT_BYTES) return undefined;\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(content);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (!parsed || typeof parsed !== \"object\") return undefined;\n\tconst raw = parsed as Record<string, unknown>;\n\tif (raw.type !== \"subagent.nested.control-request\") return undefined;\n\tif (raw.rootRunId !== route.rootRunId || raw.capabilityToken !== route.capabilityToken) return undefined;\n\tif (!isSafeNestedId(raw.requestId) || !isSafeNestedId(raw.targetRunId)) return undefined;\n\tif (raw.action !== \"interrupt\" && raw.action !== \"resume\") return undefined;\n\tconst ts = clampNumber(raw.ts);\n\tif (ts === undefined) return undefined;\n\treturn {\n\t\ttype: \"subagent.nested.control-request\",\n\t\tts,\n\t\trootRunId: route.rootRunId,\n\t\tcapabilityToken: route.capabilityToken,\n\t\trequestId: raw.requestId,\n\t\ttargetRunId: raw.targetRunId,\n\t\taction: raw.action,\n\t\t...(stringValue(raw.message, 16_000) ? { message: stringValue(raw.message, 16_000) } : {}),\n\t};\n}\n\nfunction parseControlResult(content: string, route: NestedRoute): NestedControlResultRecord | undefined {\n\tif (Buffer.byteLength(content, \"utf-8\") > MAX_EVENT_BYTES) return undefined;\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(content);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (!parsed || typeof parsed !== \"object\") return undefined;\n\tconst raw = parsed as Record<string, unknown>;\n\tif (raw.type !== \"subagent.nested.control-result\") return undefined;\n\tif (raw.rootRunId !== route.rootRunId || raw.capabilityToken !== route.capabilityToken) return undefined;\n\tif (!isSafeNestedId(raw.requestId) || !isSafeNestedId(raw.targetRunId)) return undefined;\n\tconst ts = clampNumber(raw.ts);\n\tif (ts === undefined || typeof raw.ok !== \"boolean\") return undefined;\n\treturn {\n\t\ttype: \"subagent.nested.control-result\",\n\t\tts,\n\t\trootRunId: route.rootRunId,\n\t\tcapabilityToken: route.capabilityToken,\n\t\trequestId: raw.requestId,\n\t\ttargetRunId: raw.targetRunId,\n\t\tok: raw.ok,\n\t\tmessage: stringValue(raw.message, 16_000) ?? (raw.ok ? \"Control request completed.\" : \"Control request failed.\"),\n\t};\n}\n\nexport function writeNestedControlRequest(\n\troute: NestedRoute,\n\trequest: Omit<NestedControlRequestRecord, \"type\" | \"rootRunId\" | \"capabilityToken\">,\n): string {\n\tvalidateRouteShape(route);\n\tassertSafeId(\"requestId\", request.requestId);\n\tassertSafeId(\"targetRunId\", request.targetRunId);\n\tconst record: NestedControlRequestRecord = {\n\t\ttype: \"subagent.nested.control-request\",\n\t\t...request,\n\t\trootRunId: route.rootRunId,\n\t\tcapabilityToken: route.capabilityToken,\n\t};\n\tconst sanitized = parseControlRequest(JSON.stringify(record), route);\n\tif (!sanitized) throw new Error(\"Nested control request failed validation.\");\n\treturn writeRouteRecord(route.controlInbox, sanitized.ts, sanitized);\n}\n\nexport function readNestedControlRequests(\n\troute: NestedRoute,\n): Array<NestedControlRequestRecord & { filePath: string }> {\n\tvalidateRouteShape(route);\n\tlet entries: string[] = [];\n\ttry {\n\t\tentries = fs\n\t\t\t.readdirSync(route.controlInbox)\n\t\t\t.filter((entry) => entry.endsWith(\".json\"))\n\t\t\t.sort();\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t}\n\tconst requests: Array<NestedControlRequestRecord & { filePath: string }> = [];\n\tfor (const entry of entries) {\n\t\tconst filePath = path.join(route.controlInbox, entry);\n\t\tif (!containedPath(route.controlInbox, filePath)) continue;\n\t\ttry {\n\t\t\tconst stat = fs.statSync(filePath);\n\t\t\tif (!stat.isFile() || stat.size > MAX_EVENT_BYTES) continue;\n\t\t\tconst request = parseControlRequest(fs.readFileSync(filePath, \"utf-8\"), route);\n\t\t\tif (request) requests.push({ ...request, filePath });\n\t\t} catch {}\n\t}\n\treturn requests;\n}\n\nexport function writeNestedControlResult(\n\troute: NestedRoute,\n\tresult: Omit<NestedControlResultRecord, \"type\" | \"rootRunId\" | \"capabilityToken\">,\n): void {\n\tvalidateRouteShape(route);\n\tassertSafeId(\"requestId\", result.requestId);\n\tassertSafeId(\"targetRunId\", result.targetRunId);\n\tconst record: NestedControlResultRecord = {\n\t\ttype: \"subagent.nested.control-result\",\n\t\t...result,\n\t\trootRunId: route.rootRunId,\n\t\tcapabilityToken: route.capabilityToken,\n\t};\n\tconst sanitized = parseControlResult(JSON.stringify(record), route);\n\tif (!sanitized) throw new Error(\"Nested control result failed validation.\");\n\twriteRouteRecord(route.eventSink, sanitized.ts, sanitized);\n}\n\nfunction readControlResultsFromFile(route: NestedRoute, eventPath: string): NestedControlResultRecord[] {\n\tif (!containedPath(route.eventSink, eventPath)) return [];\n\ttry {\n\t\tconst stat = fs.statSync(eventPath);\n\t\tif (!stat.isFile() || stat.size > MAX_EVENT_BYTES) return [];\n\t\tconst content = fs.readFileSync(eventPath, \"utf-8\");\n\t\tconst lines = content.includes(\"\\n\") ? content.split(\"\\n\").filter((line) => line.trim()) : [content];\n\t\treturn lines\n\t\t\t.map((line) => parseControlResult(line, route))\n\t\t\t.filter((result): result is NestedControlResultRecord => Boolean(result));\n\t} catch {\n\t\treturn [];\n\t}\n}\n\nfunction listNestedEventFiles(route: NestedRoute): string[] {\n\tvalidateRouteShape(route);\n\ttry {\n\t\treturn fs.readdirSync(route.eventSink).filter((entry) => entry.endsWith(\".json\") || entry.endsWith(\".jsonl\"));\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\t\tthrow error;\n\t}\n}\n\nexport function snapshotNestedEventFiles(route: NestedRoute): Set<string> {\n\treturn new Set(listNestedEventFiles(route));\n}\n\nexport function findNestedControlResult(\n\troute: NestedRoute,\n\trequestId: string,\n\ttargetRunId: string,\n\tignoredFiles: ReadonlySet<string>,\n): NestedControlResultRecord | undefined {\n\tconst entries = listNestedEventFiles(route)\n\t\t.filter((entry) => !ignoredFiles.has(entry))\n\t\t.sort()\n\t\t.reverse();\n\tfor (const entry of entries) {\n\t\tconst result = readControlResultsFromFile(route, path.join(route.eventSink, entry)).find(\n\t\t\t(candidate) => candidate.requestId === requestId && candidate.targetRunId === targetRunId,\n\t\t);\n\t\tif (result) return result;\n\t}\n\treturn undefined;\n}\n\nexport function readNestedControlResults(route: NestedRoute): NestedControlResultRecord[] {\n\treturn listNestedEventFiles(route)\n\t\t.sort()\n\t\t.flatMap((entry) => readControlResultsFromFile(route, path.join(route.eventSink, entry)));\n}\n\nexport function nestedRouteEnv(route: NestedRoute): Record<string, string> {\n\treturn {\n\t\t[SUBAGENT_PARENT_EVENT_SINK_ENV]: route.eventSink,\n\t\t[SUBAGENT_PARENT_CONTROL_INBOX_ENV]: route.controlInbox,\n\t\t[SUBAGENT_PARENT_ROOT_RUN_ID_ENV]: route.rootRunId,\n\t\t[SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV]: route.capabilityToken,\n\t};\n}\n\nexport function attachRootChildrenToSteps<T extends { children?: NestedRunSummary[]; index?: number }>(\n\trootRunId: string,\n\tsteps: T[] | undefined,\n\tchildren: NestedRunSummary[] | undefined,\n): void {\n\tif (!steps?.length) return;\n\tfor (const step of steps) {\n\t\tstep.children = undefined;\n\t}\n\tif (!children?.length) return;\n\tfor (const child of children) {\n\t\tif (child.parentRunId !== rootRunId || child.parentStepIndex === undefined) continue;\n\t\tconst step = steps.find((candidate, index) => (candidate.index ?? index) === child.parentStepIndex);\n\t\tif (!step) continue;\n\t\tstep.children ??= [];\n\t\tstep.children = [...step.children.filter((existing) => existing.id !== child.id), child].slice(0, MAX_CHILDREN);\n\t}\n}\n\nexport function updateAsyncJobNestedProjection(job: AsyncJobState): void {\n\tif (!job.nestedRoute) return;\n\tconst registry = projectNestedEvents(job.nestedRoute);\n\tjob.nestedChildren = registry.children;\n\tattachRootChildrenToSteps(job.asyncId, job.steps, registry.children);\n}\n\nexport function updateForegroundNestedProjection(\n\tcontrol: SubagentState[\"foregroundControls\"] extends Map<string, infer T> ? T : never,\n): void {\n\tif (!control.nestedRoute) return;\n\tconst registry = projectNestedEvents(control.nestedRoute);\n\tcontrol.nestedChildren = registry.children;\n}\n\nexport function hasLiveNestedDescendants(children: NestedRunSummary[] | undefined): boolean {\n\tif (!children?.length) return false;\n\tfor (const child of children) {\n\t\tif (!terminal(child.state)) return true;\n\t\tif (hasLiveNestedDescendants(child.children)) return true;\n\t\tif (hasLiveNestedDescendants(child.steps?.flatMap((step) => step.children ?? []))) return true;\n\t}\n\treturn false;\n}\n\nexport function nestedSummaryFromAsyncStatus(\n\tstatus: AsyncStatus,\n\tasyncDir: string,\n\tfallback: {\n\t\tid: string;\n\t\tparentRunId: string;\n\t\tparentStepIndex?: number;\n\t\tdepth: number;\n\t\tpath?: Array<{ runId: string; stepIndex?: number; agent?: string }>;\n\t\tmode?: SubagentRunMode;\n\t\tts: number;\n\t},\n): NestedRunSummary {\n\treturn {\n\t\tid: status.runId || fallback.id,\n\t\tparentRunId: fallback.parentRunId,\n\t\t...(fallback.parentStepIndex !== undefined ? { parentStepIndex: fallback.parentStepIndex } : {}),\n\t\tdepth: fallback.depth,\n\t\tpath: fallback.path ?? [\n\t\t\t{\n\t\t\t\trunId: fallback.parentRunId,\n\t\t\t\t...(fallback.parentStepIndex !== undefined ? { stepIndex: fallback.parentStepIndex } : {}),\n\t\t\t},\n\t\t],\n\t\tasyncDir,\n\t\t...(status.pid ? { pid: status.pid } : {}),\n\t\t...(status.sessionId ? { sessionId: status.sessionId } : {}),\n\t\tmode: status.mode ?? fallback.mode,\n\t\t...(status.steps?.length === 1 && status.steps[0]?.model ? { model: status.steps[0].model } : {}),\n\t\t...(status.steps?.length === 1 && status.steps[0]?.thinking ? { thinking: status.steps[0].thinking } : {}),\n\t\t...(status.processTerminal\n\t\t\t? {\n\t\t\t\t\tprocessTerminal: sanitizeProcessTerminal(\n\t\t\t\t\t\tstatus.processTerminal,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trunId: status.runId || fallback.id,\n\t\t\t\t\t\t\trunnerProcessInstanceId: status.processTerminal.runnerProcessInstanceId,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t`${asyncDir}/status.json`,\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t\t...(status.launchResolvedExtensions ? { launchResolvedExtensions: status.launchResolvedExtensions } : {}),\n\t\t...runtimeAcknowledgedEntry(status.runtimeAcknowledgedExtensions),\n\t\t...(status.capabilityCeiling ? { capabilityCeiling: status.capabilityCeiling } : {}),\n\t\t...(status.capabilityAudit ? { capabilityAudit: status.capabilityAudit } : {}),\n\t\tstate: status.state,\n\t\t...(status.currentStep !== undefined ? { currentStep: status.currentStep } : {}),\n\t\t...(status.chainStepCount !== undefined ? { chainStepCount: status.chainStepCount } : {}),\n\t\t...(status.activityState ? { activityState: status.activityState } : {}),\n\t\t...(status.lastActivityAt !== undefined ? { lastActivityAt: status.lastActivityAt } : {}),\n\t\t...(status.currentTool ? { currentTool: status.currentTool } : {}),\n\t\t...(status.currentToolStartedAt !== undefined ? { currentToolStartedAt: status.currentToolStartedAt } : {}),\n\t\t...(status.currentPath ? { currentPath: status.currentPath } : {}),\n\t\t...(status.turnCount !== undefined ? { turnCount: status.turnCount } : {}),\n\t\t...(status.toolCount !== undefined ? { toolCount: status.toolCount } : {}),\n\t\t...(status.totalTokens ? { totalTokens: status.totalTokens } : {}),\n\t\t...(status.timeoutMs !== undefined ? { timeoutMs: status.timeoutMs } : {}),\n\t\t...(status.deadlineAt !== undefined ? { deadlineAt: status.deadlineAt } : {}),\n\t\t...(status.timedOut !== undefined ? { timedOut: status.timedOut } : {}),\n\t\t...(status.stopped !== undefined ? { stopped: status.stopped } : {}),\n\t\t...(status.turnBudget ? { turnBudget: status.turnBudget } : {}),\n\t\t...(status.turnBudgetExceeded !== undefined ? { turnBudgetExceeded: status.turnBudgetExceeded } : {}),\n\t\t...(status.wrapUpRequested !== undefined ? { wrapUpRequested: status.wrapUpRequested } : {}),\n\t\t...(status.error ? { error: status.error } : {}),\n\t\t...(status.startedAt !== undefined ? { startedAt: status.startedAt } : { startedAt: fallback.ts }),\n\t\t...(status.endedAt !== undefined ? { endedAt: status.endedAt } : {}),\n\t\tlastUpdate: status.lastUpdate ?? fallback.ts,\n\t\t...(status.sessionFile ? { sessionFile: status.sessionFile } : {}),\n\t\t...(status.steps?.length\n\t\t\t? {\n\t\t\t\t\tsteps: status.steps\n\t\t\t\t\t\t.map((step, index) => ({\n\t\t\t\t\t\t\tagent: step.agent,\n\t\t\t\t\t\t\tstatus: step.status,\n\t\t\t\t\t\t\t...(step.model ? { model: step.model } : {}),\n\t\t\t\t\t\t\t...(step.thinking ? { thinking: step.thinking } : {}),\n\t\t\t\t\t\t\t...(step.sessionFile ? { sessionFile: step.sessionFile } : {}),\n\t\t\t\t\t\t\t...(step.activityState ? { activityState: step.activityState } : {}),\n\t\t\t\t\t\t\t...(step.lastActivityAt !== undefined ? { lastActivityAt: step.lastActivityAt } : {}),\n\t\t\t\t\t\t\t...(step.currentTool ? { currentTool: step.currentTool } : {}),\n\t\t\t\t\t\t\t...(step.currentToolStartedAt !== undefined\n\t\t\t\t\t\t\t\t? { currentToolStartedAt: step.currentToolStartedAt }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t...(step.currentPath ? { currentPath: step.currentPath } : {}),\n\t\t\t\t\t\t\t...(step.turnCount !== undefined ? { turnCount: step.turnCount } : {}),\n\t\t\t\t\t\t\t...(step.toolCount !== undefined ? { toolCount: step.toolCount } : {}),\n\t\t\t\t\t\t\t...(step.startedAt !== undefined ? { startedAt: step.startedAt } : {}),\n\t\t\t\t\t\t\t...(step.endedAt !== undefined ? { endedAt: step.endedAt } : {}),\n\t\t\t\t\t\t\t...(step.error ? { error: step.error } : {}),\n\t\t\t\t\t\t\t...(step.launchResolvedExtensions\n\t\t\t\t\t\t\t\t? { launchResolvedExtensions: step.launchResolvedExtensions }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t...runtimeAcknowledgedEntry(step.runtimeAcknowledgedExtensions),\n\t\t\t\t\t\t\t...(step.timedOut !== undefined ? { timedOut: step.timedOut } : {}),\n\t\t\t\t\t\t\t...(step.stopped !== undefined ? { stopped: step.stopped } : {}),\n\t\t\t\t\t\t\t...(step.turnBudget ? { turnBudget: step.turnBudget } : {}),\n\t\t\t\t\t\t\t...(step.turnBudgetExceeded !== undefined ? { turnBudgetExceeded: step.turnBudgetExceeded } : {}),\n\t\t\t\t\t\t\t...(step.wrapUpRequested !== undefined ? { wrapUpRequested: step.wrapUpRequested } : {}),\n\t\t\t\t\t\t\t...(step.processTerminal\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\tprocessTerminal: sanitizeProcessTerminal(\n\t\t\t\t\t\t\t\t\t\t\tstep.processTerminal,\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\trunId: status.runId || fallback.id,\n\t\t\t\t\t\t\t\t\t\t\t\trunnerProcessInstanceId: step.processTerminal.runnerProcessInstanceId,\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t`${asyncDir}/status.json step ${index}`,\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t...(step.capabilityCeiling ? { capabilityCeiling: step.capabilityCeiling } : {}),\n\t\t\t\t\t\t\t...(step.capabilityAudit ? { capabilityAudit: step.capabilityAudit } : {}),\n\t\t\t\t\t\t}))\n\t\t\t\t\t\t.slice(0, MAX_STEPS),\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\nexport function nestedArtifactEnv(rootRunId: string, parentRunId: string): Record<string, string> {\n\treturn {\n\t\tPI_SUBAGENT_NESTED_ROOT_RUN_ID: rootRunId,\n\t\tPI_SUBAGENT_NESTED_PARENT_RUN_ID: parentRunId,\n\t};\n}\n\nexport function isTopLevelAsyncDir(asyncDir: string): boolean {\n\tconst resolved = path.resolve(asyncDir);\n\treturn (\n\t\tcontainedPath(DIRS.async, resolved) && !containedPath(path.join(TEMP_ROOT_DIR, \"nested-subagent-runs\"), resolved)\n\t);\n}\n\nexport function nestedResultsPath(rootRunId: string, id: string): string {\n\tassertSafeId(\"rootRunId\", rootRunId);\n\tassertSafeId(\"id\", id);\n\treturn path.join(DIRS.results, \"nested\", rootRunId, `${id}.json`);\n}\n"]}