apex-code 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +46 -0
- package/dist/client/transcript.d.ts.map +1 -1
- package/dist/client/transcript.js +1 -1
- package/dist/client/transcript.js.map +1 -1
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +2 -1
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/delegation/runtime.d.ts.map +1 -1
- package/dist/core/delegation/runtime.js +2 -2
- package/dist/core/delegation/runtime.js.map +1 -1
- package/dist/core/durable-state/daemon.d.ts.map +1 -1
- package/dist/core/durable-state/daemon.js +1 -1
- package/dist/core/durable-state/daemon.js.map +1 -1
- package/dist/core/extensions/types.d.ts +1 -1
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/keybindings.d.ts +1 -1
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/mcp/mcp-tool.d.ts.map +1 -1
- package/dist/core/mcp/mcp-tool.js +2 -4
- package/dist/core/mcp/mcp-tool.js.map +1 -1
- package/dist/core/mcp/oauth/authorize.d.ts.map +1 -1
- package/dist/core/mcp/oauth/authorize.js +7 -2
- package/dist/core/mcp/oauth/authorize.js.map +1 -1
- package/dist/core/mcp/runtime.d.ts +2 -2
- package/dist/core/mcp/runtime.d.ts.map +1 -1
- package/dist/core/mcp/runtime.js +8 -3
- package/dist/core/mcp/runtime.js.map +1 -1
- package/dist/core/permissions/store.d.ts +7 -2
- package/dist/core/permissions/store.d.ts.map +1 -1
- package/dist/core/permissions/store.js +6 -1
- package/dist/core/permissions/store.js.map +1 -1
- package/dist/core/project-resources.d.ts +12 -0
- package/dist/core/project-resources.d.ts.map +1 -1
- package/dist/core/project-resources.js +19 -0
- package/dist/core/project-resources.js.map +1 -1
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +10 -1
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/resource-loader.d.ts +6 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +9 -3
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/sdk.d.ts +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +3 -3
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-manager.d.ts +16 -3
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +39 -16
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/tools/bash.d.ts +11 -7
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +37 -46
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +2 -2
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +3 -3
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +4 -4
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +4 -4
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js +4 -4
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/path-utils.d.ts +9 -0
- package/dist/core/tools/path-utils.d.ts.map +1 -1
- package/dist/core/tools/path-utils.js +235 -10
- package/dist/core/tools/path-utils.js.map +1 -1
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +11 -8
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +7 -8
- package/dist/core/tools/write.js.map +1 -1
- package/dist/core/workspace/state.d.ts.map +1 -1
- package/dist/core/workspace/state.js +1 -1
- package/dist/core/workspace/state.js.map +1 -1
- package/dist/extensions/llama/ui.d.ts.map +1 -1
- package/dist/extensions/llama/ui.js +3 -2
- package/dist/extensions/llama/ui.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +3 -1
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +0 -10
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/autocomplete-source.d.ts +8 -0
- package/dist/modes/interactive/components/autocomplete-source.d.ts.map +1 -0
- package/dist/modes/interactive/components/autocomplete-source.js +23 -0
- package/dist/modes/interactive/components/autocomplete-source.js.map +1 -0
- package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/bash-execution.js +6 -4
- package/dist/modes/interactive/components/bash-execution.js.map +1 -1
- package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -1
- package/dist/modes/interactive/components/bordered-loader.js +1 -1
- package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
- package/dist/modes/interactive/components/composer-dock.d.ts +12 -0
- package/dist/modes/interactive/components/composer-dock.d.ts.map +1 -0
- package/dist/modes/interactive/components/composer-dock.js +24 -0
- package/dist/modes/interactive/components/composer-dock.js.map +1 -0
- package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/config-selector.js +11 -9
- package/dist/modes/interactive/components/config-selector.js.map +1 -1
- package/dist/modes/interactive/components/diff.d.ts.map +1 -1
- package/dist/modes/interactive/components/diff.js +2 -2
- package/dist/modes/interactive/components/diff.js.map +1 -1
- package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-editor.js +9 -9
- package/dist/modes/interactive/components/extension-editor.js.map +1 -1
- package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-input.js +9 -5
- package/dist/modes/interactive/components/extension-input.js.map +1 -1
- package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-selector.js +11 -10
- package/dist/modes/interactive/components/extension-selector.js.map +1 -1
- package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
- package/dist/modes/interactive/components/first-time-setup.js +6 -6
- package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +8 -3
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.d.ts +21 -0
- package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.js +34 -0
- package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +27 -23
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +14 -18
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +7 -6
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/permission-preview.d.ts.map +1 -1
- package/dist/modes/interactive/components/permission-preview.js +3 -3
- package/dist/modes/interactive/components/permission-preview.js.map +1 -1
- package/dist/modes/interactive/components/prompt-input.d.ts +12 -0
- package/dist/modes/interactive/components/prompt-input.d.ts.map +1 -0
- package/dist/modes/interactive/components/prompt-input.js +18 -0
- package/dist/modes/interactive/components/prompt-input.js.map +1 -0
- package/dist/modes/interactive/components/scoped-models-selector.d.ts +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.js +4 -3
- package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +26 -19
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +39 -6
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-submenu.js +8 -6
- package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.js +10 -5
- package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +1 -11
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +9 -38
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tool-panel.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-panel.js +7 -2
- package/dist/modes/interactive/components/tool-panel.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector.js +9 -5
- package/dist/modes/interactive/components/tree-selector.js.map +1 -1
- package/dist/modes/interactive/components/trust-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/trust-selector.js +11 -11
- package/dist/modes/interactive/components/trust-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message-selector.js +2 -2
- package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message.js +6 -3
- package/dist/modes/interactive/components/user-message.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +7 -2
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +65 -65
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +49 -23
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/tsconfig.json +3 -0
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-image.js +1 -1
- package/dist/utils/clipboard-image.js.map +1 -1
- package/dist/utils/syntax-highlight.d.ts.map +1 -1
- package/dist/utils/syntax-highlight.js +22 -22
- package/dist/utils/syntax-highlight.js.map +1 -1
- package/docs/json.md +36 -0
- package/docs/models.md +1 -1
- package/docs/settings.md +1 -1
- package/examples/extensions/gondolin/package-lock.json +3 -3
- package/examples/extensions/minimal-mode.ts +6 -6
- package/examples/extensions/sandbox/package-lock.json +4 -4
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/sdk/10-settings.ts +2 -2
- package/examples/sdk/README.md +1 -1
- package/npm-shrinkwrap.json +19 -34
- package/package.json +6 -6
- package/dist/modes/interactive/components/message-spine.d.ts +0 -14
- package/dist/modes/interactive/components/message-spine.d.ts.map +0 -1
- package/dist/modes/interactive/components/message-spine.js +0 -19
- package/dist/modes/interactive/components/message-spine.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../src/core/delegation/runtime.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACvE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAGrE,OAAO,EAAkB,mBAAmB,EAAqB,MAAM,uBAAuB,CAAC;AAE/F,O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,GAAG,EAAE,GAAG,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC1E,CAAC,CAAC;QACH,IAAI,CAAC,OAAO,CAAC,UAAU;YAAE,OAAO,OAAO,CAAC;QACxC,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,oDAAoD,QAAQ,IAAI,EAAE,QAAQ,EAAE,CAAC;IAChH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,wEAAwE;QACxE,yEAAyE;QACzE,iDAAiD;QACjD,QAAQ,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC;QACxC,MAAM,QAAQ,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC;QAC9C,MAAM,KAAK,CAAC;IACb,CAAC;AAAA,CACD;AAED,uGAAuG;AACvG,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC7C,OAAiC,EACjC,QAAgB,EAChB,iBAA0B,EACE;IAC5B,IAAI,QAAQ,GAAG,OAAO,CAAC,gBAAgB,CAAC;IACxC,IAAI,CAAC,QAAQ,EAAE,CAAC;QACf,QAAQ,GAAG,IAAI,gBAAgB,EAAE,CAAC;QAClC,OAAO,CAAC,gBAAgB,GAAG,QAAQ,CAAC;IACrC,CAAC;IACD,OAAO,QAAQ,CAAC,QAAQ,CAAC,QAAQ,EAAE,iBAAiB,CAAC,CAAC;AAAA,CACtD","sourcesContent":["/**\n * The delegation runtime (roadmap Phase 5, ADR 0008, task 5.2). Consumes the\n * capability ceiling (ceiling.ts) and a derived permission store\n * (`../permissions/store.ts`'s `DerivedPermissionRuleStore`) to run a real child\n * agent whose authority can never exceed its parent's.\n *\n * Agent definitions and child-session construction are both injected rather than\n * built in here: production agent discovery lives in `core/delegation/agents.ts`\n * (markdown + frontmatter, parsed on lookup) and plugs in through the same\n * resolver interface a test fixture implements; child-session construction is\n * injected so this module stays free of\n * `AgentSession`/`createAgentSession` and therefore free of the import cycle that\n * would create (`sdk.ts` already imports `agent-session.ts`).\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { existsSync, mkdirSync, readdirSync, statSync } from \"node:fs\";\nimport { isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport type { Usage } from \"@earendil-works/pi-ai\";\nimport type { AgentRunBudgetUsage } from \"apex-code-agent-core\";\nimport { type FileEntry, loadEntriesFromFile, type SessionEntry } from \"../session-manager.ts\";\nimport type { Capability } from \"../tools/contract.ts\";\nimport { computeCapabilityCeiling } from \"./ceiling.ts\";\n\n/** A delegatable agent's static configuration. Markdown + frontmatter in production (`agents.ts`); a plain object in tests. */\nexport interface AgentDefinition {\n\tname: string;\n\tdescription: string;\n\t/** Tool names this agent may use. Never trusted directly -- the runtime derives the actual child tool list from the computed capability set, not from this list verbatim. */\n\ttools: string[];\n\t/** Optional model id. Falls back to the parent's current model when unset or unresolvable. */\n\tmodel?: string;\n\tsystemPrompt: string;\n}\n\n/** Resolve an agent type to its definition, or `undefined` if unknown. Production implements this over markdown/frontmatter (`agents.ts`); tests inject plain functions with the same shape. */\nexport type AgentDefinitionResolver = (agentType: string) => AgentDefinition | undefined;\n\n/** A running or completed child, as far as the runtime needs to know. */\nexport type ChildSessionStatus = \"idle\" | \"running\" | \"interrupted\" | \"closed\";\n\n/** Terminal outcome of a child's latest settled turn. */\nexport type ChildTurnOutcome = \"completed\" | \"failed\" | \"interrupted\";\n\n/**\n * Token and cost totals for one child run, rolled up from the child's OWN\n * session transcript (the session-file reading seam; never a second transcript\n * cache). The numbers are summed exactly as the provider reported them -- cost\n * is provider-reported, so cache reads are NOT re-priced, re-counted, or\n * double-counted; an entry without usage counts as zero.\n */\nexport interface ChildRunUsageTotals {\n\tinputTokens: number;\n\toutputTokens: number;\n\tcacheReadTokens: number;\n\tcacheWriteTokens: number;\n\ttotalTokens: number;\n\tcost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };\n\t/** Wall-clock time (ms) the rollup was computed at. */\n\tasOf: number;\n\t/** Usage-bearing transcript entries examined (assistant messages, compaction, branch summaries), including those without usage. */\n\tentriesCounted: number;\n}\n\n/** The output and terminal outcome of a child's latest settled turn, as reported by its own handle. */\nexport interface ChildTurnResult {\n\toutput: string;\n\toutcome: ChildTurnOutcome;\n}\n\n/** Terminal outcome of one attempt on a child run. `cancelled` is recorded only by an explicit interrupt-with-reason. */\nexport type ChildRunAttemptOutcome = \"completed\" | \"failed\" | \"interrupted\" | \"cancelled\";\n\n/**\n * One launch-or-resume epoch of a child run (spec 2026-09-09, \"Child\n * lifecycle\"): a launch is attempt 1; a resume closes the prior attempt with\n * its terminal outcome and opens a new one. A live run's follow-ups and\n * steering stay inside the active attempt. `usage` snapshots the child's own\n * budget controller when its session exposes one (optional on the handle).\n * `tokensAtEnd` snapshots the run-level usage/cost rollup (see\n * `ChildRunUsageTotals`) at the attempt's settlement: these are\n * CUMULATIVE-AT-END snapshots of the child's whole transcript, never per-attempt\n * deltas -- range attribution between attempts is not attempted because turns\n * that settled after the last persisted boundary are re-run on resume, so the\n * transcript alone cannot attribute usage to an epoch.\n */\nexport interface ChildRunAttempt {\n\tid: string;\n\tstartedAt: number;\n\tendedAt?: number;\n\toutcome?: ChildRunAttemptOutcome;\n\terror?: string;\n\tusage?: AgentRunBudgetUsage;\n\ttokensAtEnd?: ChildRunUsageTotals;\n}\n\nexport interface ChildSessionHandle {\n\treadonly status: ChildSessionStatus;\n\t/** Run the task to completion and return the child's final output text. */\n\trun(task: string): Promise<{ output: string }>;\n\t/**\n\t * The latest settled turn's output and terminal outcome, derived by this handle\n\t * from the actual prompt resolution; `undefined` before any turn settles. This --\n\t * not the registry's stored first-turn promise -- is the source of truth for\n\t * background retrieval after `sendInput`/`followUp`/resume.\n\t */\n\tlatestResult(): ChildTurnResult | undefined;\n\twait(): Promise<void>;\n\tinterrupt(): void;\n\tclose(): void;\n\tsendInput(input: string): Promise<void>;\n\tfollowUp(input: string): Promise<void>;\n\t/**\n\t * Point-in-time snapshot of the child's own run budget counters, when its\n\t * session exposes a controller. Optional: handles whose child session does\n\t * not surface a controller simply omit it, and every consumer treats\n\t * attempt/status usage as optional.\n\t */\n\tusage?(): AgentRunBudgetUsage | undefined;\n\t/**\n\t * Read-only view of the child's own session entries, when the handle can\n\t * reach its (possibly in-memory) session manager. Optional: fixture handles\n\t * need not expose it, and the usage rollup consults it only when the child\n\t * has no resolvable transcript file (an in-memory child never persisted\n\t * one). Without this seam AND a transcript file, the run's usage totals are\n\t * simply unreportable (`undefined`), never guessed.\n\t */\n\tsessionEntries?(): readonly SessionEntry[] | undefined;\n\t/**\n\t * The derived policy this handle's child was built with (populated by the\n\t * sdk's `buildChildSession` from the request's admission projection and its\n\t * own construction values). Optional: fixture handles may omit it, and the\n\t * runtime relays it onto the child-run record when present.\n\t */\n\tpolicy?: ChildRunPolicySnapshot;\n\t/** Release the child's resources. Called when the child or owning parent is closed. */\n\tdispose(): void;\n}\n\nexport interface BuildChildSessionRequest {\n\tagentType: string;\n\tdefinition: AgentDefinition;\n\t/** The child's tool allowlist, already ceiling-checked -- exactly `definition.tools`, never narrowed. */\n\ttoolNames: string[];\n\t/**\n\t * The admitted capability set from the shared admission projection\n\t * (`resolveAdmittedDefinition`). Consumers use it to describe the child;\n\t * they must never re-derive it (ADR 0010).\n\t */\n\tcapabilities: ReadonlySet<Capability>;\n\t/** The child's own recursion depth (the parent's depth + 1), for the runtime constructing it to record on the child's session header (task 5.3). */\n\tdepth: number;\n\t/** Stable id used for the child session and its artifact directory. */\n\tsessionId: string;\n\t/** Per-child artifact root, created before the child session is constructed. */\n\tartifactDir?: string;\n\tworkspace?: ChildWorkspaceRequest;\n\t/**\n\t * Reattachment marker (restart reconstruction): when set, `buildChildSession`\n\t * opens this existing child session transcript instead of creating a new\n\t * session. The path must be the child's own session file under its recorded\n\t * artifact directory. Every other field keeps its fresh-delegation meaning,\n\t * so permission/model/tool wiring has exactly one construction path.\n\t */\n\treattachSessionPath?: string;\n\t/**\n\t * Optional wall-time cap for the child's OWN run budget (spec 2026-09-09,\n\t * timeouts): forwarded as `maxWallTimeMs` so the existing AgentRunBudget\n\t * wall-time gate enforces it mid-run. The launch also records\n\t * `deadlineMs = Date.now() + timeoutMs` on the record for lazy observation.\n\t */\n\ttimeoutMs?: number;\n}\n\n/** The workspace authority requested by a child. Paths are advisory claims,\n * never a replacement for the path-permission gate. */\nexport interface ChildWorkspaceRequest {\n\tisolation: \"shared-read\" | \"worktree\";\n\townedPaths: readonly string[];\n\t/**\n\t * The resolved isolation root a workspace owner prepared for this child\n\t * (worktree isolation): absent on the raw request, present on what\n\t * `prepare()` returns, and the cwd the child session runs in.\n\t */\n\troot?: string;\n}\n\n/**\n * Lifecycle state of a worktree-isolated child's workspace, persisted on the\n * record (spec 2026-09-09, \"Workspace states and explicit recovery\"). Absent\n * means \"active\" -- legacy records predate the field and a live worktree is\n * active by definition. Release outcomes write \"released\" / \"retained-dirty\" /\n * \"retained-failed\"; observing a vanished root at resume writes \"missing\".\n * Explicit recovery (`recoverWorkspace`) verifies and writes \"active\".\n */\nexport type ChildWorkspaceState = \"active\" | \"released\" | \"retained-dirty\" | \"retained-failed\" | \"missing\";\n\n/** Success payload of explicit workspace recovery (`recoverChildWorkspace`). */\nexport interface ChildWorkspaceRecoveryResult {\n\t/** Always \"active\": the workspace was verified and reactivated. */\n\tworkspaceState: ChildWorkspaceState;\n\t/** The verified worktree holds uncommitted or untracked work. */\n\tdirty: boolean;\n}\n\n/**\n * Real isolation and cleanup for a child's requested workspace authority (spec\n * 2026-09-09, \"Parallel work and ownership\"): the workspace subsystem owns git;\n * delegation only negotiates the request and refuses worktree isolation when no\n * owner is available. `prepare()` runs only for `isolation: \"worktree\"` -- a\n * shared-read delegation never touches an owner and never invokes git -- and\n * the request it returns (with `root` set) is what `buildChildSession` receives.\n */\n/**\n * Terminal outcome of releasing a child workspace (worktree). A kept tree is\n * never destroyed silently: \"dirty\" means uncommitted/untracked child work\n * was preserved; \"failed\" means the remove failed for another reason and the\n * tree was left in place.\n */\nexport type WorkspaceReleaseOutcome =\n\t| { removed: true }\n\t| { removed: false; kept: \"dirty\" | \"failed\"; dir: string; error?: string };\n\nexport interface ChildWorkspaceOwner {\n\tprepare(request: ChildWorkspaceRequest & { sessionId: string }): Promise<ChildWorkspaceRequest>;\n\t/**\n\t * Release the child's workspace, reporting what happened instead of\n\t * throwing. `options.force` is the caller's explicit escape hatch to\n\t * force-remove a dirty tree; without it a dirty tree must be kept.\n\t */\n\trelease(\n\t\tsessionId: string,\n\t\toptions?: { force?: boolean },\n\t): Promise<WorkspaceReleaseOutcome> | WorkspaceReleaseOutcome;\n\t/**\n\t * Read-only verification that a recorded worktree root is still this\n\t * owner's worktree for the session in the CURRENT workspace: layout,\n\t * administrative entry, and checked-out branch. Never creates, checks out,\n\t * resets, or force-removes anything; a failed check throws with the check\n\t * named. Optional: owners that cannot verify simply never support explicit\n\t * recovery, and `recoverWorkspace` refuses rather than guessing.\n\t */\n\tverify?(sessionId: string, root: string): Promise<{ dirty: boolean }> | { dirty: boolean };\n}\n\nexport interface DelegationRuntimeOptions {\n\tresolveAgent: AgentDefinitionResolver;\n\t/** The parent's own effective capability set (its authority), unexpanded -- `exec` expansion happens inside the ceiling check, not here. */\n\tgetParentCapabilities: () => ReadonlySet<Capability>;\n\t/** Capability set a named tool requires, from the live registry. `undefined` for an unknown tool name. */\n\tgetToolCapabilities: (toolName: string) => ReadonlySet<Capability> | undefined;\n\t/** The parent session's own recursion depth (`SessionManager.getDelegationDepth()`), read fresh at delegation time. */\n\tgetDelegationDepth: () => number;\n\t/** Delegation is refused once `getDelegationDepth() >= maxDelegationDepth` -- assigned by the runtime, not by the tool, so the bound applies to any future delegation entry point. */\n\tmaxDelegationDepth: number;\n\t/**\n\t * Maximum simultaneously-active child runs this runtime admits (spec\n\t * 2026-09-09, \"Shared budgets\", concurrency cap). Checked at admission --\n\t * before any child session is built -- and refused with an actionable error\n\t * naming the limit. An admitted run holds one slot until terminal settlement\n\t * (completed/failed/interrupted), close, registry disposal, or launch\n\t * failure. `undefined` (default) is unlimited.\n\t */\n\tmaxConcurrentChildren?: number;\n\t/** Parent session directory. When supplied, child artifacts are rooted beneath it. */\n\tgetParentSessionDir?: () => string;\n\t/**\n\t * Parent session id. When supplied, child-run records carry\n\t * `parentSessionId`, tying the durable record (and every protocol payload\n\t * derived from it) to the parent session's own identity.\n\t */\n\tgetParentSessionId?: () => string;\n\tbuildChildSession: (request: BuildChildSessionRequest) => Promise<ChildSessionHandle>;\n\tchildRunRegistry?: ChildRunRegistry;\n\t/** Durable session owner. Records are appended to the parent session's existing log. */\n\tpersistChildRun?: (record: ChildRunRecord) => void;\n\t/** Optional workspace owner. It is responsible for real isolation and cleanup. */\n\tworkspaceOwner?: ChildWorkspaceOwner;\n}\n\n/**\n * Compact, derivable snapshot of the derived policy a child session was built\n * with (spec 2026-09-09, \"Derive, do not reconstruct\"). Populated at child\n * construction from the values actually used -- never re-derived by consumers.\n * `capabilities` come from the delegation runtime's single admission projection\n * (`resolveAdmittedDefinition`), so no surface ever re-classifies authority\n * (ADR 0010). Persisted on `ChildRunRecord` and surfaced through status/wait\n * payloads; legacy records without it load unchanged.\n */\nexport interface ChildRunPolicySnapshot {\n\t/** The child's tool allowlist, exactly as construction received it (ceiling-checked `definition.tools`). */\n\ttools: string[];\n\t/** The admitted capability set from the same admission projection that gated the launch. */\n\tcapabilities: string[];\n\t/** The delegation depth bound in force for this child's own delegations. */\n\tmaxDelegationDepth: number;\n\t/** The child's resolved model id (its definition's model, or the parent's current model). */\n\tmodel?: string;\n\t/** The child Agent's budget scope; children are built session-scoped so follow-ups continue one controller. */\n\tbudgetScope: \"prompt\" | \"session\";\n\t/** Whether the child answers to the tree's shared aggregate ceiling (present only when explicitly configured at the root). */\n\taggregateBudget: boolean;\n}\n\nexport interface ChildRunRecord {\n\thandleId: string;\n\tagentType: string;\n\tsessionId?: string;\n\ttask?: string;\n\tparentSessionId?: string;\n\tartifactDir?: string;\n\t/** The derived policy this child was built with, persisted so session readers describe the child without re-deriving it. Optional: legacy records predate the field. */\n\tpolicy?: ChildRunPolicySnapshot;\n\t/**\n\t * Legacy only. Records what a session written before ADR 0032 was told about OS\n\t * containment. Absent on records written since, because nothing sets it: the\n\t * harness ships no boundary and makes no containment claim. Retained so an older\n\t * session still parses and still reports what it reported (ADR 0006).\n\t */\n\tsandboxEnforced?: boolean;\n\tworkspace?: ChildWorkspaceRequest;\n\t/**\n\t * Workspace lifecycle state for worktree-isolated records (see\n\t * `ChildWorkspaceState`). Written by release outcomes, by resume-time\n\t * observation of a vanished root (\"missing\"), and by explicit recovery\n\t * (\"active\"). Absent -- on legacy records and shared-read runs -- means\n\t * \"active\"; the field only ever appears for worktree isolation.\n\t */\n\tworkspaceState?: ChildWorkspaceState;\n\tdepth?: number;\n\tlatestResult?: { output: string; outcome: ChildTurnOutcome };\n\tstatus: \"created\" | \"running\" | \"completed\" | \"failed\" | \"interrupted\" | \"closed\";\n\tupdatedAt: number;\n\t/**\n\t * Attempt epochs (launch = attempt 1; resume opens a new one). Optional on\n\t * the wire: legacy records predate the field and are synthesized on load --\n\t * one attempt derived from the record's status/updatedAt -- so every\n\t * in-memory record carries at least one.\n\t */\n\tattempts?: ChildRunAttempt[];\n\tactiveAttemptId?: string;\n\t/** Caller-supplied spawn dedupe key; a restarted parent rebuilds the key->handle map from records. */\n\tidempotencyKey?: string;\n\t/** Wall-clock deadline recorded at launch (`Date.now() + timeoutMs`); observed lazily by status/list. */\n\tdeadlineMs?: number;\n\t/** Explicit cancellation, recorded when the run is interrupted with a reason. */\n\tcancelled?: { reason: string; at: number };\n}\n\nexport interface DelegationResult {\n\tagentType: string;\n\ttask: string;\n\toutput: string;\n\t/** Present for background work; pass this handle to retrieveDelegationResult. */\n\thandleId?: string;\n\t/**\n\t * Terminal outcome of the latest settled turn. Present on registry retrieval\n\t * once any turn has settled; the foreground result of the initial run omits it.\n\t */\n\toutcome?: ChildTurnOutcome;\n}\n\n/**\n * Non-blocking status snapshot of one child run (`agent/status`,\n * `AgentSession.childRunStatus`). Built from the record/entry alone -- never by\n * awaiting a turn -- so a caller can poll without blocking on the child.\n */\nexport interface ChildRunStatus {\n\thandleId: string;\n\tagentType: string;\n\ttask: string;\n\tstatus: ChildSessionStatus;\n\t/** The active attempt's identity and its latest outcome, if any turn has settled (or a cancellation was recorded). */\n\tattempt: { id: string; outcome?: ChildRunAttemptOutcome };\n\t/** Total attempt epochs, including closed ones. */\n\tattempts: number;\n\t/** The latest settled turn, as persisted for retrieval. */\n\tlastResult?: { output: string; outcome: ChildTurnOutcome };\n\t/** Present when the run was interrupted with an explicit reason. */\n\tcancelled?: { reason: string; at: number };\n\t/** Wall-clock launch deadline (present when the spawn carried timeoutMs). */\n\tdeadlineMs?: number;\n\t/** Snapshot of the child's own budget controller, when its handle exposes one. */\n\tusage?: AgentRunBudgetUsage;\n\t/**\n\t * Cumulative token totals rolled up from the child's own session transcript\n\t * (or its in-memory entries when no transcript exists), flattened from\n\t * `ChildRunUsageTotals`. Present beside `cost` whenever a rollup is\n\t * reachable; omitted -- never zero-filled -- when nothing is reachable.\n\t */\n\ttokens?: {\n\t\tinputTokens: number;\n\t\toutputTokens: number;\n\t\tcacheReadTokens: number;\n\t\tcacheWriteTokens: number;\n\t\ttotalTokens: number;\n\t};\n\t/** Provider-reported cost totals corresponding to `tokens`. Absent whenever `tokens` is. */\n\tcost?: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };\n\t/** The run's negotiated workspace authority (isolation plus a prepared root, when a workspace owner provided one). */\n\tworkspace?: { isolation: \"shared-read\" | \"worktree\"; root?: string };\n\t/**\n\t * Workspace lifecycle state (worktree-isolated runs only). Present whenever\n\t * the workspace is worktree-isolated: the record's persisted state, or\n\t * \"active\" while the entry is live and unretained.\n\t */\n\tworkspaceState?: ChildWorkspaceState;\n\t/** The child's per-run artifact directory, when the child is file-backed. */\n\tartifactDir?: string;\n\t/**\n\t * The child's transcript path, resolved lazily from its artifact directory\n\t * per SessionManager's `<timestamp>_<sessionId>.jsonl` naming. Absent when\n\t * the child is in-memory or has not persisted a transcript yet; resolution\n\t * never throws.\n\t */\n\tsessionFile?: string;\n\t/** The parent session id the run belongs to, when the runtime supplies one. */\n\tparentSessionId?: string;\n\t/** The derived policy the child was built with; absent on legacy records and fixture handles that never carried one. */\n\tpolicy?: ChildRunPolicySnapshot;\n\t/** Legacy only, surfaced from the record; nothing sets it since ADR 0032. */\n\tsandboxEnforced?: boolean;\n}\n\n/** The registry's record of a handle's latest settled turn. */\ntype LatestTurnSettlement =\n\t| { outcome: \"completed\"; output: string }\n\t| { outcome: \"interrupted\"; output: string }\n\t| { outcome: \"failed\"; error: unknown };\n\ninterface BackgroundDelegation {\n\tagentType: string;\n\ttask: string;\n\tpromise: Promise<DelegationResult>;\n\tchild?: ChildSessionHandle;\n\tclosed?: boolean;\n\t/** The latest settled turn; `undefined` until the first settlement is recorded. */\n\tlatest?: LatestTurnSettlement;\n\t/** The turn whose settlement has not been observed through retrieval yet, if any. */\n\tpending?: Promise<unknown>;\n\t/** Durable fields, persisted on every save so a restart can reattach the child session. */\n\tartifactDir?: string;\n\tworkspace?: ChildWorkspaceRequest;\n\tdepth?: number;\n\t/** Record linkage persisted with every save (policy snapshot, sandbox flag, parent session id). */\n\tpolicy?: ChildRunPolicySnapshot;\n\tsandboxEnforced?: boolean;\n\tparentSessionId?: string;\n\t/** Attempt epochs (spec 2026-09-09, \"Child lifecycle\"). `register()` supplies attempt 1 when the caller did not. */\n\tattempts?: ChildRunAttempt[];\n\tactiveAttemptId?: string;\n\tidempotencyKey?: string;\n\tdeadlineMs?: number;\n\tcancelled?: { reason: string; at: number };\n}\n\n/** Default follow-up prompt for resuming an interrupted child run. */\nexport const RESUME_CHILD_PROMPT = \"Resume the interrupted task and continue from the existing session.\";\n\n/** The record status's terminal outcome, for closing an attempt at resume time. */\nfunction terminalOutcomeOfStatus(\n\tstatus: ChildRunRecord[\"status\"],\n\tcancelled?: { reason: string; at: number },\n): ChildRunAttemptOutcome | undefined {\n\tif (status === \"completed\" || status === \"failed\") return status;\n\tif (status === \"interrupted\") return cancelled ? \"cancelled\" : \"interrupted\";\n\treturn undefined;\n}\n\n/**\n * Attempts for a record, synthesizing one from legacy fields when the record\n * predates attempt tracking: one attempt, started (and, for a terminal status,\n * ended) at the record's `updatedAt`, with the status mapped to an outcome.\n * Older records therefore load unchanged and still report a single attempt.\n */\nfunction childRunAttemptsOf(record: ChildRunRecord): ChildRunAttempt[] {\n\tif (record.attempts && record.attempts.length > 0) return record.attempts;\n\tconst attempt: ChildRunAttempt = { id: \"attempt-1\", startedAt: record.updatedAt };\n\tconst outcome = terminalOutcomeOfStatus(record.status, record.cancelled);\n\tif (outcome !== undefined) {\n\t\tattempt.endedAt = record.updatedAt;\n\t\tattempt.outcome = outcome;\n\t}\n\treturn [attempt];\n}\n\n/** The entry's active attempt, falling back to the most recent one. */\nfunction activeAttemptOf(entry: {\n\tattempts?: ChildRunAttempt[];\n\tactiveAttemptId?: string;\n}): ChildRunAttempt | undefined {\n\tconst attempts = entry.attempts ?? [];\n\treturn attempts.find((attempt) => attempt.id === entry.activeAttemptId) ?? attempts[attempts.length - 1];\n}\n\n/**\n * Shared delegation admission: definition resolution, recursion-depth bound, and\n * the capability ceiling. One projection for both a fresh delegation and a\n * historical reattachment, so a resumed child can never hold authority the\n * current parent cannot cover (no second classification, ADR 0010). The\n * admitted capability set rides along on the result: it is what the build\n * request carries so the child's policy snapshot describes the same projection\n * instead of recomputing it.\n */\nfunction resolveAdmittedDefinition(\n\toptions: DelegationRuntimeOptions,\n\tagentType: string,\n): { definition: AgentDefinition; capabilities: ReadonlySet<Capability> } {\n\tconst definition = options.resolveAgent(agentType);\n\tif (!definition) {\n\t\tthrow new Error(`Unknown agent type \"${agentType}\".`);\n\t}\n\tconst depth = options.getDelegationDepth();\n\tif (depth >= options.maxDelegationDepth) {\n\t\tthrow new Error(\n\t\t\t`Delegation depth limit (${options.maxDelegationDepth}) reached at depth ${depth}; cannot delegate to agent \"${agentType}\" further.`,\n\t\t);\n\t}\n\tconst requestedCapabilities = new Set<Capability>();\n\tfor (const toolName of definition.tools) {\n\t\tconst capabilities = options.getToolCapabilities(toolName);\n\t\tif (!capabilities) {\n\t\t\tthrow new Error(`Agent \"${agentType}\" requests unknown tool \"${toolName}\".`);\n\t\t}\n\t\tfor (const capability of capabilities) requestedCapabilities.add(capability);\n\t}\n\tconst ceiling = computeCapabilityCeiling(options.getParentCapabilities(), requestedCapabilities);\n\tif (!ceiling.allowed) {\n\t\tthrow new Error(\n\t\t\t`Delegating to agent \"${agentType}\" requires capability \"${ceiling.deniedCapability}\", which exceeds the parent's authority.`,\n\t\t);\n\t}\n\treturn { definition, capabilities: ceiling.capabilities };\n}\n\n/**\n * Lazily resolve a child's transcript path under its artifact directory, per\n * SessionManager's `<timestamp>_<sessionId>.jsonl` naming (the timestamp prefix\n * is not recorded, so the directory is scanned). Never throws: an absent\n * directory or transcript -- an in-memory child never persisted one -- simply\n * yields `undefined`, so status payloads can resolve it lazily without\n * becoming fallible. When several transcripts match, the newest wins (resume\n * may have grown the file set).\n */\nfunction resolveSessionFile(artifactDir: string | undefined, sessionId: string | undefined): string | undefined {\n\tif (!artifactDir || !sessionId) return undefined;\n\tif (!existsSync(artifactDir)) return undefined;\n\ttry {\n\t\tconst matches = readdirSync(artifactDir).filter((name) => name.endsWith(`_${sessionId}.jsonl`));\n\t\tif (matches.length === 0) return undefined;\n\t\tif (matches.length === 1) return join(artifactDir, matches[0]!);\n\t\tconst newest = matches\n\t\t\t.map((name) => ({ name, mtime: statSync(join(artifactDir, name)).mtimeMs }))\n\t\t\t.sort((a, b) => b.mtime - a.mtime)[0]!;\n\t\treturn join(artifactDir, newest.name);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Roll provider-reported usage up over session entries (the child's OWN\n * transcript is the source; SessionManager's reader supplies the entries).\n * Every surface that reports child-run usage goes through here, so the numbers\n * are summed exactly once, exactly as the provider reported them: cost is\n * provider-reported, so cache reads are NOT re-priced or re-counted, and an\n * entry without usage contributes zero. Assistant messages carry per-turn\n * usage; compaction and branch-summary entries carry their summarization\n * call's usage, which is additional real spend and therefore included.\n * Returns `undefined` when the entries hold no usage-bearing record at all\n * (nothing to report) -- callers omit rather than zero-fill.\n */\nfunction computeUsageTotals(entries: readonly FileEntry[]): ChildRunUsageTotals | undefined {\n\tlet inputTokens = 0;\n\tlet outputTokens = 0;\n\tlet cacheReadTokens = 0;\n\tlet cacheWriteTokens = 0;\n\tlet totalTokens = 0;\n\tconst cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };\n\tlet entriesCounted = 0;\n\tconst add = (usage: Usage | undefined): void => {\n\t\tif (!usage) return; // missing/absent usage counts as zero\n\t\tinputTokens += usage.input;\n\t\toutputTokens += usage.output;\n\t\tcacheReadTokens += usage.cacheRead;\n\t\tcacheWriteTokens += usage.cacheWrite;\n\t\ttotalTokens += usage.totalTokens;\n\t\tcost.input += usage.cost.input;\n\t\tcost.output += usage.cost.output;\n\t\tcost.cacheRead += usage.cost.cacheRead;\n\t\tcost.cacheWrite += usage.cost.cacheWrite;\n\t\tcost.total += usage.cost.total;\n\t};\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"message\") {\n\t\t\tif (entry.message.role !== \"assistant\") continue;\n\t\t\tentriesCounted++;\n\t\t\tadd(entry.message.usage);\n\t\t} else if (entry.type === \"compaction\" || entry.type === \"branch_summary\") {\n\t\t\tentriesCounted++;\n\t\t\tadd(entry.usage);\n\t\t}\n\t}\n\tif (entriesCounted === 0) return undefined;\n\treturn {\n\t\tinputTokens,\n\t\toutputTokens,\n\t\tcacheReadTokens,\n\t\tcacheWriteTokens,\n\t\ttotalTokens,\n\t\tcost,\n\t\tasOf: Date.now(),\n\t\tentriesCounted,\n\t};\n}\n\n// Results deliberately stay available for the lifetime of their parent runtime.\n// Phase 5 promises in-process retrieval only; restart durability belongs to Phase 6.\nexport class ChildRunRegistry {\n\tprivate readonly entries = new Map<string, BackgroundDelegation>();\n\tprivate readonly workspaceClaims = new Map<string, string[]>();\n\tprivate readonly children = new Set<ChildSessionHandle>();\n\t/**\n\t * Session ids whose workspace this registry must release on close/dispose\n\t * (spec 2026-09-09, \"Parallel work and ownership\"): populated by\n\t * `trackWorkspace()` when a worktree-isolated delegation is prepared, and\n\t * drained exactly once per session id by `releaseWorkspaceOnce()`.\n\t */\n\tprivate readonly trackedWorkspaces = new Set<string>();\n\t/** Session ids whose workspace release has already started -- release runs once, never twice. */\n\tprivate readonly releasedWorkspaces = new Set<string>();\n\t/** Last release outcome per session id, surfaced through `workspaceReleaseOutcome()`. */\n\tprivate readonly workspaceReleaseOutcomes = new Map<string, WorkspaceReleaseOutcome>();\n\tprivate workspaceOwner?: ChildWorkspaceOwner;\n\tprivate disposed = false;\n\tprivate persist?: (record: ChildRunRecord) => void;\n\tprivate records = new Map<string, ChildRunRecord>();\n\t/**\n\t * Spawn dedupe keys -> handle ids (spec 2026-09-09, idempotent spawn). A\n\t * second spawn with a known key returns the existing handle and never builds\n\t * a second child. Populated at launch and rebuilt from persisted records on\n\t * `restore()`, so a restarted parent dedupes too.\n\t */\n\tprivate readonly idempotencyKeys = new Map<string, string>();\n\t/**\n\t * Handle ids currently holding a concurrency slot (spec 2026-09-09,\n\t * \"Shared budgets\"). Admission takes one slot per child run BEFORE any child\n\t * session is built; the slot is released on terminal settlement\n\t * (completed/failed/interrupted), close, registry disposal, or launch\n\t * failure. Keyed by handle id, so release is idempotent.\n\t */\n\tprivate readonly heldRunSlots = new Set<string>();\n\t/**\n\t * The delegation runtime this registry runs under, attached by the session\n\t * that owns it (sdk wiring) or by the first `runDelegation` call. Historical\n\t * resume reattaches through the SAME `buildChildSession` seam a live\n\t * delegation uses; without an attached runtime, historical records are still\n\t * listed and their persisted output retrievable, but they cannot reattach.\n\t */\n\tprivate runtimeOptions?: DelegationRuntimeOptions;\n\t/**\n\t * Last-computed usage totals per handle id, keyed by what makes them stale\n\t * (the transcript file's size+mtime, or the in-memory entry count+last id).\n\t * The transcript file itself stays the one source: on every read the key is\n\t * re-derived and a mismatch recomputes from the file -- this cache never\n\t * becomes a second transcript.\n\t */\n\tprivate readonly usageCache = new Map<string, { key: string; totals: ChildRunUsageTotals }>();\n\t/** First attach wins: a registry is owned by one session's runtime. */\n\tsetRuntimeOptions(options: DelegationRuntimeOptions): void {\n\t\tif (!this.runtimeOptions) this.runtimeOptions = options;\n\t}\n\tsetPersistence(persist: (record: ChildRunRecord) => void): void {\n\t\tthis.persist = persist;\n\t}\n\t/** Load validated historical records. This never constructs or starts a child. */\n\trestore(records: readonly ChildRunRecord[]): void {\n\t\tfor (const record of records) {\n\t\t\tif (\n\t\t\t\t!record ||\n\t\t\t\ttypeof record.handleId !== \"string\" ||\n\t\t\t\ttypeof record.agentType !== \"string\" ||\n\t\t\t\t!Number.isFinite(record.updatedAt) ||\n\t\t\t\t![\"created\", \"running\", \"completed\", \"failed\", \"interrupted\", \"closed\"].includes(record.status)\n\t\t\t)\n\t\t\t\tcontinue;\n\t\t\t// Legacy records without attempts load with one synthesized attempt\n\t\t\t// derived from their status/updatedAt, so every in-memory record carries\n\t\t\t// at least one attempt.\n\t\t\tconst normalized: ChildRunRecord = { ...record, attempts: childRunAttemptsOf(record) };\n\t\t\tif (normalized.activeAttemptId === undefined) {\n\t\t\t\tconst openStatus = normalized.status === \"running\" || normalized.status === \"created\";\n\t\t\t\tnormalized.activeAttemptId = openStatus\n\t\t\t\t\t? normalized.attempts![normalized.attempts!.length - 1]!.id\n\t\t\t\t\t: undefined;\n\t\t\t}\n\t\t\t// Stale-running reconciliation (restart semantics): a persisted\n\t\t\t// \"running\" record cannot be live in this fresh process, so its\n\t\t\t// in-memory status becomes \"interrupted\" and its active attempt closes\n\t\t\t// as interrupted. The historical JSONL is never rewritten here -- the\n\t\t\t// corrected status persists with the record's NEXT save (e.g. a resume).\n\t\t\t// This is also the honest statement of restart semantics: a resumed run\n\t\t\t// continues from the last persisted transcript boundary, never\n\t\t\t// exactly-once -- turns that settled after the last save are re-run.\n\t\t\tif (normalized.status === \"running\") {\n\t\t\t\tnormalized.status = \"interrupted\";\n\t\t\t\tnormalized.attempts = normalized.attempts!.map((attempt) => ({ ...attempt }));\n\t\t\t\tconst attempt = normalized.attempts[normalized.attempts.length - 1];\n\t\t\t\tif (attempt) {\n\t\t\t\t\tattempt.endedAt ??= Date.now();\n\t\t\t\t\tattempt.outcome ??= \"interrupted\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.records.set(normalized.handleId, normalized);\n\t\t\tif (typeof normalized.idempotencyKey === \"string\") {\n\t\t\t\tthis.idempotencyKeys.set(normalized.idempotencyKey, normalized.handleId);\n\t\t\t}\n\t\t}\n\t}\n\t/** The handle a spawn dedupe key already maps to, if any. */\n\thandleForIdempotencyKey(key: string): string | undefined {\n\t\treturn this.idempotencyKeys.get(key);\n\t}\n\t/** True when `id` is known only as a persisted record -- no live entry in this process. */\n\tisHistorical(id: string): boolean {\n\t\treturn !this.entries.has(id) && this.records.has(id);\n\t}\n\t/**\n\t * Resolve a historical record's child session file. Verified against\n\t * SessionManager's naming (`<timestamp>_<sessionId>.jsonl` inside the\n\t * per-child artifact directory, which IS the child's session dir): the\n\t * timestamp prefix is not recorded, so the directory is scanned for the file\n\t * whose name ends in `_<sessionId>.jsonl`. Returns the validated triple so\n\t * the reattachment request carries checked values, not optional record fields.\n\t */\n\tprivate resolveHistoricalSession(record: ChildRunRecord): { path: string; sessionId: string; artifactDir: string } {\n\t\tconst artifactDir = record.artifactDir ? resolve(record.artifactDir) : undefined;\n\t\tconst sessionId = typeof record.sessionId === \"string\" ? record.sessionId : undefined;\n\t\tif (!sessionId || !artifactDir) {\n\t\t\tthrow new Error(\n\t\t\t\t`Child run \"${record.handleId}\" was never file-backed (no persisted child session directory; in-memory child), so it cannot be resumed after restart.`,\n\t\t\t);\n\t\t}\n\t\tif (!existsSync(artifactDir)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Child run \"${record.handleId}\" cannot be resumed: its artifact directory is missing: ${artifactDir}.`,\n\t\t\t);\n\t\t}\n\t\tconst path = resolveSessionFile(artifactDir, sessionId);\n\t\tif (!path) {\n\t\t\tthrow new Error(\n\t\t\t\t`Child run \"${record.handleId}\" cannot be resumed: no child session file for session \"${sessionId}\" exists under ${artifactDir} (the child never persisted a transcript).`,\n\t\t\t);\n\t\t}\n\t\treturn { path, sessionId, artifactDir };\n\t}\n\t/**\n\t * Reattach a persisted child run to its existing child session and continue\n\t * it with one turn (restart reconstruction). The child session file recorded\n\t * under the run's artifact directory is reopened through the same\n\t * `buildChildSession` seam a live delegation uses (reattachment marker), and\n\t * the run then behaves like any live entry: settlement is observed and\n\t * persisted, and wait/retrieve/sendInput work on the same handle id.\n\t *\n\t * Never-file-backed (in-memory) children, records whose artifact directory or\n\t * session file is gone, closed runs, and runs whose recorded worktree was\n\t * released all refuse with an actionable error; nothing is reconstructed\n\t * from nothing.\n\t */\n\tasync resumeHistorical(id: string, input?: string): Promise<ChildSessionStatus> {\n\t\tthis.assertOpen();\n\t\tif (this.entries.has(id)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Child run \"${id}\" is already live in this process; use sendInput instead of historical resume.`,\n\t\t\t);\n\t\t}\n\t\tconst record = this.records.get(id);\n\t\tif (!record) throw new Error(`Unknown delegation handle \"${id}\".`);\n\t\t// The worktree gate runs BEFORE the closed check: a retained (or missing)\n\t\t// workspace is the more actionable refusal for a released child, and it\n\t\t// names the persisted state and the explicit-recovery way out.\n\t\tif (record.workspace?.isolation === \"worktree\") this.rejectUnresumableWorktree(id, record);\n\t\tif (record.status === \"closed\") throw new Error(`Child run \"${id}\" was closed and cannot be resumed.`);\n\t\tif (typeof record.agentType !== \"string\" || record.agentType === \"\") {\n\t\t\tthrow new Error(`Child run \"${id}\" has a malformed record (no agent type) and cannot be resumed.`);\n\t\t}\n\t\tconst { path: sessionPath, sessionId, artifactDir } = this.resolveHistoricalSession(record);\n\t\tconst runtime = this.runtimeOptions;\n\t\tif (!runtime?.buildChildSession) {\n\t\t\tthrow new Error(`Child run \"${id}\" cannot be resumed: no delegation runtime is attached to this registry.`);\n\t\t}\n\t\tconst { definition, capabilities } = resolveAdmittedDefinition(runtime, record.agentType);\n\t\tconst workspace = record.workspace ?? { isolation: \"shared-read\" as const, ownedPaths: [] as string[] };\n\t\tconst claims = [...workspace.ownedPaths].map((p) => resolve(p));\n\t\tfor (const claim of this.activeWorkspaceClaims()) {\n\t\t\tif (claims.some((path) => claimPathsOverlap(path, claim))) {\n\t\t\t\tthrow new Error(`Resuming child run \"${id}\" overlaps an active write ownership claim.`);\n\t\t\t}\n\t\t}\n\t\tthis.claimWorkspace(id, claims);\n\t\ttry {\n\t\t\t// A resumed run counts against the concurrency limit exactly like a\n\t\t\t// live delegation, from before the child is built (spec 2026-09-09,\n\t\t\t// \"Shared budgets\").\n\t\t\tthis.admitChildRun(id);\n\t\t\tconst child = await runtime.buildChildSession({\n\t\t\t\tagentType: record.agentType,\n\t\t\t\tdefinition,\n\t\t\t\ttoolNames: definition.tools,\n\t\t\t\tcapabilities,\n\t\t\t\tdepth: typeof record.depth === \"number\" ? record.depth : 1,\n\t\t\t\tsessionId,\n\t\t\t\tartifactDir,\n\t\t\t\tworkspace,\n\t\t\t\treattachSessionPath: sessionPath,\n\t\t\t});\n\t\t\tthis.own(child);\n\t\t\t// Resume closes the previous attempt with its terminal outcome and opens\n\t\t\t// a NEW attempt (spec 2026-09-09, \"Child lifecycle\"): the resumed turn\n\t\t\t// is a fresh epoch of the same child session, never a continuation of\n\t\t\t// the interrupted attempt.\n\t\t\tconst priorAttempts = childRunAttemptsOf(record).map((attempt) => ({ ...attempt }));\n\t\t\tconst priorOutcome = terminalOutcomeOfStatus(record.status, record.cancelled);\n\t\t\tconst prior = record.activeAttemptId\n\t\t\t\t? priorAttempts.find((attempt) => attempt.id === record.activeAttemptId)\n\t\t\t\t: undefined;\n\t\t\tconst closing = prior ?? priorAttempts[priorAttempts.length - 1];\n\t\t\tif (closing && closing.endedAt === undefined) {\n\t\t\t\tclosing.endedAt = Date.now();\n\t\t\t\tclosing.outcome ??= priorOutcome;\n\t\t\t}\n\t\t\t// The resumed epoch's predecessor gets its cumulative-at-end rollup\n\t\t\t// here when the settlement before the restart never produced one: the\n\t\t\t// persisted transcript is all that survived, so its current totals are\n\t\t\t// the honest snapshot (see ChildRunAttempt.tokensAtEnd).\n\t\t\tif (closing && closing.tokensAtEnd === undefined) {\n\t\t\t\tconst totals = this.usageTotalsFor(id, record.artifactDir);\n\t\t\t\tif (totals) closing.tokensAtEnd = totals;\n\t\t\t}\n\t\t\tconst attempt: ChildRunAttempt = { id: `attempt-${priorAttempts.length + 1}`, startedAt: Date.now() };\n\t\t\tconst entry: BackgroundDelegation = {\n\t\t\t\tagentType: record.agentType,\n\t\t\t\ttask: record.task ?? \"\",\n\t\t\t\t// No initial-turn promise: each resumed turn is tracked through\n\t\t\t\t// sendInput's settlement observation, like any live entry.\n\t\t\t\tpromise: new Promise<DelegationResult>(() => {}),\n\t\t\t\tchild,\n\t\t\t\tartifactDir: record.artifactDir,\n\t\t\t\tworkspace,\n\t\t\t\tdepth: record.depth,\n\t\t\t\t// Record linkage: the reattached construction re-derives the policy\n\t\t\t\t// through the same admission projection; the record's persisted\n\t\t\t\t// values stand in when a fixture handle reports none.\n\t\t\t\tpolicy: child.policy ?? record.policy,\n\t\t\t\tsandboxEnforced: record.sandboxEnforced,\n\t\t\t\tparentSessionId: record.parentSessionId,\n\t\t\t\tattempts: [...priorAttempts, attempt],\n\t\t\t\tactiveAttemptId: attempt.id,\n\t\t\t\tidempotencyKey: typeof record.idempotencyKey === \"string\" ? record.idempotencyKey : undefined,\n\t\t\t};\n\t\t\tthis.entries.set(id, entry);\n\t\t\tthis.save(id, entry, \"running\");\n\t\t\tawait this.sendInput(id, input ?? RESUME_CHILD_PROMPT);\n\t\t\treturn child.status;\n\t\t} catch (error) {\n\t\t\tthis.releaseChildRunSlot(id);\n\t\t\tthis.releaseWorkspace(id);\n\t\t\tthrow error;\n\t\t}\n\t}\n\t/**\n\t * Gate a worktree-isolated historical resume on the workspace's persisted\n\t * state (spec 2026-09-09, \"Workspace states and explicit recovery\"). A\n\t * vanished root classifies the record \"missing\" (persisted) and refuses; a\n\t * retained (dirty/failed) root refuses, naming the persisted state and\n\t * pointing at explicit recovery. Legacy records and recovered (\"active\")\n\t * workspaces pass. Read-only: nothing is recreated, checked out, or reset.\n\t */\n\tprivate rejectUnresumableWorktree(id: string, record: ChildRunRecord): void {\n\t\tconst workspace = record.workspace!;\n\t\tconst root = workspace.root;\n\t\tif (!root) return; // never prepared: the launch failed before the owner ran\n\t\tif (!existsSync(root)) {\n\t\t\tif (record.workspaceState !== \"released\") {\n\t\t\t\trecord.workspaceState = \"missing\";\n\t\t\t\trecord.updatedAt = Date.now();\n\t\t\t\ttry {\n\t\t\t\t\tthis.persist?.(record);\n\t\t\t\t} catch {\n\t\t\t\t\t// The in-memory classification stands even if persistence cannot.\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow new Error(\n\t\t\t\t`Child run \"${id}\" cannot be resumed: its worktree workspace \"${root}\" no longer exists ` +\n\t\t\t\t\t`(workspace state: \"${record.workspaceState ?? \"missing\"}\"). Worktrees are released or retained when the ` +\n\t\t\t\t\t`owning session closes; a missing workspace cannot be recovered -- start a new delegation instead.`,\n\t\t\t);\n\t\t}\n\t\tif (record.workspaceState === \"retained-dirty\" || record.workspaceState === \"retained-failed\") {\n\t\t\tthrow new Error(\n\t\t\t\t`Child run \"${id}\" cannot be resumed: its worktree workspace \"${root}\" was retained at release ` +\n\t\t\t\t\t`(workspace state: \"${record.workspaceState}\"; uncommitted work is preserved there). Recover it explicitly first -- ` +\n\t\t\t\t\t`recoverChildWorkspace(\"${id}\") verifies the worktree and reactivates it -- then resume.`,\n\t\t\t);\n\t\t}\n\t}\n\t/**\n\t * Explicitly verify and reactivate a retained child worktree (spec\n\t * 2026-09-09, \"Workspace states and explicit recovery\"). Read-only\n\t * inspection only -- the workspace owner's verification reads the\n\t * administrative entry and the checked-out branch and never creates,\n\t * checks out, resets, or force-removes anything -- and on success the\n\t * record's workspace state becomes \"active\" (persisted) so the child can be\n\t * resumed in the SAME worktree. Automatic recreation stays out of scope by\n\t * design: every failed check refuses with an actionable error naming the\n\t * failed check, and the workspace state stays unverified.\n\t */\n\tasync recoverWorkspace(id: string): Promise<ChildWorkspaceRecoveryResult> {\n\t\tthis.assertOpen();\n\t\tconst record = this.records.get(id);\n\t\tif (!record) throw new Error(`Unknown delegation handle \"${id}\".`);\n\t\tconst workspace = record.workspace;\n\t\tif (!workspace || workspace.isolation !== \"worktree\" || !workspace.root) {\n\t\t\tthrow new Error(\n\t\t\t\t`Child workspace recovery refused for run \"${id}\": it has no worktree workspace to recover ` +\n\t\t\t\t\t`(isolation: ${workspace?.isolation ?? \"none\"}). Only worktree-isolated children hold a recoverable workspace; ` +\n\t\t\t\t\t`nothing was verified and the record is unchanged.`,\n\t\t\t);\n\t\t}\n\t\tconst root = workspace.root;\n\t\tif (!existsSync(root)) {\n\t\t\tif (record.workspaceState !== \"released\") {\n\t\t\t\trecord.workspaceState = \"missing\";\n\t\t\t\trecord.updatedAt = Date.now();\n\t\t\t\ttry {\n\t\t\t\t\tthis.persist?.(record);\n\t\t\t\t} catch {\n\t\t\t\t\t// The in-memory classification stands even if persistence cannot.\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow new Error(\n\t\t\t\t`Child workspace recovery refused for run \"${id}\": its recorded worktree root \"${root}\" does not exist ` +\n\t\t\t\t\t`(workspace state: \"${record.workspaceState ?? \"missing\"}\"). A missing workspace cannot be recovered; ` +\n\t\t\t\t\t`nothing was created.`,\n\t\t\t);\n\t\t}\n\t\tconst owner = this.workspaceOwner ?? this.runtimeOptions?.workspaceOwner;\n\t\tif (!owner || typeof owner.verify !== \"function\") {\n\t\t\tthrow new Error(\n\t\t\t\t`Child workspace recovery refused for run \"${id}\": no workspace owner with verification is available for ` +\n\t\t\t\t\t`this session. The workspace at \"${root}\" was not inspected and stays unverified.`,\n\t\t\t);\n\t\t}\n\t\tlet dirty: boolean;\n\t\ttry {\n\t\t\t({ dirty } = await owner.verify(id, root));\n\t\t} catch (error) {\n\t\t\tconst detail = error instanceof Error ? error.message : String(error);\n\t\t\tthrow new Error(\n\t\t\t\t`Child workspace recovery refused for run \"${id}\": ${detail} No recovery was performed and the ` +\n\t\t\t\t\t`workspace stays unverified.`,\n\t\t\t);\n\t\t}\n\t\trecord.workspaceState = \"active\";\n\t\trecord.updatedAt = Date.now();\n\t\ttry {\n\t\t\tthis.persist?.(record);\n\t\t} catch {\n\t\t\t// The in-memory record is reactivated regardless; the persisted state\n\t\t\t// catches up with the next save.\n\t\t}\n\t\treturn { workspaceState: \"active\", dirty };\n\t}\n\t/**\n\t * The owner consulted when a tracked child's lifecycle ends. Optional:\n\t * without one, close/dispose still clean claims but release nothing.\n\t */\n\tsetWorkspaceOwner(owner: ChildWorkspaceOwner | undefined): void {\n\t\tthis.workspaceOwner = owner;\n\t}\n\t/** Record that a child session's workspace (worktree) must be released when its lifecycle ends. */\n\ttrackWorkspace(sessionId: string): void {\n\t\tthis.trackedWorkspaces.add(sessionId);\n\t}\n\t/**\n\t * Release a tracked child's workspace through the owner, once per session\n\t * id. Best effort: a missing owner is tolerated and an owner failure never\n\t * propagates -- cleanup must never break close or dispose. The outcome is\n\t * stored per session id (`workspaceReleaseOutcome()`), and a kept tree is\n\t * warned about loudly so silent data loss cannot hide behind best-effort\n\t * cleanup.\n\t */\n\tprivate releaseWorkspaceOnce(sessionId: string): Promise<void> {\n\t\tif (this.releasedWorkspaces.has(sessionId)) return Promise.resolve();\n\t\tthis.releasedWorkspaces.add(sessionId);\n\t\tthis.trackedWorkspaces.delete(sessionId);\n\t\tconst owner = this.workspaceOwner;\n\t\tif (!owner) return Promise.resolve();\n\t\treturn Promise.resolve()\n\t\t\t.then(() => owner.release(sessionId))\n\t\t\t.catch(\n\t\t\t\t(error: unknown): WorkspaceReleaseOutcome => ({\n\t\t\t\t\tremoved: false,\n\t\t\t\t\tkept: \"failed\",\n\t\t\t\t\tdir: \"\",\n\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t}),\n\t\t\t)\n\t\t\t.then((outcome) => {\n\t\t\t\tthis.workspaceReleaseOutcomes.set(sessionId, outcome);\n\t\t\t\tthis.recordWorkspaceState(sessionId, outcome);\n\t\t\t\tif (!outcome.removed) {\n\t\t\t\t\tif (outcome.kept === \"dirty\") {\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`[apex-code] Child worktree for session \"${sessionId}\" kept at ${outcome.dir}; uncommitted child work preserved. ` +\n\t\t\t\t\t\t\t\t`Resume after reattach is refused for worktree children. Manual removal: git worktree remove --force ${outcome.dir}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`[apex-code] Child worktree release failed for session \"${sessionId}\" (tree kept at ${outcome.dir}): ${outcome.error ?? \"unknown error\"}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.catch(() => undefined);\n\t}\n\t/**\n\t * Classify a finished release on the record (spec 2026-09-09, \"Workspace\n\t * states and explicit recovery\"): removed -> \"released\", kept dirty ->\n\t * \"retained-dirty\", kept failed -> \"retained-failed\". Only worktree-isolated\n\t * records carry the state. The classified record persists immediately -- even\n\t * though release is fire-and-forget -- so a restarted parent sees the\n\t * classification and can refuse or recover accordingly.\n\t */\n\tprivate recordWorkspaceState(sessionId: string, outcome: WorkspaceReleaseOutcome): void {\n\t\tconst record = this.records.get(sessionId);\n\t\tif (!record || record.workspace?.isolation !== \"worktree\") return;\n\t\trecord.workspaceState = outcome.removed\n\t\t\t? \"released\"\n\t\t\t: outcome.kept === \"dirty\"\n\t\t\t\t? \"retained-dirty\"\n\t\t\t\t: \"retained-failed\";\n\t\trecord.updatedAt = Date.now();\n\t\ttry {\n\t\t\tthis.persist?.(record);\n\t\t} catch {\n\t\t\t// The in-memory record still carries the classification even when\n\t\t\t// persistence cannot run (best effort, like the release itself).\n\t\t}\n\t}\n\t/** The stored outcome of this session id's workspace release, if it has run. */\n\tworkspaceReleaseOutcome(sessionId: string): WorkspaceReleaseOutcome | undefined {\n\t\treturn this.workspaceReleaseOutcomes.get(sessionId);\n\t}\n\t/** Awaitable variant for the delegation failure path, which must release before the throw surfaces. */\n\tasync releaseWorkspaceNow(sessionId: string): Promise<void> {\n\t\tawait this.releaseWorkspaceOnce(sessionId);\n\t\tthis.workspaceClaims.delete(sessionId);\n\t}\n\treleaseWorkspace(sessionId: string): void {\n\t\tthis.workspaceClaims.delete(sessionId);\n\t}\n\tactiveWorkspaceClaims(): string[] {\n\t\treturn [...this.workspaceClaims.values()].flat();\n\t}\n\tclaimWorkspace(sessionId: string, paths: string[]): void {\n\t\tif (paths.length) this.workspaceClaims.set(sessionId, paths);\n\t}\n\tprivate save(handleId: string, entry: BackgroundDelegation, status: ChildRunRecord[\"status\"]): void {\n\t\tconst latest = entry.latest;\n\t\tconst record: ChildRunRecord = {\n\t\t\thandleId,\n\t\t\tagentType: entry.agentType,\n\t\t\tsessionId: handleId,\n\t\t\ttask: entry.task,\n\t\t\tartifactDir: entry.artifactDir,\n\t\t\tworkspace: entry.workspace,\n\t\t\tdepth: entry.depth,\n\t\t\tstatus,\n\t\t\tupdatedAt: Date.now(),\n\t\t\t// Attempts, the active attempt, and the spawn dedupe key persist with\n\t\t\t// every save: a restarted parent rebuilds attempts and the key->handle\n\t\t\t// map from these records alone.\n\t\t\tattempts: (entry.attempts ?? []).map((attempt) => ({ ...attempt })),\n\t\t\tactiveAttemptId: entry.activeAttemptId,\n\t\t\t// Record linkage (policy snapshot, sandbox flag, parent session id)\n\t\t\t// persists with every save too, so session readers describe the child\n\t\t\t// without re-deriving its policy (spec 2026-09-09, \"Derive, do not\n\t\t\t// reconstruct\").\n\t\t\t...(entry.parentSessionId !== undefined ? { parentSessionId: entry.parentSessionId } : {}),\n\t\t\t...(entry.policy\n\t\t\t\t? {\n\t\t\t\t\t\tpolicy: {\n\t\t\t\t\t\t\t...entry.policy,\n\t\t\t\t\t\t\ttools: [...entry.policy.tools],\n\t\t\t\t\t\t\tcapabilities: [...entry.policy.capabilities],\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(entry.sandboxEnforced !== undefined ? { sandboxEnforced: entry.sandboxEnforced } : {}),\n\t\t\t...(entry.idempotencyKey !== undefined ? { idempotencyKey: entry.idempotencyKey } : {}),\n\t\t\t...(entry.deadlineMs !== undefined ? { deadlineMs: entry.deadlineMs } : {}),\n\t\t\t...(entry.cancelled ? { cancelled: { ...entry.cancelled } } : {}),\n\t\t};\n\t\t// The settlement's output persists with the record so a historical run's\n\t\t// result stays retrievable after restart without reattaching the child.\n\t\tif (latest) {\n\t\t\trecord.latestResult = {\n\t\t\t\toutput:\n\t\t\t\t\tlatest.outcome === \"failed\"\n\t\t\t\t\t\t? latest.error instanceof Error\n\t\t\t\t\t\t\t? latest.error.message\n\t\t\t\t\t\t\t: String(latest.error)\n\t\t\t\t\t\t: latest.output,\n\t\t\t\toutcome: latest.outcome,\n\t\t\t};\n\t\t}\n\t\tthis.records.set(handleId, record);\n\t\tthis.persist?.(record);\n\t}\n\t/**\n\t * Record a turn settlement from the child handle's own report, falling back to\n\t * the settlement value for handles that did not report. The latest settlement\n\t * wins; retrieval serves it instead of the stored first-turn promise.\n\t */\n\tprivate recordCompletion(id: string, entry: BackgroundDelegation, fallbackOutput: string): void {\n\t\tconst reported = entry.child?.latestResult?.();\n\t\tentry.latest =\n\t\t\t!reported || reported.outcome === \"completed\"\n\t\t\t\t? { outcome: \"completed\", output: reported?.output ?? fallbackOutput }\n\t\t\t\t: reported.outcome === \"interrupted\"\n\t\t\t\t\t? { outcome: \"interrupted\", output: reported.output }\n\t\t\t\t\t: { outcome: \"failed\", error: new Error(reported.output || \"Child run failed.\") };\n\t\tthis.persistSettlement(id, entry);\n\t}\n\tprivate recordFailure(id: string, entry: BackgroundDelegation, error: unknown): void {\n\t\tconst reported = entry.child?.latestResult?.();\n\t\tentry.latest =\n\t\t\treported?.outcome === \"interrupted\" || (!reported && entry.child?.status === \"interrupted\")\n\t\t\t\t? { outcome: \"interrupted\", output: reported?.output ?? \"\" }\n\t\t\t\t: { outcome: \"failed\", error };\n\t\tthis.persistSettlement(id, entry);\n\t}\n\t/**\n\t * Stamp the active attempt with the settled turn's outcome. A cancellation\n\t * recorded on the entry wins for an interrupted settlement: the attempt\n\t * stays `cancelled` instead of downgrading to plain `interrupted`. Attempt\n\t * usage snapshots from the child's own controller where its handle exposes\n\t * one; handles without a controller leave usage unset. `tokensAtEnd`\n\t * snapshots the run-level token/cost rollup at settlement time (a\n\t * cumulative-at-end snapshot of the whole transcript -- see\n\t * `ChildRunAttempt`); when nothing is reachable it stays unset.\n\t */\n\tprivate stampAttemptSettlement(id: string, entry: BackgroundDelegation): void {\n\t\tconst attempt = activeAttemptOf(entry);\n\t\tconst latest = entry.latest;\n\t\tif (!attempt || !latest) return;\n\t\tattempt.outcome = latest.outcome === \"interrupted\" && entry.cancelled ? \"cancelled\" : latest.outcome;\n\t\tif (latest.outcome === \"failed\") {\n\t\t\tattempt.error = latest.error instanceof Error ? latest.error.message : String(latest.error);\n\t\t}\n\t\tconst usage = entry.child?.usage?.();\n\t\tif (usage) attempt.usage = usage;\n\t\tconst totals = this.usageTotalsFor(id, entry.artifactDir, entry.child);\n\t\tif (totals) attempt.tokensAtEnd = totals;\n\t}\n\t/** Persist the settlement's status. A closed run's terminal status is never overwritten by late settlement. */\n\tprivate persistSettlement(id: string, entry: BackgroundDelegation): void {\n\t\tif (entry.closed) return;\n\t\tconst latest = entry.latest;\n\t\tif (!latest) return;\n\t\tthis.stampAttemptSettlement(id, entry);\n\t\tthis.save(\n\t\t\tid,\n\t\t\tentry,\n\t\t\tlatest.outcome === \"completed\" ? \"completed\" : latest.outcome === \"interrupted\" ? \"interrupted\" : \"failed\",\n\t\t);\n\t\t// Terminal settlement (completed/failed/interrupted) releases the run's\n\t\t// concurrency slot (spec 2026-09-09, \"Shared budgets\").\n\t\tthis.releaseChildRunSlot(id);\n\t}\n\tassertOpen(): void {\n\t\tif (this.disposed) throw new Error(\"Child run registry is disposed.\");\n\t}\n\t/** The configured child-run concurrency limit, if any. */\n\tprivate concurrencyLimit(): number | undefined {\n\t\tconst limit = this.runtimeOptions?.maxConcurrentChildren;\n\t\treturn typeof limit === \"number\" && Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : undefined;\n\t}\n\t/**\n\t * Concurrency admission (spec 2026-09-09, \"Shared budgets\"): refuse with an\n\t * actionable error naming the limit BEFORE any child session is built when\n\t * every slot is occupied. An admitted run holds one slot until terminal\n\t * settlement, close, dispose, or a launch failure releases it.\n\t */\n\tadmitChildRun(handleId: string): void {\n\t\tconst limit = this.concurrencyLimit();\n\t\tif (limit === undefined) return;\n\t\tif (this.heldRunSlots.size >= limit) {\n\t\t\tthrow new Error(\n\t\t\t\t`Delegation refused: maxConcurrentChildren=${limit} and ${this.heldRunSlots.size} child run(s) are still active. Wait for a child run to finish or close it, or raise maxConcurrentChildren.`,\n\t\t\t);\n\t\t}\n\t\tthis.heldRunSlots.add(handleId);\n\t}\n\t/** Release a run's concurrency slot. Idempotent. */\n\treleaseChildRunSlot(handleId: string): void {\n\t\tthis.heldRunSlots.delete(handleId);\n\t}\n\town(child: ChildSessionHandle): void {\n\t\tif (this.disposed) {\n\t\t\tchild.dispose();\n\t\t\tthis.assertOpen();\n\t\t}\n\t\tthis.children.add(child);\n\t}\n\trelease(child: ChildSessionHandle): void {\n\t\tif (this.children.delete(child)) child.dispose();\n\t}\n\tregister(id: string, entry: BackgroundDelegation): void {\n\t\tthis.assertOpen();\n\t\t// A launch is attempt 1: an entry without attempts starts its first epoch\n\t\t// here (resumeHistorical supplies its own carried-over attempts).\n\t\tif (entry.attempts === undefined || entry.attempts.length === 0) {\n\t\t\tentry.attempts = [{ id: \"attempt-1\", startedAt: Date.now() }];\n\t\t\tentry.activeAttemptId ??= entry.attempts[0]!.id;\n\t\t}\n\t\tif (entry.idempotencyKey !== undefined) {\n\t\t\tthis.idempotencyKeys.set(entry.idempotencyKey, id);\n\t\t}\n\t\tif (!this.entries.has(id)) {\n\t\t\tthis.entries.set(id, entry);\n\t\t\t// Observe the initial turn's settlement here so the latest result is\n\t\t\t// recorded even when retrieval never happens; this derived branch always\n\t\t\t// resolves, so it can never become an unhandled rejection itself.\n\t\t\tconst settled = entry.promise.then(\n\t\t\t\t(result) => {\n\t\t\t\t\tthis.recordCompletion(id, entry, result.output);\n\t\t\t\t\treturn result;\n\t\t\t\t},\n\t\t\t\t(error) => {\n\t\t\t\t\tthis.recordFailure(id, entry, error);\n\t\t\t\t\treturn undefined as unknown as DelegationResult;\n\t\t\t\t},\n\t\t\t);\n\t\t\tvoid settled.catch(() => undefined);\n\t\t\tentry.pending = settled;\n\t\t}\n\t\tthis.save(id, entry, \"created\");\n\t}\n\tretrieve(id: string, expected?: string): Promise<DelegationResult> {\n\t\tconst entry = this.entries.get(id);\n\t\tif (!entry) {\n\t\t\tconst record = this.records.get(id);\n\t\t\tif (!record) throw new Error(`Unknown delegation handle \"${id}\".`);\n\t\t\tif (expected !== undefined && record.agentType !== expected)\n\t\t\t\tthrow new Error(`Delegation handle \"${id}\" belongs to agent \"${record.agentType}\", not \"${expected}\".`);\n\t\t\tconst latest = record.latestResult;\n\t\t\tif (!latest) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Child run \"${id}\" has no persisted output, so its result cannot be recovered after restart. Resume it with resumeChildRun(\"${id}\") to reattach its child session.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn Promise.resolve({\n\t\t\t\tagentType: record.agentType,\n\t\t\t\ttask: record.task ?? \"\",\n\t\t\t\toutput: latest.output,\n\t\t\t\toutcome: latest.outcome,\n\t\t\t});\n\t\t}\n\t\tif (expected !== undefined && entry.agentType !== expected)\n\t\t\tthrow new Error(`Delegation handle \"${id}\" belongs to agent \"${entry.agentType}\", not \"${expected}\".`);\n\t\treturn this.latestDelegationResult(entry);\n\t}\n\t/** Await any in-flight turn, then serve its settled outcome -- not the stored first-turn promise. */\n\tprivate async latestDelegationResult(entry: BackgroundDelegation): Promise<DelegationResult> {\n\t\tif (entry.pending) await entry.pending.catch(() => undefined);\n\t\tconst latest = entry.latest;\n\t\tif (!latest) return entry.promise;\n\t\tif (latest.outcome === \"failed\") throw latest.error;\n\t\treturn { agentType: entry.agentType, task: entry.task, output: latest.output, outcome: latest.outcome };\n\t}\n\t/**\n\t * One entry per child run -- live entries first, then historical records --\n\t * each as `{handleId, agentType, task, status, attemptCount}`. Backward\n\t * compatible: fields were only ever added. Observing the list lazily\n\t * interrupts a live running child whose wall-clock deadline has passed.\n\t */\n\tlist(): { handleId: string; agentType: string; task: string; status: ChildSessionStatus; attemptCount: number }[] {\n\t\tthis.observeDeadlines();\n\t\tconst historical = [...this.records]\n\t\t\t.filter(([id]) => !this.entries.has(id))\n\t\t\t.map(([handleId, record]) => ({\n\t\t\t\thandleId,\n\t\t\t\tagentType: record.agentType,\n\t\t\t\ttask: record.task ?? \"\",\n\t\t\t\tstatus:\n\t\t\t\t\trecord.status === \"closed\"\n\t\t\t\t\t\t? \"closed\"\n\t\t\t\t\t\t: record.status === \"interrupted\"\n\t\t\t\t\t\t\t? \"interrupted\"\n\t\t\t\t\t\t\t: record.status === \"running\"\n\t\t\t\t\t\t\t\t? \"running\"\n\t\t\t\t\t\t\t\t: (\"idle\" as ChildSessionStatus),\n\t\t\t\tattemptCount: childRunAttemptsOf(record).length,\n\t\t\t}));\n\t\treturn [...this.entries]\n\t\t\t.map(([handleId, entry]) => ({\n\t\t\t\thandleId,\n\t\t\t\tagentType: entry.agentType,\n\t\t\t\ttask: entry.task,\n\t\t\t\tstatus: entry.closed ? \"closed\" : (entry.child?.status ?? \"idle\"),\n\t\t\t\tattemptCount: (entry.attempts ?? []).length,\n\t\t\t}))\n\t\t\t.concat(historical);\n\t}\n\t/**\n\t * Non-blocking status snapshot for one handle (spec 2026-09-09, pollable\n\t * status): built from the live entry or the persisted record alone, never by\n\t * awaiting a turn. Unknown ids still error. Observing the status lazily\n\t * interrupts a live running child whose wall-clock deadline has passed, so a\n\t * timed-out run is reported (and stopped) at observation time.\n\t */\n\tstatus(id: string): ChildRunStatus {\n\t\tthis.assertOpen();\n\t\tthis.observeDeadlines();\n\t\tconst entry = this.entries.get(id);\n\t\tif (entry) return this.statusFromEntry(id, entry);\n\t\tconst record = this.records.get(id);\n\t\tif (!record) throw new Error(`Unknown delegation handle \"${id}\".`);\n\t\treturn this.statusFromRecord(record);\n\t}\n\t/**\n\t * The run's token/cost totals, rolled up on demand from the child's OWN\n\t * session transcript (the session-file reading seam) -- or from the handle's\n\t * in-memory session entries when no transcript file exists. Reads lazily and\n\t * caches only the last-computed totals, keyed by transcript size/mtime or\n\t * entry count, so the cache can never become a second transcript.\n\t * `undefined` -- never zero-filled, never a throw -- when nothing is\n\t * reachable: an in-memory child without a reachable transcript, or a\n\t * historical record whose transcript is gone. Unknown ids error like\n\t * `status`.\n\t */\n\tusageTotals(id: string): ChildRunUsageTotals | undefined {\n\t\tthis.assertOpen();\n\t\tconst entry = this.entries.get(id);\n\t\tif (entry) return this.usageTotalsFor(id, entry.artifactDir, entry.child);\n\t\tconst record = this.records.get(id);\n\t\tif (!record) throw new Error(`Unknown delegation handle \"${id}\".`);\n\t\treturn this.usageTotalsFor(id, record.artifactDir);\n\t}\n\t/**\n\t * One rollup read for both live entries and historical records: a\n\t * resolvable transcript file wins (the persisted transcript is the source of\n\t * truth, including after restart); the handle's in-memory session entries\n\t * cover an in-memory child whose transcript was never written.\n\t */\n\tprivate usageTotalsFor(\n\t\tid: string,\n\t\tartifactDir: string | undefined,\n\t\tchild?: ChildSessionHandle,\n\t): ChildRunUsageTotals | undefined {\n\t\tconst sessionFile = resolveSessionFile(artifactDir, id);\n\t\tif (sessionFile) {\n\t\t\ttry {\n\t\t\t\tconst stats = statSync(sessionFile);\n\t\t\t\tconst key = `file:${stats.size}:${stats.mtimeMs}`;\n\t\t\t\tconst cached = this.usageCache.get(id);\n\t\t\t\tif (cached && cached.key === key) return cached.totals;\n\t\t\t\tconst totals = computeUsageTotals(loadEntriesFromFile(sessionFile));\n\t\t\t\tif (totals) this.usageCache.set(id, { key, totals });\n\t\t\t\treturn totals;\n\t\t\t} catch {\n\t\t\t\t// An unreadable transcript falls through to the in-memory seam below;\n\t\t\t\t// reporting usage must never turn a status read into a failure.\n\t\t\t}\n\t\t}\n\t\tconst entries = child?.sessionEntries?.();\n\t\tif (entries) {\n\t\t\tconst last = entries[entries.length - 1];\n\t\t\tconst key = `mem:${entries.length}:${last?.id ?? \"\"}`;\n\t\t\tconst cached = this.usageCache.get(id);\n\t\t\tif (cached && cached.key === key) return cached.totals;\n\t\t\tconst totals = computeUsageTotals(entries);\n\t\t\tif (totals) this.usageCache.set(id, { key, totals });\n\t\t\treturn totals;\n\t\t}\n\t\treturn undefined;\n\t}\n\t/** The status payload's flattened view of the rollup, omitted when unreachable. */\n\tprivate static usageSummaryOf(totals: ChildRunUsageTotals | undefined): {\n\t\ttokens?: ChildRunStatus[\"tokens\"];\n\t\tcost?: ChildRunStatus[\"cost\"];\n\t} {\n\t\tif (!totals) return {};\n\t\treturn {\n\t\t\ttokens: {\n\t\t\t\tinputTokens: totals.inputTokens,\n\t\t\t\toutputTokens: totals.outputTokens,\n\t\t\t\tcacheReadTokens: totals.cacheReadTokens,\n\t\t\t\tcacheWriteTokens: totals.cacheWriteTokens,\n\t\t\t\ttotalTokens: totals.totalTokens,\n\t\t\t},\n\t\t\tcost: { ...totals.cost },\n\t\t};\n\t}\n\tprivate statusFromEntry(id: string, entry: BackgroundDelegation): ChildRunStatus {\n\t\tconst attempt = activeAttemptOf(entry);\n\t\tconst latest = entry.latest;\n\t\tconst usage = entry.child?.usage?.();\n\t\tconst workspace = entry.workspace;\n\t\t// The persisted record is the authority for a worktree's lifecycle state\n\t\t// (a closed-but-live entry's release may already have classified it);\n\t\t// while the record has none the live workspace is simply active.\n\t\tconst workspaceState = this.records.get(id)?.workspaceState;\n\t\t// Entries never carry their own session id: save() always records the\n\t\t// handle id as the child session id, so transcript resolution uses it.\n\t\tconst sessionFile = resolveSessionFile(entry.artifactDir, id);\n\t\treturn {\n\t\t\thandleId: id,\n\t\t\tagentType: entry.agentType,\n\t\t\ttask: entry.task,\n\t\t\tstatus: entry.closed ? \"closed\" : (entry.child?.status ?? \"idle\"),\n\t\t\tattempt: {\n\t\t\t\tid: attempt?.id ?? \"\",\n\t\t\t\t...(attempt?.outcome !== undefined ? { outcome: attempt.outcome } : {}),\n\t\t\t},\n\t\t\tattempts: (entry.attempts ?? []).length,\n\t\t\t...(latest\n\t\t\t\t? {\n\t\t\t\t\t\tlastResult: {\n\t\t\t\t\t\t\toutput:\n\t\t\t\t\t\t\t\tlatest.outcome === \"failed\"\n\t\t\t\t\t\t\t\t\t? latest.error instanceof Error\n\t\t\t\t\t\t\t\t\t\t? latest.error.message\n\t\t\t\t\t\t\t\t\t\t: String(latest.error)\n\t\t\t\t\t\t\t\t\t: latest.output,\n\t\t\t\t\t\t\toutcome: latest.outcome,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(entry.cancelled ? { cancelled: { ...entry.cancelled } } : {}),\n\t\t\t...(entry.deadlineMs !== undefined ? { deadlineMs: entry.deadlineMs } : {}),\n\t\t\t...(usage ? { usage } : {}),\n\t\t\t// Token/cost rollup from the child's own transcript, on the same lazy,\n\t\t\t// cached seam `usageTotals` serves; omitted when nothing is reachable.\n\t\t\t...ChildRunRegistry.usageSummaryOf(this.usageTotalsFor(id, entry.artifactDir, entry.child)),\n\t\t\t...(workspace\n\t\t\t\t? {\n\t\t\t\t\t\tworkspace: {\n\t\t\t\t\t\t\tisolation: workspace.isolation,\n\t\t\t\t\t\t\t...(workspace.root ? { root: workspace.root } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t...(workspace.isolation === \"worktree\" ? { workspaceState: workspaceState ?? \"active\" } : {}),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t// Record linkage (additive): artifact/session-file/parent identity,\n\t\t\t// the derived policy, and the sandbox flag ride along when known and\n\t\t\t// are simply omitted otherwise.\n\t\t\t...(entry.artifactDir !== undefined ? { artifactDir: entry.artifactDir } : {}),\n\t\t\t...(sessionFile !== undefined ? { sessionFile } : {}),\n\t\t\t...(entry.parentSessionId !== undefined ? { parentSessionId: entry.parentSessionId } : {}),\n\t\t\t...(entry.policy ? { policy: entry.policy } : {}),\n\t\t\t...(entry.sandboxEnforced !== undefined ? { sandboxEnforced: entry.sandboxEnforced } : {}),\n\t\t};\n\t}\n\tprivate statusFromRecord(record: ChildRunRecord): ChildRunStatus {\n\t\tconst attempts = childRunAttemptsOf(record);\n\t\t// The active attempt when one is open; otherwise (terminal or legacy\n\t\t// record) the most recent attempt carries the reported outcome.\n\t\tconst attempt = record.activeAttemptId\n\t\t\t? (attempts.find((candidate) => candidate.id === record.activeAttemptId) ?? attempts[attempts.length - 1])\n\t\t\t: attempts[attempts.length - 1];\n\t\tconst workspace = record.workspace;\n\t\tconst sessionFile = resolveSessionFile(record.artifactDir, record.sessionId);\n\t\treturn {\n\t\t\thandleId: record.handleId,\n\t\t\tagentType: record.agentType,\n\t\t\ttask: record.task ?? \"\",\n\t\t\tstatus:\n\t\t\t\trecord.status === \"closed\"\n\t\t\t\t\t? \"closed\"\n\t\t\t\t\t: record.status === \"interrupted\"\n\t\t\t\t\t\t? \"interrupted\"\n\t\t\t\t\t\t: record.status === \"running\"\n\t\t\t\t\t\t\t? \"running\"\n\t\t\t\t\t\t\t: (\"idle\" as ChildSessionStatus),\n\t\t\tattempt: {\n\t\t\t\tid: attempt?.id ?? attempts[attempts.length - 1]?.id ?? \"\",\n\t\t\t\t...(attempt?.outcome !== undefined ? { outcome: attempt.outcome } : {}),\n\t\t\t},\n\t\t\tattempts: attempts.length,\n\t\t\t...(record.latestResult ? { lastResult: { ...record.latestResult } } : {}),\n\t\t\t...(record.cancelled ? { cancelled: { ...record.cancelled } } : {}),\n\t\t\t...(record.deadlineMs !== undefined ? { deadlineMs: record.deadlineMs } : {}),\n\t\t\t// Token/cost rollup from the persisted transcript, so a restarted\n\t\t\t// parent reports the same totals without a live child.\n\t\t\t...ChildRunRegistry.usageSummaryOf(this.usageTotalsFor(record.handleId, record.artifactDir)),\n\t\t\t...(workspace\n\t\t\t\t? {\n\t\t\t\t\t\tworkspace: {\n\t\t\t\t\t\t\tisolation: workspace.isolation,\n\t\t\t\t\t\t\t...(workspace.root ? { root: workspace.root } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t// Absent means active (legacy records predate the field).\n\t\t\t\t\t\t...(workspace.isolation === \"worktree\" ? { workspaceState: record.workspaceState ?? \"active\" } : {}),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t// Record linkage (additive): legacy records without the fields simply\n\t\t\t// omit them (spec 2026-09-09, policy/sandbox/artifact linkage).\n\t\t\t...(record.artifactDir !== undefined ? { artifactDir: record.artifactDir } : {}),\n\t\t\t...(sessionFile !== undefined ? { sessionFile } : {}),\n\t\t\t...(record.parentSessionId !== undefined ? { parentSessionId: record.parentSessionId } : {}),\n\t\t\t...(record.policy ? { policy: record.policy } : {}),\n\t\t\t...(record.sandboxEnforced !== undefined ? { sandboxEnforced: record.sandboxEnforced } : {}),\n\t\t};\n\t}\n\t/**\n\t * Lazy deadline observation (spec 2026-09-09, timeouts): a live RUNNING child\n\t * past its recorded wall-clock deadline is interrupted at observation time.\n\t * The interrupt carries no reason -- a wall-time timeout is not a user\n\t * cancellation -- so the attempt settles `interrupted`, and the child's own\n\t * budget gate names \"wall-time\" in the settlement error path when the run's\n\t * turn was refused for time. Historical records have no live child to\n\t * interrupt and are left untouched.\n\t */\n\tprivate observeDeadlines(): void {\n\t\tconst now = Date.now();\n\t\tfor (const [id, entry] of this.entries) {\n\t\t\tif (entry.closed || entry.deadlineMs === undefined || now < entry.deadlineMs) continue;\n\t\t\tif (entry.child?.status !== \"running\") continue;\n\t\t\ttry {\n\t\t\t\tthis.interrupt(id);\n\t\t\t} catch {\n\t\t\t\t// The child vanished between the check and the interrupt; nothing left to observe.\n\t\t\t}\n\t\t}\n\t}\n\tprivate child(id: string): ChildSessionHandle {\n\t\tthis.assertOpen();\n\t\tconst entry = this.entries.get(id);\n\t\tif (!entry) throw new Error(`Unknown delegation handle \"${id}\".`);\n\t\tif (entry.closed) throw new Error(`Child session \"${id}\" is closed.`);\n\t\tif (!entry.child) throw new Error(`Delegation handle \"${id}\" has no child session.`);\n\t\treturn entry.child;\n\t}\n\tasync wait(id: string): Promise<DelegationResult> {\n\t\tconst entry = this.entries.get(id);\n\t\t// A historical record has nothing to await: its persisted settlement (if\n\t\t// any) is served through retrieve, which throws the actionable error when\n\t\t// no output was persisted.\n\t\tif (!entry) return this.retrieve(id);\n\t\tif (!entry.closed) {\n\t\t\tconst child = this.child(id);\n\t\t\tif (entry.pending || child.status === \"running\") this.save(id, entry, \"running\");\n\t\t\t// A turn that ends interrupted or failed rejects here; retrieval below owns\n\t\t\t// propagation, surfacing interrupted as an outcome and failed as a throw.\n\t\t\tawait child.wait().catch(() => undefined);\n\t\t}\n\t\treturn this.retrieve(id);\n\t}\n\tsendInput(id: string, input: string): Promise<void> {\n\t\t// Unknown and closed handles throw synchronously, matching close()'s contract.\n\t\tconst child = this.child(id);\n\t\tconst entry = this.entries.get(id)!;\n\t\tconst turn = child.sendInput(input).then(\n\t\t\t() => {\n\t\t\t\tthis.recordCompletion(id, entry, \"\");\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\tthis.recordFailure(id, entry, error);\n\t\t\t\tthrow error;\n\t\t\t},\n\t\t);\n\t\tvoid turn.catch(() => undefined);\n\t\tentry.pending = turn;\n\t\treturn turn;\n\t}\n\t/**\n\t * Interrupt a live child. An optional reason turns the interrupt into an\n\t * explicit cancellation: `{reason, at}` is persisted on the record\n\t * immediately and the active attempt is marked `cancelled`; without a\n\t * reason the attempt settles plain `interrupted` at the turn's settlement.\n\t */\n\tinterrupt(id: string, reason?: string): void {\n\t\tthis.child(id).interrupt();\n\t\tif (reason === undefined) return;\n\t\tconst entry = this.entries.get(id);\n\t\tif (!entry) return; // Unreachable: child(id) already validated the handle.\n\t\tentry.cancelled = { reason, at: Date.now() };\n\t\tconst attempt = activeAttemptOf(entry);\n\t\tif (attempt) attempt.outcome = \"cancelled\";\n\t\t// The child's post-interrupt handle status maps onto the record's status\n\t\t// vocabulary (\"idle\" is a handle state, not a record state).\n\t\tconst childStatus = entry.child?.status;\n\t\tconst recordStatus: ChildRunRecord[\"status\"] = childStatus === \"running\" ? \"running\" : \"interrupted\";\n\t\tthis.save(id, entry, recordStatus);\n\t}\n\t/**\n\t * Close a live run's active attempt with its latest settled outcome and open\n\t * a new one for the resuming turn (spec 2026-09-09, \"Child lifecycle\"):\n\t * `AgentSession.resumeChildRun` calls this on the live path before\n\t * `sendInput` so a resume is a distinct attempt epoch, while ordinary\n\t * follow-ups on a live run stay inside the active attempt.\n\t */\n\tbeginResumeAttempt(id: string): void {\n\t\tconst entry = this.entries.get(id);\n\t\tif (!entry) throw new Error(`Unknown delegation handle \"${id}\".`);\n\t\tconst prior = activeAttemptOf(entry);\n\t\tif (prior && prior.endedAt === undefined) {\n\t\t\tprior.endedAt = Date.now();\n\t\t\tprior.outcome ??= entry.latest?.outcome;\n\t\t}\n\t\t// A resume close stamps the closed attempt's cumulative-at-end rollup\n\t\t// when its settlement never produced one (a settlement-stamped snapshot\n\t\t// is never overwritten with the later, larger transcript).\n\t\tif (prior && prior.tokensAtEnd === undefined) {\n\t\t\tconst totals = this.usageTotalsFor(id, entry.artifactDir, entry.child);\n\t\t\tif (totals) prior.tokensAtEnd = totals;\n\t\t}\n\t\tconst attempts = entry.attempts ?? [];\n\t\tconst attempt: ChildRunAttempt = { id: `attempt-${attempts.length + 1}`, startedAt: Date.now() };\n\t\tattempts.push(attempt);\n\t\tentry.attempts = attempts;\n\t\tentry.activeAttemptId = attempt.id;\n\t}\n\tclose(id: string): void {\n\t\tthis.assertOpen();\n\t\tconst entry = this.entries.get(id);\n\t\tif (!entry) throw new Error(`Unknown delegation handle \"${id}\".`);\n\t\tif (entry.closed) return;\n\t\tentry.closed = true;\n\t\tthis.workspaceClaims.delete(id);\n\t\t// A closed run's slot is released with it (spec 2026-09-09, \"Shared\n\t\t// budgets\"), even when its turn never settles.\n\t\tthis.releaseChildRunSlot(id);\n\t\t// Release the child's workspace (worktree) with its lifecycle; best effort,\n\t\t// fire-and-forget: close() is synchronous and must never throw on cleanup.\n\t\tvoid this.releaseWorkspaceOnce(id);\n\t\tthis.save(id, entry, \"closed\");\n\t\tif (entry.child) {\n\t\t\tthis.children.delete(entry.child);\n\t\t\tentry.child.close();\n\t\t}\n\t}\n\t/** Stop tracking handles and release any children and workspaces still owned by this registry. */\n\tdispose(): void {\n\t\tif (this.disposed) return;\n\t\tthis.disposed = true;\n\t\tfor (const child of this.children) {\n\t\t\ttry {\n\t\t\t\tchild.interrupt();\n\t\t\t} catch {}\n\t\t\ttry {\n\t\t\t\tthis.release(child);\n\t\t\t} catch {}\n\t\t}\n\t\t// Release every tracked child workspace (worktree) with the registry.\n\t\t// Best effort and fire-and-forget: dispose() is synchronous.\n\t\tfor (const sessionId of this.trackedWorkspaces) {\n\t\t\tvoid this.releaseWorkspaceOnce(sessionId);\n\t\t}\n\t\tthis.entries.clear();\n\t\tthis.workspaceClaims.clear();\n\t\tthis.usageCache.clear();\n\t\t// No run holds a concurrency slot past the registry's disposal.\n\t\tthis.heldRunSlots.clear();\n\t}\n}\n\n/**\n * Run one delegation to completion. Throws rather than returning a failure value,\n * matching this codebase's convention for model-facing routine failures (e.g.\n * `tool_schema`'s unknown-tool case, `web_search`'s unconfigured-backend case): a\n * thrown `Error` here is caught by the agent loop and surfaces as a normal,\n * model-readable `isError` tool result, not a fatal turn failure.\n *\n * The capability check is all-or-nothing by design (ceiling.ts): a definition\n * requesting a tool the parent's own capabilities cannot cover refuses the whole\n * delegation, naming the capability, rather than silently building a child missing\n * that one tool. `buildChildSession` is therefore never called for a refused\n * delegation -- there is no code path that produces a child holding a capability\n * outside the ceiling.\n *\n * The depth check (task 5.3) runs right after agent-type resolution and before the\n * capability check, so recursion is bounded regardless of what is being delegated --\n * a refusal at the bound still names the agent type, but never reaches the ceiling\n * or `buildChildSession`. `buildChildSession` receives the child's depth (parent + 1)\n * so the caller can record it on the child's own session header.\n */\n/**\n * Whether two resolved paths denote the same directory or either contains the\n * other. Comparison is separator-correct: forward-slash prefix matching\n * silently never matches on platforms whose resolve() produces backslashes.\n */\nexport function claimPathsOverlap(a: string, b: string): boolean {\n\tconst ab = relative(a, b);\n\tif (ab !== \"..\" && !ab.startsWith(`..${sep}`) && !isAbsolute(ab)) return true;\n\tconst ba = relative(b, a);\n\treturn ba !== \"..\" && !ba.startsWith(`..${sep}`) && !isAbsolute(ba);\n}\n\nexport async function runDelegation(\n\toptions: DelegationRuntimeOptions,\n\tagentType: string,\n\ttask: string,\n\trequest: {\n\t\tbackground?: boolean;\n\t\tworkspace?: ChildWorkspaceRequest;\n\t\thandleId?: string;\n\t\t/** Spawn dedupe key (spec 2026-09-09, idempotent spawn): a known key returns the EXISTING handle without building a second child. */\n\t\tidempotencyKey?: string;\n\t\t/** Wall-time cap for the child's own run budget; also recorded as the record's deadlineMs for lazy observation. */\n\t\ttimeoutMs?: number;\n\t} = {},\n): Promise<DelegationResult> {\n\tlet registry = options.childRunRegistry;\n\tif (!registry) {\n\t\tregistry = new ChildRunRegistry();\n\t\toptions.childRunRegistry = registry;\n\t}\n\tregistry.assertOpen();\n\tregistry.setRuntimeOptions(options);\n\t// Idempotent spawn: a key that already maps to a handle returns that handle\n\t// BEFORE any admission or child construction, so a duplicate spawn consumes\n\t// no second concurrency slot. The map is rebuilt from persisted records on\n\t// restore, so a restarted parent dedupes too.\n\tif (request.idempotencyKey !== undefined) {\n\t\tconst existing = registry.handleForIdempotencyKey(request.idempotencyKey);\n\t\tif (existing !== undefined) {\n\t\t\treturn {\n\t\t\t\tagentType,\n\t\t\t\ttask,\n\t\t\t\toutput: `Delegation already started with handle \"${existing}\" (idempotency key \"${request.idempotencyKey}\"); retrieve it with that handle.`,\n\t\t\t\thandleId: existing,\n\t\t\t};\n\t\t}\n\t}\n\tconst timeoutMs =\n\t\ttypeof request.timeoutMs === \"number\" && Number.isFinite(request.timeoutMs) ? request.timeoutMs : undefined;\n\tconst { definition, capabilities } = resolveAdmittedDefinition(options, agentType);\n\tconst workspace = request.workspace ?? { isolation: \"shared-read\", ownedPaths: [] };\n\t// The owner is read only for worktree isolation, so production callers can\n\t// construct it lazily: a shared-read delegation never builds an owner and\n\t// never invokes git.\n\tconst workspaceOwner = workspace.isolation === \"worktree\" ? options.workspaceOwner : undefined;\n\tif (workspace.isolation === \"worktree\" && !workspaceOwner) {\n\t\tthrow new Error(\n\t\t\t`Delegation to agent \"${agentType}\" requested worktree isolation, but no workspace owner is available.`,\n\t\t);\n\t}\n\tconst claims = [...workspace.ownedPaths].map((p) => resolve(p));\n\tfor (const entry of registry.activeWorkspaceClaims()) {\n\t\tif (claims.some((path) => claimPathsOverlap(path, entry))) {\n\t\t\tthrow new Error(`Delegation to agent \"${agentType}\" overlaps an active write ownership claim.`);\n\t\t}\n\t}\n\n\t// The depth bound and capability ceiling are enforced inside\n\t// resolveAdmittedDefinition above, shared with historical reattachment.\n\t// The caller may provide the public handle so the registry identity and\n\t// child session identity cannot diverge. Existing callers retain generated IDs.\n\tconst sessionId = request.handleId ?? randomUUID();\n\tconst depth = options.getDelegationDepth();\n\tregistry.claimWorkspace(sessionId, claims);\n\tif (workspaceOwner) {\n\t\t// Worktree isolation: the registry releases this workspace when the run\n\t\t// closes or the registry disposes, through the same owner.\n\t\tregistry.setWorkspaceOwner(workspaceOwner);\n\t\tregistry.trackWorkspace(sessionId);\n\t}\n\ttry {\n\t\t// Concurrency admission (spec 2026-09-09, \"Shared budgets\"): over the\n\t\t// limit this throws BEFORE any child session is built, naming the limit.\n\t\tregistry.admitChildRun(sessionId);\n\t\tconst preparedWorkspace = workspaceOwner\n\t\t\t? await workspaceOwner.prepare({ ...workspace, ownedPaths: claims, sessionId })\n\t\t\t: workspace;\n\t\tlet artifactDir: string | undefined;\n\t\tconst parentSessionDir = options.getParentSessionDir?.();\n\t\tif (parentSessionDir) {\n\t\t\tconst parentRoot = resolve(parentSessionDir);\n\t\t\tartifactDir = join(parentRoot, \"delegations\", sessionId);\n\t\t\tmkdirSync(artifactDir, { recursive: true });\n\t\t}\n\t\tconst child = await options.buildChildSession({\n\t\t\tagentType,\n\t\t\tdefinition,\n\t\t\ttoolNames: definition.tools,\n\t\t\tcapabilities,\n\t\t\tdepth: depth + 1,\n\t\t\tsessionId,\n\t\t\tartifactDir,\n\t\t\tworkspace: preparedWorkspace,\n\t\t\t...(timeoutMs !== undefined ? { timeoutMs } : {}),\n\t\t});\n\t\tregistry.own(child);\n\t\tconst handleId = sessionId;\n\t\tconst promise = child.run(task).then(({ output }) => ({ agentType, task, output }));\n\t\t// register() observes the turn's settlement: it records the handle's latest\n\t\t// result (retrieval follows that, not this promise) and persists the run's\n\t\t// terminal status, so no separate settlement hook is needed here. The\n\t\t// durable fields ride along so every save() can persist them for restart.\n\t\t// A launch is attempt 1; timeoutMs also records the wall-clock deadline the\n\t\t// pollable status observes lazily. The record linkage (policy snapshot,\n\t\t// sandbox flag, parent session id) comes from the handle's own\n\t\t// construction report -- the values buildChildSession actually used --\n\t\t// and the runtime's parent-session seam; fixture handles that omit them\n\t\t// simply leave the record fields absent.\n\t\tregistry.register(handleId, {\n\t\t\tagentType,\n\t\t\ttask,\n\t\t\tpromise,\n\t\t\tchild,\n\t\t\tartifactDir,\n\t\t\tworkspace: preparedWorkspace,\n\t\t\tdepth: depth + 1,\n\t\t\tattempts: [{ id: \"attempt-1\", startedAt: Date.now() }],\n\t\t\tactiveAttemptId: \"attempt-1\",\n\t\t\t...(child.policy ? { policy: child.policy } : {}),\n\t\t\t...(options.getParentSessionId ? { parentSessionId: options.getParentSessionId() } : {}),\n\t\t\t...(request.idempotencyKey !== undefined ? { idempotencyKey: request.idempotencyKey } : {}),\n\t\t\t...(timeoutMs !== undefined ? { deadlineMs: Date.now() + timeoutMs } : {}),\n\t\t});\n\t\tif (!request.background) return promise;\n\t\treturn { agentType, task, output: `Delegation started. Retrieve result with handle \"${handleId}\".`, handleId };\n\t} catch (error) {\n\t\t// The delegation never started: release the workspace immediately (also\n\t\t// marks it released, so a later close/dispose cannot double-release) and\n\t\t// give back the concurrency slot admitted above.\n\t\tregistry.releaseChildRunSlot(sessionId);\n\t\tawait registry.releaseWorkspaceNow(sessionId);\n\t\tthrow error;\n\t}\n}\n\n/** Retrieve a background delegation. Running children are awaited; unknown handles fail explicitly. */\nexport async function retrieveDelegationResult(\n\toptions: DelegationRuntimeOptions,\n\thandleId: string,\n\texpectedAgentType?: string,\n): Promise<DelegationResult> {\n\tlet registry = options.childRunRegistry;\n\tif (!registry) {\n\t\tregistry = new ChildRunRegistry();\n\t\toptions.childRunRegistry = registry;\n\t}\n\treturn registry.retrieve(handleId, expectedAgentType);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../src/core/delegation/runtime.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACvE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAGrE,OAAO,EAAkB,mBAAmB,EAAqB,MAAM,uBAAuB,CAAC;AAE/F,OAAO,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC;AAkbxD,sEAAsE;AACtE,MAAM,CAAC,MAAM,mBAAmB,GAAG,qEAAqE,CAAC;AAEzG,mFAAmF;AACnF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,IAAI,EAAE,MAAM,EAAE,oDAAoD,QAAQ,IAAI,EAAE,QAAQ,EAAE,CAAC;IAChH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,wEAAwE;QACxE,yEAAyE;QACzE,iDAAiD;QACjD,QAAQ,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC;QACxC,MAAM,QAAQ,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC;QAC9C,MAAM,KAAK,CAAC;IACb,CAAC;AAAA,CACD;AAED,uGAAuG;AACvG,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC7C,OAAiC,EACjC,QAAgB,EAChB,iBAA0B,EACE;IAC5B,IAAI,QAAQ,GAAG,OAAO,CAAC,gBAAgB,CAAC;IACxC,IAAI,CAAC,QAAQ,EAAE,CAAC;QACf,QAAQ,GAAG,IAAI,gBAAgB,EAAE,CAAC;QAClC,OAAO,CAAC,gBAAgB,GAAG,QAAQ,CAAC;IACrC,CAAC;IACD,OAAO,QAAQ,CAAC,QAAQ,CAAC,QAAQ,EAAE,iBAAiB,CAAC,CAAC;AAAA,CACtD","sourcesContent":["/**\n * The delegation runtime (roadmap Phase 5, ADR 0008, task 5.2). Consumes the\n * capability ceiling (ceiling.ts) and a derived permission store\n * (`../permissions/store.ts`'s `DerivedPermissionRuleStore`) to run a real child\n * agent whose authority can never exceed its parent's.\n *\n * Agent definitions and child-session construction are both injected rather than\n * built in here: production agent discovery lives in `core/delegation/agents.ts`\n * (markdown + frontmatter, parsed on lookup) and plugs in through the same\n * resolver interface a test fixture implements; child-session construction is\n * injected so this module stays free of\n * `AgentSession`/`createAgentSession` and therefore free of the import cycle that\n * would create (`sdk.ts` already imports `agent-session.ts`).\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { existsSync, mkdirSync, readdirSync, statSync } from \"node:fs\";\nimport { isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport type { Usage } from \"@earendil-works/pi-ai\";\nimport type { AgentRunBudgetUsage } from \"apex-code-agent-core\";\nimport { type FileEntry, loadEntriesFromFile, type SessionEntry } from \"../session-manager.ts\";\nimport type { Capability } from \"../tools/contract.ts\";\nimport { computeCapabilityCeiling } from \"./ceiling.ts\";\n\n/** A delegatable agent's static configuration. Markdown + frontmatter in production (`agents.ts`); a plain object in tests. */\nexport interface AgentDefinition {\n\tname: string;\n\tdescription: string;\n\t/** Tool names this agent may use. Never trusted directly -- the runtime derives the actual child tool list from the computed capability set, not from this list verbatim. */\n\ttools: string[];\n\t/** Optional model id. Falls back to the parent's current model when unset or unresolvable. */\n\tmodel?: string;\n\tsystemPrompt: string;\n}\n\n/** Resolve an agent type to its definition, or `undefined` if unknown. Production implements this over markdown/frontmatter (`agents.ts`); tests inject plain functions with the same shape. */\nexport type AgentDefinitionResolver = (agentType: string) => AgentDefinition | undefined;\n\n/** A running or completed child, as far as the runtime needs to know. */\nexport type ChildSessionStatus = \"idle\" | \"running\" | \"interrupted\" | \"closed\";\n\n/** Terminal outcome of a child's latest settled turn. */\nexport type ChildTurnOutcome = \"completed\" | \"failed\" | \"interrupted\";\n\n/**\n * Token and cost totals for one child run, rolled up from the child's OWN\n * session transcript (the session-file reading seam; never a second transcript\n * cache). The numbers are summed exactly as the provider reported them -- cost\n * is provider-reported, so cache reads are NOT re-priced, re-counted, or\n * double-counted; an entry without usage counts as zero.\n */\nexport interface ChildRunUsageTotals {\n\tinputTokens: number;\n\toutputTokens: number;\n\tcacheReadTokens: number;\n\tcacheWriteTokens: number;\n\ttotalTokens: number;\n\tcost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };\n\t/** Wall-clock time (ms) the rollup was computed at. */\n\tasOf: number;\n\t/** Usage-bearing transcript entries examined (assistant messages, compaction, branch summaries), including those without usage. */\n\tentriesCounted: number;\n}\n\n/** The output and terminal outcome of a child's latest settled turn, as reported by its own handle. */\nexport interface ChildTurnResult {\n\toutput: string;\n\toutcome: ChildTurnOutcome;\n}\n\n/** Terminal outcome of one attempt on a child run. `cancelled` is recorded only by an explicit interrupt-with-reason. */\nexport type ChildRunAttemptOutcome = \"completed\" | \"failed\" | \"interrupted\" | \"cancelled\";\n\n/**\n * One launch-or-resume epoch of a child run (spec 2026-09-09, \"Child\n * lifecycle\"): a launch is attempt 1; a resume closes the prior attempt with\n * its terminal outcome and opens a new one. A live run's follow-ups and\n * steering stay inside the active attempt. `usage` snapshots the child's own\n * budget controller when its session exposes one (optional on the handle).\n * `tokensAtEnd` snapshots the run-level usage/cost rollup (see\n * `ChildRunUsageTotals`) at the attempt's settlement: these are\n * CUMULATIVE-AT-END snapshots of the child's whole transcript, never per-attempt\n * deltas -- range attribution between attempts is not attempted because turns\n * that settled after the last persisted boundary are re-run on resume, so the\n * transcript alone cannot attribute usage to an epoch.\n */\nexport interface ChildRunAttempt {\n\tid: string;\n\tstartedAt: number;\n\tendedAt?: number;\n\toutcome?: ChildRunAttemptOutcome;\n\terror?: string;\n\tusage?: AgentRunBudgetUsage;\n\ttokensAtEnd?: ChildRunUsageTotals;\n}\n\nexport interface ChildSessionHandle {\n\treadonly status: ChildSessionStatus;\n\t/** Run the task to completion and return the child's final output text. */\n\trun(task: string): Promise<{ output: string }>;\n\t/**\n\t * The latest settled turn's output and terminal outcome, derived by this handle\n\t * from the actual prompt resolution; `undefined` before any turn settles. This --\n\t * not the registry's stored first-turn promise -- is the source of truth for\n\t * background retrieval after `sendInput`/`followUp`/resume.\n\t */\n\tlatestResult(): ChildTurnResult | undefined;\n\twait(): Promise<void>;\n\tinterrupt(): void;\n\tclose(): void;\n\tsendInput(input: string): Promise<void>;\n\tfollowUp(input: string): Promise<void>;\n\t/**\n\t * Point-in-time snapshot of the child's own run budget counters, when its\n\t * session exposes a controller. Optional: handles whose child session does\n\t * not surface a controller simply omit it, and every consumer treats\n\t * attempt/status usage as optional.\n\t */\n\tusage?(): AgentRunBudgetUsage | undefined;\n\t/**\n\t * Read-only view of the child's own session entries, when the handle can\n\t * reach its (possibly in-memory) session manager. Optional: fixture handles\n\t * need not expose it, and the usage rollup consults it only when the child\n\t * has no resolvable transcript file (an in-memory child never persisted\n\t * one). Without this seam AND a transcript file, the run's usage totals are\n\t * simply unreportable (`undefined`), never guessed.\n\t */\n\tsessionEntries?(): readonly SessionEntry[] | undefined;\n\t/**\n\t * The derived policy this handle's child was built with (populated by the\n\t * sdk's `buildChildSession` from the request's admission projection and its\n\t * own construction values). Optional: fixture handles may omit it, and the\n\t * runtime relays it onto the child-run record when present.\n\t */\n\tpolicy?: ChildRunPolicySnapshot;\n\t/** Release the child's resources. Called when the child or owning parent is closed. */\n\tdispose(): void;\n}\n\nexport interface BuildChildSessionRequest {\n\tagentType: string;\n\tdefinition: AgentDefinition;\n\t/** The child's tool allowlist, already ceiling-checked -- exactly `definition.tools`, never narrowed. */\n\ttoolNames: string[];\n\t/**\n\t * The admitted capability set from the shared admission projection\n\t * (`resolveAdmittedDefinition`). Consumers use it to describe the child;\n\t * they must never re-derive it (ADR 0010).\n\t */\n\tcapabilities: ReadonlySet<Capability>;\n\t/** The child's own recursion depth (the parent's depth + 1), for the runtime constructing it to record on the child's session header (task 5.3). */\n\tdepth: number;\n\t/** Stable id used for the child session and its artifact directory. */\n\tsessionId: string;\n\t/** Per-child artifact root, created before the child session is constructed. */\n\tartifactDir?: string;\n\tworkspace?: ChildWorkspaceRequest;\n\t/**\n\t * Reattachment marker (restart reconstruction): when set, `buildChildSession`\n\t * opens this existing child session transcript instead of creating a new\n\t * session. The path must be the child's own session file under its recorded\n\t * artifact directory. Every other field keeps its fresh-delegation meaning,\n\t * so permission/model/tool wiring has exactly one construction path.\n\t */\n\treattachSessionPath?: string;\n\t/**\n\t * Optional wall-time cap for the child's OWN run budget (spec 2026-09-09,\n\t * timeouts): forwarded as `maxWallTimeMs` so the existing AgentRunBudget\n\t * wall-time gate enforces it mid-run. The launch also records\n\t * `deadlineMs = Date.now() + timeoutMs` on the record for lazy observation.\n\t */\n\ttimeoutMs?: number;\n}\n\n/** The workspace authority requested by a child. Paths are advisory claims,\n * never a replacement for the path-permission gate. */\nexport interface ChildWorkspaceRequest {\n\tisolation: \"shared-read\" | \"worktree\";\n\townedPaths: readonly string[];\n\t/**\n\t * The resolved isolation root a workspace owner prepared for this child\n\t * (worktree isolation): absent on the raw request, present on what\n\t * `prepare()` returns, and the cwd the child session runs in.\n\t */\n\troot?: string;\n}\n\n/**\n * Lifecycle state of a worktree-isolated child's workspace, persisted on the\n * record (spec 2026-09-09, \"Workspace states and explicit recovery\"). Absent\n * means \"active\" -- legacy records predate the field and a live worktree is\n * active by definition. Release outcomes write \"released\" / \"retained-dirty\" /\n * \"retained-failed\"; observing a vanished root at resume writes \"missing\".\n * Explicit recovery (`recoverWorkspace`) verifies and writes \"active\".\n */\nexport type ChildWorkspaceState = \"active\" | \"released\" | \"retained-dirty\" | \"retained-failed\" | \"missing\";\n\n/** Success payload of explicit workspace recovery (`recoverChildWorkspace`). */\nexport interface ChildWorkspaceRecoveryResult {\n\t/** Always \"active\": the workspace was verified and reactivated. */\n\tworkspaceState: ChildWorkspaceState;\n\t/** The verified worktree holds uncommitted or untracked work. */\n\tdirty: boolean;\n}\n\n/**\n * Real isolation and cleanup for a child's requested workspace authority (spec\n * 2026-09-09, \"Parallel work and ownership\"): the workspace subsystem owns git;\n * delegation only negotiates the request and refuses worktree isolation when no\n * owner is available. `prepare()` runs only for `isolation: \"worktree\"` -- a\n * shared-read delegation never touches an owner and never invokes git -- and\n * the request it returns (with `root` set) is what `buildChildSession` receives.\n */\n/**\n * Terminal outcome of releasing a child workspace (worktree). A kept tree is\n * never destroyed silently: \"dirty\" means uncommitted/untracked child work\n * was preserved; \"failed\" means the remove failed for another reason and the\n * tree was left in place.\n */\nexport type WorkspaceReleaseOutcome =\n\t| { removed: true }\n\t| { removed: false; kept: \"dirty\" | \"failed\"; dir: string; error?: string };\n\nexport interface ChildWorkspaceOwner {\n\tprepare(request: ChildWorkspaceRequest & { sessionId: string }): Promise<ChildWorkspaceRequest>;\n\t/**\n\t * Release the child's workspace, reporting what happened instead of\n\t * throwing. `options.force` is the caller's explicit escape hatch to\n\t * force-remove a dirty tree; without it a dirty tree must be kept.\n\t */\n\trelease(\n\t\tsessionId: string,\n\t\toptions?: { force?: boolean },\n\t): Promise<WorkspaceReleaseOutcome> | WorkspaceReleaseOutcome;\n\t/**\n\t * Read-only verification that a recorded worktree root is still this\n\t * owner's worktree for the session in the CURRENT workspace: layout,\n\t * administrative entry, and checked-out branch. Never creates, checks out,\n\t * resets, or force-removes anything; a failed check throws with the check\n\t * named. Optional: owners that cannot verify simply never support explicit\n\t * recovery, and `recoverWorkspace` refuses rather than guessing.\n\t */\n\tverify?(sessionId: string, root: string): Promise<{ dirty: boolean }> | { dirty: boolean };\n}\n\nexport interface DelegationRuntimeOptions {\n\tresolveAgent: AgentDefinitionResolver;\n\t/** The parent's own effective capability set (its authority), unexpanded -- `exec` expansion happens inside the ceiling check, not here. */\n\tgetParentCapabilities: () => ReadonlySet<Capability>;\n\t/** Capability set a named tool requires, from the live registry. `undefined` for an unknown tool name. */\n\tgetToolCapabilities: (toolName: string) => ReadonlySet<Capability> | undefined;\n\t/** The parent session's own recursion depth (`SessionManager.getDelegationDepth()`), read fresh at delegation time. */\n\tgetDelegationDepth: () => number;\n\t/** Delegation is refused once `getDelegationDepth() >= maxDelegationDepth` -- assigned by the runtime, not by the tool, so the bound applies to any future delegation entry point. */\n\tmaxDelegationDepth: number;\n\t/**\n\t * Maximum simultaneously-active child runs this runtime admits (spec\n\t * 2026-09-09, \"Shared budgets\", concurrency cap). Checked at admission --\n\t * before any child session is built -- and refused with an actionable error\n\t * naming the limit. An admitted run holds one slot until terminal settlement\n\t * (completed/failed/interrupted), close, registry disposal, or launch\n\t * failure. `undefined` (default) is unlimited.\n\t */\n\tmaxConcurrentChildren?: number;\n\t/** Parent session directory. When supplied, child artifacts are rooted beneath it. */\n\tgetParentSessionDir?: () => string;\n\t/**\n\t * Parent session id. When supplied, child-run records carry\n\t * `parentSessionId`, tying the durable record (and every protocol payload\n\t * derived from it) to the parent session's own identity.\n\t */\n\tgetParentSessionId?: () => string;\n\tbuildChildSession: (request: BuildChildSessionRequest) => Promise<ChildSessionHandle>;\n\tchildRunRegistry?: ChildRunRegistry;\n\t/** Durable session owner. Records are appended to the parent session's existing log. */\n\tpersistChildRun?: (record: ChildRunRecord) => void;\n\t/** Optional workspace owner. It is responsible for real isolation and cleanup. */\n\tworkspaceOwner?: ChildWorkspaceOwner;\n}\n\n/**\n * Compact, derivable snapshot of the derived policy a child session was built\n * with (spec 2026-09-09, \"Derive, do not reconstruct\"). Populated at child\n * construction from the values actually used -- never re-derived by consumers.\n * `capabilities` come from the delegation runtime's single admission projection\n * (`resolveAdmittedDefinition`), so no surface ever re-classifies authority\n * (ADR 0010). Persisted on `ChildRunRecord` and surfaced through status/wait\n * payloads; legacy records without it load unchanged.\n */\nexport interface ChildRunPolicySnapshot {\n\t/** The child's tool allowlist, exactly as construction received it (ceiling-checked `definition.tools`). */\n\ttools: string[];\n\t/** The admitted capability set from the same admission projection that gated the launch. */\n\tcapabilities: string[];\n\t/** The delegation depth bound in force for this child's own delegations. */\n\tmaxDelegationDepth: number;\n\t/** The child's resolved model id (its definition's model, or the parent's current model). */\n\tmodel?: string;\n\t/** The child Agent's budget scope; children are built session-scoped so follow-ups continue one controller. */\n\tbudgetScope: \"prompt\" | \"session\";\n\t/** Whether the child answers to the tree's shared aggregate ceiling (present only when explicitly configured at the root). */\n\taggregateBudget: boolean;\n}\n\nexport interface ChildRunRecord {\n\thandleId: string;\n\tagentType: string;\n\tsessionId?: string;\n\ttask?: string;\n\tparentSessionId?: string;\n\tartifactDir?: string;\n\t/** The derived policy this child was built with, persisted so session readers describe the child without re-deriving it. Optional: legacy records predate the field. */\n\tpolicy?: ChildRunPolicySnapshot;\n\t/**\n\t * Legacy only. Records what a session written before ADR 0032 was told about OS\n\t * containment. Absent on records written since, because nothing sets it: the\n\t * harness ships no boundary and makes no containment claim. Retained so an older\n\t * session still parses and still reports what it reported (ADR 0006).\n\t */\n\tsandboxEnforced?: boolean;\n\tworkspace?: ChildWorkspaceRequest;\n\t/**\n\t * Workspace lifecycle state for worktree-isolated records (see\n\t * `ChildWorkspaceState`). Written by release outcomes, by resume-time\n\t * observation of a vanished root (\"missing\"), and by explicit recovery\n\t * (\"active\"). Absent -- on legacy records and shared-read runs -- means\n\t * \"active\"; the field only ever appears for worktree isolation.\n\t */\n\tworkspaceState?: ChildWorkspaceState;\n\tdepth?: number;\n\tlatestResult?: { output: string; outcome: ChildTurnOutcome };\n\tstatus: \"created\" | \"running\" | \"completed\" | \"failed\" | \"interrupted\" | \"closed\";\n\tupdatedAt: number;\n\t/**\n\t * Attempt epochs (launch = attempt 1; resume opens a new one). Optional on\n\t * the wire: legacy records predate the field and are synthesized on load --\n\t * one attempt derived from the record's status/updatedAt -- so every\n\t * in-memory record carries at least one.\n\t */\n\tattempts?: ChildRunAttempt[];\n\tactiveAttemptId?: string;\n\t/** Caller-supplied spawn dedupe key; a restarted parent rebuilds the key->handle map from records. */\n\tidempotencyKey?: string;\n\t/** Wall-clock deadline recorded at launch (`Date.now() + timeoutMs`); observed lazily by status/list. */\n\tdeadlineMs?: number;\n\t/** Explicit cancellation, recorded when the run is interrupted with a reason. */\n\tcancelled?: { reason: string; at: number };\n}\n\nexport interface DelegationResult {\n\tagentType: string;\n\ttask: string;\n\toutput: string;\n\t/** Present for background work; pass this handle to retrieveDelegationResult. */\n\thandleId?: string;\n\t/**\n\t * Terminal outcome of the latest settled turn. Present on registry retrieval\n\t * once any turn has settled; the foreground result of the initial run omits it.\n\t */\n\toutcome?: ChildTurnOutcome;\n}\n\n/**\n * Non-blocking status snapshot of one child run (`agent/status`,\n * `AgentSession.childRunStatus`). Built from the record/entry alone -- never by\n * awaiting a turn -- so a caller can poll without blocking on the child.\n */\nexport interface ChildRunStatus {\n\thandleId: string;\n\tagentType: string;\n\ttask: string;\n\tstatus: ChildSessionStatus;\n\t/** The active attempt's identity and its latest outcome, if any turn has settled (or a cancellation was recorded). */\n\tattempt: { id: string; outcome?: ChildRunAttemptOutcome };\n\t/** Total attempt epochs, including closed ones. */\n\tattempts: number;\n\t/** The latest settled turn, as persisted for retrieval. */\n\tlastResult?: { output: string; outcome: ChildTurnOutcome };\n\t/** Present when the run was interrupted with an explicit reason. */\n\tcancelled?: { reason: string; at: number };\n\t/** Wall-clock launch deadline (present when the spawn carried timeoutMs). */\n\tdeadlineMs?: number;\n\t/** Snapshot of the child's own budget controller, when its handle exposes one. */\n\tusage?: AgentRunBudgetUsage;\n\t/**\n\t * Cumulative token totals rolled up from the child's own session transcript\n\t * (or its in-memory entries when no transcript exists), flattened from\n\t * `ChildRunUsageTotals`. Present beside `cost` whenever a rollup is\n\t * reachable; omitted -- never zero-filled -- when nothing is reachable.\n\t */\n\ttokens?: {\n\t\tinputTokens: number;\n\t\toutputTokens: number;\n\t\tcacheReadTokens: number;\n\t\tcacheWriteTokens: number;\n\t\ttotalTokens: number;\n\t};\n\t/** Provider-reported cost totals corresponding to `tokens`. Absent whenever `tokens` is. */\n\tcost?: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };\n\t/** The run's negotiated workspace authority (isolation plus a prepared root, when a workspace owner provided one). */\n\tworkspace?: { isolation: \"shared-read\" | \"worktree\"; root?: string };\n\t/**\n\t * Workspace lifecycle state (worktree-isolated runs only). Present whenever\n\t * the workspace is worktree-isolated: the record's persisted state, or\n\t * \"active\" while the entry is live and unretained.\n\t */\n\tworkspaceState?: ChildWorkspaceState;\n\t/** The child's per-run artifact directory, when the child is file-backed. */\n\tartifactDir?: string;\n\t/**\n\t * The child's transcript path, resolved lazily from its artifact directory\n\t * per SessionManager's `<timestamp>_<sessionId>.jsonl` naming. Absent when\n\t * the child is in-memory or has not persisted a transcript yet; resolution\n\t * never throws.\n\t */\n\tsessionFile?: string;\n\t/** The parent session id the run belongs to, when the runtime supplies one. */\n\tparentSessionId?: string;\n\t/** The derived policy the child was built with; absent on legacy records and fixture handles that never carried one. */\n\tpolicy?: ChildRunPolicySnapshot;\n\t/** Legacy only, surfaced from the record; nothing sets it since ADR 0032. */\n\tsandboxEnforced?: boolean;\n}\n\n/** The registry's record of a handle's latest settled turn. */\ntype LatestTurnSettlement =\n\t| { outcome: \"completed\"; output: string }\n\t| { outcome: \"interrupted\"; output: string }\n\t| { outcome: \"failed\"; error: unknown };\n\ninterface BackgroundDelegation {\n\tagentType: string;\n\ttask: string;\n\tpromise: Promise<DelegationResult>;\n\tchild?: ChildSessionHandle;\n\tclosed?: boolean;\n\t/** The latest settled turn; `undefined` until the first settlement is recorded. */\n\tlatest?: LatestTurnSettlement;\n\t/** The turn whose settlement has not been observed through retrieval yet, if any. */\n\tpending?: Promise<unknown>;\n\t/** Durable fields, persisted on every save so a restart can reattach the child session. */\n\tartifactDir?: string;\n\tworkspace?: ChildWorkspaceRequest;\n\tdepth?: number;\n\t/** Record linkage persisted with every save (policy snapshot, sandbox flag, parent session id). */\n\tpolicy?: ChildRunPolicySnapshot;\n\tsandboxEnforced?: boolean;\n\tparentSessionId?: string;\n\t/** Attempt epochs (spec 2026-09-09, \"Child lifecycle\"). `register()` supplies attempt 1 when the caller did not. */\n\tattempts?: ChildRunAttempt[];\n\tactiveAttemptId?: string;\n\tidempotencyKey?: string;\n\tdeadlineMs?: number;\n\tcancelled?: { reason: string; at: number };\n}\n\n/** Default follow-up prompt for resuming an interrupted child run. */\nexport const RESUME_CHILD_PROMPT = \"Resume the interrupted task and continue from the existing session.\";\n\n/** The record status's terminal outcome, for closing an attempt at resume time. */\nfunction terminalOutcomeOfStatus(\n\tstatus: ChildRunRecord[\"status\"],\n\tcancelled?: { reason: string; at: number },\n): ChildRunAttemptOutcome | undefined {\n\tif (status === \"completed\" || status === \"failed\") return status;\n\tif (status === \"interrupted\") return cancelled ? \"cancelled\" : \"interrupted\";\n\treturn undefined;\n}\n\n/**\n * Attempts for a record, synthesizing one from legacy fields when the record\n * predates attempt tracking: one attempt, started (and, for a terminal status,\n * ended) at the record's `updatedAt`, with the status mapped to an outcome.\n * Older records therefore load unchanged and still report a single attempt.\n */\nfunction childRunAttemptsOf(record: ChildRunRecord): ChildRunAttempt[] {\n\tif (record.attempts && record.attempts.length > 0) return record.attempts;\n\tconst attempt: ChildRunAttempt = { id: \"attempt-1\", startedAt: record.updatedAt };\n\tconst outcome = terminalOutcomeOfStatus(record.status, record.cancelled);\n\tif (outcome !== undefined) {\n\t\tattempt.endedAt = record.updatedAt;\n\t\tattempt.outcome = outcome;\n\t}\n\treturn [attempt];\n}\n\n/** The entry's active attempt, falling back to the most recent one. */\nfunction activeAttemptOf(entry: {\n\tattempts?: ChildRunAttempt[];\n\tactiveAttemptId?: string;\n}): ChildRunAttempt | undefined {\n\tconst attempts = entry.attempts ?? [];\n\treturn attempts.find((attempt) => attempt.id === entry.activeAttemptId) ?? attempts[attempts.length - 1];\n}\n\n/**\n * Shared delegation admission: definition resolution, recursion-depth bound, and\n * the capability ceiling. One projection for both a fresh delegation and a\n * historical reattachment, so a resumed child can never hold authority the\n * current parent cannot cover (no second classification, ADR 0010). The\n * admitted capability set rides along on the result: it is what the build\n * request carries so the child's policy snapshot describes the same projection\n * instead of recomputing it.\n */\nfunction resolveAdmittedDefinition(\n\toptions: DelegationRuntimeOptions,\n\tagentType: string,\n): { definition: AgentDefinition; capabilities: ReadonlySet<Capability> } {\n\tconst definition = options.resolveAgent(agentType);\n\tif (!definition) {\n\t\tthrow new Error(`Unknown agent type \"${agentType}\".`);\n\t}\n\tconst depth = options.getDelegationDepth();\n\tif (depth >= options.maxDelegationDepth) {\n\t\tthrow new Error(\n\t\t\t`Delegation depth limit (${options.maxDelegationDepth}) reached at depth ${depth}; cannot delegate to agent \"${agentType}\" further.`,\n\t\t);\n\t}\n\tconst requestedCapabilities = new Set<Capability>();\n\tfor (const toolName of definition.tools) {\n\t\tconst capabilities = options.getToolCapabilities(toolName);\n\t\tif (!capabilities) {\n\t\t\tthrow new Error(`Agent \"${agentType}\" requests unknown tool \"${toolName}\".`);\n\t\t}\n\t\tfor (const capability of capabilities) requestedCapabilities.add(capability);\n\t}\n\tconst ceiling = computeCapabilityCeiling(options.getParentCapabilities(), requestedCapabilities);\n\tif (!ceiling.allowed) {\n\t\tthrow new Error(\n\t\t\t`Delegating to agent \"${agentType}\" requires capability \"${ceiling.deniedCapability}\", which exceeds the parent's authority.`,\n\t\t);\n\t}\n\treturn { definition, capabilities: ceiling.capabilities };\n}\n\n/**\n * Lazily resolve a child's transcript path under its artifact directory, per\n * SessionManager's `<timestamp>_<sessionId>.jsonl` naming (the timestamp prefix\n * is not recorded, so the directory is scanned). Never throws: an absent\n * directory or transcript -- an in-memory child never persisted one -- simply\n * yields `undefined`, so status payloads can resolve it lazily without\n * becoming fallible. When several transcripts match, the newest wins (resume\n * may have grown the file set).\n */\nfunction resolveSessionFile(artifactDir: string | undefined, sessionId: string | undefined): string | undefined {\n\tif (!artifactDir || !sessionId) return undefined;\n\tif (!existsSync(artifactDir)) return undefined;\n\ttry {\n\t\tconst matches = readdirSync(artifactDir).filter((name) => name.endsWith(`_${sessionId}.jsonl`));\n\t\tif (matches.length === 0) return undefined;\n\t\tif (matches.length === 1) return join(artifactDir, matches[0]!);\n\t\tconst newest = matches\n\t\t\t.map((name) => ({ name, mtime: statSync(join(artifactDir, name)).mtimeMs }))\n\t\t\t.sort((a, b) => b.mtime - a.mtime)[0]!;\n\t\treturn join(artifactDir, newest.name);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Roll provider-reported usage up over session entries (the child's OWN\n * transcript is the source; SessionManager's reader supplies the entries).\n * Every surface that reports child-run usage goes through here, so the numbers\n * are summed exactly once, exactly as the provider reported them: cost is\n * provider-reported, so cache reads are NOT re-priced or re-counted, and an\n * entry without usage contributes zero. Assistant messages carry per-turn\n * usage; compaction and branch-summary entries carry their summarization\n * call's usage, which is additional real spend and therefore included.\n * Returns `undefined` when the entries hold no usage-bearing record at all\n * (nothing to report) -- callers omit rather than zero-fill.\n */\nfunction computeUsageTotals(entries: readonly FileEntry[]): ChildRunUsageTotals | undefined {\n\tlet inputTokens = 0;\n\tlet outputTokens = 0;\n\tlet cacheReadTokens = 0;\n\tlet cacheWriteTokens = 0;\n\tlet totalTokens = 0;\n\tconst cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };\n\tlet entriesCounted = 0;\n\tconst add = (usage: Usage | undefined): void => {\n\t\tif (!usage) return; // missing/absent usage counts as zero\n\t\tinputTokens += usage.input;\n\t\toutputTokens += usage.output;\n\t\tcacheReadTokens += usage.cacheRead;\n\t\tcacheWriteTokens += usage.cacheWrite;\n\t\ttotalTokens += usage.totalTokens;\n\t\tcost.input += usage.cost.input;\n\t\tcost.output += usage.cost.output;\n\t\tcost.cacheRead += usage.cost.cacheRead;\n\t\tcost.cacheWrite += usage.cost.cacheWrite;\n\t\tcost.total += usage.cost.total;\n\t};\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"message\") {\n\t\t\tif (entry.message.role !== \"assistant\") continue;\n\t\t\tentriesCounted++;\n\t\t\tadd(entry.message.usage);\n\t\t} else if (entry.type === \"compaction\" || entry.type === \"branch_summary\") {\n\t\t\tentriesCounted++;\n\t\t\tadd(entry.usage);\n\t\t}\n\t}\n\tif (entriesCounted === 0) return undefined;\n\treturn {\n\t\tinputTokens,\n\t\toutputTokens,\n\t\tcacheReadTokens,\n\t\tcacheWriteTokens,\n\t\ttotalTokens,\n\t\tcost,\n\t\tasOf: Date.now(),\n\t\tentriesCounted,\n\t};\n}\n\n// Results deliberately stay available for the lifetime of their parent runtime.\n// Phase 5 promises in-process retrieval only; restart durability belongs to Phase 6.\nexport class ChildRunRegistry {\n\tprivate readonly entries = new Map<string, BackgroundDelegation>();\n\tprivate readonly workspaceClaims = new Map<string, string[]>();\n\tprivate readonly children = new Set<ChildSessionHandle>();\n\t/**\n\t * Session ids whose workspace this registry must release on close/dispose\n\t * (spec 2026-09-09, \"Parallel work and ownership\"): populated by\n\t * `trackWorkspace()` when a worktree-isolated delegation is prepared, and\n\t * drained exactly once per session id by `releaseWorkspaceOnce()`.\n\t */\n\tprivate readonly trackedWorkspaces = new Set<string>();\n\t/** Session ids whose workspace release has already started -- release runs once, never twice. */\n\tprivate readonly releasedWorkspaces = new Set<string>();\n\t/** Last release outcome per session id, surfaced through `workspaceReleaseOutcome()`. */\n\tprivate readonly workspaceReleaseOutcomes = new Map<string, WorkspaceReleaseOutcome>();\n\tprivate workspaceOwner?: ChildWorkspaceOwner;\n\tprivate disposed = false;\n\tprivate persist?: (record: ChildRunRecord) => void;\n\tprivate records = new Map<string, ChildRunRecord>();\n\t/**\n\t * Spawn dedupe keys -> handle ids (spec 2026-09-09, idempotent spawn). A\n\t * second spawn with a known key returns the existing handle and never builds\n\t * a second child. Populated at launch and rebuilt from persisted records on\n\t * `restore()`, so a restarted parent dedupes too.\n\t */\n\tprivate readonly idempotencyKeys = new Map<string, string>();\n\t/**\n\t * Handle ids currently holding a concurrency slot (spec 2026-09-09,\n\t * \"Shared budgets\"). Admission takes one slot per child run BEFORE any child\n\t * session is built; the slot is released on terminal settlement\n\t * (completed/failed/interrupted), close, registry disposal, or launch\n\t * failure. Keyed by handle id, so release is idempotent.\n\t */\n\tprivate readonly heldRunSlots = new Set<string>();\n\t/**\n\t * The delegation runtime this registry runs under, attached by the session\n\t * that owns it (sdk wiring) or by the first `runDelegation` call. Historical\n\t * resume reattaches through the SAME `buildChildSession` seam a live\n\t * delegation uses; without an attached runtime, historical records are still\n\t * listed and their persisted output retrievable, but they cannot reattach.\n\t */\n\tprivate runtimeOptions?: DelegationRuntimeOptions;\n\t/**\n\t * Last-computed usage totals per handle id, keyed by what makes them stale\n\t * (the transcript file's size+mtime, or the in-memory entry count+last id).\n\t * The transcript file itself stays the one source: on every read the key is\n\t * re-derived and a mismatch recomputes from the file -- this cache never\n\t * becomes a second transcript.\n\t */\n\tprivate readonly usageCache = new Map<string, { key: string; totals: ChildRunUsageTotals }>();\n\t/** First attach wins: a registry is owned by one session's runtime. */\n\tsetRuntimeOptions(options: DelegationRuntimeOptions): void {\n\t\tif (!this.runtimeOptions) this.runtimeOptions = options;\n\t}\n\tsetPersistence(persist: (record: ChildRunRecord) => void): void {\n\t\tthis.persist = persist;\n\t}\n\t/** Load validated historical records. This never constructs or starts a child. */\n\trestore(records: readonly ChildRunRecord[]): void {\n\t\tfor (const record of records) {\n\t\t\tif (\n\t\t\t\t!record ||\n\t\t\t\ttypeof record.handleId !== \"string\" ||\n\t\t\t\ttypeof record.agentType !== \"string\" ||\n\t\t\t\t!Number.isFinite(record.updatedAt) ||\n\t\t\t\t![\"created\", \"running\", \"completed\", \"failed\", \"interrupted\", \"closed\"].includes(record.status)\n\t\t\t)\n\t\t\t\tcontinue;\n\t\t\t// Legacy records without attempts load with one synthesized attempt\n\t\t\t// derived from their status/updatedAt, so every in-memory record carries\n\t\t\t// at least one attempt.\n\t\t\tconst normalized: ChildRunRecord = { ...record, attempts: childRunAttemptsOf(record) };\n\t\t\tif (normalized.activeAttemptId === undefined) {\n\t\t\t\tconst openStatus = normalized.status === \"running\" || normalized.status === \"created\";\n\t\t\t\tnormalized.activeAttemptId = openStatus\n\t\t\t\t\t? normalized.attempts![normalized.attempts!.length - 1]!.id\n\t\t\t\t\t: undefined;\n\t\t\t}\n\t\t\t// Stale-running reconciliation (restart semantics): a persisted\n\t\t\t// \"running\" record cannot be live in this fresh process, so its\n\t\t\t// in-memory status becomes \"interrupted\" and its active attempt closes\n\t\t\t// as interrupted. The historical JSONL is never rewritten here -- the\n\t\t\t// corrected status persists with the record's NEXT save (e.g. a resume).\n\t\t\t// This is also the honest statement of restart semantics: a resumed run\n\t\t\t// continues from the last persisted transcript boundary, never\n\t\t\t// exactly-once -- turns that settled after the last save are re-run.\n\t\t\tif (normalized.status === \"running\") {\n\t\t\t\tnormalized.status = \"interrupted\";\n\t\t\t\tnormalized.attempts = normalized.attempts!.map((attempt) => ({ ...attempt }));\n\t\t\t\tconst attempt = normalized.attempts[normalized.attempts.length - 1];\n\t\t\t\tif (attempt) {\n\t\t\t\t\tattempt.endedAt ??= Date.now();\n\t\t\t\t\tattempt.outcome ??= \"interrupted\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.records.set(normalized.handleId, normalized);\n\t\t\tif (typeof normalized.idempotencyKey === \"string\") {\n\t\t\t\tthis.idempotencyKeys.set(normalized.idempotencyKey, normalized.handleId);\n\t\t\t}\n\t\t}\n\t}\n\t/** The handle a spawn dedupe key already maps to, if any. */\n\thandleForIdempotencyKey(key: string): string | undefined {\n\t\treturn this.idempotencyKeys.get(key);\n\t}\n\t/** True when `id` is known only as a persisted record -- no live entry in this process. */\n\tisHistorical(id: string): boolean {\n\t\treturn !this.entries.has(id) && this.records.has(id);\n\t}\n\t/**\n\t * Resolve a historical record's child session file. Verified against\n\t * SessionManager's naming (`<timestamp>_<sessionId>.jsonl` inside the\n\t * per-child artifact directory, which IS the child's session dir): the\n\t * timestamp prefix is not recorded, so the directory is scanned for the file\n\t * whose name ends in `_<sessionId>.jsonl`. Returns the validated triple so\n\t * the reattachment request carries checked values, not optional record fields.\n\t */\n\tprivate resolveHistoricalSession(record: ChildRunRecord): { path: string; sessionId: string; artifactDir: string } {\n\t\tconst artifactDir = record.artifactDir ? resolve(record.artifactDir) : undefined;\n\t\tconst sessionId = typeof record.sessionId === \"string\" ? record.sessionId : undefined;\n\t\tif (!sessionId || !artifactDir) {\n\t\t\tthrow new Error(\n\t\t\t\t`Child run \"${record.handleId}\" was never file-backed (no persisted child session directory; in-memory child), so it cannot be resumed after restart.`,\n\t\t\t);\n\t\t}\n\t\tif (!existsSync(artifactDir)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Child run \"${record.handleId}\" cannot be resumed: its artifact directory is missing: ${artifactDir}.`,\n\t\t\t);\n\t\t}\n\t\tconst path = resolveSessionFile(artifactDir, sessionId);\n\t\tif (!path) {\n\t\t\tthrow new Error(\n\t\t\t\t`Child run \"${record.handleId}\" cannot be resumed: no child session file for session \"${sessionId}\" exists under ${artifactDir} (the child never persisted a transcript).`,\n\t\t\t);\n\t\t}\n\t\treturn { path, sessionId, artifactDir };\n\t}\n\t/**\n\t * Reattach a persisted child run to its existing child session and continue\n\t * it with one turn (restart reconstruction). The child session file recorded\n\t * under the run's artifact directory is reopened through the same\n\t * `buildChildSession` seam a live delegation uses (reattachment marker), and\n\t * the run then behaves like any live entry: settlement is observed and\n\t * persisted, and wait/retrieve/sendInput work on the same handle id.\n\t *\n\t * Never-file-backed (in-memory) children, records whose artifact directory or\n\t * session file is gone, closed runs, and runs whose recorded worktree was\n\t * released all refuse with an actionable error; nothing is reconstructed\n\t * from nothing.\n\t */\n\tasync resumeHistorical(id: string, input?: string): Promise<ChildSessionStatus> {\n\t\tthis.assertOpen();\n\t\tif (this.entries.has(id)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Child run \"${id}\" is already live in this process; use sendInput instead of historical resume.`,\n\t\t\t);\n\t\t}\n\t\tconst record = this.records.get(id);\n\t\tif (!record) throw new Error(`Unknown delegation handle \"${id}\".`);\n\t\t// The worktree gate runs BEFORE the closed check: a retained (or missing)\n\t\t// workspace is the more actionable refusal for a released child, and it\n\t\t// names the persisted state and the explicit-recovery way out.\n\t\tif (record.workspace?.isolation === \"worktree\") this.rejectUnresumableWorktree(id, record);\n\t\tif (record.status === \"closed\") throw new Error(`Child run \"${id}\" was closed and cannot be resumed.`);\n\t\tif (typeof record.agentType !== \"string\" || record.agentType === \"\") {\n\t\t\tthrow new Error(`Child run \"${id}\" has a malformed record (no agent type) and cannot be resumed.`);\n\t\t}\n\t\tconst { path: sessionPath, sessionId, artifactDir } = this.resolveHistoricalSession(record);\n\t\tconst runtime = this.runtimeOptions;\n\t\tif (!runtime?.buildChildSession) {\n\t\t\tthrow new Error(`Child run \"${id}\" cannot be resumed: no delegation runtime is attached to this registry.`);\n\t\t}\n\t\tconst { definition, capabilities } = resolveAdmittedDefinition(runtime, record.agentType);\n\t\tconst workspace = record.workspace ?? { isolation: \"shared-read\" as const, ownedPaths: [] as string[] };\n\t\tconst claims = [...workspace.ownedPaths].map((p) => resolve(p));\n\t\tfor (const claim of this.activeWorkspaceClaims()) {\n\t\t\tif (claims.some((path) => claimPathsOverlap(path, claim))) {\n\t\t\t\tthrow new Error(`Resuming child run \"${id}\" overlaps an active write ownership claim.`);\n\t\t\t}\n\t\t}\n\t\tthis.claimWorkspace(id, claims);\n\t\ttry {\n\t\t\t// A resumed run counts against the concurrency limit exactly like a\n\t\t\t// live delegation, from before the child is built (spec 2026-09-09,\n\t\t\t// \"Shared budgets\").\n\t\t\tthis.admitChildRun(id);\n\t\t\tconst child = await runtime.buildChildSession({\n\t\t\t\tagentType: record.agentType,\n\t\t\t\tdefinition,\n\t\t\t\ttoolNames: definition.tools,\n\t\t\t\tcapabilities,\n\t\t\t\tdepth: typeof record.depth === \"number\" ? record.depth : 1,\n\t\t\t\tsessionId,\n\t\t\t\tartifactDir,\n\t\t\t\tworkspace,\n\t\t\t\treattachSessionPath: sessionPath,\n\t\t\t});\n\t\t\tthis.own(child);\n\t\t\t// Resume closes the previous attempt with its terminal outcome and opens\n\t\t\t// a NEW attempt (spec 2026-09-09, \"Child lifecycle\"): the resumed turn\n\t\t\t// is a fresh epoch of the same child session, never a continuation of\n\t\t\t// the interrupted attempt.\n\t\t\tconst priorAttempts = childRunAttemptsOf(record).map((attempt) => ({ ...attempt }));\n\t\t\tconst priorOutcome = terminalOutcomeOfStatus(record.status, record.cancelled);\n\t\t\tconst prior = record.activeAttemptId\n\t\t\t\t? priorAttempts.find((attempt) => attempt.id === record.activeAttemptId)\n\t\t\t\t: undefined;\n\t\t\tconst closing = prior ?? priorAttempts[priorAttempts.length - 1];\n\t\t\tif (closing && closing.endedAt === undefined) {\n\t\t\t\tclosing.endedAt = Date.now();\n\t\t\t\tclosing.outcome ??= priorOutcome;\n\t\t\t}\n\t\t\t// The resumed epoch's predecessor gets its cumulative-at-end rollup\n\t\t\t// here when the settlement before the restart never produced one: the\n\t\t\t// persisted transcript is all that survived, so its current totals are\n\t\t\t// the honest snapshot (see ChildRunAttempt.tokensAtEnd).\n\t\t\tif (closing && closing.tokensAtEnd === undefined) {\n\t\t\t\tconst totals = this.usageTotalsFor(id, record.artifactDir);\n\t\t\t\tif (totals) closing.tokensAtEnd = totals;\n\t\t\t}\n\t\t\tconst attempt: ChildRunAttempt = { id: `attempt-${priorAttempts.length + 1}`, startedAt: Date.now() };\n\t\t\tconst entry: BackgroundDelegation = {\n\t\t\t\tagentType: record.agentType,\n\t\t\t\ttask: record.task ?? \"\",\n\t\t\t\t// No initial-turn promise: each resumed turn is tracked through\n\t\t\t\t// sendInput's settlement observation, like any live entry.\n\t\t\t\tpromise: new Promise<DelegationResult>(() => {}),\n\t\t\t\tchild,\n\t\t\t\tartifactDir: record.artifactDir,\n\t\t\t\tworkspace,\n\t\t\t\tdepth: record.depth,\n\t\t\t\t// Record linkage: the reattached construction re-derives the policy\n\t\t\t\t// through the same admission projection; the record's persisted\n\t\t\t\t// values stand in when a fixture handle reports none.\n\t\t\t\tpolicy: child.policy ?? record.policy,\n\t\t\t\tsandboxEnforced: record.sandboxEnforced,\n\t\t\t\tparentSessionId: record.parentSessionId,\n\t\t\t\tattempts: [...priorAttempts, attempt],\n\t\t\t\tactiveAttemptId: attempt.id,\n\t\t\t\tidempotencyKey: typeof record.idempotencyKey === \"string\" ? record.idempotencyKey : undefined,\n\t\t\t};\n\t\t\tthis.entries.set(id, entry);\n\t\t\tthis.save(id, entry, \"running\");\n\t\t\tawait this.sendInput(id, input ?? RESUME_CHILD_PROMPT);\n\t\t\treturn child.status;\n\t\t} catch (error) {\n\t\t\tthis.releaseChildRunSlot(id);\n\t\t\tthis.releaseWorkspace(id);\n\t\t\tthrow error;\n\t\t}\n\t}\n\t/**\n\t * Gate a worktree-isolated historical resume on the workspace's persisted\n\t * state (spec 2026-09-09, \"Workspace states and explicit recovery\"). A\n\t * vanished root classifies the record \"missing\" (persisted) and refuses; a\n\t * retained (dirty/failed) root refuses, naming the persisted state and\n\t * pointing at explicit recovery. Legacy records and recovered (\"active\")\n\t * workspaces pass. Read-only: nothing is recreated, checked out, or reset.\n\t */\n\tprivate rejectUnresumableWorktree(id: string, record: ChildRunRecord): void {\n\t\tconst workspace = record.workspace!;\n\t\tconst root = workspace.root;\n\t\tif (!root) return; // never prepared: the launch failed before the owner ran\n\t\tif (!existsSync(root)) {\n\t\t\tif (record.workspaceState !== \"released\") {\n\t\t\t\trecord.workspaceState = \"missing\";\n\t\t\t\trecord.updatedAt = Date.now();\n\t\t\t\ttry {\n\t\t\t\t\tthis.persist?.(record);\n\t\t\t\t} catch {\n\t\t\t\t\t// The in-memory classification stands even if persistence cannot.\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow new Error(\n\t\t\t\t`Child run \"${id}\" cannot be resumed: its worktree workspace \"${root}\" no longer exists ` +\n\t\t\t\t\t`(workspace state: \"${record.workspaceState ?? \"missing\"}\"). Worktrees are released or retained when the ` +\n\t\t\t\t\t`owning session closes; a missing workspace cannot be recovered -- start a new delegation instead.`,\n\t\t\t);\n\t\t}\n\t\tif (record.workspaceState === \"retained-dirty\" || record.workspaceState === \"retained-failed\") {\n\t\t\tthrow new Error(\n\t\t\t\t`Child run \"${id}\" cannot be resumed: its worktree workspace \"${root}\" was retained at release ` +\n\t\t\t\t\t`(workspace state: \"${record.workspaceState}\"; uncommitted work is preserved there). Recover it explicitly first -- ` +\n\t\t\t\t\t`recoverChildWorkspace(\"${id}\") verifies the worktree and reactivates it -- then resume.`,\n\t\t\t);\n\t\t}\n\t}\n\t/**\n\t * Explicitly verify and reactivate a retained child worktree (spec\n\t * 2026-09-09, \"Workspace states and explicit recovery\"). Read-only\n\t * inspection only -- the workspace owner's verification reads the\n\t * administrative entry and the checked-out branch and never creates,\n\t * checks out, resets, or force-removes anything -- and on success the\n\t * record's workspace state becomes \"active\" (persisted) so the child can be\n\t * resumed in the SAME worktree. Automatic recreation stays out of scope by\n\t * design: every failed check refuses with an actionable error naming the\n\t * failed check, and the workspace state stays unverified.\n\t */\n\tasync recoverWorkspace(id: string): Promise<ChildWorkspaceRecoveryResult> {\n\t\tthis.assertOpen();\n\t\tconst record = this.records.get(id);\n\t\tif (!record) throw new Error(`Unknown delegation handle \"${id}\".`);\n\t\tconst workspace = record.workspace;\n\t\tif (workspace?.isolation !== \"worktree\" || !workspace.root) {\n\t\t\tthrow new Error(\n\t\t\t\t`Child workspace recovery refused for run \"${id}\": it has no worktree workspace to recover ` +\n\t\t\t\t\t`(isolation: ${workspace?.isolation ?? \"none\"}). Only worktree-isolated children hold a recoverable workspace; ` +\n\t\t\t\t\t`nothing was verified and the record is unchanged.`,\n\t\t\t);\n\t\t}\n\t\tconst root = workspace.root;\n\t\tif (!existsSync(root)) {\n\t\t\tif (record.workspaceState !== \"released\") {\n\t\t\t\trecord.workspaceState = \"missing\";\n\t\t\t\trecord.updatedAt = Date.now();\n\t\t\t\ttry {\n\t\t\t\t\tthis.persist?.(record);\n\t\t\t\t} catch {\n\t\t\t\t\t// The in-memory classification stands even if persistence cannot.\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow new Error(\n\t\t\t\t`Child workspace recovery refused for run \"${id}\": its recorded worktree root \"${root}\" does not exist ` +\n\t\t\t\t\t`(workspace state: \"${record.workspaceState ?? \"missing\"}\"). A missing workspace cannot be recovered; ` +\n\t\t\t\t\t`nothing was created.`,\n\t\t\t);\n\t\t}\n\t\tconst owner = this.workspaceOwner ?? this.runtimeOptions?.workspaceOwner;\n\t\tif (!owner || typeof owner.verify !== \"function\") {\n\t\t\tthrow new Error(\n\t\t\t\t`Child workspace recovery refused for run \"${id}\": no workspace owner with verification is available for ` +\n\t\t\t\t\t`this session. The workspace at \"${root}\" was not inspected and stays unverified.`,\n\t\t\t);\n\t\t}\n\t\tlet dirty: boolean;\n\t\ttry {\n\t\t\t({ dirty } = await owner.verify(id, root));\n\t\t} catch (error) {\n\t\t\tconst detail = error instanceof Error ? error.message : String(error);\n\t\t\tthrow new Error(\n\t\t\t\t`Child workspace recovery refused for run \"${id}\": ${detail} No recovery was performed and the ` +\n\t\t\t\t\t`workspace stays unverified.`,\n\t\t\t);\n\t\t}\n\t\trecord.workspaceState = \"active\";\n\t\trecord.updatedAt = Date.now();\n\t\ttry {\n\t\t\tthis.persist?.(record);\n\t\t} catch {\n\t\t\t// The in-memory record is reactivated regardless; the persisted state\n\t\t\t// catches up with the next save.\n\t\t}\n\t\treturn { workspaceState: \"active\", dirty };\n\t}\n\t/**\n\t * The owner consulted when a tracked child's lifecycle ends. Optional:\n\t * without one, close/dispose still clean claims but release nothing.\n\t */\n\tsetWorkspaceOwner(owner: ChildWorkspaceOwner | undefined): void {\n\t\tthis.workspaceOwner = owner;\n\t}\n\t/** Record that a child session's workspace (worktree) must be released when its lifecycle ends. */\n\ttrackWorkspace(sessionId: string): void {\n\t\tthis.trackedWorkspaces.add(sessionId);\n\t}\n\t/**\n\t * Release a tracked child's workspace through the owner, once per session\n\t * id. Best effort: a missing owner is tolerated and an owner failure never\n\t * propagates -- cleanup must never break close or dispose. The outcome is\n\t * stored per session id (`workspaceReleaseOutcome()`), and a kept tree is\n\t * warned about loudly so silent data loss cannot hide behind best-effort\n\t * cleanup.\n\t */\n\tprivate releaseWorkspaceOnce(sessionId: string): Promise<void> {\n\t\tif (this.releasedWorkspaces.has(sessionId)) return Promise.resolve();\n\t\tthis.releasedWorkspaces.add(sessionId);\n\t\tthis.trackedWorkspaces.delete(sessionId);\n\t\tconst owner = this.workspaceOwner;\n\t\tif (!owner) return Promise.resolve();\n\t\treturn Promise.resolve()\n\t\t\t.then(() => owner.release(sessionId))\n\t\t\t.catch(\n\t\t\t\t(error: unknown): WorkspaceReleaseOutcome => ({\n\t\t\t\t\tremoved: false,\n\t\t\t\t\tkept: \"failed\",\n\t\t\t\t\tdir: \"\",\n\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t}),\n\t\t\t)\n\t\t\t.then((outcome) => {\n\t\t\t\tthis.workspaceReleaseOutcomes.set(sessionId, outcome);\n\t\t\t\tthis.recordWorkspaceState(sessionId, outcome);\n\t\t\t\tif (!outcome.removed) {\n\t\t\t\t\tif (outcome.kept === \"dirty\") {\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`[apex-code] Child worktree for session \"${sessionId}\" kept at ${outcome.dir}; uncommitted child work preserved. ` +\n\t\t\t\t\t\t\t\t`Resume after reattach is refused for worktree children. Manual removal: git worktree remove --force ${outcome.dir}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`[apex-code] Child worktree release failed for session \"${sessionId}\" (tree kept at ${outcome.dir}): ${outcome.error ?? \"unknown error\"}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.catch(() => undefined);\n\t}\n\t/**\n\t * Classify a finished release on the record (spec 2026-09-09, \"Workspace\n\t * states and explicit recovery\"): removed -> \"released\", kept dirty ->\n\t * \"retained-dirty\", kept failed -> \"retained-failed\". Only worktree-isolated\n\t * records carry the state. The classified record persists immediately -- even\n\t * though release is fire-and-forget -- so a restarted parent sees the\n\t * classification and can refuse or recover accordingly.\n\t */\n\tprivate recordWorkspaceState(sessionId: string, outcome: WorkspaceReleaseOutcome): void {\n\t\tconst record = this.records.get(sessionId);\n\t\tif (record?.workspace?.isolation !== \"worktree\") return;\n\t\trecord.workspaceState = outcome.removed\n\t\t\t? \"released\"\n\t\t\t: outcome.kept === \"dirty\"\n\t\t\t\t? \"retained-dirty\"\n\t\t\t\t: \"retained-failed\";\n\t\trecord.updatedAt = Date.now();\n\t\ttry {\n\t\t\tthis.persist?.(record);\n\t\t} catch {\n\t\t\t// The in-memory record still carries the classification even when\n\t\t\t// persistence cannot run (best effort, like the release itself).\n\t\t}\n\t}\n\t/** The stored outcome of this session id's workspace release, if it has run. */\n\tworkspaceReleaseOutcome(sessionId: string): WorkspaceReleaseOutcome | undefined {\n\t\treturn this.workspaceReleaseOutcomes.get(sessionId);\n\t}\n\t/** Awaitable variant for the delegation failure path, which must release before the throw surfaces. */\n\tasync releaseWorkspaceNow(sessionId: string): Promise<void> {\n\t\tawait this.releaseWorkspaceOnce(sessionId);\n\t\tthis.workspaceClaims.delete(sessionId);\n\t}\n\treleaseWorkspace(sessionId: string): void {\n\t\tthis.workspaceClaims.delete(sessionId);\n\t}\n\tactiveWorkspaceClaims(): string[] {\n\t\treturn [...this.workspaceClaims.values()].flat();\n\t}\n\tclaimWorkspace(sessionId: string, paths: string[]): void {\n\t\tif (paths.length) this.workspaceClaims.set(sessionId, paths);\n\t}\n\tprivate save(handleId: string, entry: BackgroundDelegation, status: ChildRunRecord[\"status\"]): void {\n\t\tconst latest = entry.latest;\n\t\tconst record: ChildRunRecord = {\n\t\t\thandleId,\n\t\t\tagentType: entry.agentType,\n\t\t\tsessionId: handleId,\n\t\t\ttask: entry.task,\n\t\t\tartifactDir: entry.artifactDir,\n\t\t\tworkspace: entry.workspace,\n\t\t\tdepth: entry.depth,\n\t\t\tstatus,\n\t\t\tupdatedAt: Date.now(),\n\t\t\t// Attempts, the active attempt, and the spawn dedupe key persist with\n\t\t\t// every save: a restarted parent rebuilds attempts and the key->handle\n\t\t\t// map from these records alone.\n\t\t\tattempts: (entry.attempts ?? []).map((attempt) => ({ ...attempt })),\n\t\t\tactiveAttemptId: entry.activeAttemptId,\n\t\t\t// Record linkage (policy snapshot, sandbox flag, parent session id)\n\t\t\t// persists with every save too, so session readers describe the child\n\t\t\t// without re-deriving its policy (spec 2026-09-09, \"Derive, do not\n\t\t\t// reconstruct\").\n\t\t\t...(entry.parentSessionId !== undefined ? { parentSessionId: entry.parentSessionId } : {}),\n\t\t\t...(entry.policy\n\t\t\t\t? {\n\t\t\t\t\t\tpolicy: {\n\t\t\t\t\t\t\t...entry.policy,\n\t\t\t\t\t\t\ttools: [...entry.policy.tools],\n\t\t\t\t\t\t\tcapabilities: [...entry.policy.capabilities],\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(entry.sandboxEnforced !== undefined ? { sandboxEnforced: entry.sandboxEnforced } : {}),\n\t\t\t...(entry.idempotencyKey !== undefined ? { idempotencyKey: entry.idempotencyKey } : {}),\n\t\t\t...(entry.deadlineMs !== undefined ? { deadlineMs: entry.deadlineMs } : {}),\n\t\t\t...(entry.cancelled ? { cancelled: { ...entry.cancelled } } : {}),\n\t\t};\n\t\t// The settlement's output persists with the record so a historical run's\n\t\t// result stays retrievable after restart without reattaching the child.\n\t\tif (latest) {\n\t\t\trecord.latestResult = {\n\t\t\t\toutput:\n\t\t\t\t\tlatest.outcome === \"failed\"\n\t\t\t\t\t\t? latest.error instanceof Error\n\t\t\t\t\t\t\t? latest.error.message\n\t\t\t\t\t\t\t: String(latest.error)\n\t\t\t\t\t\t: latest.output,\n\t\t\t\toutcome: latest.outcome,\n\t\t\t};\n\t\t}\n\t\tthis.records.set(handleId, record);\n\t\tthis.persist?.(record);\n\t}\n\t/**\n\t * Record a turn settlement from the child handle's own report, falling back to\n\t * the settlement value for handles that did not report. The latest settlement\n\t * wins; retrieval serves it instead of the stored first-turn promise.\n\t */\n\tprivate recordCompletion(id: string, entry: BackgroundDelegation, fallbackOutput: string): void {\n\t\tconst reported = entry.child?.latestResult?.();\n\t\tentry.latest =\n\t\t\t!reported || reported.outcome === \"completed\"\n\t\t\t\t? { outcome: \"completed\", output: reported?.output ?? fallbackOutput }\n\t\t\t\t: reported.outcome === \"interrupted\"\n\t\t\t\t\t? { outcome: \"interrupted\", output: reported.output }\n\t\t\t\t\t: { outcome: \"failed\", error: new Error(reported.output || \"Child run failed.\") };\n\t\tthis.persistSettlement(id, entry);\n\t}\n\tprivate recordFailure(id: string, entry: BackgroundDelegation, error: unknown): void {\n\t\tconst reported = entry.child?.latestResult?.();\n\t\tentry.latest =\n\t\t\treported?.outcome === \"interrupted\" || (!reported && entry.child?.status === \"interrupted\")\n\t\t\t\t? { outcome: \"interrupted\", output: reported?.output ?? \"\" }\n\t\t\t\t: { outcome: \"failed\", error };\n\t\tthis.persistSettlement(id, entry);\n\t}\n\t/**\n\t * Stamp the active attempt with the settled turn's outcome. A cancellation\n\t * recorded on the entry wins for an interrupted settlement: the attempt\n\t * stays `cancelled` instead of downgrading to plain `interrupted`. Attempt\n\t * usage snapshots from the child's own controller where its handle exposes\n\t * one; handles without a controller leave usage unset. `tokensAtEnd`\n\t * snapshots the run-level token/cost rollup at settlement time (a\n\t * cumulative-at-end snapshot of the whole transcript -- see\n\t * `ChildRunAttempt`); when nothing is reachable it stays unset.\n\t */\n\tprivate stampAttemptSettlement(id: string, entry: BackgroundDelegation): void {\n\t\tconst attempt = activeAttemptOf(entry);\n\t\tconst latest = entry.latest;\n\t\tif (!attempt || !latest) return;\n\t\tattempt.outcome = latest.outcome === \"interrupted\" && entry.cancelled ? \"cancelled\" : latest.outcome;\n\t\tif (latest.outcome === \"failed\") {\n\t\t\tattempt.error = latest.error instanceof Error ? latest.error.message : String(latest.error);\n\t\t}\n\t\tconst usage = entry.child?.usage?.();\n\t\tif (usage) attempt.usage = usage;\n\t\tconst totals = this.usageTotalsFor(id, entry.artifactDir, entry.child);\n\t\tif (totals) attempt.tokensAtEnd = totals;\n\t}\n\t/** Persist the settlement's status. A closed run's terminal status is never overwritten by late settlement. */\n\tprivate persistSettlement(id: string, entry: BackgroundDelegation): void {\n\t\tif (entry.closed) return;\n\t\tconst latest = entry.latest;\n\t\tif (!latest) return;\n\t\tthis.stampAttemptSettlement(id, entry);\n\t\tthis.save(\n\t\t\tid,\n\t\t\tentry,\n\t\t\tlatest.outcome === \"completed\" ? \"completed\" : latest.outcome === \"interrupted\" ? \"interrupted\" : \"failed\",\n\t\t);\n\t\t// Terminal settlement (completed/failed/interrupted) releases the run's\n\t\t// concurrency slot (spec 2026-09-09, \"Shared budgets\").\n\t\tthis.releaseChildRunSlot(id);\n\t}\n\tassertOpen(): void {\n\t\tif (this.disposed) throw new Error(\"Child run registry is disposed.\");\n\t}\n\t/** The configured child-run concurrency limit, if any. */\n\tprivate concurrencyLimit(): number | undefined {\n\t\tconst limit = this.runtimeOptions?.maxConcurrentChildren;\n\t\treturn typeof limit === \"number\" && Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : undefined;\n\t}\n\t/**\n\t * Concurrency admission (spec 2026-09-09, \"Shared budgets\"): refuse with an\n\t * actionable error naming the limit BEFORE any child session is built when\n\t * every slot is occupied. An admitted run holds one slot until terminal\n\t * settlement, close, dispose, or a launch failure releases it.\n\t */\n\tadmitChildRun(handleId: string): void {\n\t\tconst limit = this.concurrencyLimit();\n\t\tif (limit === undefined) return;\n\t\tif (this.heldRunSlots.size >= limit) {\n\t\t\tthrow new Error(\n\t\t\t\t`Delegation refused: maxConcurrentChildren=${limit} and ${this.heldRunSlots.size} child run(s) are still active. Wait for a child run to finish or close it, or raise maxConcurrentChildren.`,\n\t\t\t);\n\t\t}\n\t\tthis.heldRunSlots.add(handleId);\n\t}\n\t/** Release a run's concurrency slot. Idempotent. */\n\treleaseChildRunSlot(handleId: string): void {\n\t\tthis.heldRunSlots.delete(handleId);\n\t}\n\town(child: ChildSessionHandle): void {\n\t\tif (this.disposed) {\n\t\t\tchild.dispose();\n\t\t\tthis.assertOpen();\n\t\t}\n\t\tthis.children.add(child);\n\t}\n\trelease(child: ChildSessionHandle): void {\n\t\tif (this.children.delete(child)) child.dispose();\n\t}\n\tregister(id: string, entry: BackgroundDelegation): void {\n\t\tthis.assertOpen();\n\t\t// A launch is attempt 1: an entry without attempts starts its first epoch\n\t\t// here (resumeHistorical supplies its own carried-over attempts).\n\t\tif (entry.attempts === undefined || entry.attempts.length === 0) {\n\t\t\tentry.attempts = [{ id: \"attempt-1\", startedAt: Date.now() }];\n\t\t\tentry.activeAttemptId ??= entry.attempts[0]!.id;\n\t\t}\n\t\tif (entry.idempotencyKey !== undefined) {\n\t\t\tthis.idempotencyKeys.set(entry.idempotencyKey, id);\n\t\t}\n\t\tif (!this.entries.has(id)) {\n\t\t\tthis.entries.set(id, entry);\n\t\t\t// Observe the initial turn's settlement here so the latest result is\n\t\t\t// recorded even when retrieval never happens; this derived branch always\n\t\t\t// resolves, so it can never become an unhandled rejection itself.\n\t\t\tconst settled = entry.promise.then(\n\t\t\t\t(result) => {\n\t\t\t\t\tthis.recordCompletion(id, entry, result.output);\n\t\t\t\t\treturn result;\n\t\t\t\t},\n\t\t\t\t(error) => {\n\t\t\t\t\tthis.recordFailure(id, entry, error);\n\t\t\t\t\treturn undefined as unknown as DelegationResult;\n\t\t\t\t},\n\t\t\t);\n\t\t\tvoid settled.catch(() => undefined);\n\t\t\tentry.pending = settled;\n\t\t}\n\t\tthis.save(id, entry, \"created\");\n\t}\n\tretrieve(id: string, expected?: string): Promise<DelegationResult> {\n\t\tconst entry = this.entries.get(id);\n\t\tif (!entry) {\n\t\t\tconst record = this.records.get(id);\n\t\t\tif (!record) throw new Error(`Unknown delegation handle \"${id}\".`);\n\t\t\tif (expected !== undefined && record.agentType !== expected)\n\t\t\t\tthrow new Error(`Delegation handle \"${id}\" belongs to agent \"${record.agentType}\", not \"${expected}\".`);\n\t\t\tconst latest = record.latestResult;\n\t\t\tif (!latest) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Child run \"${id}\" has no persisted output, so its result cannot be recovered after restart. Resume it with resumeChildRun(\"${id}\") to reattach its child session.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn Promise.resolve({\n\t\t\t\tagentType: record.agentType,\n\t\t\t\ttask: record.task ?? \"\",\n\t\t\t\toutput: latest.output,\n\t\t\t\toutcome: latest.outcome,\n\t\t\t});\n\t\t}\n\t\tif (expected !== undefined && entry.agentType !== expected)\n\t\t\tthrow new Error(`Delegation handle \"${id}\" belongs to agent \"${entry.agentType}\", not \"${expected}\".`);\n\t\treturn this.latestDelegationResult(entry);\n\t}\n\t/** Await any in-flight turn, then serve its settled outcome -- not the stored first-turn promise. */\n\tprivate async latestDelegationResult(entry: BackgroundDelegation): Promise<DelegationResult> {\n\t\tif (entry.pending) await entry.pending.catch(() => undefined);\n\t\tconst latest = entry.latest;\n\t\tif (!latest) return entry.promise;\n\t\tif (latest.outcome === \"failed\") throw latest.error;\n\t\treturn { agentType: entry.agentType, task: entry.task, output: latest.output, outcome: latest.outcome };\n\t}\n\t/**\n\t * One entry per child run -- live entries first, then historical records --\n\t * each as `{handleId, agentType, task, status, attemptCount}`. Backward\n\t * compatible: fields were only ever added. Observing the list lazily\n\t * interrupts a live running child whose wall-clock deadline has passed.\n\t */\n\tlist(): { handleId: string; agentType: string; task: string; status: ChildSessionStatus; attemptCount: number }[] {\n\t\tthis.observeDeadlines();\n\t\tconst historical = [...this.records]\n\t\t\t.filter(([id]) => !this.entries.has(id))\n\t\t\t.map(([handleId, record]) => ({\n\t\t\t\thandleId,\n\t\t\t\tagentType: record.agentType,\n\t\t\t\ttask: record.task ?? \"\",\n\t\t\t\tstatus:\n\t\t\t\t\trecord.status === \"closed\"\n\t\t\t\t\t\t? \"closed\"\n\t\t\t\t\t\t: record.status === \"interrupted\"\n\t\t\t\t\t\t\t? \"interrupted\"\n\t\t\t\t\t\t\t: record.status === \"running\"\n\t\t\t\t\t\t\t\t? \"running\"\n\t\t\t\t\t\t\t\t: (\"idle\" as ChildSessionStatus),\n\t\t\t\tattemptCount: childRunAttemptsOf(record).length,\n\t\t\t}));\n\t\treturn [...this.entries]\n\t\t\t.map(([handleId, entry]) => ({\n\t\t\t\thandleId,\n\t\t\t\tagentType: entry.agentType,\n\t\t\t\ttask: entry.task,\n\t\t\t\tstatus: entry.closed ? \"closed\" : (entry.child?.status ?? \"idle\"),\n\t\t\t\tattemptCount: (entry.attempts ?? []).length,\n\t\t\t}))\n\t\t\t.concat(historical);\n\t}\n\t/**\n\t * Non-blocking status snapshot for one handle (spec 2026-09-09, pollable\n\t * status): built from the live entry or the persisted record alone, never by\n\t * awaiting a turn. Unknown ids still error. Observing the status lazily\n\t * interrupts a live running child whose wall-clock deadline has passed, so a\n\t * timed-out run is reported (and stopped) at observation time.\n\t */\n\tstatus(id: string): ChildRunStatus {\n\t\tthis.assertOpen();\n\t\tthis.observeDeadlines();\n\t\tconst entry = this.entries.get(id);\n\t\tif (entry) return this.statusFromEntry(id, entry);\n\t\tconst record = this.records.get(id);\n\t\tif (!record) throw new Error(`Unknown delegation handle \"${id}\".`);\n\t\treturn this.statusFromRecord(record);\n\t}\n\t/**\n\t * The run's token/cost totals, rolled up on demand from the child's OWN\n\t * session transcript (the session-file reading seam) -- or from the handle's\n\t * in-memory session entries when no transcript file exists. Reads lazily and\n\t * caches only the last-computed totals, keyed by transcript size/mtime or\n\t * entry count, so the cache can never become a second transcript.\n\t * `undefined` -- never zero-filled, never a throw -- when nothing is\n\t * reachable: an in-memory child without a reachable transcript, or a\n\t * historical record whose transcript is gone. Unknown ids error like\n\t * `status`.\n\t */\n\tusageTotals(id: string): ChildRunUsageTotals | undefined {\n\t\tthis.assertOpen();\n\t\tconst entry = this.entries.get(id);\n\t\tif (entry) return this.usageTotalsFor(id, entry.artifactDir, entry.child);\n\t\tconst record = this.records.get(id);\n\t\tif (!record) throw new Error(`Unknown delegation handle \"${id}\".`);\n\t\treturn this.usageTotalsFor(id, record.artifactDir);\n\t}\n\t/**\n\t * One rollup read for both live entries and historical records: a\n\t * resolvable transcript file wins (the persisted transcript is the source of\n\t * truth, including after restart); the handle's in-memory session entries\n\t * cover an in-memory child whose transcript was never written.\n\t */\n\tprivate usageTotalsFor(\n\t\tid: string,\n\t\tartifactDir: string | undefined,\n\t\tchild?: ChildSessionHandle,\n\t): ChildRunUsageTotals | undefined {\n\t\tconst sessionFile = resolveSessionFile(artifactDir, id);\n\t\tif (sessionFile) {\n\t\t\ttry {\n\t\t\t\tconst stats = statSync(sessionFile);\n\t\t\t\tconst key = `file:${stats.size}:${stats.mtimeMs}`;\n\t\t\t\tconst cached = this.usageCache.get(id);\n\t\t\t\tif (cached && cached.key === key) return cached.totals;\n\t\t\t\tconst totals = computeUsageTotals(loadEntriesFromFile(sessionFile));\n\t\t\t\tif (totals) this.usageCache.set(id, { key, totals });\n\t\t\t\treturn totals;\n\t\t\t} catch {\n\t\t\t\t// An unreadable transcript falls through to the in-memory seam below;\n\t\t\t\t// reporting usage must never turn a status read into a failure.\n\t\t\t}\n\t\t}\n\t\tconst entries = child?.sessionEntries?.();\n\t\tif (entries) {\n\t\t\tconst last = entries[entries.length - 1];\n\t\t\tconst key = `mem:${entries.length}:${last?.id ?? \"\"}`;\n\t\t\tconst cached = this.usageCache.get(id);\n\t\t\tif (cached && cached.key === key) return cached.totals;\n\t\t\tconst totals = computeUsageTotals(entries);\n\t\t\tif (totals) this.usageCache.set(id, { key, totals });\n\t\t\treturn totals;\n\t\t}\n\t\treturn undefined;\n\t}\n\t/** The status payload's flattened view of the rollup, omitted when unreachable. */\n\tprivate static usageSummaryOf(totals: ChildRunUsageTotals | undefined): {\n\t\ttokens?: ChildRunStatus[\"tokens\"];\n\t\tcost?: ChildRunStatus[\"cost\"];\n\t} {\n\t\tif (!totals) return {};\n\t\treturn {\n\t\t\ttokens: {\n\t\t\t\tinputTokens: totals.inputTokens,\n\t\t\t\toutputTokens: totals.outputTokens,\n\t\t\t\tcacheReadTokens: totals.cacheReadTokens,\n\t\t\t\tcacheWriteTokens: totals.cacheWriteTokens,\n\t\t\t\ttotalTokens: totals.totalTokens,\n\t\t\t},\n\t\t\tcost: { ...totals.cost },\n\t\t};\n\t}\n\tprivate statusFromEntry(id: string, entry: BackgroundDelegation): ChildRunStatus {\n\t\tconst attempt = activeAttemptOf(entry);\n\t\tconst latest = entry.latest;\n\t\tconst usage = entry.child?.usage?.();\n\t\tconst workspace = entry.workspace;\n\t\t// The persisted record is the authority for a worktree's lifecycle state\n\t\t// (a closed-but-live entry's release may already have classified it);\n\t\t// while the record has none the live workspace is simply active.\n\t\tconst workspaceState = this.records.get(id)?.workspaceState;\n\t\t// Entries never carry their own session id: save() always records the\n\t\t// handle id as the child session id, so transcript resolution uses it.\n\t\tconst sessionFile = resolveSessionFile(entry.artifactDir, id);\n\t\treturn {\n\t\t\thandleId: id,\n\t\t\tagentType: entry.agentType,\n\t\t\ttask: entry.task,\n\t\t\tstatus: entry.closed ? \"closed\" : (entry.child?.status ?? \"idle\"),\n\t\t\tattempt: {\n\t\t\t\tid: attempt?.id ?? \"\",\n\t\t\t\t...(attempt?.outcome !== undefined ? { outcome: attempt.outcome } : {}),\n\t\t\t},\n\t\t\tattempts: (entry.attempts ?? []).length,\n\t\t\t...(latest\n\t\t\t\t? {\n\t\t\t\t\t\tlastResult: {\n\t\t\t\t\t\t\toutput:\n\t\t\t\t\t\t\t\tlatest.outcome === \"failed\"\n\t\t\t\t\t\t\t\t\t? latest.error instanceof Error\n\t\t\t\t\t\t\t\t\t\t? latest.error.message\n\t\t\t\t\t\t\t\t\t\t: String(latest.error)\n\t\t\t\t\t\t\t\t\t: latest.output,\n\t\t\t\t\t\t\toutcome: latest.outcome,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(entry.cancelled ? { cancelled: { ...entry.cancelled } } : {}),\n\t\t\t...(entry.deadlineMs !== undefined ? { deadlineMs: entry.deadlineMs } : {}),\n\t\t\t...(usage ? { usage } : {}),\n\t\t\t// Token/cost rollup from the child's own transcript, on the same lazy,\n\t\t\t// cached seam `usageTotals` serves; omitted when nothing is reachable.\n\t\t\t...ChildRunRegistry.usageSummaryOf(this.usageTotalsFor(id, entry.artifactDir, entry.child)),\n\t\t\t...(workspace\n\t\t\t\t? {\n\t\t\t\t\t\tworkspace: {\n\t\t\t\t\t\t\tisolation: workspace.isolation,\n\t\t\t\t\t\t\t...(workspace.root ? { root: workspace.root } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t...(workspace.isolation === \"worktree\" ? { workspaceState: workspaceState ?? \"active\" } : {}),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t// Record linkage (additive): artifact/session-file/parent identity,\n\t\t\t// the derived policy, and the sandbox flag ride along when known and\n\t\t\t// are simply omitted otherwise.\n\t\t\t...(entry.artifactDir !== undefined ? { artifactDir: entry.artifactDir } : {}),\n\t\t\t...(sessionFile !== undefined ? { sessionFile } : {}),\n\t\t\t...(entry.parentSessionId !== undefined ? { parentSessionId: entry.parentSessionId } : {}),\n\t\t\t...(entry.policy ? { policy: entry.policy } : {}),\n\t\t\t...(entry.sandboxEnforced !== undefined ? { sandboxEnforced: entry.sandboxEnforced } : {}),\n\t\t};\n\t}\n\tprivate statusFromRecord(record: ChildRunRecord): ChildRunStatus {\n\t\tconst attempts = childRunAttemptsOf(record);\n\t\t// The active attempt when one is open; otherwise (terminal or legacy\n\t\t// record) the most recent attempt carries the reported outcome.\n\t\tconst attempt = record.activeAttemptId\n\t\t\t? (attempts.find((candidate) => candidate.id === record.activeAttemptId) ?? attempts[attempts.length - 1])\n\t\t\t: attempts[attempts.length - 1];\n\t\tconst workspace = record.workspace;\n\t\tconst sessionFile = resolveSessionFile(record.artifactDir, record.sessionId);\n\t\treturn {\n\t\t\thandleId: record.handleId,\n\t\t\tagentType: record.agentType,\n\t\t\ttask: record.task ?? \"\",\n\t\t\tstatus:\n\t\t\t\trecord.status === \"closed\"\n\t\t\t\t\t? \"closed\"\n\t\t\t\t\t: record.status === \"interrupted\"\n\t\t\t\t\t\t? \"interrupted\"\n\t\t\t\t\t\t: record.status === \"running\"\n\t\t\t\t\t\t\t? \"running\"\n\t\t\t\t\t\t\t: (\"idle\" as ChildSessionStatus),\n\t\t\tattempt: {\n\t\t\t\tid: attempt?.id ?? attempts[attempts.length - 1]?.id ?? \"\",\n\t\t\t\t...(attempt?.outcome !== undefined ? { outcome: attempt.outcome } : {}),\n\t\t\t},\n\t\t\tattempts: attempts.length,\n\t\t\t...(record.latestResult ? { lastResult: { ...record.latestResult } } : {}),\n\t\t\t...(record.cancelled ? { cancelled: { ...record.cancelled } } : {}),\n\t\t\t...(record.deadlineMs !== undefined ? { deadlineMs: record.deadlineMs } : {}),\n\t\t\t// Token/cost rollup from the persisted transcript, so a restarted\n\t\t\t// parent reports the same totals without a live child.\n\t\t\t...ChildRunRegistry.usageSummaryOf(this.usageTotalsFor(record.handleId, record.artifactDir)),\n\t\t\t...(workspace\n\t\t\t\t? {\n\t\t\t\t\t\tworkspace: {\n\t\t\t\t\t\t\tisolation: workspace.isolation,\n\t\t\t\t\t\t\t...(workspace.root ? { root: workspace.root } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t// Absent means active (legacy records predate the field).\n\t\t\t\t\t\t...(workspace.isolation === \"worktree\" ? { workspaceState: record.workspaceState ?? \"active\" } : {}),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t// Record linkage (additive): legacy records without the fields simply\n\t\t\t// omit them (spec 2026-09-09, policy/sandbox/artifact linkage).\n\t\t\t...(record.artifactDir !== undefined ? { artifactDir: record.artifactDir } : {}),\n\t\t\t...(sessionFile !== undefined ? { sessionFile } : {}),\n\t\t\t...(record.parentSessionId !== undefined ? { parentSessionId: record.parentSessionId } : {}),\n\t\t\t...(record.policy ? { policy: record.policy } : {}),\n\t\t\t...(record.sandboxEnforced !== undefined ? { sandboxEnforced: record.sandboxEnforced } : {}),\n\t\t};\n\t}\n\t/**\n\t * Lazy deadline observation (spec 2026-09-09, timeouts): a live RUNNING child\n\t * past its recorded wall-clock deadline is interrupted at observation time.\n\t * The interrupt carries no reason -- a wall-time timeout is not a user\n\t * cancellation -- so the attempt settles `interrupted`, and the child's own\n\t * budget gate names \"wall-time\" in the settlement error path when the run's\n\t * turn was refused for time. Historical records have no live child to\n\t * interrupt and are left untouched.\n\t */\n\tprivate observeDeadlines(): void {\n\t\tconst now = Date.now();\n\t\tfor (const [id, entry] of this.entries) {\n\t\t\tif (entry.closed || entry.deadlineMs === undefined || now < entry.deadlineMs) continue;\n\t\t\tif (entry.child?.status !== \"running\") continue;\n\t\t\ttry {\n\t\t\t\tthis.interrupt(id);\n\t\t\t} catch {\n\t\t\t\t// The child vanished between the check and the interrupt; nothing left to observe.\n\t\t\t}\n\t\t}\n\t}\n\tprivate child(id: string): ChildSessionHandle {\n\t\tthis.assertOpen();\n\t\tconst entry = this.entries.get(id);\n\t\tif (!entry) throw new Error(`Unknown delegation handle \"${id}\".`);\n\t\tif (entry.closed) throw new Error(`Child session \"${id}\" is closed.`);\n\t\tif (!entry.child) throw new Error(`Delegation handle \"${id}\" has no child session.`);\n\t\treturn entry.child;\n\t}\n\tasync wait(id: string): Promise<DelegationResult> {\n\t\tconst entry = this.entries.get(id);\n\t\t// A historical record has nothing to await: its persisted settlement (if\n\t\t// any) is served through retrieve, which throws the actionable error when\n\t\t// no output was persisted.\n\t\tif (!entry) return this.retrieve(id);\n\t\tif (!entry.closed) {\n\t\t\tconst child = this.child(id);\n\t\t\tif (entry.pending || child.status === \"running\") this.save(id, entry, \"running\");\n\t\t\t// A turn that ends interrupted or failed rejects here; retrieval below owns\n\t\t\t// propagation, surfacing interrupted as an outcome and failed as a throw.\n\t\t\tawait child.wait().catch(() => undefined);\n\t\t}\n\t\treturn this.retrieve(id);\n\t}\n\tsendInput(id: string, input: string): Promise<void> {\n\t\t// Unknown and closed handles throw synchronously, matching close()'s contract.\n\t\tconst child = this.child(id);\n\t\tconst entry = this.entries.get(id)!;\n\t\tconst turn = child.sendInput(input).then(\n\t\t\t() => {\n\t\t\t\tthis.recordCompletion(id, entry, \"\");\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\tthis.recordFailure(id, entry, error);\n\t\t\t\tthrow error;\n\t\t\t},\n\t\t);\n\t\tvoid turn.catch(() => undefined);\n\t\tentry.pending = turn;\n\t\treturn turn;\n\t}\n\t/**\n\t * Interrupt a live child. An optional reason turns the interrupt into an\n\t * explicit cancellation: `{reason, at}` is persisted on the record\n\t * immediately and the active attempt is marked `cancelled`; without a\n\t * reason the attempt settles plain `interrupted` at the turn's settlement.\n\t */\n\tinterrupt(id: string, reason?: string): void {\n\t\tthis.child(id).interrupt();\n\t\tif (reason === undefined) return;\n\t\tconst entry = this.entries.get(id);\n\t\tif (!entry) return; // Unreachable: child(id) already validated the handle.\n\t\tentry.cancelled = { reason, at: Date.now() };\n\t\tconst attempt = activeAttemptOf(entry);\n\t\tif (attempt) attempt.outcome = \"cancelled\";\n\t\t// The child's post-interrupt handle status maps onto the record's status\n\t\t// vocabulary (\"idle\" is a handle state, not a record state).\n\t\tconst childStatus = entry.child?.status;\n\t\tconst recordStatus: ChildRunRecord[\"status\"] = childStatus === \"running\" ? \"running\" : \"interrupted\";\n\t\tthis.save(id, entry, recordStatus);\n\t}\n\t/**\n\t * Close a live run's active attempt with its latest settled outcome and open\n\t * a new one for the resuming turn (spec 2026-09-09, \"Child lifecycle\"):\n\t * `AgentSession.resumeChildRun` calls this on the live path before\n\t * `sendInput` so a resume is a distinct attempt epoch, while ordinary\n\t * follow-ups on a live run stay inside the active attempt.\n\t */\n\tbeginResumeAttempt(id: string): void {\n\t\tconst entry = this.entries.get(id);\n\t\tif (!entry) throw new Error(`Unknown delegation handle \"${id}\".`);\n\t\tconst prior = activeAttemptOf(entry);\n\t\tif (prior && prior.endedAt === undefined) {\n\t\t\tprior.endedAt = Date.now();\n\t\t\tprior.outcome ??= entry.latest?.outcome;\n\t\t}\n\t\t// A resume close stamps the closed attempt's cumulative-at-end rollup\n\t\t// when its settlement never produced one (a settlement-stamped snapshot\n\t\t// is never overwritten with the later, larger transcript).\n\t\tif (prior && prior.tokensAtEnd === undefined) {\n\t\t\tconst totals = this.usageTotalsFor(id, entry.artifactDir, entry.child);\n\t\t\tif (totals) prior.tokensAtEnd = totals;\n\t\t}\n\t\tconst attempts = entry.attempts ?? [];\n\t\tconst attempt: ChildRunAttempt = { id: `attempt-${attempts.length + 1}`, startedAt: Date.now() };\n\t\tattempts.push(attempt);\n\t\tentry.attempts = attempts;\n\t\tentry.activeAttemptId = attempt.id;\n\t}\n\tclose(id: string): void {\n\t\tthis.assertOpen();\n\t\tconst entry = this.entries.get(id);\n\t\tif (!entry) throw new Error(`Unknown delegation handle \"${id}\".`);\n\t\tif (entry.closed) return;\n\t\tentry.closed = true;\n\t\tthis.workspaceClaims.delete(id);\n\t\t// A closed run's slot is released with it (spec 2026-09-09, \"Shared\n\t\t// budgets\"), even when its turn never settles.\n\t\tthis.releaseChildRunSlot(id);\n\t\t// Release the child's workspace (worktree) with its lifecycle; best effort,\n\t\t// fire-and-forget: close() is synchronous and must never throw on cleanup.\n\t\tvoid this.releaseWorkspaceOnce(id);\n\t\tthis.save(id, entry, \"closed\");\n\t\tif (entry.child) {\n\t\t\tthis.children.delete(entry.child);\n\t\t\tentry.child.close();\n\t\t}\n\t}\n\t/** Stop tracking handles and release any children and workspaces still owned by this registry. */\n\tdispose(): void {\n\t\tif (this.disposed) return;\n\t\tthis.disposed = true;\n\t\tfor (const child of this.children) {\n\t\t\ttry {\n\t\t\t\tchild.interrupt();\n\t\t\t} catch {}\n\t\t\ttry {\n\t\t\t\tthis.release(child);\n\t\t\t} catch {}\n\t\t}\n\t\t// Release every tracked child workspace (worktree) with the registry.\n\t\t// Best effort and fire-and-forget: dispose() is synchronous.\n\t\tfor (const sessionId of this.trackedWorkspaces) {\n\t\t\tvoid this.releaseWorkspaceOnce(sessionId);\n\t\t}\n\t\tthis.entries.clear();\n\t\tthis.workspaceClaims.clear();\n\t\tthis.usageCache.clear();\n\t\t// No run holds a concurrency slot past the registry's disposal.\n\t\tthis.heldRunSlots.clear();\n\t}\n}\n\n/**\n * Run one delegation to completion. Throws rather than returning a failure value,\n * matching this codebase's convention for model-facing routine failures (e.g.\n * `tool_schema`'s unknown-tool case, `web_search`'s unconfigured-backend case): a\n * thrown `Error` here is caught by the agent loop and surfaces as a normal,\n * model-readable `isError` tool result, not a fatal turn failure.\n *\n * The capability check is all-or-nothing by design (ceiling.ts): a definition\n * requesting a tool the parent's own capabilities cannot cover refuses the whole\n * delegation, naming the capability, rather than silently building a child missing\n * that one tool. `buildChildSession` is therefore never called for a refused\n * delegation -- there is no code path that produces a child holding a capability\n * outside the ceiling.\n *\n * The depth check (task 5.3) runs right after agent-type resolution and before the\n * capability check, so recursion is bounded regardless of what is being delegated --\n * a refusal at the bound still names the agent type, but never reaches the ceiling\n * or `buildChildSession`. `buildChildSession` receives the child's depth (parent + 1)\n * so the caller can record it on the child's own session header.\n */\n/**\n * Whether two resolved paths denote the same directory or either contains the\n * other. Comparison is separator-correct: forward-slash prefix matching\n * silently never matches on platforms whose resolve() produces backslashes.\n */\nexport function claimPathsOverlap(a: string, b: string): boolean {\n\tconst ab = relative(a, b);\n\tif (ab !== \"..\" && !ab.startsWith(`..${sep}`) && !isAbsolute(ab)) return true;\n\tconst ba = relative(b, a);\n\treturn ba !== \"..\" && !ba.startsWith(`..${sep}`) && !isAbsolute(ba);\n}\n\nexport async function runDelegation(\n\toptions: DelegationRuntimeOptions,\n\tagentType: string,\n\ttask: string,\n\trequest: {\n\t\tbackground?: boolean;\n\t\tworkspace?: ChildWorkspaceRequest;\n\t\thandleId?: string;\n\t\t/** Spawn dedupe key (spec 2026-09-09, idempotent spawn): a known key returns the EXISTING handle without building a second child. */\n\t\tidempotencyKey?: string;\n\t\t/** Wall-time cap for the child's own run budget; also recorded as the record's deadlineMs for lazy observation. */\n\t\ttimeoutMs?: number;\n\t} = {},\n): Promise<DelegationResult> {\n\tlet registry = options.childRunRegistry;\n\tif (!registry) {\n\t\tregistry = new ChildRunRegistry();\n\t\toptions.childRunRegistry = registry;\n\t}\n\tregistry.assertOpen();\n\tregistry.setRuntimeOptions(options);\n\t// Idempotent spawn: a key that already maps to a handle returns that handle\n\t// BEFORE any admission or child construction, so a duplicate spawn consumes\n\t// no second concurrency slot. The map is rebuilt from persisted records on\n\t// restore, so a restarted parent dedupes too.\n\tif (request.idempotencyKey !== undefined) {\n\t\tconst existing = registry.handleForIdempotencyKey(request.idempotencyKey);\n\t\tif (existing !== undefined) {\n\t\t\treturn {\n\t\t\t\tagentType,\n\t\t\t\ttask,\n\t\t\t\toutput: `Delegation already started with handle \"${existing}\" (idempotency key \"${request.idempotencyKey}\"); retrieve it with that handle.`,\n\t\t\t\thandleId: existing,\n\t\t\t};\n\t\t}\n\t}\n\tconst timeoutMs =\n\t\ttypeof request.timeoutMs === \"number\" && Number.isFinite(request.timeoutMs) ? request.timeoutMs : undefined;\n\tconst { definition, capabilities } = resolveAdmittedDefinition(options, agentType);\n\tconst workspace = request.workspace ?? { isolation: \"shared-read\", ownedPaths: [] };\n\t// The owner is read only for worktree isolation, so production callers can\n\t// construct it lazily: a shared-read delegation never builds an owner and\n\t// never invokes git.\n\tconst workspaceOwner = workspace.isolation === \"worktree\" ? options.workspaceOwner : undefined;\n\tif (workspace.isolation === \"worktree\" && !workspaceOwner) {\n\t\tthrow new Error(\n\t\t\t`Delegation to agent \"${agentType}\" requested worktree isolation, but no workspace owner is available.`,\n\t\t);\n\t}\n\tconst claims = [...workspace.ownedPaths].map((p) => resolve(p));\n\tfor (const entry of registry.activeWorkspaceClaims()) {\n\t\tif (claims.some((path) => claimPathsOverlap(path, entry))) {\n\t\t\tthrow new Error(`Delegation to agent \"${agentType}\" overlaps an active write ownership claim.`);\n\t\t}\n\t}\n\n\t// The depth bound and capability ceiling are enforced inside\n\t// resolveAdmittedDefinition above, shared with historical reattachment.\n\t// The caller may provide the public handle so the registry identity and\n\t// child session identity cannot diverge. Existing callers retain generated IDs.\n\tconst sessionId = request.handleId ?? randomUUID();\n\tconst depth = options.getDelegationDepth();\n\tregistry.claimWorkspace(sessionId, claims);\n\tif (workspaceOwner) {\n\t\t// Worktree isolation: the registry releases this workspace when the run\n\t\t// closes or the registry disposes, through the same owner.\n\t\tregistry.setWorkspaceOwner(workspaceOwner);\n\t\tregistry.trackWorkspace(sessionId);\n\t}\n\ttry {\n\t\t// Concurrency admission (spec 2026-09-09, \"Shared budgets\"): over the\n\t\t// limit this throws BEFORE any child session is built, naming the limit.\n\t\tregistry.admitChildRun(sessionId);\n\t\tconst preparedWorkspace = workspaceOwner\n\t\t\t? await workspaceOwner.prepare({ ...workspace, ownedPaths: claims, sessionId })\n\t\t\t: workspace;\n\t\tlet artifactDir: string | undefined;\n\t\tconst parentSessionDir = options.getParentSessionDir?.();\n\t\tif (parentSessionDir) {\n\t\t\tconst parentRoot = resolve(parentSessionDir);\n\t\t\tartifactDir = join(parentRoot, \"delegations\", sessionId);\n\t\t\tmkdirSync(artifactDir, { recursive: true });\n\t\t}\n\t\tconst child = await options.buildChildSession({\n\t\t\tagentType,\n\t\t\tdefinition,\n\t\t\ttoolNames: definition.tools,\n\t\t\tcapabilities,\n\t\t\tdepth: depth + 1,\n\t\t\tsessionId,\n\t\t\tartifactDir,\n\t\t\tworkspace: preparedWorkspace,\n\t\t\t...(timeoutMs !== undefined ? { timeoutMs } : {}),\n\t\t});\n\t\tregistry.own(child);\n\t\tconst handleId = sessionId;\n\t\tconst promise = child.run(task).then(({ output }) => ({ agentType, task, output }));\n\t\t// register() observes the turn's settlement: it records the handle's latest\n\t\t// result (retrieval follows that, not this promise) and persists the run's\n\t\t// terminal status, so no separate settlement hook is needed here. The\n\t\t// durable fields ride along so every save() can persist them for restart.\n\t\t// A launch is attempt 1; timeoutMs also records the wall-clock deadline the\n\t\t// pollable status observes lazily. The record linkage (policy snapshot,\n\t\t// sandbox flag, parent session id) comes from the handle's own\n\t\t// construction report -- the values buildChildSession actually used --\n\t\t// and the runtime's parent-session seam; fixture handles that omit them\n\t\t// simply leave the record fields absent.\n\t\tregistry.register(handleId, {\n\t\t\tagentType,\n\t\t\ttask,\n\t\t\tpromise,\n\t\t\tchild,\n\t\t\tartifactDir,\n\t\t\tworkspace: preparedWorkspace,\n\t\t\tdepth: depth + 1,\n\t\t\tattempts: [{ id: \"attempt-1\", startedAt: Date.now() }],\n\t\t\tactiveAttemptId: \"attempt-1\",\n\t\t\t...(child.policy ? { policy: child.policy } : {}),\n\t\t\t...(options.getParentSessionId ? { parentSessionId: options.getParentSessionId() } : {}),\n\t\t\t...(request.idempotencyKey !== undefined ? { idempotencyKey: request.idempotencyKey } : {}),\n\t\t\t...(timeoutMs !== undefined ? { deadlineMs: Date.now() + timeoutMs } : {}),\n\t\t});\n\t\tif (!request.background) return promise;\n\t\treturn { agentType, task, output: `Delegation started. Retrieve result with handle \"${handleId}\".`, handleId };\n\t} catch (error) {\n\t\t// The delegation never started: release the workspace immediately (also\n\t\t// marks it released, so a later close/dispose cannot double-release) and\n\t\t// give back the concurrency slot admitted above.\n\t\tregistry.releaseChildRunSlot(sessionId);\n\t\tawait registry.releaseWorkspaceNow(sessionId);\n\t\tthrow error;\n\t}\n}\n\n/** Retrieve a background delegation. Running children are awaited; unknown handles fail explicitly. */\nexport async function retrieveDelegationResult(\n\toptions: DelegationRuntimeOptions,\n\thandleId: string,\n\texpectedAgentType?: string,\n): Promise<DelegationResult> {\n\tlet registry = options.childRunRegistry;\n\tif (!registry) {\n\t\tregistry = new ChildRunRegistry();\n\t\toptions.childRunRegistry = registry;\n\t}\n\treturn registry.retrieve(handleId, expectedAgentType);\n}\n"]}
|