@tangle-network/agent-runtime 0.133.4 → 0.133.5
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/dist/{activation-WLt7Dmfv.js → activation-CeZdt1R3.js} +2 -2
- package/dist/{activation-WLt7Dmfv.js.map → activation-CeZdt1R3.js.map} +1 -1
- package/dist/agent.js +2 -2
- package/dist/{authoring-Da9lWfh7.js → authoring-Cbz3BYqD.js} +2 -2
- package/dist/{authoring-Da9lWfh7.js.map → authoring-Cbz3BYqD.js.map} +1 -1
- package/dist/{environment-provider-mDsjfGjY.js → environment-provider-DTJA4ZiM.js} +10 -5
- package/dist/{environment-provider-mDsjfGjY.js.map → environment-provider-DTJA4ZiM.js.map} +1 -1
- package/dist/environment-provider.js +1 -1
- package/dist/{graph-TkrwBJCS.js → graph-BcwxFLW_.js} +2 -2
- package/dist/{graph-TkrwBJCS.js.map → graph-BcwxFLW_.js.map} +1 -1
- package/dist/{improvement-cycle-ClbcuXvP.js → improvement-cycle-CXY8XmhV.js} +3 -3
- package/dist/{improvement-cycle-ClbcuXvP.js.map → improvement-cycle-CXY8XmhV.js.map} +1 -1
- package/dist/index.js +7 -7
- package/dist/intelligence.js +4 -4
- package/dist/kernel.js +7 -7
- package/dist/{knowledge-CwPnD1pI.js → knowledge-vEyPvtRm.js} +3 -3
- package/dist/{knowledge-CwPnD1pI.js.map → knowledge-vEyPvtRm.js.map} +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-DWQCX7cS.js → loop-runner-bin-BrF0g950.js} +3 -3
- package/dist/{loop-runner-bin-DWQCX7cS.js.map → loop-runner-bin-BrF0g950.js.map} +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.js +4 -4
- package/dist/{openai-tools-DYZaZVDC.js → openai-tools-BEeoh5i0.js} +2 -2
- package/dist/{openai-tools-DYZaZVDC.js.map → openai-tools-BEeoh5i0.js.map} +1 -1
- package/dist/{runtime-DRr7g_2C.js → runtime-BX5c47Qm.js} +7 -7
- package/dist/{runtime-DRr7g_2C.js.map → runtime-BX5c47Qm.js.map} +1 -1
- package/dist/{structural-rollout-BfOB1pIb.js → structural-rollout-CHq3qJau.js} +2 -2
- package/dist/{structural-rollout-BfOB1pIb.js.map → structural-rollout-CHq3qJau.js.map} +1 -1
- package/dist/{supervise-C3yRHeDk.js → supervise-D-e9RIuG.js} +2 -2
- package/dist/{supervise-C3yRHeDk.js.map → supervise-D-e9RIuG.js.map} +1 -1
- package/dist/{supervisor-D8sBmGYd.js → supervisor-GBIOnjUo.js} +25 -15
- package/dist/supervisor-GBIOnjUo.js.map +1 -0
- package/dist/testing.js +11 -11
- package/package.json +1 -1
- package/dist/supervisor-D8sBmGYd.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"supervisor-GBIOnjUo.js","names":["profileMaterializationAxes","sleep","abortableSleep","TEARDOWN_TIMEOUT_MS","isAbortError","linkSignals","httpsRequest","httpRequest","isAsyncIterable","zeroSpend","addSpend"],"sources":["../src/agent/profile-materialization.ts","../src/mcp/codex-diagnostics.ts","../src/mcp/local-harness.ts","../src/mcp/worktree.ts","../src/mcp/worktree-harness.ts","../src/sanitize.ts","../src/otel-export.ts","../src/mcp/trace-propagation.ts","../src/runtime/model-identity.ts","../src/runtime/tool-loop.ts","../src/runtime/router-client.ts","../src/runtime/sandbox-acquire.ts","../src/runtime/sandbox-backend.ts","../src/runtime/sandbox-capabilities.ts","../src/runtime/sandbox-lineage.ts","../src/runtime/run-loop.ts","../src/runtime/supervise/inbox.ts","../src/runtime/supervise/progress.ts","../src/runtime/supervise/trace-source.ts","../src/runtime/supervise/sandbox-session.ts","../src/runtime/supervise/worker-trace.ts","../src/runtime/supervise/worktree-cli-executor.ts","../src/runtime/supervise/runtime.ts","../src/runtime/supervise/budget.ts","../src/runtime/supervise/deadline.ts","../src/runtime/supervise/dispatch.ts","../src/runtime/supervise/wait.ts","../src/runtime/supervise/scope.ts","../src/runtime/supervise/driver-executor.ts","../src/runtime/supervise/finalizer.ts","../src/runtime/supervise/supervisor.ts"],"sourcesContent":["import {\n AGENT_PROFILE_MATERIALIZATION_AXES,\n type CanonicalAgentProfileMaterializationAxis,\n profileMaterializationAxes,\n} from '@tangle-network/agent-interface'\nimport { ValidationError } from '../errors'\n\nexport type { CanonicalAgentProfileMaterializationAxis }\n/**\n * The canonical AgentProfile leaves, re-exported from `@tangle-network/agent-interface`.\n *\n * These are LEAVES only: `modelReasoningEffort`, not `model`; `systemPrompt`, not `prompt`. A\n * contract must name every leaf it carries, because claiming a compound parent while dropping one\n * of its children is exactly the silent-drop this module exists to catch.\n */\nexport { AGENT_PROFILE_MATERIALIZATION_AXES, profileMaterializationAxes }\n\nexport type KnownAgentProfileMaterializationAxis = CanonicalAgentProfileMaterializationAxis\n\n/** AgentProfile axis name, with `custom:<name>` reserved for caller-owned extensions. */\nexport type AgentProfileMaterializationAxis =\n | KnownAgentProfileMaterializationAxis\n | `custom:${string}`\n\n/** Declares which AgentProfile axes a concrete run path really carries. */\nexport interface ProfileMaterializationContract {\n /** Human-readable run path, e.g. `createSandboxAct` or `prompt-only-message`. */\n name: string\n /** Profile axes this run path actually carries into execution. */\n axes: readonly AgentProfileMaterializationAxis[]\n}\n\n/** One changed AgentProfile axis that would be dropped by a run path. */\nexport interface ProfileMaterializationIssue {\n contract: string\n axis: AgentProfileMaterializationAxis\n reason: 'unsupported-axis'\n supportedAxes: readonly AgentProfileMaterializationAxis[]\n}\n\n/** Input for declaring a run path's profile-axis support. */\nexport interface DefineProfileMaterializationContractOptions {\n name: string\n axes: readonly AgentProfileMaterializationAxis[]\n}\n\n/** Input for checking a candidate diff against a run path. */\nexport interface ValidateProfileMaterializationOptions {\n contract: ProfileMaterializationContract\n changedAxes: readonly AgentProfileMaterializationAxis[]\n}\n\n/** Input for throwing on dropped profile axes. */\nexport interface AssertProfileMaterializationOptions extends ValidateProfileMaterializationOptions {\n /** Extra label included in the thrown error, usually the caller or run id. */\n context?: string\n}\n\nconst KNOWN_AXIS_SET = new Set<string>(AGENT_PROFILE_MATERIALIZATION_AXES)\n\n/**\n * Compound AgentProfile properties and the canonical leaves they cover.\n *\n * agent-interface publishes two axis vocabularies, and this module has to sit between them:\n * `profileMaterializationAxes` emits canonical LEAVES, while `changedAgentProfileAxes` emits\n * DIFF axes, which are compound property names (`model`, `prompt`, `resources`, `identity`) for\n * everything except the already-scalar properties. A changed-axis input is therefore expanded\n * through this map, so both producers compose with this validator.\n *\n * A CONTRACT may still only name leaves. Expanding an input is safe — it asks about more, never\n * less — whereas letting a contract claim a parent is what silently swallows a dropped child.\n */\nconst compoundAxisLeaves: Record<string, readonly CanonicalAgentProfileMaterializationAxis[]> = {\n identity: ['name', 'description', 'version', 'tags'],\n prompt: ['systemPrompt', 'instructions'],\n model: ['modelDefault', 'modelSmall', 'modelProvider', 'modelReasoningEffort', 'modelMetadata'],\n resources: [\n 'files',\n 'resourceTools',\n 'skills',\n 'resourceAgents',\n 'commands',\n 'resourceInstructions',\n 'resourceFailOnError',\n ],\n mcpConnections: ['mcp'],\n}\n\n/** Materialization contract for a run path that executes every canonical AgentProfile leaf. */\nexport const fullProfileMaterialization = defineProfileMaterializationContract({\n name: 'full-profile-execution',\n axes: AGENT_PROFILE_MATERIALIZATION_AXES,\n})\n\n/**\n * Materialization contract for an intentionally limited prompt-and-model execution path.\n * Identity, harness, and metadata are control fields consumed for naming, placement,\n * authorization, and durable attribution; they are carried without adding worker behavior.\n * Every behavioral axis other than prompt and model remains unsupported.\n */\nexport const promptModelProfileMaterialization = defineProfileMaterializationContract({\n name: 'prompt-model-execution',\n axes: [\n 'name',\n 'systemPrompt',\n 'instructions',\n 'modelDefault',\n 'modelProvider',\n 'modelReasoningEffort',\n 'modelMetadata',\n 'harness',\n 'metadata',\n ],\n})\n\n/**\n * Materialization contract for a local coding CLI in an isolated git worktree.\n * The shared workspace materializer carries native tools, permissions, MCP, hooks, subagents,\n * modes, and file-backed resources when the selected CLI supports their exact values.\n * `resourceFailOnError` is carried: it is the fail-closed policy the pre-worktree resource\n * RESOLUTION step (`resolveAgentProfileResources`) applies to remote profile resources. Runtime\n * placement concerns (hub connections and confidential execution), provider-native extensions,\n * and unused model hints are deliberately absent so they fail before a worktree or executor is\n * created rather than being mistaken for an effective candidate change.\n */\nexport const worktreeCliProfileMaterialization = defineProfileMaterializationContract({\n name: 'worktree-cli-execution',\n axes: [\n 'name',\n 'systemPrompt',\n 'instructions',\n 'modelDefault',\n 'modelProvider',\n 'modelReasoningEffort',\n 'harness',\n 'permissions',\n 'tools',\n 'mcp',\n 'subagents',\n 'files',\n 'resourceTools',\n 'skills',\n 'resourceAgents',\n 'commands',\n 'resourceInstructions',\n 'resourceFailOnError',\n 'hooks',\n 'modes',\n 'metadata',\n ],\n})\n\n/** Materialization contract for a raw process path that carries only control/identity fields. */\nexport const controlProfileMaterialization = defineProfileMaterializationContract({\n name: 'control-only-execution',\n axes: ['name', 'harness', 'metadata'],\n})\n\n/** Materialization contract for an injected inference function whose surrounding driver still\n * applies the profile prompt, name, placement, and metadata, but not model selection. */\nexport const promptControlProfileMaterialization = defineProfileMaterializationContract({\n name: 'prompt-control-execution',\n axes: [\n 'name',\n 'systemPrompt',\n 'instructions',\n 'modelDefault',\n 'modelProvider',\n 'modelReasoningEffort',\n 'modelMetadata',\n 'harness',\n 'metadata',\n ],\n})\n\n/**\n * Materialization contract for `createSandboxAct`.\n *\n * `createSandboxAct` hands the whole `AgentProfile` to the sandbox as `backend.profile`, so every\n * profile leaf crosses the boundary. `buildBackendOptions` resolves the runner only from\n * `profile.harness`; an explicit `sandboxOverrides.backend.type` may confirm that choice but cannot\n * replace it. A candidate declaring a harness the sandbox cannot run throws rather than running\n * elsewhere and reporting success.\n */\nexport const sandboxActProfileMaterialization = defineProfileMaterializationContract({\n name: 'createSandboxAct',\n axes: fullProfileMaterialization.axes,\n})\n\n/** Materialization contract for a run path that only injects prompt text. */\nexport const promptOnlyProfileMaterialization = defineProfileMaterializationContract({\n name: 'prompt-only-message',\n axes: ['systemPrompt', 'instructions'],\n})\n\n/**\n * Materialization contract for a run path that injects prompt text plus inline resources.\n *\n * `resourceFailOnError` is absent: it is a resolution POLICY the attaching path would have to\n * enforce, and inlining resource content does not carry it.\n */\nexport const promptResourceProfileMaterialization = defineProfileMaterializationContract({\n name: 'prompt-resource-attachment',\n axes: [\n 'systemPrompt',\n 'instructions',\n 'files',\n 'resourceTools',\n 'skills',\n 'resourceAgents',\n 'commands',\n 'resourceInstructions',\n ],\n})\n\n/** Define the profile axes a concrete run path actually carries into execution. */\nexport function defineProfileMaterializationContract(\n options: DefineProfileMaterializationContractOptions,\n): ProfileMaterializationContract {\n const name = options.name.trim()\n if (!name) {\n throw new ValidationError('defineProfileMaterializationContract: name is required')\n }\n return {\n name,\n axes: normalizeContractAxes(options.axes, `${name}.axes`),\n }\n}\n\n/** Return every changed profile axis that the selected run path would drop. */\nexport function validateProfileMaterialization(\n options: ValidateProfileMaterializationOptions,\n): readonly ProfileMaterializationIssue[] {\n const changedAxes = normalizeChangedAxes(options.changedAxes, 'changedAxes')\n const supported = new Set<string>(\n normalizeContractAxes(options.contract.axes, `${options.contract.name}.axes`),\n )\n const issues: ProfileMaterializationIssue[] = []\n for (const axis of changedAxes) {\n if (isAxisSupported(axis, supported)) continue\n issues.push({\n contract: options.contract.name,\n axis,\n reason: 'unsupported-axis',\n supportedAxes: [...supported] as AgentProfileMaterializationAxis[],\n })\n }\n return issues\n}\n\n/** Throw when a candidate changes axes the selected run path cannot carry. */\nexport function assertProfileMaterialization(options: AssertProfileMaterializationOptions): void {\n const issues = validateProfileMaterialization(options)\n if (issues.length === 0) return\n throw new ValidationError(renderProfileMaterializationIssues(issues, options.context))\n}\n\n/** Format profile-axis drop issues into a concise operator-facing error. */\nexport function renderProfileMaterializationIssues(\n issues: readonly ProfileMaterializationIssue[],\n context?: string,\n): string {\n if (issues.length === 0) return ''\n const contract = issues[0]?.contract ?? '<unknown>'\n const prefix = context ? `${context}: ` : ''\n const droppedAxes = issues.map((issue) => issue.axis).join(', ')\n const supportedAxes = issues[0]?.supportedAxes.join(', ') || '<none>'\n return [\n `${prefix}profile materialization would drop axis changes on \"${contract}\": ${droppedAxes}.`,\n `Supported axes: ${supportedAxes}.`,\n 'Use a run path that carries those AgentProfile axes, or remove them from the candidate.',\n ].join('\\n')\n}\n\n/** Contract side: leaves (or `custom:`) only. A parent claim would hide a dropped child. */\nfunction normalizeContractAxes(\n axes: readonly AgentProfileMaterializationAxis[],\n label: string,\n): AgentProfileMaterializationAxis[] {\n return dedupe(axes.map((raw) => assertLeafAxis(raw, label)))\n}\n\n/**\n * Input side: leaves, `custom:`, and compound diff axes, which expand to their leaves so\n * `changedAgentProfileAxes` output composes with a leaf-only contract.\n */\nfunction normalizeChangedAxes(\n axes: readonly AgentProfileMaterializationAxis[],\n label: string,\n): AgentProfileMaterializationAxis[] {\n const out: AgentProfileMaterializationAxis[] = []\n for (const raw of axes) {\n const axis = readAxisName(raw, label)\n const leaves = compoundAxisLeaves[axis]\n if (leaves && !KNOWN_AXIS_SET.has(axis)) {\n out.push(...leaves)\n continue\n }\n out.push(assertLeafAxis(raw, label))\n }\n return dedupe(out)\n}\n\nfunction dedupe(\n axes: readonly AgentProfileMaterializationAxis[],\n): AgentProfileMaterializationAxis[] {\n const out: AgentProfileMaterializationAxis[] = []\n const seen = new Set<string>()\n for (const axis of axes) {\n if (seen.has(axis)) continue\n seen.add(axis)\n out.push(axis)\n }\n return out\n}\n\nfunction readAxisName(raw: AgentProfileMaterializationAxis, label: string): string {\n if (typeof raw !== 'string') {\n throw new ValidationError(`${label}: profile axis must be a string`)\n }\n const axis = raw.trim()\n if (!axis) {\n throw new ValidationError(`${label}: profile axis must be non-empty`)\n }\n return axis\n}\n\nfunction assertLeafAxis(\n raw: AgentProfileMaterializationAxis,\n label: string,\n): AgentProfileMaterializationAxis {\n const axis = readAxisName(raw, label)\n if (!KNOWN_AXIS_SET.has(axis) && !axis.startsWith('custom:')) {\n const leaves = compoundAxisLeaves[axis]\n if (leaves) {\n throw new ValidationError(\n `${label}: \"${axis}\" is a compound AgentProfile property, not a materialization axis. ` +\n `Name the exact leaves this path carries: ${leaves.join(', ')}.`,\n )\n }\n throw new ValidationError(\n `${label}: unknown profile axis \"${axis}\". Use a known axis or custom:<name>.`,\n )\n }\n return axis as AgentProfileMaterializationAxis\n}\n\nfunction isAxisSupported(\n axis: AgentProfileMaterializationAxis,\n supported: ReadonlySet<string>,\n): boolean {\n return supported.has(axis)\n}\n","import { constants } from 'node:fs'\nimport { open } from 'node:fs/promises'\nimport { stripVTControlCharacters } from 'node:util'\n\n/** Bounded, credential-redacted process context attached when reproducible Codex output fails\n * validation. The process still fails closed; this only preserves enough evidence to diagnose it. */\nexport interface CodexExecutionFailureDiagnostic {\n exitCode: number | null\n killedBySignal: NodeJS.Signals | null\n timedOut: boolean\n aborted?: boolean\n durationMs: number\n stdout: string\n stderr: string\n stdoutTruncated: boolean\n stderrTruncated: boolean\n}\n\n/** Thrown when reproducible Codex exits without one valid terminal usage event. */\nexport class CodexExecutionDiagnosticError extends Error {\n readonly code = 'CODEX_EXECUTION_DIAGNOSTIC'\n\n constructor(\n readonly reason: string,\n readonly diagnostic: CodexExecutionFailureDiagnostic,\n cause?: unknown,\n ) {\n super(\n `runLocalHarness: reproducible Codex execution failed: ${reason}; diagnostic=${JSON.stringify(diagnostic)}`,\n { cause },\n )\n this.name = 'CodexExecutionDiagnosticError'\n }\n}\n\nconst CODEX_FAILURE_STREAM_MAX_CHARS = 4096\nconst CODEX_AUTH_MAX_BYTES = 1024 * 1024\nconst CODEX_REDACTED = '<REDACTED_CREDENTIAL>'\nexport const codexSensitiveEnvironmentName = /(TOKEN|KEY|SECRET|PASSWORD|CREDENTIAL|AUTH|COOKIE)/i\n\nexport function createCodexExecutionDiagnosticError(opts: {\n reason: string\n exitCode: number | null\n killedBySignal: NodeJS.Signals | null\n timedOut: boolean\n aborted?: boolean\n durationMs: number\n stdout: string\n stderr: string\n codexHome: string | undefined\n redactionValues: string[]\n cause: unknown\n}): CodexExecutionDiagnosticError {\n const redact = (value: string) =>\n redactCodexDiagnostic(value, opts.codexHome, opts.redactionValues)\n const boundedStdout = boundCodexDiagnostic(redact(opts.stdout))\n const boundedStderr = boundCodexDiagnostic(redact(opts.stderr))\n const diagnostic: CodexExecutionFailureDiagnostic = {\n exitCode: opts.exitCode,\n killedBySignal: opts.killedBySignal,\n timedOut: opts.timedOut,\n ...(opts.aborted !== undefined ? { aborted: opts.aborted } : {}),\n durationMs: opts.durationMs,\n stdout: boundedStdout.value,\n stderr: boundedStderr.value,\n stdoutTruncated: boundedStdout.truncated,\n stderrTruncated: boundedStderr.truncated,\n }\n const safeReason = boundCodexDiagnostic(redact(opts.reason), 1024).value\n return new CodexExecutionDiagnosticError(\n safeReason,\n diagnostic,\n redactCodexErrorCause(opts.cause, safeReason, redact),\n )\n}\n\nexport function redactCodexHome(value: string, codexHome: string | undefined): string {\n return codexHome ? value.replaceAll(codexHome, '<ISOLATED_CODEX_HOME>') : value\n}\n\nexport function collectCodexDiagnosticRedactionValues(\n env: NodeJS.ProcessEnv,\n authText: string,\n): string[] {\n const values = Object.entries(env)\n .filter(\n ([name, value]) => codexSensitiveEnvironmentName.test(name) && typeof value === 'string',\n )\n .map(([, value]) => value as string)\n try {\n collectStringLeaves(JSON.parse(authText), values)\n } catch {\n // Invalid auth JSON is diagnosed by Codex; generic credential patterns still redact it.\n }\n const encoded = values\n .filter((value) => value.length >= 8)\n .flatMap((value) => [\n Buffer.from(value, 'utf8').toString('base64'),\n Buffer.from(value, 'utf8').toString('base64url'),\n encodeURIComponent(value),\n JSON.stringify(value).slice(1, -1),\n ])\n return [...new Set([...values, ...encoded])]\n}\n\nexport async function readCodexAuthRedactionText(path: string): Promise<string> {\n const handle = await open(path, constants.O_RDONLY | constants.O_NONBLOCK)\n try {\n const stats = await handle.stat()\n if (!stats.isFile() || !Number.isSafeInteger(stats.size) || stats.size > CODEX_AUTH_MAX_BYTES) {\n throw new Error('Codex auth.json must be a regular file no larger than 1 MiB')\n }\n const buffer = Buffer.alloc(stats.size)\n let offset = 0\n while (offset < buffer.length) {\n const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, offset)\n if (bytesRead === 0) break\n offset += bytesRead\n }\n return buffer.subarray(0, offset).toString('utf8')\n } finally {\n await handle.close()\n }\n}\n\nfunction boundCodexDiagnostic(\n value: string,\n maxChars = CODEX_FAILURE_STREAM_MAX_CHARS,\n): { value: string; truncated: boolean } {\n if (value.length <= maxChars) return { value, truncated: false }\n const marker = '\\n<... OUTPUT TRUNCATED ...>\\n'\n const contentChars = maxChars - marker.length\n const headChars = Math.floor(contentChars / 2)\n const tailChars = contentChars - headChars\n return {\n value: `${value.slice(0, headChars)}${marker}${value.slice(-tailChars)}`,\n truncated: true,\n }\n}\n\nfunction redactCodexDiagnostic(\n value: string,\n codexHome: string | undefined,\n protectedValues: ReadonlyArray<string>,\n): string {\n let redacted = redactCodexHome(stripVTControlCharacters(value), codexHome)\n const exactValues = [...new Set(protectedValues.filter((item) => item.length >= 6))].sort(\n (a, b) => b.length - a.length,\n )\n for (const secret of exactValues) redacted = redacted.replaceAll(secret, CODEX_REDACTED)\n redacted = redacted\n .replace(/(\\bBearer\\s+)[A-Za-z0-9._~+/=-]{6,}/gi, `$1${CODEX_REDACTED}`)\n .replace(/\\b(?:sk|rk|pk)-[A-Za-z0-9._-]{8,}\\b/g, CODEX_REDACTED)\n .replace(/\\beyJ[A-Za-z0-9_-]{6,}\\.[A-Za-z0-9_-]{6,}\\.[A-Za-z0-9_-]{6,}\\b/g, CODEX_REDACTED)\n .replace(\n /((?:[\"']?(?:api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|private[-_]?key|session[-_]?(?:id|token)|secret|password|passwd|authorization|credential|cookie)[\"']?)\\s*[:=]\\s*)([\"'])[^\"'\\r\\n]*\\2/gi,\n `$1$2${CODEX_REDACTED}$2`,\n )\n .replace(\n /((?:[\"']?(?:api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|private[-_]?key|session[-_]?(?:id|token)|secret|password|passwd|authorization|credential|cookie)[\"']?)\\s*[:=]\\s*)([^\\s,;}]+)/gi,\n `$1${CODEX_REDACTED}`,\n )\n for (const secret of exactValues) redacted = redacted.replaceAll(secret, CODEX_REDACTED)\n return redacted\n}\n\nfunction redactCodexErrorCause(\n cause: unknown,\n safeReason: string,\n redact: (value: string) => string,\n): Error | undefined {\n if (!(cause instanceof Error)) return undefined\n const safeCause = new Error(safeReason)\n safeCause.name = cause.name\n if (cause.stack) safeCause.stack = boundCodexDiagnostic(redact(cause.stack)).value\n return safeCause\n}\n\nfunction collectStringLeaves(value: unknown, output: string[]): void {\n if (typeof value === 'string') {\n output.push(value)\n return\n }\n if (Array.isArray(value)) {\n for (const item of value) collectStringLeaves(item, output)\n return\n }\n if (value !== null && typeof value === 'object') {\n for (const item of Object.values(value)) collectStringLeaves(item, output)\n }\n}\n","/**\n *\n * Subprocess wrappers for the local coding-harness CLIs installed in the\n * sandbox image (claude-code, codex, opencode). Used by the in-process\n * delegation executor (`createInProcessExecutor`) so a delegated coding task\n * spawns a real harness on a real git worktree instead of provisioning a\n * sibling sandbox.\n *\n * All harness invocations:\n * - run with `cwd` set to the worktree\n * - inherit env from the parent (the MCP server inside the sandbox has\n * the harness's auth already)\n * - capture stdout/stderr\n * - support cancellation via AbortSignal\n * - enforce a wall-clock timeout\n *\n * @experimental\n */\n\nimport { type ChildProcess, spawn } from 'node:child_process'\nimport { createHash, randomUUID } from 'node:crypto'\nimport { constants, createReadStream } from 'node:fs'\nimport {\n access,\n chmod,\n copyFile,\n mkdir,\n mkdtemp,\n open,\n readFile,\n realpath,\n rm,\n symlink,\n writeFile,\n} from 'node:fs/promises'\nimport { homedir, tmpdir } from 'node:os'\nimport { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from 'node:path'\nimport type { AgentProfile, HarnessType, ReasoningEffort } from '@tangle-network/agent-interface'\nimport { concreteProfileModel } from '../runtime/supervise/model-policy'\nimport {\n codexSensitiveEnvironmentName,\n collectCodexDiagnosticRedactionValues,\n createCodexExecutionDiagnosticError,\n readCodexAuthRedactionText,\n redactCodexHome,\n} from './codex-diagnostics'\n\nexport type { CodexExecutionFailureDiagnostic } from './codex-diagnostics'\nexport { CodexExecutionDiagnosticError } from './codex-diagnostics'\n\n/**\n * Local coding harness available inside the sandbox — a narrowing of the shared `HarnessType`\n * vocabulary, NOT a private spelling of it. The harness id is `claude-code`; `claude` is the\n * EXECUTABLE name and lives only in the `command` field below. Keeping one vocabulary is what\n * lets a `LocalHarness` be handed straight to the profile materializer and the capability table\n * with no translation step.\n */\nexport type LocalHarness = Extract<HarnessType, 'claude-code' | 'codex' | 'opencode'>\n\n/**\n * Canonical reasoning effort → the native level string a harness's own control accepts.\n * PRESENCE of a key is the capability claim: a level with no entry has no native spelling on\n * that harness and is refused rather than silently dropped.\n */\ntype NativeReasoningLevels = Partial<Record<ReasoningEffort, string>>\n\n/** `codex -c model_reasoning_effort=…`. `ultracode` has no distinct native level; it saturates\n * at `xhigh`, which is also the ceiling `assertCodexReproducibleInvocation` admits. */\nconst CODEX_REASONING_LEVELS: NativeReasoningLevels = {\n none: 'none',\n minimal: 'minimal',\n low: 'low',\n medium: 'medium',\n high: 'high',\n xhigh: 'xhigh',\n ultracode: 'xhigh',\n}\n\n/** `claude --effort <level>` accepts `low, medium, high, xhigh, max` (verified against the\n * installed CLI's `--help`); canonical `ultracode` is its `max`. It expresses no thinking-off\n * or `minimal` level, so those two canonical levels have no entry. */\nconst CLAUDE_CODE_REASONING_LEVELS: NativeReasoningLevels = {\n low: 'low',\n medium: 'medium',\n high: 'high',\n xhigh: 'xhigh',\n ultracode: 'max',\n}\n\n/** `opencode run --variant <variant>` is documented as \"provider-specific reasoning effort,\n * e.g. high, max, minimal\", so the canonical level passes through as the variant name and\n * `ultracode` maps to `max`. Thinking-off is expressed by omitting the flag, not by a variant\n * named `none`, so `none` has no entry. */\nconst OPENCODE_REASONING_LEVELS: NativeReasoningLevels = {\n minimal: 'minimal',\n low: 'low',\n medium: 'medium',\n high: 'high',\n xhigh: 'xhigh',\n ultracode: 'max',\n}\n\ninterface HarnessInvocationSpec {\n command: string\n buildArgs: (taskPrompt: string) => string[]\n /** Map a resolved model to the harness's model-selector flag. */\n modelArgs: (model: string) => string[]\n /** Native reasoning-effort control, absent when the harness exposes none. */\n reasoning?: {\n levels: NativeReasoningLevels\n args: (nativeLevel: string) => string[]\n }\n /**\n * Argv that lets an unattended run edit its workspace without stopping on an interactive\n * approval gate. Absent when the harness has no such gate on its non-interactive path.\n */\n permissionBypassArgs?: () => string[]\n}\n\n/**\n * Default per-harness command + arg shape. `buildArgs` takes ONLY the task prompt and\n * emits the prompt-only invocation (no model, no system prompt) — the safe default shape\n * the in-process executor's `streamPrompt` drives. `modelArgs` maps a resolved model to\n * the harness's selector flag (every supported harness takes `-m <model>`). The §1.5\n * profile-aware mapper `harnessInvocation` composes these to thread the full\n * supervisor-authored profile (systemPrompt + model) into argv.\n *\n * Every per-harness difference is a FIELD on this row, never a test on the harness name at a\n * call site: adding harness N+1 is one entry here, and a caller asking for a capability the\n * row does not declare is refused up front instead of silently losing the request.\n */\nconst HARNESS_INVOCATIONS: Record<LocalHarness, HarnessInvocationSpec> = {\n 'claude-code': {\n command: 'claude',\n // `-p` IS headless/print mode; the old `--headless` flag was removed from the CLI.\n // Permission bypass is an explicit per-run opt-in below, never the public default.\n buildArgs: (taskPrompt) => ['-p', taskPrompt],\n modelArgs: (model) => ['-m', model],\n reasoning: {\n levels: CLAUDE_CODE_REASONING_LEVELS,\n args: (level) => ['--effort', level],\n },\n permissionBypassArgs: () => ['--dangerously-skip-permissions'],\n },\n codex: {\n command: 'codex',\n buildArgs: (taskPrompt) => ['exec', taskPrompt],\n modelArgs: (model) => ['-m', model],\n reasoning: {\n levels: CODEX_REASONING_LEVELS,\n args: (level) => ['-c', `model_reasoning_effort=\"${level}\"`],\n },\n // Non-interactive editing WITHOUT surrendering the OS sandbox. `codex exec` has no approval\n // gate to stall on (`-a/--ask-for-approval` exists only on the top-level `codex`), so\n // `--dangerously-bypass-approvals-and-sandbox` buys nothing on the approvals axis and pays the\n // entire sandbox for it — writes would escape the worktree to ~/.ssh, ~/.aws, and secrets.\n // The sandbox is what MAKES the blast radius the worktree. Same form as CODEX_REPRODUCIBLE_ARGS.\n permissionBypassArgs: () => ['--sandbox', 'workspace-write', '-c', 'approval_policy=\"never\"'],\n },\n opencode: {\n command: 'opencode',\n buildArgs: (taskPrompt) => ['run', taskPrompt],\n modelArgs: (model) => ['-m', model],\n reasoning: {\n levels: OPENCODE_REASONING_LEVELS,\n args: (level) => ['--variant', level],\n },\n // `opencode run` is non-interactive and has no approval gate to bypass.\n },\n}\n\n/** Every local harness, in table order — the one list `AGENT_RUNTIME_LOCAL_HARNESSES` and any\n * other harness enumeration reads, so adding a row above is the only edit a new harness needs. */\nexport const LOCAL_HARNESSES = Object.keys(HARNESS_INVOCATIONS) as ReadonlyArray<LocalHarness>\n\n/** The harness a caller gets when it expresses no preference. A composition-root default, not a\n * capability claim: one constant so the several entry points cannot drift apart. */\nexport const DEFAULT_LOCAL_HARNESS: LocalHarness = 'claude-code'\n\n/** The CLI binary a harness id runs. The two are NOT the same string (`claude-code` runs `claude`),\n * so anything spawning a harness — a version probe, a login check — reads it from here rather than\n * passing the harness id as a command. */\nexport function localHarnessExecutable(harness: LocalHarness): string {\n return HARNESS_INVOCATIONS[harness].command\n}\n\n/**\n * Whether the harness's native control can express this reasoning effort. Admission checks read\n * this so a profile the invocation would later refuse is rejected BEFORE any workspace state is\n * created, against the same table that emits the argv.\n */\nexport function harnessSupportsReasoningEffort(\n harness: LocalHarness,\n reasoningEffort: ReasoningEffort,\n): boolean {\n return HARNESS_INVOCATIONS[harness].reasoning?.levels[reasoningEffort] !== undefined\n}\n\nfunction harnessReasoningArgs(harness: LocalHarness, reasoningEffort: ReasoningEffort): string[] {\n const reasoning = HARNESS_INVOCATIONS[harness].reasoning\n const level = reasoning?.levels[reasoningEffort]\n if (reasoning === undefined || level === undefined) {\n throw new Error(\n `harnessInvocation: ${harness} cannot express reasoning effort ${String(reasoningEffort)}`,\n )\n }\n return reasoning.args(level)\n}\n\n/** Result of mapping an `AgentProfile` + task prompt onto a harness invocation. */\nexport interface HarnessInvocation {\n command: string\n args: string[]\n /** Exact profile-composed prompt carried by the invocation. */\n prompt: string\n}\n\nexport interface HarnessInvocationOptions {\n /** Let an unattended process edit its isolated candidate worktree without stopping on an\n * interactive approval gate. A property of the WORKSPACE, not of any one CLI: each harness\n * contributes its own `permissionBypassArgs`, and a harness with no approval gate on its\n * non-interactive path contributes nothing.\n *\n * This never surrenders an OS sandbox. A harness that offers one flag for \"skip approvals\" and\n * another for \"skip approvals AND sandbox\" must contribute the former: the sandbox is what keeps\n * the blast radius equal to the worktree, and without it a prompt-injected worker reaches\n * `~/.ssh`, `~/.aws`, and any secrets on the box. */\n dangerouslySkipPermissions?: boolean\n /** Run Codex with benchmark-safe process controls and JSONL usage output.\n * Valid only for the Codex harness. */\n codexReproducible?: boolean\n}\n\nconst CODEX_REPRODUCIBLE_ARGS = [\n '--ephemeral',\n '--ignore-rules',\n '--json',\n '-c',\n 'approval_policy=\"never\"',\n '-c',\n 'web_search=\"disabled\"',\n '-c',\n 'project_doc_max_bytes=0',\n '-c',\n 'skills.include_instructions=false',\n '-c',\n 'include_apps_instructions=false',\n '--disable',\n 'tool_suggest',\n '-c',\n 'features.multi_agent_v2.root_agent_usage_hint_text=\"\"',\n '-c',\n 'features.multi_agent_v2.subagent_usage_hint_text=\"\"',\n '-c',\n 'features.multi_agent_v2.multi_agent_mode_hint_text=\"\"',\n '--strict-config',\n] as const\n\nfunction buildHarnessArgs(\n harness: LocalHarness,\n taskPrompt: string,\n options: HarnessInvocationOptions = {},\n): string[] {\n const invocation = HARNESS_INVOCATIONS[harness]\n const args = invocation.buildArgs(taskPrompt)\n // Reproducible mode pins `approval_policy=\"never\"` inside its own controlled config, which is\n // the same non-interactive guarantee with the sandbox left INTACT. Emitting a blanket bypass\n // flag on top would tear that sandbox down and break the exact-argv reproducibility contract,\n // so the reproducible arg set owns approvals whenever it is active.\n if (options.dangerouslySkipPermissions && !options.codexReproducible) {\n args.push(...(invocation.permissionBypassArgs?.() ?? []))\n }\n if (options.codexReproducible) {\n // KEPT harness-name test: same reason as `runLocalHarness` below — `codexReproducible` is a\n // codex-SPECIFIC public option, so this asserts caller self-consistency and throws loudly.\n if (harness !== 'codex') {\n throw new Error('harnessInvocation: codexReproducible requires the Codex harness')\n }\n args.push(...CODEX_REPRODUCIBLE_ARGS)\n }\n return args\n}\n\n/**\n * Map a supervisor-authored `AgentProfile` + the per-task prompt onto a concrete harness\n * `command` + `args` (the §1.5 fix). UNLIKE the prompt-only `HARNESS_INVOCATIONS.buildArgs`\n * — which drops both the authored model and the system prompt — this threads the FULL\n * profile payload into argv:\n *\n * - `profile.prompt.systemPrompt` → the PROMPT channel: a portable, harness-agnostic\n * default that prepends the system prompt above the task prompt (`<system>\\n\\n<task>`),\n * so the authored standing instructions reach EVERY harness (none of the three CLIs\n * expose a portable replace-system-prompt flag for a one-shot non-interactive run).\n * - `profile.prompt.instructions[]` → appended prompt sections in authored order.\n * - `profile.model.default` → the harness's `-m <model>` selector.\n *\n * The task prompt alone is the floor; an empty/absent profile yields exactly the legacy\n * `buildArgs(taskPrompt)` shape so existing callers are byte-identical.\n */\nexport function harnessInvocation(\n harness: LocalHarness,\n profile: AgentProfile,\n taskPrompt: string,\n options: HarnessInvocationOptions = {},\n): HarnessInvocation {\n const invocation = HARNESS_INVOCATIONS[harness]\n if (!invocation) {\n throw new Error(`harnessInvocation: unknown harness ${String(harness)}`)\n }\n\n if (options.codexReproducible) {\n const model = harnessProfileModel(harness, profile)\n if (!model) {\n throw new Error('harnessInvocation: codexReproducible requires profile.model.default')\n }\n if (profile.model?.reasoningEffort === undefined) {\n throw new Error('harnessInvocation: codexReproducible requires profile.model.reasoningEffort')\n }\n }\n\n const systemPrompt = profile.prompt?.systemPrompt\n const instructions = profile.prompt?.instructions\n if (\n instructions !== undefined &&\n (!Array.isArray(instructions) ||\n instructions.some((instruction) => typeof instruction !== 'string'))\n ) {\n throw new Error('harnessInvocation: profile.prompt.instructions must be an array of strings')\n }\n const promptSections = [\n ...(typeof systemPrompt === 'string' && systemPrompt.trim().length > 0 ? [systemPrompt] : []),\n ...(instructions?.filter((instruction) => instruction.trim().length > 0) ?? []),\n taskPrompt,\n ]\n const composedPrompt = promptSections.join('\\n\\n')\n\n const args = buildHarnessArgs(harness, composedPrompt, options)\n\n const model = harnessProfileModel(harness, profile)\n if (model) {\n args.push(...invocation.modelArgs(model))\n }\n\n const reasoningEffort = profile.model?.reasoningEffort\n if (reasoningEffort !== undefined) {\n args.push(...harnessReasoningArgs(harness, reasoningEffort))\n }\n\n return { command: invocation.command, args, prompt: composedPrompt }\n}\n\n/** Render the exact profile provider/model through the selected native harness. */\nfunction harnessProfileModel(harness: LocalHarness, profile: AgentProfile): string | undefined {\n const model = concreteProfileModel(profile)\n if (!model) return undefined\n const provider = profile.model?.provider?.trim()\n if (!provider) return model\n if (harness === 'opencode') {\n return model.includes('/') ? model : `${provider}/${model}`\n }\n const nativeProvider = harness === 'codex' ? 'openai' : 'anthropic'\n if (provider !== nativeProvider) {\n throw new Error(\n `harnessInvocation: ${harness} cannot materialize model provider ${JSON.stringify(provider)}; expected ${nativeProvider}`,\n )\n }\n return model\n}\n\n/** @experimental */\nexport interface RunLocalHarnessOptions {\n harness: LocalHarness\n /** Working directory for the subprocess (typically a worktree path). */\n cwd: string\n /** Prompt forwarded as the harness CLI's task argument. */\n taskPrompt: string\n /**\n * Pre-built command + args (e.g. from `harnessInvocation` so the full authored\n * `AgentProfile` — systemPrompt + model — reaches the harness). When set it OVERRIDES the\n * default prompt-only `buildArgs(taskPrompt)` path; `command` defaults to the harness's\n * default binary when only `args` is supplied. When absent the legacy prompt-only shape\n * is used unchanged.\n */\n invocation?: { command?: string; args: ReadonlyArray<string> }\n /** Allow autonomous edits without an interactive approval gate, using whichever bypass argv the\n * harness declares. Use only when `cwd` is an isolated candidate worktree. */\n dangerouslySkipPermissions?: boolean\n /** Isolate Codex from ambient configuration/instructions and require JSONL token usage.\n * The invocation should come from `harnessInvocation(..., { codexReproducible: true })`. */\n codexReproducible?: boolean\n /** Absolute host paths that reproducible Codex must not read. The normalized set is compiled\n * into the controlled permission profile and its digest is returned in execution evidence. */\n codexReadDeniedPaths?: ReadonlyArray<string>\n /** Wall-clock kill deadline (ms). Default 5 min. Subprocess SIGTERMed on expiry. */\n timeoutMs?: number\n /** Newest stdout/stderr bytes retained per stream. Default 64 MiB. */\n maxOutputBytes?: number\n /** Caller cancellation. SIGTERM is sent on abort. */\n signal?: AbortSignal\n /** Override env (defaults to inheriting from the parent). */\n env?: NodeJS.ProcessEnv\n /**\n * Test seam — inject a custom spawner so unit tests can mock the\n * subprocess without touching the OS. Defaults to node's `child_process.spawn`.\n */\n spawn?: (\n command: string,\n args: ReadonlyArray<string>,\n opts: {\n cwd: string\n env: NodeJS.ProcessEnv\n stdio: 'pipe'\n detached: boolean\n },\n ) => ChildProcess\n /** Test seam for locating the native Codex executable before it is staged in the worktree. */\n resolveCodexExecutable?: (command: string, env: NodeJS.ProcessEnv) => Promise<string>\n}\n\n/** Exact aggregate usage emitted by Codex's terminal `turn.completed` JSONL event. */\nexport interface CodexTokenUsage {\n inputTokens: number\n cachedInputTokens: number\n outputTokens: number\n reasoningOutputTokens: number\n}\n\n/** Isolation settings asserted before a reproducible Codex run is allowed to start. */\nexport interface CodexExecutionPolicy {\n sessionPersistence: 'ephemeral'\n userConfig: false\n rules: false\n projectInstructions: false\n skillInstructions: false\n appInstructions: false\n toolSuggestions: false\n multiAgentInstructions: false\n sandbox: 'workspace-write'\n permissionProfile: 'agent_runtime_reproducible'\n approvalPolicy: 'never'\n shellNetwork: false\n webSearch: false\n serviceTier: 'default'\n shellEnvironment: 'core-filtered'\n loginShell: false\n credentialsReadable: false\n hostHomeReadable: false\n procEnvironment: 'private-sanitized'\n sensitiveEnvironmentNamesVisible: false\n parentRepoRead: false\n gitMetadata: false\n temporaryDirectory: 'workspace-private'\n stagedExecutable: 'static-elf-read-only'\n callerReadDeniedPaths: 'enforced'\n containerSockets: false\n}\n\n/** Zero-model-call evidence for the exact Codex process about to run. */\nexport interface CodexExecutionEvidence {\n cliVersion: string\n executableSha256: string\n /** SHA-256 of the exact composed prompt argument proved present in the rendered prompt. */\n requestedPromptSha256: string\n effectivePromptSha256: string\n nonPromptArgsSha256: string\n controlledConfigSha256: string\n /** Sorted normalized paths compiled into the permission profile. */\n readDeniedPaths: string[]\n readDeniedPathsSha256: string\n readDeniedPathCount: number\n policy: CodexExecutionPolicy\n}\n\n/** @experimental */\nexport interface LocalHarnessResult {\n /** OS exit code. `null` when killed before exit. */\n exitCode: number | null\n /** Concatenated stdout. */\n stdout: string\n /** Concatenated stderr. */\n stderr: string\n /** Set when the process exited via signal (timeout / abort). */\n killedBySignal: NodeJS.Signals | null\n /** Wall-clock duration ms (spawn → exit). */\n durationMs: number\n /** Set when timeoutMs elapsed before exit. */\n timedOut: boolean\n /**\n * Set when the caller's AbortSignal fired before this result settled.\n * Optional so injected runners and stored results from older releases remain valid.\n */\n aborted?: boolean\n /** Present for a reproducible Codex run; parsed from the real terminal JSONL event. */\n usage?: CodexTokenUsage\n /** Present for reproducible Codex runs; generated and checked before model execution. */\n evidence?: CodexExecutionEvidence\n}\n\nconst DEFAULT_TIMEOUT_MS = 5 * 60 * 1000\nconst DEFAULT_MAX_OUTPUT_BYTES = 64 * 1024 * 1024\nconst processKillGraceMs = 250\nconst processGroupExitConfirmMs = 1_000\nconst processGroupExitPollMs = 10\n\nclass RollingByteCapture {\n private readonly chunks: Buffer[] = []\n private bytes = 0\n\n constructor(private readonly maxBytes: number) {}\n\n append(chunk: unknown): void {\n if (this.maxBytes === 0) return\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))\n this.chunks.push(buffer)\n this.bytes += buffer.length\n let excess = this.bytes - this.maxBytes\n while (excess > 0 && this.chunks.length > 0) {\n const first = this.chunks[0]!\n if (first.length <= excess) {\n this.chunks.shift()\n this.bytes -= first.length\n excess -= first.length\n } else {\n this.chunks[0] = first.subarray(excess)\n this.bytes -= excess\n excess = 0\n }\n }\n }\n\n text(): string {\n return Buffer.concat(this.chunks, this.bytes).toString('utf8')\n }\n}\n\n/**\n * Spawn a local coding harness CLI as a subprocess + collect its output.\n *\n * NOT responsible for parsing the harness's output or extracting a diff —\n * the in-process executor's `streamPrompt` orchestrates `git diff` against\n * the worktree after this resolves. This function is intentionally narrow:\n * spawn, wait, capture, return.\n *\n * Fails loud — throws when:\n * - `cwd` doesn't exist (subprocess emits ENOENT; surfaced as Error)\n * - the harness binary is not on PATH (ENOENT)\n * - the caller signal was already aborted before process launch\n *\n * Does NOT throw when:\n * - the subprocess exits non-zero (`result.exitCode` carries the code)\n * - a non-reproducible subprocess is aborted / timed out (`result.aborted` /\n * `result.timedOut` carries the reason even when a TERM-aware child exits zero)\n *\n * Reproducible Codex additionally requires a terminal usage event. If cancellation\n * prevents that event, this rejects with `CodexExecutionDiagnosticError` instead of\n * returning an incomplete reproducibility receipt.\n *\n * @experimental\n */\nexport async function runLocalHarness(\n options: RunLocalHarnessOptions,\n): Promise<LocalHarnessResult> {\n const { harness, cwd, taskPrompt } = options\n // KEPT harness-name test: `codexReproducible` is a codex-SPECIFIC public option (its arg set,\n // its permission profile, its JSONL usage event), so this guard asserts caller self-consistency\n // and throws loudly rather than varying behavior by name. When a second harness gains a\n // reproducible mode, rename the option and make the arg set a row on `HARNESS_INVOCATIONS`.\n if (options.codexReproducible && harness !== 'codex') {\n throw new Error('runLocalHarness: codexReproducible requires the Codex harness')\n }\n if (options.codexReproducible && process.platform !== 'linux') {\n throw new Error('runLocalHarness: codexReproducible currently requires Linux')\n }\n if (options.codexReadDeniedPaths !== undefined && !options.codexReproducible) {\n throw new Error('runLocalHarness: codexReadDeniedPaths requires codexReproducible')\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES\n if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 0) {\n throw new Error('runLocalHarness: maxOutputBytes must be a non-negative safe integer')\n }\n const spawnImpl = options.spawn ?? spawn\n\n const invocation = HARNESS_INVOCATIONS[harness]\n if (!invocation) {\n throw new Error(`runLocalHarness: unknown harness ${String(harness)}`)\n }\n\n const startedAt = Date.now()\n const requestedCommand = options.invocation?.command ?? invocation.command\n const args = options.invocation\n ? [...options.invocation.args]\n : buildHarnessArgs(harness, taskPrompt, options)\n if (options.codexReproducible) assertCodexReproducibleInvocation(requestedCommand, args)\n options.signal?.throwIfAborted()\n\n // We spawn the harness with `cwd`, but a harness that resolves its working\n // directory from `$PWD` rather than `getcwd()` (opencode does; the others may)\n // inherits the parent's stale `PWD` and edits the WRONG directory — its\n // worktree diff then comes back empty and the delegation fails with a phantom\n // \"empty patch\". Pin `PWD` to `cwd` so the harness edits where it was placed.\n // `baseEnv` feeds both the codex-isolated and the plain spawn paths below, so\n // pinning it here covers every runLocalHarness consumer.\n const baseEnv: NodeJS.ProcessEnv = { ...(options.env ?? process.env), PWD: cwd }\n const isolated = options.codexReproducible\n ? await isolateCodexHome({\n baseEnv,\n cwd,\n command: requestedCommand,\n readDeniedPaths: options.codexReadDeniedPaths ?? [],\n resolveExecutable: options.resolveCodexExecutable ?? resolveCodexNativeExecutable,\n })\n : {\n env: baseEnv,\n command: requestedCommand,\n cleanup: async () => undefined,\n controlledConfigSha256: '',\n executableSha256: '',\n readDeniedPathsSha256: '',\n readDeniedPathCount: 0,\n readDeniedPaths: [] as string[],\n diagnosticRedactionValues: [] as string[],\n ambientAuth: '',\n isolatedAuth: '',\n writeProbe: '',\n stagedWriteProbe: '',\n deniedProbePaths: [] as string[],\n }\n const env = isolated.env\n const command = isolated.command\n if (options.codexReproducible) assertCodexReproducibleInvocation(command, args)\n\n try {\n const evidence = options.codexReproducible\n ? await collectCodexExecutionEvidence({\n command,\n args,\n cwd,\n env,\n spawn: spawnImpl,\n controlledConfigSha256: isolated.controlledConfigSha256,\n executableSha256: isolated.executableSha256,\n readDeniedPathsSha256: isolated.readDeniedPathsSha256,\n readDeniedPathCount: isolated.readDeniedPathCount,\n readDeniedPaths: isolated.readDeniedPaths,\n ambientAuth: isolated.ambientAuth,\n isolatedAuth: isolated.isolatedAuth,\n writeProbe: isolated.writeProbe,\n stagedWriteProbe: isolated.stagedWriteProbe,\n deniedProbePaths: isolated.deniedProbePaths,\n ...(options.signal ? { signal: options.signal } : {}),\n })\n : undefined\n return await new Promise<LocalHarnessResult>((resolve, reject) => {\n let child: ChildProcess\n try {\n options.signal?.throwIfAborted()\n child = spawnImpl(command, args, {\n cwd,\n env,\n stdio: 'pipe',\n detached: process.platform !== 'win32',\n })\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)))\n return\n }\n\n // The harness takes its task as an argv arg, not on stdin. Leaving stdin\n // OPEN makes a non-TTY `opencode run` (and likely the other harnesses)\n // BLOCK forever waiting on input — zero output, SIGTERM at the wall cap,\n // empty patch -> \"no candidate passed validation\". Close stdin so the\n // subprocess sees EOF and proceeds (the `cliExecutor` leaf does the same).\n child.stdin?.end()\n\n const stdoutCapture = new RollingByteCapture(maxOutputBytes)\n const stderrCapture = new RollingByteCapture(maxOutputBytes)\n let timedOut = false\n let aborted = false\n let settled = false\n let leaderClosed = false\n let timer: ReturnType<typeof setTimeout> | null = null\n let termination: Promise<void> | null = null\n\n const clearLifecycle = () => {\n if (timer) clearTimeout(timer)\n options.signal?.removeEventListener('abort', onAbort)\n }\n const rejectOnce = (err: unknown) => {\n if (settled) return\n settled = true\n clearLifecycle()\n reject(err instanceof Error ? err : new Error(String(err)))\n }\n const terminate = (): Promise<void> => {\n if (!termination) {\n termination = terminateProcessTreeAndConfirm(child, () => leaderClosed)\n void termination.catch(rejectOnce)\n }\n return termination\n }\n\n timer =\n timeoutMs > 0\n ? setTimeout(() => {\n timedOut = true\n void terminate()\n }, timeoutMs)\n : null\n if (timer && typeof (timer as { unref?: () => void }).unref === 'function') {\n ;(timer as { unref: () => void }).unref()\n }\n\n const onAbort = () => {\n aborted = true\n void terminate()\n }\n if (options.signal) {\n if (options.signal.aborted) onAbort()\n else options.signal.addEventListener('abort', onAbort, { once: true })\n }\n\n child.stdout?.on('data', (chunk) => {\n stdoutCapture.append(chunk)\n })\n child.stderr?.on('data', (chunk) => {\n stderrCapture.append(chunk)\n })\n\n const finalize = (result: LocalHarnessResult) => {\n if (settled) return\n settled = true\n clearLifecycle()\n resolve(result)\n }\n\n child.on('error', (err) => {\n leaderClosed = true\n if (timer) clearTimeout(timer)\n void (async () => {\n try {\n if (termination) await termination\n rejectOnce(err)\n } catch (terminationError) {\n rejectOnce(terminationError)\n }\n })()\n })\n\n child.on('close', (code, signal) => {\n leaderClosed = true\n if (timer) clearTimeout(timer)\n void (async () => {\n const stdout = stdoutCapture.text()\n const stderr = stderrCapture.text()\n try {\n if (\n !termination &&\n process.platform !== 'win32' &&\n typeof child.pid === 'number' &&\n processGroupExists(child.pid)\n ) {\n await terminate()\n }\n if (termination) await termination\n const durationMs = Date.now() - startedAt\n const usage = options.codexReproducible ? parseCodexTokenUsage(stdout) : undefined\n finalize({\n exitCode: code,\n stdout,\n stderr: redactCodexHome(stderr, env.CODEX_HOME),\n killedBySignal: signal,\n durationMs,\n timedOut,\n aborted,\n ...(usage ? { usage } : {}),\n ...(evidence ? { evidence } : {}),\n })\n } catch (err) {\n if (settled) return\n settled = true\n clearLifecycle()\n const durationMs = Date.now() - startedAt\n const reason = err instanceof Error ? err.message : String(err)\n reject(\n options.codexReproducible\n ? createCodexExecutionDiagnosticError({\n reason,\n exitCode: code,\n killedBySignal: signal,\n timedOut,\n aborted,\n durationMs,\n stdout,\n stderr,\n codexHome: env.CODEX_HOME,\n redactionValues: isolated.diagnosticRedactionValues,\n cause: err,\n })\n : err instanceof Error\n ? err\n : new Error(reason),\n )\n }\n })()\n })\n })\n } finally {\n await isolated.cleanup()\n }\n}\n\nconst CODEX_EXECUTION_POLICY: CodexExecutionPolicy = {\n sessionPersistence: 'ephemeral',\n userConfig: false,\n rules: false,\n projectInstructions: false,\n skillInstructions: false,\n appInstructions: false,\n toolSuggestions: false,\n multiAgentInstructions: false,\n sandbox: 'workspace-write',\n permissionProfile: 'agent_runtime_reproducible',\n approvalPolicy: 'never',\n shellNetwork: false,\n webSearch: false,\n serviceTier: 'default',\n shellEnvironment: 'core-filtered',\n loginShell: false,\n credentialsReadable: false,\n hostHomeReadable: false,\n procEnvironment: 'private-sanitized',\n sensitiveEnvironmentNamesVisible: false,\n parentRepoRead: false,\n gitMetadata: false,\n temporaryDirectory: 'workspace-private',\n stagedExecutable: 'static-elf-read-only',\n callerReadDeniedPaths: 'enforced',\n containerSockets: false,\n}\n\nconst FORBIDDEN_CODEX_PROMPT_MARKERS = [\n '<skills_instructions>',\n '# AGENTS.md instructions',\n '<apps_instructions>',\n '<recommended_plugins>',\n '<multi_agent_mode>',\n 'You are `/root`, the primary agent',\n] as const\n\nasync function collectCodexExecutionEvidence(opts: {\n command: string\n args: string[]\n cwd: string\n env: NodeJS.ProcessEnv\n spawn: NonNullable<RunLocalHarnessOptions['spawn']>\n controlledConfigSha256: string\n readDeniedPaths: string[]\n executableSha256: string\n readDeniedPathsSha256: string\n readDeniedPathCount: number\n ambientAuth: string\n isolatedAuth: string\n writeProbe: string\n stagedWriteProbe: string\n deniedProbePaths: string[]\n signal?: AbortSignal\n}): Promise<CodexExecutionEvidence> {\n assertCodexReproducibleInvocation(opts.command, opts.args)\n const prompt = opts.args[1]\n if (opts.args[0] !== 'exec' || typeof prompt !== 'string' || prompt.length === 0) {\n throw new Error('runLocalHarness: reproducible Codex invocation must be codex exec <prompt>')\n }\n const cliVersion = (await runCodexProbe(opts, ['--version'])).stdout.trim()\n if (!/^codex-cli \\d+\\.\\d+\\.\\d+(?:[-+].+)?$/.test(cliVersion)) {\n throw new Error(\n `runLocalHarness: unexpected Codex CLI version output ${JSON.stringify(cliVersion)}`,\n )\n }\n\n const hiddenEnvironmentChecks = [\n 'CODEX_HOME',\n 'CODEX_ACCESS_TOKEN',\n 'CODEX_API_KEY',\n 'OPENAI_API_KEY',\n ]\n .map((name) => `test -z \"\\${${name}:-}\"`)\n .join(' && ')\n const sandboxProof = [\n hiddenEnvironmentChecks,\n 'test -r .',\n '! test -r .git',\n 'touch \"$1\"',\n 'rm \"$1\"',\n 'staged_dir=$(dirname \"$2\")',\n 'test -x \"$staged_dir/codex\"',\n '! chmod 700 \"$staged_dir\" 2>/dev/null',\n '! rm \"$staged_dir/codex\" 2>/dev/null',\n '! touch \"$2\" 2>/dev/null',\n 'shift 2',\n 'for path in \"$@\"; do ! test -r \"$path\" || exit 1; done',\n 'touch \"$TMPDIR/.agent-runtime-tmp-proof\"',\n 'rm \"$TMPDIR/.agent-runtime-tmp-proof\"',\n ].join(' && ')\n await runCodexProbe(opts, [\n 'sandbox',\n '-P',\n CODEX_PERMISSION_PROFILE,\n '-C',\n opts.cwd,\n 'sh',\n '-c',\n sandboxProof,\n 'sh',\n opts.writeProbe,\n opts.stagedWriteProbe,\n ...opts.deniedProbePaths,\n ])\n await runCodexProbe(opts, [\n 'sandbox',\n '-P',\n CODEX_PERMISSION_PROFILE,\n '-C',\n opts.cwd,\n 'python3',\n '-c',\n `import os,re\npattern=re.compile(br'(TOKEN|KEY|SECRET|PASSWORD|CREDENTIAL|AUTH|COOKIE|CODEX_HOME)', re.I)\npaths=('/proc/1/environ', '/proc/self/environ', f'/proc/{os.getppid()}/environ')\nfor path in dict.fromkeys(paths):\n data=open(path,'rb').read().split(b'\\\\0')\n names=(item.split(b'=',1)[0] for item in data if b'=' in item)\n assert not any(pattern.search(name) for name in names), path`,\n ])\n await runCodexProbe(opts, [\n 'sandbox',\n '-P',\n CODEX_PERMISSION_PROFILE,\n '-C',\n opts.cwd,\n 'python3',\n '-c',\n 'import socket,sys\\nfor path in sys.argv[1:]:\\n s=socket.socket(socket.AF_UNIX)\\n try: s.connect(path)\\n except OSError: continue\\n raise SystemExit(1)',\n '/var/run/docker.sock',\n '/run/docker.sock',\n '/var/run/containerd/containerd.sock',\n '/run/containerd/containerd.sock',\n ])\n\n const debugArgs = codexPromptDebugArgs(opts.args, prompt)\n const renderedPrompt = (await runCodexProbe(opts, debugArgs)).stdout\n let parsedPrompt: unknown\n try {\n parsedPrompt = JSON.parse(renderedPrompt)\n } catch {\n throw new Error('runLocalHarness: codex debug prompt-input returned invalid JSON')\n }\n const promptEvidenceText = normalizeCodexDebugPromptNewlines(prompt)\n if (!Array.isArray(parsedPrompt) || !jsonTextContains(parsedPrompt, promptEvidenceText)) {\n throw new Error('runLocalHarness: Codex prompt evidence did not contain the exact task prompt')\n }\n const promptContextWithoutTask = JSON.stringify(redactJsonText(parsedPrompt, promptEvidenceText))\n for (const marker of FORBIDDEN_CODEX_PROMPT_MARKERS) {\n if (promptContextWithoutTask.includes(marker)) {\n throw new Error(`runLocalHarness: Codex prompt evidence contains forbidden marker ${marker}`)\n }\n }\n for (const marker of ['<permissions instructions>', '<environment_context>']) {\n if (!renderedPrompt.includes(marker)) {\n throw new Error(`runLocalHarness: Codex prompt evidence is missing required marker ${marker}`)\n }\n }\n\n const nonPromptArgs = [\n 'codex',\n ...opts.args.map((arg, index) => (index === 1 ? '<PROMPT>' : arg)),\n ]\n return {\n cliVersion,\n executableSha256: opts.executableSha256,\n requestedPromptSha256: sha256(prompt),\n effectivePromptSha256: sha256(renderedPrompt),\n nonPromptArgsSha256: sha256(JSON.stringify(nonPromptArgs)),\n controlledConfigSha256: opts.controlledConfigSha256,\n readDeniedPathsSha256: opts.readDeniedPathsSha256,\n readDeniedPathCount: opts.readDeniedPathCount,\n readDeniedPaths: [...opts.readDeniedPaths],\n policy: { ...CODEX_EXECUTION_POLICY },\n }\n}\n\nfunction assertCodexReproducibleInvocation(command: string, args: string[]): void {\n const executable = basename(command)\n if (executable !== 'codex' && executable !== 'codex.exe') {\n throw new Error('runLocalHarness: reproducible Codex invocation must use the Codex executable')\n }\n const prompt = args[1]\n const expectedPrefix = ['exec', prompt, ...CODEX_REPRODUCIBLE_ARGS]\n const hasExactPrefix = expectedPrefix.every((arg, index) => args[index] === arg)\n const tail = args.slice(expectedPrefix.length)\n const validModel =\n tail[0] === '-m' &&\n typeof tail[1] === 'string' &&\n tail[1].length > 0 &&\n !tail[1].startsWith('-')\n const validReasoning =\n tail[2] === '-c' &&\n typeof tail[3] === 'string' &&\n /^model_reasoning_effort=\"(?:none|minimal|low|medium|high|xhigh)\"$/.test(tail[3])\n if (!hasExactPrefix || tail.length !== 4 || !validModel || !validReasoning) {\n throw new Error(\n 'runLocalHarness: reproducible Codex invocation does not match the required isolated argv',\n )\n }\n}\n\nfunction codexPromptDebugArgs(execArgs: string[], prompt: string): string[] {\n const debugArgs = ['debug', 'prompt-input']\n for (let index = 2; index < execArgs.length; index += 1) {\n const arg = execArgs[index]\n const value = execArgs[index + 1]\n if (arg === '-c' && value !== undefined) {\n debugArgs.push('-c', value)\n index += 1\n } else if (arg === '--disable' && value !== undefined) {\n debugArgs.push('--disable', value)\n index += 1\n } else if (arg === '-m' && value !== undefined) {\n debugArgs.push('-c', `model=${JSON.stringify(value)}`)\n index += 1\n } else if (arg === '-s' && value !== undefined) {\n debugArgs.push('-c', `sandbox_mode=${JSON.stringify(value)}`)\n index += 1\n }\n }\n debugArgs.push(prompt)\n return debugArgs\n}\n\nfunction runCodexProbe(\n opts: {\n command: string\n cwd: string\n env: NodeJS.ProcessEnv\n spawn: NonNullable<RunLocalHarnessOptions['spawn']>\n signal?: AbortSignal\n },\n args: string[],\n): Promise<{ stdout: string; stderr: string }> {\n return new Promise((resolve, reject) => {\n let child: ChildProcess\n try {\n child = opts.spawn(opts.command, args, {\n cwd: opts.cwd,\n env: opts.env,\n stdio: 'pipe',\n detached: process.platform !== 'win32',\n })\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)))\n return\n }\n child.stdin?.end()\n let stdout = ''\n let stderr = ''\n let settled = false\n let leaderClosed = false\n let termination: Promise<void> | null = null\n let terminationReason: 'aborted' | 'timed out' | null = null\n const clearLifecycle = () => {\n clearTimeout(timer)\n opts.signal?.removeEventListener('abort', onAbort)\n }\n const rejectOnce = (err: unknown) => {\n if (settled) return\n settled = true\n clearLifecycle()\n reject(err instanceof Error ? err : new Error(String(err)))\n }\n const terminate = (reason?: 'aborted' | 'timed out'): Promise<void> => {\n if (reason) terminationReason ??= reason\n if (!termination) {\n termination = terminateProcessTreeAndConfirm(child, () => leaderClosed)\n void termination.catch(rejectOnce)\n }\n return termination\n }\n const timer = setTimeout(() => {\n void terminate('timed out')\n }, 10_000)\n timer.unref?.()\n const onAbort = () => {\n void terminate('aborted')\n }\n if (opts.signal) {\n if (opts.signal.aborted) onAbort()\n else opts.signal.addEventListener('abort', onAbort, { once: true })\n }\n child.stdout?.on('data', (chunk) => {\n stdout += String(chunk)\n })\n child.stderr?.on('data', (chunk) => {\n stderr += String(chunk)\n })\n child.on('error', (err) => {\n leaderClosed = true\n clearTimeout(timer)\n void (async () => {\n try {\n if (termination) await termination\n rejectOnce(err)\n } catch (terminationError) {\n rejectOnce(terminationError)\n }\n })()\n })\n child.on('close', (code, signal) => {\n leaderClosed = true\n clearTimeout(timer)\n void (async () => {\n try {\n if (\n !termination &&\n process.platform !== 'win32' &&\n typeof child.pid === 'number' &&\n processGroupExists(child.pid)\n ) {\n await terminate()\n }\n if (termination) await termination\n if (settled) return\n settled = true\n clearLifecycle()\n if (code !== 0 || terminationReason) {\n const safeStderr = redactCodexHome(stderr, opts.env.CODEX_HOME)\n reject(\n new Error(\n `runLocalHarness: Codex evidence probe ${terminationReason ?? 'failed'} (exit ${String(code)}, signal ${String(signal)}): ${safeStderr.trim()}`,\n ),\n )\n return\n }\n resolve({ stdout, stderr })\n } catch (err) {\n rejectOnce(err)\n }\n })()\n })\n })\n}\n\nfunction sha256(value: string): string {\n return createHash('sha256').update(value).digest('hex')\n}\n\n/** Codex's debug renderer converts CRLF pairs to LF. No other whitespace is equivalent. */\nfunction normalizeCodexDebugPromptNewlines(value: string): string {\n return value.replaceAll('\\r\\n', '\\n')\n}\n\nfunction jsonTextContains(value: unknown, needle: string): boolean {\n if (typeof value === 'string') return value.includes(needle)\n if (Array.isArray(value)) return value.some((item) => jsonTextContains(item, needle))\n if (isRecord(value)) return Object.values(value).some((item) => jsonTextContains(item, needle))\n return false\n}\n\nfunction redactJsonText(value: unknown, text: string): unknown {\n if (typeof value === 'string') return value.replaceAll(text, '')\n if (Array.isArray(value)) return value.map((item) => redactJsonText(item, text))\n if (isRecord(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([key, item]) => [key, redactJsonText(item, text)]),\n )\n }\n return value\n}\n\nconst CODEX_AUTH_ENV = ['CODEX_ACCESS_TOKEN', 'CODEX_API_KEY', 'OPENAI_API_KEY'] as const\n\nconst CODEX_PERMISSION_PROFILE = 'agent_runtime_reproducible'\n\nasync function isolateCodexHome(opts: {\n baseEnv: NodeJS.ProcessEnv\n cwd: string\n command: string\n readDeniedPaths: ReadonlyArray<string>\n resolveExecutable: (command: string, env: NodeJS.ProcessEnv) => Promise<string>\n}): Promise<{\n env: NodeJS.ProcessEnv\n command: string\n cleanup: () => Promise<void>\n controlledConfigSha256: string\n executableSha256: string\n readDeniedPaths: string[]\n readDeniedPathsSha256: string\n readDeniedPathCount: number\n diagnosticRedactionValues: string[]\n ambientAuth: string\n isolatedAuth: string\n writeProbe: string\n stagedWriteProbe: string\n deniedProbePaths: string[]\n}> {\n const isolatedHome = await mkdtemp(join(tmpdir(), 'agent-runtime-codex-'))\n await chmod(isolatedHome, 0o700)\n let workspaceTemp = ''\n let stagedExecutableDir = ''\n let ownsStagedExecutableDir = false\n let writeProbe = ''\n const cleanup = async () => {\n if (ownsStagedExecutableDir) {\n await chmod(stagedExecutableDir, 0o700).catch(() => undefined)\n }\n await Promise.all([\n ...(writeProbe ? [rm(writeProbe, { force: true })] : []),\n ...(workspaceTemp ? [rm(workspaceTemp, { recursive: true, force: true })] : []),\n ...(ownsStagedExecutableDir\n ? [rm(stagedExecutableDir, { recursive: true, force: true })]\n : []),\n rm(isolatedHome, { recursive: true, force: true }),\n ])\n }\n try {\n const readDeniedPaths = await normalizeReadDeniedPaths(opts.readDeniedPaths)\n const candidateRoot = await realpath(opts.cwd)\n writeProbe = join(candidateRoot, `.agent-runtime-write-proof-${randomUUID()}`)\n const stagedPath = join(candidateRoot, '.agent-runtime-bin')\n if (\n readDeniedPaths.some(\n (path) =>\n isSameOrDescendant(candidateRoot, path) ||\n isSameOrDescendant(stagedPath, path) ||\n isSameOrDescendant(path, stagedPath),\n )\n ) {\n throw new Error(\n 'runLocalHarness: codexReadDeniedPaths cannot contain the candidate root or staged executable',\n )\n }\n const nativeExecutable = await opts.resolveExecutable(opts.command, opts.baseEnv)\n if (!(await isStaticElfExecutable(nativeExecutable))) {\n throw new Error(\n 'runLocalHarness: reproducible Codex mode requires a statically linked Linux Codex ELF',\n )\n }\n const sourceExecutableSha256 = await sha256File(nativeExecutable)\n\n stagedExecutableDir = stagedPath\n try {\n await mkdir(stagedExecutableDir, { mode: 0o700 })\n ownsStagedExecutableDir = true\n } catch (err) {\n throw new Error(\n `runLocalHarness: candidate-private .agent-runtime-bin must not already exist: ${String((err as NodeJS.ErrnoException).code ?? err)}`,\n )\n }\n const stagedExecutable = join(stagedExecutableDir, 'codex')\n await copyFile(nativeExecutable, stagedExecutable, constants.COPYFILE_FICLONE)\n await chmod(stagedExecutable, 0o500)\n const executableSha256 = await sha256File(stagedExecutable)\n if (\n executableSha256 !== sourceExecutableSha256 ||\n !(await isStaticElfExecutable(stagedExecutable))\n ) {\n throw new Error('runLocalHarness: staged Codex executable digest mismatch')\n }\n await chmod(stagedExecutableDir, 0o500)\n\n workspaceTemp = await mkdtemp(join(candidateRoot, '.agent-runtime-tmp-'))\n await chmod(workspaceTemp, 0o700)\n const ambientHome = resolve(opts.baseEnv.CODEX_HOME?.trim() || join(homedir(), '.codex'))\n const ambientAuth = join(ambientHome, 'auth.json')\n const isolatedAuth = join(isolatedHome, 'auth.json')\n let authText = ''\n try {\n await access(ambientAuth, constants.R_OK)\n authText = await readCodexAuthRedactionText(ambientAuth)\n await symlink(ambientAuth, isolatedAuth)\n } catch (err) {\n throw new Error(\n `runLocalHarness: reproducible Codex mode requires readable auth.json: ${String((err as NodeJS.ErrnoException).code ?? err)}`,\n )\n }\n const deniedHostRoots = [homedir(), opts.baseEnv.HOME?.trim(), ambientHome]\n .filter((path): path is string => Boolean(path))\n .map((path) => resolve(path))\n .filter((path, index, paths) => paths.indexOf(path) === index)\n const controlledConfig = codexControlledConfig({\n ambientTmp: opts.baseEnv.TMPDIR?.trim() || tmpdir(),\n deniedHostRoots,\n workspaceTemp,\n stagedExecutableDir,\n readDeniedPaths,\n })\n await writeFile(join(isolatedHome, 'config.toml'), controlledConfig, { mode: 0o600 })\n const env = { ...opts.baseEnv }\n for (const name of Object.keys(env)) {\n if (\n codexSensitiveEnvironmentName.test(name) ||\n CODEX_AUTH_ENV.some((authName) => authName === name)\n ) {\n delete env[name]\n }\n }\n env.CODEX_HOME = isolatedHome\n const home = homedir()\n const deniedProbePaths = [\n ...deniedHostRoots,\n ambientAuth,\n isolatedAuth,\n join(home, '.claude', '.credentials.json'),\n join(home, '.claude.json'),\n join(home, '.local', 'share', 'opencode', 'auth.json'),\n join(home, '.agents'),\n join(home, 'Documents'),\n join(home, 'Downloads'),\n join(home, '.npm'),\n join(home, 'code'),\n ...readDeniedPaths,\n ].filter((path, index, paths) => paths.indexOf(path) === index)\n return {\n env,\n command: stagedExecutable,\n cleanup,\n controlledConfigSha256: sha256(controlledConfig),\n executableSha256,\n readDeniedPaths,\n readDeniedPathsSha256: sha256(JSON.stringify(readDeniedPaths)),\n readDeniedPathCount: readDeniedPaths.length,\n diagnosticRedactionValues: collectCodexDiagnosticRedactionValues(opts.baseEnv, authText),\n ambientAuth,\n isolatedAuth,\n writeProbe,\n stagedWriteProbe: join(stagedExecutableDir, 'write-proof'),\n deniedProbePaths,\n }\n } catch (err) {\n await cleanup()\n throw err\n }\n}\n\nfunction codexControlledConfig(opts: {\n ambientTmp: string\n deniedHostRoots: string[]\n workspaceTemp: string\n stagedExecutableDir: string\n readDeniedPaths: string[]\n}): string {\n const rules = new Map<string, 'deny' | 'read' | 'write'>()\n const broadDeniedPaths = minimalPathRoots([\n ...opts.deniedHostRoots.map((path) => resolve(path)),\n tmpdir(),\n opts.ambientTmp,\n '/proc',\n '/run/docker',\n '/run/containerd',\n ])\n for (const path of broadDeniedPaths) {\n rules.set(path, 'deny')\n }\n const workspaceRoot = dirname(opts.workspaceTemp)\n for (const path of opts.readDeniedPaths) {\n const alreadyDenied = broadDeniedPaths.some((root) => isSameOrDescendant(path, root))\n if (!alreadyDenied || isSameOrDescendant(path, workspaceRoot)) rules.set(path, 'deny')\n }\n if (!rules.has(opts.workspaceTemp)) rules.set(opts.workspaceTemp, 'write')\n if (!rules.has(opts.stagedExecutableDir)) rules.set(opts.stagedExecutableDir, 'read')\n const filesystemRules = [...rules]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([path, access]) => `${JSON.stringify(path)} = ${JSON.stringify(access)}`)\n .join('\\n')\n return `default_permissions = \"${CODEX_PERMISSION_PROFILE}\"\napproval_policy = \"never\"\nallow_login_shell = false\nservice_tier = \"default\"\n\n[shell_environment_policy]\ninherit = \"core\"\nignore_default_excludes = false\nexclude = [\"^CODEX_HOME$\", \"(?i).*TOKEN.*\", \"(?i).*KEY.*\", \"(?i).*SECRET.*\", \"(?i).*PASSWORD.*\", \"(?i).*CREDENTIAL.*\", \"(?i).*AUTH.*\", \"(?i).*COOKIE.*\"]\nset = { TMPDIR = ${JSON.stringify(opts.workspaceTemp)} }\n\n[permissions.${CODEX_PERMISSION_PROFILE}.filesystem]\n\":minimal\" = \"read\"\n${filesystemRules}\n\":slash_tmp\" = \"deny\"\n\n[permissions.${CODEX_PERMISSION_PROFILE}.filesystem.\":workspace_roots\"]\n\".\" = \"write\"\n\".git\" = \"deny\"\n\n[permissions.${CODEX_PERMISSION_PROFILE}.network]\nenabled = false\n\n[permissions.${CODEX_PERMISSION_PROFILE}.network.unix_sockets]\n\"/var/run/docker.sock\" = \"deny\"\n\"/run/docker.sock\" = \"deny\"\n\"/var/run/containerd/containerd.sock\" = \"deny\"\n\"/run/containerd/containerd.sock\" = \"deny\"\n`\n}\n\nfunction isSameOrDescendant(path: string, root: string): boolean {\n const normalizedPath = resolve(path)\n const normalizedRoot = resolve(root)\n return normalizedPath === normalizedRoot || normalizedPath.startsWith(`${normalizedRoot}${sep}`)\n}\n\nfunction minimalPathRoots(paths: ReadonlyArray<string>): string[] {\n const ordered = [...new Set(paths.map((path) => resolve(path)))].sort(\n (a, b) => a.length - b.length || a.localeCompare(b),\n )\n return ordered.filter(\n (path, index) => !ordered.slice(0, index).some((root) => isSameOrDescendant(path, root)),\n )\n}\n\nasync function normalizeReadDeniedPaths(paths: ReadonlyArray<string>): Promise<string[]> {\n if (!Array.isArray(paths)) {\n throw new Error('runLocalHarness: codexReadDeniedPaths must be an array of absolute paths')\n }\n const normalized = new Set<string>()\n for (const path of paths) {\n if (typeof path !== 'string' || path.length === 0 || path.includes('\\0') || !isAbsolute(path)) {\n throw new Error('runLocalHarness: codexReadDeniedPaths must contain absolute paths')\n }\n const absolute = resolve(path)\n normalized.add(absolute)\n try {\n normalized.add(await realpath(absolute))\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err\n }\n }\n return [...normalized].sort()\n}\n\nasync function resolveCodexNativeExecutable(\n command: string,\n env: NodeJS.ProcessEnv,\n): Promise<string> {\n const candidates =\n command.includes(sep) || isAbsolute(command)\n ? [resolve(command)]\n : (env.PATH ?? '')\n .split(delimiter)\n .filter(Boolean)\n .map((entry) => join(entry, command))\n const seen = new Set<string>()\n for (const candidate of candidates) {\n let resolved: string\n try {\n await access(candidate, constants.X_OK)\n resolved = await realpath(candidate)\n } catch {\n continue\n }\n if (seen.has(resolved)) continue\n seen.add(resolved)\n if (await isStaticElfExecutable(resolved)) return resolved\n const packageRoot = await findCodexPackageRoot(resolved)\n if (!packageRoot) continue\n const bundled = await findBundledCodexExecutable(packageRoot)\n if (bundled) return bundled\n }\n throw new Error(\n 'runLocalHarness: could not resolve the native Codex executable from the requested command',\n )\n}\n\nasync function findCodexPackageRoot(file: string): Promise<string | undefined> {\n let cursor = dirname(file)\n while (true) {\n try {\n const parsed = JSON.parse(await readFile(join(cursor, 'package.json'), 'utf8')) as {\n name?: unknown\n }\n if (parsed.name === '@openai/codex') return cursor\n } catch {\n // Keep walking; PATH wrappers commonly live outside the package directory.\n }\n const parent = dirname(cursor)\n if (parent === cursor) return undefined\n cursor = parent\n }\n}\n\nasync function findBundledCodexExecutable(packageRoot: string): Promise<string | undefined> {\n const target = linuxCodexTarget()\n const candidates = [\n join(\n packageRoot,\n 'node_modules',\n '@openai',\n target.packageName,\n 'vendor',\n target.triple,\n 'bin',\n 'codex',\n ),\n join(packageRoot, 'vendor', target.triple, 'bin', 'codex'),\n ]\n for (const executable of candidates) {\n if (await isStaticElfExecutable(executable)) return executable\n }\n return undefined\n}\n\nfunction linuxCodexTarget(): { packageName: string; triple: string } {\n if (process.platform !== 'linux') {\n throw new Error('runLocalHarness: reproducible Codex mode requires Linux')\n }\n if (process.arch === 'x64') {\n return { packageName: 'codex-linux-x64', triple: 'x86_64-unknown-linux-musl' }\n }\n if (process.arch === 'arm64') {\n return { packageName: 'codex-linux-arm64', triple: 'aarch64-unknown-linux-musl' }\n }\n throw new Error(`runLocalHarness: unsupported Linux architecture ${process.arch}`)\n}\n\nasync function isStaticElfExecutable(path: string): Promise<boolean> {\n let handle: Awaited<ReturnType<typeof open>> | undefined\n try {\n await access(path, constants.X_OK)\n handle = await open(path, 'r')\n const header = Buffer.alloc(64)\n const { bytesRead } = await handle.read(header, 0, header.length, 0)\n if (\n bytesRead !== header.length ||\n !header.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])) ||\n header[4] !== 2 ||\n header[5] !== 1\n ) {\n return false\n }\n const programHeaderOffset = Number(header.readBigUInt64LE(32))\n const programHeaderSize = header.readUInt16LE(54)\n const programHeaderCount = header.readUInt16LE(56)\n const expectedMachine = process.arch === 'x64' ? 62 : process.arch === 'arm64' ? 183 : -1\n if (\n ![2, 3].includes(header.readUInt16LE(16)) ||\n header.readUInt16LE(18) !== expectedMachine ||\n !Number.isSafeInteger(programHeaderOffset) ||\n programHeaderOffset < 64 ||\n programHeaderSize < 56 ||\n programHeaderSize > 1024 ||\n programHeaderCount === 0 ||\n programHeaderCount > 1024\n ) {\n return false\n }\n const tableSize = programHeaderSize * programHeaderCount\n const table = Buffer.alloc(tableSize)\n const tableRead = await handle.read(table, 0, tableSize, programHeaderOffset)\n if (tableRead.bytesRead !== tableSize) return false\n for (let index = 0; index < programHeaderCount; index += 1) {\n const type = table.readUInt32LE(index * programHeaderSize)\n if (type === 3) return false\n }\n return true\n } catch {\n return false\n } finally {\n await handle?.close()\n }\n}\n\nfunction sha256File(path: string): Promise<string> {\n return new Promise((resolveDigest, reject) => {\n const hash = createHash('sha256')\n const stream = createReadStream(path)\n stream.on('error', reject)\n stream.on('data', (chunk) => hash.update(chunk))\n stream.on('end', () => resolveDigest(hash.digest('hex')))\n })\n}\n\nfunction signalProcessTree(child: ChildProcess, signal: NodeJS.Signals): void {\n if (process.platform !== 'win32' && typeof child.pid === 'number') {\n try {\n process.kill(-child.pid, signal)\n return\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ESRCH') return\n }\n }\n try {\n child.kill(signal)\n } catch {\n // The process may have exited between the timer and signal delivery.\n }\n}\n\nexport async function terminateProcessTreeAndConfirm(\n child: ChildProcess,\n leaderClosed: () => boolean,\n context = 'runLocalHarness',\n): Promise<void> {\n signalProcessTree(child, 'SIGTERM')\n if (process.platform === 'win32' || typeof child.pid !== 'number') {\n const graceDeadline = Date.now() + processKillGraceMs\n while (!leaderClosed() && Date.now() < graceDeadline) {\n await delayUntilNextProcessCheck(graceDeadline)\n }\n if (!leaderClosed()) signalProcessTree(child, 'SIGKILL')\n return\n }\n const processGroupId = child.pid\n const graceDeadline = Date.now() + processKillGraceMs\n if (await waitForProcessGroupExit(processGroupId, graceDeadline)) return\n\n signalProcessTree(child, 'SIGKILL')\n const killDeadline = Date.now() + processGroupExitConfirmMs\n if (await waitForProcessGroupExit(processGroupId, killDeadline)) return\n throw new Error(`${context}: process group ${processGroupId} survived SIGKILL`)\n}\n\nasync function waitForProcessGroupExit(processGroupId: number, deadline: number): Promise<boolean> {\n while (processGroupExists(processGroupId)) {\n if (Date.now() >= deadline) return false\n await delayUntilNextProcessCheck(deadline)\n }\n return true\n}\n\nasync function delayUntilNextProcessCheck(deadline: number): Promise<void> {\n const delayMs = Math.min(processGroupExitPollMs, Math.max(0, deadline - Date.now()))\n if (delayMs > 0) await new Promise((resolve) => setTimeout(resolve, delayMs))\n}\n\nfunction processGroupExists(processGroupId: number): boolean {\n try {\n process.kill(-processGroupId, 0)\n return true\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ESRCH') return false\n return true\n }\n}\n\n/** Parse and validate the one terminal usage event emitted by `codex exec --json`. */\nexport function parseCodexTokenUsage(stdout: string): CodexTokenUsage {\n const completed: unknown[] = []\n for (const [index, line] of stdout.split(/\\r?\\n/).entries()) {\n if (line.trim().length === 0) continue\n let event: unknown\n try {\n event = JSON.parse(line)\n } catch {\n throw new Error(`runLocalHarness: Codex JSONL line ${index + 1} is not valid JSON`)\n }\n if (isRecord(event) && event.type === 'turn.completed') completed.push(event)\n }\n if (completed.length !== 1) {\n throw new Error(\n `runLocalHarness: expected exactly one Codex turn.completed usage event, received ${completed.length}`,\n )\n }\n const event = completed[0]\n if (!isRecord(event) || !isRecord(event.usage)) {\n throw new Error('runLocalHarness: Codex turn.completed event is missing usage')\n }\n const usage = event.usage\n const inputTokens = naturalNumber(usage.input_tokens, 'input_tokens')\n const cachedInputTokens = naturalNumber(usage.cached_input_tokens, 'cached_input_tokens')\n const outputTokens = naturalNumber(usage.output_tokens, 'output_tokens')\n const reasoningOutputTokens = naturalNumber(\n usage.reasoning_output_tokens,\n 'reasoning_output_tokens',\n )\n if (cachedInputTokens > inputTokens) {\n throw new Error('runLocalHarness: Codex cached_input_tokens exceeds input_tokens')\n }\n if (reasoningOutputTokens > outputTokens) {\n throw new Error('runLocalHarness: Codex reasoning_output_tokens exceeds output_tokens')\n }\n return { inputTokens, cachedInputTokens, outputTokens, reasoningOutputTokens }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction naturalNumber(value: unknown, field: string): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new Error(`runLocalHarness: Codex usage.${field} must be a non-negative safe integer`)\n }\n return value\n}\n","/**\n *\n * Git worktree helpers for the in-process delegation executor. Each\n * delegation runs in its own worktree so multiple parallel harness\n * subprocesses (claude / codex / opencode in a 3-way fanout) don't clobber\n * each other's edits on the shared workspace.\n *\n * Worktrees live under `<repoRoot>/.agent-worktrees/<runId>/`. After the\n * harness exits + the diff is captured, the worktree is removed.\n *\n * All operations spawn `git` via `child_process.spawn` synchronously\n * (via a `runGit` helper). Stays narrow on purpose: no commits, no rebases.\n * Diff capture stages all changes (`git add -A`) into the ephemeral worktree's\n * index so created (untracked) files appear in the `--cached` diff.\n *\n * @experimental\n */\n\nimport { spawn } from 'node:child_process'\nimport { isAbsolute, win32 } from 'node:path'\n\n/** @experimental */\nexport interface WorktreeHandle {\n /** Absolute path to the worktree directory. */\n path: string\n /** SHA the worktree was created at. */\n baseSha: string\n /** Branch name created for this worktree (typically `delegate/<runId>`). */\n branch: string\n}\n\n/** @experimental */\nexport interface CreateWorktreeOptions {\n /** Absolute path to the main git checkout. */\n repoRoot: string\n /** Unique id for the worktree path + branch. Use the delegation run id. */\n runId: string\n /** Parent directory the worktree lives under. Defaults to `.agent-worktrees`. */\n variantsDir?: string\n /** Override the base ref (default `HEAD`). */\n baseRef?: string\n /** Test seam — inject a custom git runner. */\n runGit?: GitRunner\n}\n\n/** @experimental */\nexport interface DiffOptions {\n /** Worktree to diff. */\n worktree: WorktreeHandle\n /** What to compare against. Default `worktree.baseSha`. */\n baseRef?: string\n /**\n * Repository-relative input paths to omit from the captured worker patch.\n * Paths are passed to Git with literal exclusion magic, so profile-provided\n * `*`, `?`, `[` and `:` characters can never expand into broader pathspecs.\n */\n excludePaths?: ReadonlyArray<string>\n /** Test seam. */\n runGit?: GitRunner\n}\n\n/** @experimental */\nexport interface DiffResult {\n patch: string\n stats: {\n filesChanged: number\n insertions: number\n deletions: number\n }\n}\n\n/** @experimental */\nexport interface RemoveWorktreeOptions {\n worktree: WorktreeHandle\n repoRoot: string\n /** Force removal even if dirty (default true; the loser of a fanout has uncommitted changes). */\n force?: boolean\n /** Test seam. */\n runGit?: GitRunner\n}\n\n/** Pluggable git runner (sync) — replaceable in tests. */\nexport type GitRunner = (\n args: ReadonlyArray<string>,\n opts: { cwd: string },\n) => { stdout: string; stderr: string; exitCode: number }\n\nasync function runGitAsync(\n args: ReadonlyArray<string>,\n cwd: string,\n runner?: GitRunner,\n): Promise<{ stdout: string; stderr: string; exitCode: number }> {\n if (runner) return runner(args, { cwd })\n return new Promise((resolve, reject) => {\n const proc = spawn('git', args, { cwd, stdio: 'pipe' })\n let stdout = ''\n let stderr = ''\n proc.stdout?.on('data', (c) => {\n stdout += String(c)\n })\n proc.stderr?.on('data', (c) => {\n stderr += String(c)\n })\n proc.on('error', reject)\n proc.on('close', (code) => resolve({ stdout, stderr, exitCode: code ?? -1 }))\n })\n}\n\nfunction ensureGitOk(\n step: string,\n result: { stdout: string; stderr: string; exitCode: number },\n): void {\n if (result.exitCode !== 0) {\n throw gitFailure(step, result)\n }\n}\n\nfunction gitFailure(\n step: string,\n result: { stdout: string; stderr: string; exitCode: number },\n): Error {\n return new Error(\n `worktree: git ${step} failed (exit ${result.exitCode}): ${result.stderr.slice(0, 400)}`,\n )\n}\n\n/** Checkout a fresh git worktree for a delegation run on a new branch under `variantsDir`. @experimental */\nexport async function createWorktree(options: CreateWorktreeOptions): Promise<WorktreeHandle> {\n const variants = options.variantsDir ?? '.agent-worktrees'\n const baseRef = options.baseRef ?? 'HEAD'\n const branch = `delegate/${options.runId}`\n const path = `${options.repoRoot.replace(/\\/+$/, '')}/${variants}/${options.runId}`\n\n const headSha = await runGitAsync(['rev-parse', baseRef], options.repoRoot, options.runGit)\n ensureGitOk(`rev-parse ${baseRef}`, headSha)\n\n const add = await runGitAsync(\n ['worktree', 'add', '-b', branch, path, baseRef],\n options.repoRoot,\n options.runGit,\n )\n ensureGitOk(`worktree add ${path}`, add)\n\n return { path, baseSha: headSha.stdout.trim(), branch }\n}\n\n/** Stage worker changes and return the diff + shortstat, excluding declared input paths. @experimental */\nexport async function captureWorktreeDiff(options: DiffOptions): Promise<DiffResult> {\n const baseRef = options.baseRef ?? options.worktree.baseSha\n const pathspecs = worktreeDiffPathspecs(options.excludePaths ?? [])\n // Stage everything (incl. NEW/untracked files) before diffing: a plain `git diff <ref>`\n // omits untracked files, so a worker that delivers by CREATING a file (a fresh dossier,\n // a new module) would produce an empty diff and silently fail to compound. Staging into\n // the index and diffing `--cached` captures created files. The worktree is ephemeral, so\n // mutating its index has no observable side effect.\n const staged = await runGitAsync(\n ['add', '-A', ...(pathspecs.length > 0 ? ['--', '.', ...pathspecs] : [])],\n options.worktree.path,\n options.runGit,\n )\n ensureGitOk('add -A', staged)\n const patch = await runGitAsync(\n ['diff', '--cached', baseRef, ...(pathspecs.length > 0 ? ['--', '.', ...pathspecs] : [])],\n options.worktree.path,\n options.runGit,\n )\n ensureGitOk(`diff --cached ${baseRef}`, patch)\n\n // Stats: `git diff --shortstat` produces e.g. \" 3 files changed, 42 insertions(+), 10 deletions(-)\".\n const shortstat = await runGitAsync(\n [\n 'diff',\n '--cached',\n '--shortstat',\n baseRef,\n ...(pathspecs.length > 0 ? ['--', '.', ...pathspecs] : []),\n ],\n options.worktree.path,\n options.runGit,\n )\n ensureGitOk(`diff --cached --shortstat ${baseRef}`, shortstat)\n const stats = parseShortstat(shortstat.stdout)\n return { patch: patch.stdout, stats }\n}\n\nfunction worktreeDiffPathspecs(paths: ReadonlyArray<string>): string[] {\n const normalized = new Set<string>()\n for (const path of paths) {\n if (\n typeof path !== 'string' ||\n path.length === 0 ||\n path.includes('\\\\') ||\n hasControlCharacter(path) ||\n isAbsolute(path) ||\n win32.isAbsolute(path)\n ) {\n throw new Error(\n `worktree: excluded path must be a canonical repository-relative path: ${path}`,\n )\n }\n const segments = path.split('/')\n if (segments.some((segment) => segment.length === 0 || segment === '.' || segment === '..')) {\n throw new Error(\n `worktree: excluded path must be a canonical repository-relative path: ${path}`,\n )\n }\n normalized.add(path)\n }\n return [...normalized]\n .sort((left, right) => left.localeCompare(right))\n .map((path) => `:(top,exclude,literal)${path}`)\n}\n\nfunction hasControlCharacter(value: string): boolean {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index)\n if (code < 0x20 || code === 0x7f) return true\n }\n return false\n}\n\nfunction parseShortstat(text: string): DiffResult['stats'] {\n // `text` is the raw stdout of `git diff --shortstat`. Empty when no\n // changes. Parse defensively — the format is stable but we don't trust\n // it for type-safety.\n const out = { filesChanged: 0, insertions: 0, deletions: 0 }\n const filesMatch = text.match(/(\\d+)\\s+files?\\s+changed/)\n if (filesMatch?.[1]) out.filesChanged = Number(filesMatch[1])\n const insertMatch = text.match(/(\\d+)\\s+insertions?/)\n if (insertMatch?.[1]) out.insertions = Number(insertMatch[1])\n const deleteMatch = text.match(/(\\d+)\\s+deletions?/)\n if (deleteMatch?.[1]) out.deletions = Number(deleteMatch[1])\n return out\n}\n\n/**\n * Remove a git worktree and delete its branch. Already-removed paths are harmless; every other\n * Git failure rejects so callers cannot report a worktree as destroyed when cleanup failed.\n * @experimental\n */\nexport async function removeWorktree(options: RemoveWorktreeOptions): Promise<void> {\n const force = options.force ?? true\n const args = ['worktree', 'remove']\n if (force) args.push('--force')\n args.push(options.worktree.path)\n const removal = await runGitAsync(args, options.repoRoot, options.runGit)\n const removalError =\n removal.exitCode !== 0 && !/not a working tree/iu.test(removal.stderr)\n ? gitFailure(`worktree remove ${options.worktree.path}`, removal)\n : undefined\n\n // Worktree removal leaves its branch behind by design. Missing branches are repeat cleanup.\n const branchRemoval = await runGitAsync(\n ['branch', '-D', options.worktree.branch],\n options.repoRoot,\n options.runGit,\n )\n const branchError =\n branchRemoval.exitCode !== 0 && !/branch .+ not found/iu.test(branchRemoval.stderr)\n ? gitFailure(`branch -D ${options.worktree.branch}`, branchRemoval)\n : undefined\n\n if (removalError && branchError) {\n throw new AggregateError(\n [removalError, branchError],\n 'worktree: failed to remove worktree and branch',\n )\n }\n if (removalError) throw removalError\n if (branchError) throw branchError\n}\n","/**\n *\n * The ONE worktree-harness execution core. The physical act — run a supervisor-authored\n * `AgentProfile` on a local coding-harness CLI (claude / codex / opencode) against a fresh git\n * worktree off `repoRoot`, capture the diff, derive the test/typecheck PASS signals, then clean\n * up — lives here ONCE. Two executors adapt it to two ports without re-implementing it:\n * - `createWorktreeCliExecutor` — the `Scope`/`Supervisor` leaf `Executor`.\n * - `createInProcessExecutor` — the `runAgentRounds` `SandboxClient` / coder-delegate path.\n *\n * §1.5 by construction: prompt + model reach the direct invocation, while file-backed resources\n * are lowered by the shared profile materializer and applied before spawn. Resource instructions\n * join the direct prompt because reproducible Codex intentionally disables ambient project docs.\n *\n * Lifecycle: `createWorktree` → materialize profile inputs → `harnessInvocation` +\n * `runLocalHarness` → `captureWorktreeDiff` excluding those inputs (BEFORE checks, so the patch is\n * the harness's output, not polluted by files a test run writes) → configured checks → return the\n * result + caller-owned `cleanup`. A throw cleans up before propagating.\n *\n * @experimental\n */\n\nimport { spawn } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport {\n applyWorkspacePlan,\n type HarnessId,\n hashWorkspacePlan,\n materializeProfile,\n type ResolveAgentProfileResourcesOptions,\n resolveAgentProfileResources,\n type WorkspacePlan,\n type WorkspacePlanArgument,\n type WorkspacePlanConfigValue,\n type WorkspacePlanReceipt,\n} from '@tangle-network/agent-profile-materialize'\nimport {\n assertProfileMaterialization,\n profileMaterializationAxes,\n worktreeCliProfileMaterialization,\n} from '../agent/profile-materialization'\nimport {\n type CodexExecutionPolicy,\n type CodexTokenUsage,\n harnessInvocation,\n harnessSupportsReasoningEffort,\n type LocalHarness,\n type LocalHarnessResult,\n runLocalHarness,\n terminateProcessTreeAndConfirm,\n} from './local-harness'\nimport {\n captureWorktreeDiff,\n createWorktree,\n type GitRunner,\n removeWorktree,\n type WorktreeHandle,\n} from './worktree'\n\n/** Outcome of one verification command run in the worktree (test or typecheck). */\nexport interface WorktreeCommandResult {\n /** The shell command line that was run. */\n command: string\n /** Did the command exit 0? The PASS signal a deliverable gate / coder output reads. */\n passed: boolean\n /** OS exit code, or `null` when killed before exit. */\n exitCode: number | null\n /** Combined stdout+stderr (capped) — surfaced in traces for diagnosis. */\n output: string\n}\n\n/** Proof of the profile inputs delivered before the worker process started. */\nexport interface WorktreeProfileMaterializationReceipt {\n /** Digest of the exact materializer plan: files, modes, environment, flags, and unsupported rows. */\n workspacePlanDigest: string\n /** Repository-relative profile input files written into the worker worktree. */\n writtenPaths: string[]\n /** Must be empty on a successful run because this path fails closed. */\n unsupported: WorkspacePlanReceipt['unsupported']\n /** Environment variable names added to the worker process. Values remain out of telemetry. */\n environmentNames: string[]\n /** Exact additional CLI arguments emitted by the materializer. */\n flags: string[]\n /** `resources.instructions` bypasses native project files so reproducible Codex cannot drop it. */\n resourceInstructions: {\n delivery: 'none' | 'invocation-prompt'\n sha256: string | null\n byteLength: number\n }\n}\n\n/** Pure, pre-execution identity for the exact profile workspace plan this module later applies. */\nexport interface WorktreeProfileExecutionPlan {\n readonly workspacePlanDigest: string\n readonly harness: HarnessId\n readonly resourceInstructions: WorktreeProfileMaterializationReceipt['resourceInstructions']\n}\n\n/** The canonical result of one worktree-harness run, projected by each port to its own shape. */\nexport interface WorktreeHarnessResult {\n /** The branch the worktree was cut on (`delegate/<runId>`). */\n branch: string\n /** `git diff` of the worktree against its base — the unified patch the harness produced. */\n patch: string\n /** Shortstat-derived change counts. */\n stats: { filesChanged: number; insertions: number; deletions: number }\n /**\n * Exact profile materialization applied before the harness launched.\n * Absent on transports that cannot return a materializer receipt; never fabricated.\n */\n profileMaterialization?: WorktreeProfileMaterializationReceipt\n /** The harness subprocess outcome. */\n harness: {\n name: LocalHarness | 'bridge'\n exitCode: number | null\n timedOut: boolean\n killedBySignal: NodeJS.Signals | null\n durationMs: number\n stdout: string\n stderr: string\n /** Exact Codex JSONL usage when reproducible mode is enabled. */\n usage?: CodexTokenUsage\n /** Installed CLI version captured immediately before execution. */\n cliVersion?: string\n /** SHA-256 of the native Codex executable staged read-only in the candidate worktree. */\n executableSha256?: string\n /** SHA-256 of the exact composed prompt argument proved present in Codex's rendered prompt. */\n requestedPromptSha256?: string\n /** SHA-256 of `codex debug prompt-input` output for the exact isolated prompt. */\n effectivePromptSha256?: string\n /** SHA-256 of the exact executable + argv with prompt content replaced by `<PROMPT>`. */\n nonPromptArgsSha256?: string\n /** SHA-256 of the isolated config that fixes permissions and shell environment. */\n controlledConfigSha256?: string\n /** SHA-256 of the normalized caller-supplied host read-denial paths. */\n readDeniedPathsSha256?: string\n /** Sorted normalized caller-supplied host read-denial paths. */\n readDeniedPaths?: string[]\n /** Number of normalized caller-supplied host read-denial paths. */\n readDeniedPathCount?: number\n /** Explicit isolation claims checked before model execution. */\n executionPolicy?: CodexExecutionPolicy\n }\n /** Verification signals derived in the live worktree (present only when commands were given). */\n checks?: {\n tests?: WorktreeCommandResult\n typecheck?: WorktreeCommandResult\n }\n}\n\n/** The single shell-command-in-worktree runner seam (replaces the per-executor copies). */\nexport type WorktreeCheckRunner = (opts: {\n command: string\n cwd: string\n timeoutMs: number\n signal?: AbortSignal\n}) => Promise<{ exitCode: number | null; output: string }>\n\n/** @experimental */\nexport interface RunWorktreeHarnessOptions {\n /** Absolute path to the git checkout the worktree is cut from. */\n repoRoot: string\n /**\n * Supervisor-authored prompt/model plus structural resources materialized into the worktree.\n * `model.default` selects the one-shot model. Routing-only model hints and\n * `resources.failOnError` are rejected because this path cannot honor them.\n */\n profile: AgentProfile\n /** Local harness for this run. This explicit choice overrides `profile.harness`. */\n harness: LocalHarness\n /** The per-task instruction handed to the harness (composed under the system prompt). */\n taskPrompt: string\n /** Unique id for the worktree path + branch. */\n runId: string\n /** Override the base ref the worktree is cut from (default `HEAD`). */\n baseRef?: string\n /** Shell command run in the live worktree to derive the tests-PASS signal. Omit to skip. */\n testCmd?: string\n /** Shell command run in the live worktree to derive the typecheck-PASS signal. Omit to skip. */\n typecheckCmd?: string\n /** Wall-clock cap per harness subprocess (ms). */\n harnessTimeoutMs?: number\n /** Run Codex in isolated, network-off JSONL mode and require real token usage. */\n codexReproducible?: boolean\n /** Absolute host paths the reproducible Codex process must not read. */\n codexReadDeniedPaths?: ReadonlyArray<string>\n /** Wall-clock cap per verification command (ms). Default = `harnessTimeoutMs` or 5 min. */\n checkTimeoutMs?: number\n /** Cap on each check's captured output. Default 16k. */\n checkOutputCap?: number\n /** Abort signal — linked into the harness subprocess and the check commands. */\n signal?: AbortSignal\n /** Resource fetch options. GitHub-backed profile resources resolve before worker launch. */\n resourceResolution?: ResolveAgentProfileResourcesOptions\n /** Test seam — inject a git runner so unit tests drive the worktree helpers without git. */\n runGit?: GitRunner\n /** Test seam — inject the harness runner so unit tests script a `LocalHarnessResult`. */\n runHarness?: typeof runLocalHarness\n /** Test seam — inject the verification-command runner. Defaults to a `/bin/sh -c` spawn. */\n runCommand?: WorktreeCheckRunner\n}\n\n/** One worktree-harness run: the result + the worktree handle + caller-owned `cleanup`. */\nexport interface WorktreeHarnessRun {\n worktree: WorktreeHandle\n result: WorktreeHarnessResult\n /** Remove the worktree. The caller invokes this at its own teardown point (the leaf in its\n * `Executor.teardown`, the SandboxClient in its `streamPrompt` finally). On a thrown run the\n * core already cleaned up, so the caller never double-removes. */\n cleanup: () => Promise<void>\n}\n\nconst defaultCheckOutputCap = 16_000\n\n/** This harness runs public plans only — it has no secret provider, so any\n * templated argument or secret-ref env value is refused rather than leaked\n * or silently stringified. */\nfunction publicPlanString(value: WorkspacePlanArgument | WorkspacePlanConfigValue): string {\n if (typeof value === 'string') return value\n throw new Error(\n 'runWorktreeHarness: plan value requires a secret provider; this harness applies public plans only',\n )\n}\n\nfunction resolvePublicPlanEnv(\n env: Record<string, WorkspacePlanConfigValue | undefined>,\n): Record<string, string> {\n const resolved: Record<string, string> = {}\n for (const [name, value] of Object.entries(env)) {\n if (value === undefined) continue\n resolved[name] = publicPlanString(value)\n }\n return resolved\n}\n\n/**\n * Run the one worktree-harness operation. A failed run attempts cleanup before propagating; if\n * cleanup also fails, both errors are preserved. The caller cleans up a successful run.\n */\nexport async function runWorktreeHarness(\n opts: RunWorktreeHarnessOptions,\n): Promise<WorktreeHarnessRun> {\n opts.signal?.throwIfAborted()\n const runHarness = opts.runHarness ?? runLocalHarness\n const runCommand = opts.runCommand ?? defaultRunCommand\n const checkTimeoutMs = opts.checkTimeoutMs ?? opts.harnessTimeoutMs ?? 5 * 60 * 1000\n const cap = opts.checkOutputCap ?? defaultCheckOutputCap\n\n // Profile support is a pure admission decision. Resolve it before creating a branch/worktree so\n // a refused candidate leaves no repository state behind and starts no external process. Remote\n // (GitHub-backed) profile resources are fetched here too — also before any repository state —\n // with the caller's abort signal linked into every fetch.\n assertSupportedWorktreeProfile(opts.profile, opts.harness)\n assertSafeProfileResourcePaths(opts.profile)\n const profile = await resolveAgentProfileResources(\n opts.profile,\n resourceResolutionOptions(opts.resourceResolution, opts.signal),\n )\n opts.signal?.throwIfAborted()\n const prepared = prepareWorktreeProfile(profile, opts.harness)\n const { plan, resourceInstructions } = prepared\n\n const worktree = await createWorktree({\n repoRoot: opts.repoRoot,\n runId: opts.runId,\n ...(opts.baseRef ? { baseRef: opts.baseRef } : {}),\n ...(opts.runGit ? { runGit: opts.runGit } : {}),\n })\n\n const cleanup = (): Promise<void> =>\n removeWorktree({\n worktree,\n repoRoot: opts.repoRoot,\n ...(opts.runGit ? { runGit: opts.runGit } : {}),\n })\n\n try {\n const applied = applyWorkspacePlan(plan, worktree.path, { existingFiles: 'reject' })\n if (applied.unsupported.length > 0) {\n throw new Error('runWorktreeHarness: applied profile unexpectedly retained unsupported rows')\n }\n\n // §1.5: the authored prompt + model reach the harness directly. Resource instructions use\n // the same explicit channel because reproducible Codex deliberately disables native project\n // instructions; the workspace projection therefore omits both prompt sources.\n const invocationProfile = profileWithResourceInstructions(profile, resourceInstructions)\n const { command, args } = harnessInvocation(opts.harness, invocationProfile, opts.taskPrompt, {\n // This helper created the candidate worktree above; autonomous edits are permitted only\n // inside that isolated checkout. Which argv (if any) expresses that is the harness row's\n // business — the workspace being disposable is what decides it here.\n dangerouslySkipPermissions: true,\n ...(opts.codexReproducible ? { codexReproducible: true } : {}),\n })\n const harnessResult: LocalHarnessResult = await runHarness({\n harness: opts.harness,\n cwd: worktree.path,\n taskPrompt: opts.taskPrompt,\n invocation: { command, args: [...args, ...applied.flags.map(publicPlanString)] },\n env: { ...process.env, ...resolvePublicPlanEnv(applied.env) },\n ...(opts.codexReproducible ? { codexReproducible: true } : {}),\n ...(opts.codexReadDeniedPaths ? { codexReadDeniedPaths: opts.codexReadDeniedPaths } : {}),\n ...(opts.harnessTimeoutMs !== undefined ? { timeoutMs: opts.harnessTimeoutMs } : {}),\n ...(opts.signal ? { signal: opts.signal } : {}),\n })\n\n if (harnessResult.aborted || opts.signal?.aborted) {\n throw new Error('runWorktreeHarness: harness was cancelled by the caller', {\n cause: opts.signal?.reason,\n })\n }\n opts.signal?.throwIfAborted()\n\n // Diff BEFORE checks — the patch is the harness's output, not whatever a test run left behind.\n const diff = await captureWorktreeDiff({\n worktree,\n excludePaths: applied.written,\n ...(opts.runGit ? { runGit: opts.runGit } : {}),\n })\n opts.signal?.throwIfAborted()\n\n const checks = await runWorktreeChecks({\n worktreePath: worktree.path,\n ...(opts.testCmd !== undefined ? { testCmd: opts.testCmd } : {}),\n ...(opts.typecheckCmd !== undefined ? { typecheckCmd: opts.typecheckCmd } : {}),\n timeoutMs: checkTimeoutMs,\n cap,\n runCommand,\n ...(opts.signal ? { signal: opts.signal } : {}),\n })\n opts.signal?.throwIfAborted()\n\n const result: WorktreeHarnessResult = {\n branch: worktree.branch,\n patch: diff.patch,\n stats: diff.stats,\n profileMaterialization: profileMaterializationReceipt(applied, resourceInstructions),\n harness: {\n name: opts.harness,\n exitCode: harnessResult.exitCode,\n timedOut: harnessResult.timedOut,\n killedBySignal: harnessResult.killedBySignal,\n durationMs: harnessResult.durationMs,\n stdout: harnessResult.stdout,\n stderr: harnessResult.stderr,\n ...(harnessResult.usage ? { usage: harnessResult.usage } : {}),\n ...(harnessResult.evidence\n ? {\n cliVersion: harnessResult.evidence.cliVersion,\n executableSha256: harnessResult.evidence.executableSha256,\n requestedPromptSha256: harnessResult.evidence.requestedPromptSha256,\n effectivePromptSha256: harnessResult.evidence.effectivePromptSha256,\n nonPromptArgsSha256: harnessResult.evidence.nonPromptArgsSha256,\n controlledConfigSha256: harnessResult.evidence.controlledConfigSha256,\n readDeniedPaths: [...harnessResult.evidence.readDeniedPaths],\n readDeniedPathsSha256: harnessResult.evidence.readDeniedPathsSha256,\n readDeniedPathCount: harnessResult.evidence.readDeniedPathCount,\n executionPolicy: harnessResult.evidence.policy,\n }\n : {}),\n },\n ...(checks ? { checks } : {}),\n }\n return { worktree, result, cleanup }\n } catch (err) {\n try {\n await cleanup()\n } catch (cleanupError) {\n throw new AggregateError(\n [err, cleanupError],\n 'runWorktreeHarness: run failed and worktree cleanup also failed',\n )\n }\n throw err\n }\n}\n\n/** Compute the same plan identity `runWorktreeHarness` consumes, with no repository or process IO. */\nexport function worktreeProfileExecutionPlan(\n profile: AgentProfile,\n harness: LocalHarness,\n): WorktreeProfileExecutionPlan {\n const { plan, resourceInstructions } = prepareWorktreeProfile(profile, harness)\n return Object.freeze({\n workspacePlanDigest: hashWorkspacePlan(plan),\n harness: plan.harness,\n resourceInstructions: resourceInstructionReceipt(resourceInstructions),\n })\n}\n\nfunction prepareWorktreeProfile(\n profile: AgentProfile,\n harness: LocalHarness,\n): {\n readonly plan: WorkspacePlan\n readonly resourceInstructions: string | undefined\n} {\n const resourceInstructions = resolveResourceInstructions(profile)\n const workspaceProfile = materializationOnlyProfile(profile)\n assertSupportedWorktreeProfile(profile, harness)\n assertSafeProfileResourcePaths(profile)\n const plan = materializeProfile(workspaceProfile, harness)\n if (plan.unsupported.length > 0) {\n throw new Error(\n `runWorktreeHarness: profile cannot be materialized for ${harness}: ${plan.unsupported\n .map(({ dimension, reason }) => `${dimension}: ${reason}`)\n .join('; ')}`,\n )\n }\n assertSafeMaterializedPaths(plan)\n return { plan, resourceInstructions }\n}\n\nfunction resourceResolutionOptions(\n options: ResolveAgentProfileResourcesOptions | undefined,\n signal: AbortSignal | undefined,\n): ResolveAgentProfileResourcesOptions | undefined {\n if (!signal) return options\n const fetchResource = options?.fetch ?? globalThis.fetch\n return {\n ...options,\n fetch: (input, init) => {\n signal.throwIfAborted()\n const requestSignal = init?.signal\n return fetchResource(input, {\n ...init,\n signal: requestSignal ? AbortSignal.any([signal, requestSignal]) : signal,\n })\n },\n }\n}\n\nfunction resolveResourceInstructions(profile: AgentProfile): string | undefined {\n const instructions = profile.resources?.instructions\n if (instructions === undefined) return undefined\n if (typeof instructions === 'string')\n return instructions.trim().length > 0 ? instructions : undefined\n if (instructions.kind === 'inline' && typeof instructions.content === 'string') {\n return instructions.content.trim().length > 0 ? instructions.content : undefined\n }\n throw new Error(\n 'runWorktreeHarness: resources.instructions must be a string or inline resource; remote refs require pre-resolution',\n )\n}\n\nfunction profileWithResourceInstructions(\n profile: AgentProfile,\n resourceInstructions: string | undefined,\n): AgentProfile {\n let resources: AgentProfile['resources'] | undefined\n if (profile.resources) {\n const { instructions: _instructions, ...structuralResources } = profile.resources\n resources = structuralResources\n }\n return {\n ...profile,\n ...(resources ? { resources } : {}),\n ...(resourceInstructions === undefined\n ? {}\n : {\n prompt: {\n ...profile.prompt,\n instructions: [...(profile.prompt?.instructions ?? []), resourceInstructions],\n },\n }),\n }\n}\n\nfunction materializationOnlyProfile(profile: AgentProfile): AgentProfile {\n const {\n prompt: _prompt,\n model: _model,\n resources: profileResources,\n ...structuralProfile\n } = profile\n let resources: AgentProfile['resources'] | undefined\n if (profileResources) {\n const { instructions: _instructions, ...fileBackedResources } = profileResources\n resources = fileBackedResources\n }\n return {\n ...structuralProfile,\n ...(resources ? { resources } : {}),\n }\n}\n\nfunction assertSupportedWorktreeProfile(profile: AgentProfile, harness: LocalHarness): void {\n assertProfileMaterialization({\n contract: worktreeCliProfileMaterialization,\n changedAxes: profileMaterializationAxes(profile),\n context: 'runWorktreeHarness',\n })\n // `profile.harness` is only a preference and the explicit run option wins. The contract above\n // rejects routing-only model hints and `resources.failOnError`; this check refuses an axis the\n // chosen harness's own capability row cannot express, so the refusal lands before any worktree\n // exists and cannot drift from the argv the invocation would build.\n const unsupportedAxes: string[] = []\n const reasoningEffort = profile.model?.reasoningEffort\n if (reasoningEffort !== undefined && !harnessSupportsReasoningEffort(harness, reasoningEffort)) {\n unsupportedAxes.push('model.reasoningEffort')\n }\n if (unsupportedAxes.length > 0) {\n throw new Error(\n `runWorktreeHarness: profile requests unsupported worktree behavior: ${unsupportedAxes.join(', ')}`,\n )\n }\n}\n\nfunction assertSafeMaterializedPaths(plan: WorkspacePlan): void {\n for (const file of plan.files) {\n if (file.relPath.split('/').some(isGitMetadataSegment)) {\n throw new Error(\n `runWorktreeHarness: profile file cannot target reserved Git metadata: ${file.relPath}`,\n )\n }\n }\n}\n\nfunction assertSafeProfileResourcePaths(profile: AgentProfile): void {\n for (const file of profile.resources?.files ?? []) {\n if (file.path.split('/').some(isGitMetadataSegment)) {\n throw new Error(\n `runWorktreeHarness: profile file cannot target reserved Git metadata: ${file.path}`,\n )\n }\n }\n}\n\nfunction isGitMetadataSegment(segment: string): boolean {\n const windowsCanonical = segment.replace(/[ .]+$/u, '').toLowerCase()\n return windowsCanonical === '.git' || windowsCanonical.startsWith('.git:')\n}\n\nfunction profileMaterializationReceipt(\n applied: WorkspacePlanReceipt,\n resourceInstructions: string | undefined,\n): WorktreeProfileMaterializationReceipt {\n return {\n workspacePlanDigest: applied.workspacePlanDigest,\n writtenPaths: [...applied.written],\n unsupported: [...applied.unsupported],\n environmentNames: Object.keys(applied.env).sort(),\n flags: applied.flags.map(publicPlanString),\n resourceInstructions: resourceInstructionReceipt(resourceInstructions),\n }\n}\n\nfunction resourceInstructionReceipt(\n resourceInstructions: string | undefined,\n): WorktreeProfileMaterializationReceipt['resourceInstructions'] {\n if (resourceInstructions === undefined) {\n return { delivery: 'none', sha256: null, byteLength: 0 }\n }\n const instructionBytes = Buffer.from(resourceInstructions, 'utf8')\n return {\n delivery: 'invocation-prompt',\n sha256: `sha256:${createHash('sha256').update(instructionBytes).digest('hex')}`,\n byteLength: instructionBytes.byteLength,\n }\n}\n\n/** Run the configured test + typecheck commands in the live worktree, projecting exit codes into\n * `checks`. Returns `undefined` when neither was configured (so the result omits `checks`). */\nexport async function runWorktreeChecks(opts: {\n worktreePath: string\n testCmd?: string\n typecheckCmd?: string\n timeoutMs: number\n cap: number\n runCommand?: WorktreeCheckRunner\n signal?: AbortSignal\n}): Promise<WorktreeHarnessResult['checks'] | undefined> {\n opts.signal?.throwIfAborted()\n if (opts.testCmd === undefined && opts.typecheckCmd === undefined) return undefined\n const runCommand = opts.runCommand ?? defaultRunCommand\n const run = async (command: string): Promise<WorktreeCommandResult> => {\n opts.signal?.throwIfAborted()\n const res = await runCommand({\n command,\n cwd: opts.worktreePath,\n timeoutMs: opts.timeoutMs,\n ...(opts.signal ? { signal: opts.signal } : {}),\n })\n opts.signal?.throwIfAborted()\n return {\n command,\n passed: res.exitCode === 0,\n exitCode: res.exitCode,\n output: res.output.length > opts.cap ? res.output.slice(-opts.cap) : res.output,\n }\n }\n const checks: NonNullable<WorktreeHarnessResult['checks']> = {}\n if (opts.testCmd !== undefined) checks.tests = await run(opts.testCmd)\n opts.signal?.throwIfAborted()\n if (opts.typecheckCmd !== undefined) checks.typecheck = await run(opts.typecheckCmd)\n opts.signal?.throwIfAborted()\n return checks\n}\n\ninterface SettledCommandResult {\n exitCode: number | null\n stdout: string\n stderr: string\n killedBySignal: NodeJS.Signals | null\n timedOut: boolean\n}\n\n/** Internal argv-safe process runner shared by worktree checks and improvement verifiers. */\nexport async function runSettledCommand(opts: {\n command: string\n args?: string[]\n cwd: string\n timeoutMs: number\n signal?: AbortSignal\n}): Promise<SettledCommandResult> {\n opts.signal?.throwIfAborted()\n return new Promise((resolve, reject) => {\n const child = spawn(opts.command, opts.args ?? [], {\n cwd: opts.cwd,\n stdio: ['ignore', 'pipe', 'pipe'],\n detached: process.platform !== 'win32',\n })\n const stdout: string[] = []\n const stderr: string[] = []\n let settled = false\n let leaderClosed = false\n let timedOut = false\n let termination: Promise<void> | null = null\n const terminate = (): Promise<void> => {\n termination ??= terminateProcessTreeAndConfirm(child, () => leaderClosed, 'defaultRunCommand')\n return termination\n }\n const timer = setTimeout(() => {\n timedOut = true\n void terminate().catch(fail)\n }, opts.timeoutMs)\n const onAbort = () => void terminate().catch(fail)\n if (opts.signal) {\n if (opts.signal.aborted) onAbort()\n else opts.signal.addEventListener('abort', onAbort, { once: true })\n }\n child.stdout?.on('data', (d) => stdout.push(String(d)))\n child.stderr?.on('data', (d) => stderr.push(String(d)))\n const finish = (fn: () => void) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n opts.signal?.removeEventListener('abort', onAbort)\n fn()\n }\n function fail(err: unknown): void {\n finish(() => reject(err instanceof Error ? err : new Error(String(err))))\n }\n child.on('error', (err) => {\n leaderClosed = true\n void (termination ?? Promise.resolve()).then(() => fail(err), fail)\n })\n child.on('close', (code, killedBySignal) => {\n leaderClosed = true\n void (async () => {\n try {\n await (termination ?? terminate())\n opts.signal?.throwIfAborted()\n finish(() =>\n resolve({\n exitCode: code,\n stdout: stdout.join(''),\n stderr: stderr.join(''),\n killedBySignal,\n timedOut,\n }),\n )\n } catch (err) {\n fail(err)\n }\n })()\n })\n })\n}\n\n/** Default verification-command runner — `/bin/sh -c <command>` in the worktree, capturing\n * combined stdout+stderr. Never throws on a non-zero exit (that IS the fail signal); spawn\n * failures and caller cancellation reject. Timeout terminates and confirms the whole process\n * group before returning. */\nexport async function defaultRunCommand(opts: {\n command: string\n cwd: string\n timeoutMs: number\n signal?: AbortSignal\n}): Promise<{ exitCode: number | null; output: string }> {\n const result = await runSettledCommand({\n command: '/bin/sh',\n args: ['-c', opts.command],\n cwd: opts.cwd,\n timeoutMs: opts.timeoutMs,\n ...(opts.signal ? { signal: opts.signal } : {}),\n })\n return { exitCode: result.exitCode, output: result.stdout + result.stderr }\n}\n","/**\n *\n * Sanitization for runtime telemetry. The rule: nothing user-controlled leaks\n * unless the caller opts in with a `RuntimeTelemetryOptions` flag. This is the\n * envelope that ends up in `agent_run.metadata.runtimeEvents` on every\n * consumer, so the default must be safe.\n *\n * @stable\n */\n\nimport type {\n ControlEvalResult,\n ControlRunResult,\n ControlStep,\n DataAcquisitionPlan,\n KnowledgeReadinessReport,\n KnowledgeRequirement,\n UserQuestion,\n} from '@tangle-network/agent-eval'\n\nimport type {\n AgentRuntimeEvent,\n AgentTaskSpec,\n AgentTaskStatus,\n RuntimeSession,\n RuntimeStreamEvent,\n} from './types'\n\n/** @stable */\nexport interface RuntimeTelemetryOptions {\n /**\n * Include raw task inputs. Off by default because task inputs often contain\n * customer facts, credentials, source text, or internal IDs.\n */\n includeInputs?: boolean\n /** Include requirement descriptions. Secret requirements are always redacted. */\n includeRequirementDescriptions?: boolean\n /** Include evidence IDs. Off by default; counts are safer for shared reports. */\n includeEvidenceIds?: boolean\n /** Include user answers from question preflight. Off by default. */\n includeUserAnswers?: boolean\n /** Include action payloads and action results for control steps. Off by default. */\n includeControlPayloads?: boolean\n /** Include task metadata. Off by default because metadata may carry IDs or policy internals. */\n includeMetadata?: boolean\n /** Include eval detail/evidence strings. Off by default because validators may echo private input. */\n includeEvalDetails?: boolean\n}\n\n/** @stable */\nexport interface SanitizedKnowledgeRequirement {\n id: string\n description?: string\n requiredFor: string[]\n category: KnowledgeRequirement['category']\n acquisitionMode: KnowledgeRequirement['acquisitionMode']\n importance: KnowledgeRequirement['importance']\n freshness: KnowledgeRequirement['freshness']\n sensitivity: KnowledgeRequirement['sensitivity']\n confidenceNeeded: number\n currentConfidence: number\n evidenceCount: number\n evidenceIds?: string[]\n fallbackPolicy: KnowledgeRequirement['fallbackPolicy']\n}\n\n/** @stable */\nexport interface SanitizedKnowledgeReadinessReport {\n taskId: string\n readinessScore: number\n recommendedAction: KnowledgeReadinessReport['recommendedAction']\n severity: KnowledgeReadinessReport['severity']\n reason: string\n blockingMissingRequirements: SanitizedKnowledgeRequirement[]\n nonBlockingGaps: SanitizedKnowledgeRequirement[]\n evidenceCount: number\n evidenceIds?: string[]\n missingRequirementIds: string[]\n}\n\n/** Strip PII and large blobs from a `KnowledgeReadinessReport` for safe telemetry emission. @stable */\nexport function sanitizeKnowledgeReadinessReport(\n report: KnowledgeReadinessReport,\n options: RuntimeTelemetryOptions = {},\n): SanitizedKnowledgeReadinessReport {\n return {\n taskId: report.taskId,\n readinessScore: report.readinessScore,\n recommendedAction: report.recommendedAction,\n severity: report.severity,\n reason: report.reason,\n blockingMissingRequirements: report.blockingMissingRequirements.map((requirement) =>\n sanitizeKnowledgeRequirement(requirement, options),\n ),\n nonBlockingGaps: report.nonBlockingGaps.map((requirement) =>\n sanitizeKnowledgeRequirement(requirement, options),\n ),\n evidenceCount: report.bundle.evidenceIds.length,\n evidenceIds: options.includeEvidenceIds ? report.bundle.evidenceIds : undefined,\n missingRequirementIds: report.bundle.missing.map((requirement) => requirement.id),\n }\n}\n\n/** Reduce an `AgentRuntimeEvent` to a PII-safe, serializable plain object for telemetry. @stable */\nexport function sanitizeAgentRuntimeEvent<\n TState,\n TAction,\n TActionResult,\n TEval extends ControlEvalResult,\n>(\n event: AgentRuntimeEvent<TState, TAction, TActionResult, TEval>,\n options: RuntimeTelemetryOptions = {},\n): Record<string, unknown> {\n const base = { type: event.type, task: sanitizeTask(event.task, options) }\n if (\n event.type === 'readiness_start' ||\n event.type === 'task_start' ||\n event.type === 'control_start'\n ) {\n return event.type === 'control_start'\n ? { ...base, knowledge: sanitizeKnowledgeReadinessReport(event.knowledge, options) }\n : base\n }\n if (event.type === 'readiness_end') {\n return { ...base, knowledge: sanitizeKnowledgeReadinessReport(event.knowledge, options) }\n }\n if (event.type === 'questions_start') {\n return {\n ...base,\n questions: event.questions.map((question) => sanitizeQuestion(question, options)),\n }\n }\n if (event.type === 'questions_end') {\n return {\n ...base,\n questions: event.questions.map((question) => sanitizeQuestion(question, options)),\n userAnswers: options.includeUserAnswers ? event.userAnswers : redactRecord(event.userAnswers),\n }\n }\n if (event.type === 'acquisition_start') {\n return { ...base, acquisitionPlans: event.acquisitionPlans.map(sanitizeAcquisitionPlan) }\n }\n if (event.type === 'acquisition_end') {\n return {\n ...base,\n acquisitionPlans: event.acquisitionPlans.map(sanitizeAcquisitionPlan),\n acquiredEvidenceCount: event.acquiredEvidenceIds.length,\n acquiredEvidenceIds: options.includeEvidenceIds ? event.acquiredEvidenceIds : undefined,\n }\n }\n if (event.type === 'control_step') {\n return { ...base, step: sanitizeControlStep(event.step, options) }\n }\n if (event.type === 'control_end') {\n return { ...base, control: sanitizeControlRun(event.control, options) }\n }\n return { ...base, status: event.status, reason: event.reason }\n}\n\n/** Reduce a `RuntimeStreamEvent` to a PII-safe, serializable plain object for telemetry. @stable */\nexport function sanitizeRuntimeStreamEvent(\n event: RuntimeStreamEvent,\n options: RuntimeTelemetryOptions = {},\n): Record<string, unknown> {\n const withTask = 'task' in event && event.task ? { task: sanitizeTask(event.task, options) } : {}\n const withSession =\n 'session' in event && event.session\n ? { session: sanitizeRuntimeSession(event.session, options) }\n : {}\n\n if (event.type === 'readiness_end') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n decision: event.decision,\n knowledge: sanitizeKnowledgeReadinessReport(event.knowledge, options),\n }\n }\n if (event.type === 'questions_start') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n questions: event.questions.map((question) => sanitizeQuestion(question, options)),\n }\n }\n if (event.type === 'questions_end') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n questions: event.questions.map((question) => sanitizeQuestion(question, options)),\n userAnswers: options.includeUserAnswers ? event.userAnswers : redactRecord(event.userAnswers),\n }\n }\n if (event.type === 'acquisition_start') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n acquisitionPlans: event.acquisitionPlans.map(sanitizeAcquisitionPlan),\n }\n }\n if (event.type === 'acquisition_end') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n acquisitionPlans: event.acquisitionPlans.map(sanitizeAcquisitionPlan),\n acquiredEvidenceCount: event.acquiredEvidenceIds.length,\n acquiredEvidenceIds: options.includeEvidenceIds ? event.acquiredEvidenceIds : undefined,\n }\n }\n if (event.type === 'tool_call') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n toolName: event.toolName,\n toolCallId: event.toolCallId,\n args: options.includeControlPayloads ? event.args : undefined,\n }\n }\n if (event.type === 'tool_result') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n toolName: event.toolName,\n toolCallId: event.toolCallId,\n result: options.includeControlPayloads ? event.result : undefined,\n }\n }\n if (event.type === 'llm_call') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n model: event.model,\n tokensIn: event.tokensIn,\n tokensOut: event.tokensOut,\n costUsd: event.costUsd,\n latencyMs: event.latencyMs,\n finishReason: event.finishReason,\n }\n }\n if (event.type === 'artifact') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n artifactId: event.artifactId,\n name: event.name,\n mimeType: event.mimeType,\n uri: options.includeEvidenceIds ? event.uri : undefined,\n content: options.includeControlPayloads ? event.content : undefined,\n metadata: options.includeMetadata ? event.metadata : undefined,\n }\n }\n if (event.type === 'proposal_created') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n proposalId: event.proposalId,\n title: options.includeControlPayloads ? event.title : undefined,\n content: options.includeControlPayloads ? event.content : undefined,\n status: event.status,\n }\n }\n if (event.type === 'final') {\n // Surface error `kind` + `status` always — operators need failure\n // classification regardless of telemetry payload opt-in. `body` follows\n // the same gating as raw payloads (`includeControlPayloads`) because it\n // can echo user-visible text from the upstream provider's error page.\n const sanitizedError =\n event.error !== undefined\n ? {\n kind: event.error.kind,\n message: event.error.message,\n status: event.error.status,\n body: options.includeControlPayloads ? event.error.body : undefined,\n }\n : undefined\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n status: event.status,\n reason: event.reason,\n text: options.includeControlPayloads ? event.text : undefined,\n metadata: options.includeMetadata ? event.metadata : undefined,\n ...(sanitizedError !== undefined ? { error: sanitizedError } : {}),\n }\n }\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: 'timestamp' in event ? event.timestamp : undefined,\n ...pickPublicStreamFields(event),\n }\n}\n\nfunction sanitizeTask(\n task: AgentTaskSpec,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n return {\n id: task.id,\n intent: task.intent,\n domain: task.domain,\n inputs: options.includeInputs ? task.inputs : task.inputs ? '[redacted]' : undefined,\n requiredKnowledge: task.requiredKnowledge?.map((requirement) =>\n sanitizeKnowledgeRequirement(requirement, options),\n ),\n metadata: options.includeMetadata ? task.metadata : task.metadata ? '[redacted]' : undefined,\n }\n}\n\nfunction sanitizeRuntimeSession(\n session: RuntimeSession,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n return {\n id: session.id,\n backend: session.backend,\n status: session.status,\n hasResumeToken: Boolean(session.resumeToken),\n createdAt: session.createdAt,\n updatedAt: session.updatedAt,\n metadata: options.includeMetadata\n ? session.metadata\n : session.metadata\n ? '[redacted]'\n : undefined,\n }\n}\n\nfunction sanitizeKnowledgeRequirement(\n requirement: KnowledgeRequirement,\n options: RuntimeTelemetryOptions,\n): SanitizedKnowledgeRequirement {\n const includeDescription =\n options.includeRequirementDescriptions && requirement.sensitivity !== 'secret'\n return {\n id: requirement.id,\n description: includeDescription ? requirement.description : undefined,\n requiredFor: requirement.requiredFor,\n category: requirement.category,\n acquisitionMode: requirement.acquisitionMode,\n importance: requirement.importance,\n freshness: requirement.freshness,\n sensitivity: requirement.sensitivity,\n confidenceNeeded: requirement.confidenceNeeded,\n currentConfidence: requirement.currentConfidence,\n evidenceCount: requirement.evidenceIds.length,\n evidenceIds: options.includeEvidenceIds ? requirement.evidenceIds : undefined,\n fallbackPolicy: requirement.fallbackPolicy,\n }\n}\n\nfunction sanitizeQuestion(\n question: UserQuestion,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n return {\n id: question.id,\n question:\n options.includeRequirementDescriptions && question.answerType !== 'credential'\n ? question.question\n : undefined,\n reason: options.includeRequirementDescriptions ? question.reason : undefined,\n requirementId: question.requirementId,\n importance: question.importance,\n answerType: question.answerType,\n impactIfUnknown: options.includeRequirementDescriptions ? question.impactIfUnknown : undefined,\n optionCount: question.options?.length ?? 0,\n }\n}\n\nfunction sanitizeAcquisitionPlan(plan: DataAcquisitionPlan): Record<string, unknown> {\n return {\n id: plan.id,\n requirementIds: plan.requirementIds,\n mode: plan.mode,\n priority: plan.priority,\n expectedEvidenceCount: plan.expectedEvidenceIds?.length ?? 0,\n questionCount: plan.questions?.length ?? 0,\n }\n}\n\nfunction sanitizeControlStep<TState, TAction, TActionResult, TEval extends ControlEvalResult>(\n step: ControlStep<TState, TAction, TActionResult, TEval>,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n const actionOutcome = step.actionOutcome\n return {\n index: step.index,\n decisionType: step.decision.type,\n reason: step.decision.reason,\n action:\n options.includeControlPayloads && step.decision.type === 'continue'\n ? step.decision.action\n : undefined,\n result: options.includeControlPayloads && actionOutcome?.ok ? actionOutcome.result : undefined,\n actionOk: actionOutcome?.ok,\n actionError: actionOutcome?.ok === false ? actionOutcome.error : undefined,\n durationMs: actionOutcome?.durationMs,\n evalsBefore: summarizeEvals(step.evalsBefore, options),\n evalsAfter: summarizeEvals(step.evalsAfter, options),\n startedAt: step.startedAt,\n endedAt: step.endedAt,\n }\n}\n\nfunction sanitizeControlRun<TState, TAction, TActionResult, TEval extends ControlEvalResult>(\n control: ControlRunResult<TState, TAction, TActionResult, TEval>,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n return {\n pass: control.pass,\n completed: control.completed,\n reason: control.reason,\n score: control.score,\n stepCount: control.steps.length,\n wallMs: control.wallMs,\n spentCostUsd: control.spentCostUsd,\n failureClass: control.failureClass,\n stoppedBy: control.stoppedBy,\n runId: control.runId,\n runtimeErrorCount: control.runtimeErrors.length,\n finalEvals: summarizeEvals(control.finalEvals, options),\n }\n}\n\nfunction summarizeEvals(\n evals: ControlEvalResult[],\n options: RuntimeTelemetryOptions,\n): Array<Record<string, unknown>> {\n return evals.map((evalResult) => ({\n id: evalResult.id,\n passed: evalResult.passed,\n score: evalResult.score,\n severity: evalResult.severity,\n objective: evalResult.objective,\n detail: options.includeEvalDetails ? evalResult.detail : undefined,\n evidence: options.includeEvalDetails ? evalResult.evidence : undefined,\n }))\n}\n\nfunction redactRecord(record: Record<string, string>): Record<string, string> {\n return Object.fromEntries(Object.keys(record).map((key) => [key, '[redacted]']))\n}\n\nfunction pickPublicStreamFields(event: RuntimeStreamEvent): Record<string, unknown> {\n if (event.type === 'session_created' || event.type === 'session_resumed') return {}\n if (event.type === 'backend_start' || event.type === 'backend_end')\n return { backend: event.backend }\n if (event.type === 'backend_error') {\n // `error.body` is the truncated upstream response — it can carry\n // user-visible text (a `free_tier_limit` envelope is safe, but an HTML\n // error page from a misconfigured proxy may echo the request URL with\n // query string). Redact body by default; surface `kind` + `status` so\n // operators can still classify the failure without raw text.\n const sanitizedError =\n event.error !== undefined\n ? {\n kind: event.error.kind,\n status: event.error.status,\n }\n : undefined\n return {\n backend: event.backend,\n message: event.message,\n recoverable: event.recoverable,\n ...(sanitizedError !== undefined ? { error: sanitizedError } : {}),\n }\n }\n if (event.type === 'task_end') return { status: event.status, reason: event.reason }\n if (event.type === 'text_delta' || event.type === 'reasoning_delta') return { text: event.text }\n return {}\n}\n\n/** @stable */\nexport interface RuntimeEventCollector<\n TState = unknown,\n TAction = unknown,\n TActionResult = unknown,\n TEval extends ControlEvalResult = ControlEvalResult,\n> {\n onEvent: (event: AgentRuntimeEvent<TState, TAction, TActionResult, TEval>) => void\n events: Array<Record<string, unknown>>\n}\n\n/** @stable */\nexport type RuntimeStreamEventSink = (event: RuntimeStreamEvent) => void\n\n/** @stable */\nexport interface RuntimeStreamEventSummary {\n /** Total count of sanitized events collected. */\n eventCount: number\n /** Count of events per `type`. Useful for log-line summaries. */\n eventCountsByType: Record<string, number>\n /** First session id observed in a `session_created` / `session_resumed` event, if any. */\n firstSessionId?: string\n /** Last `final` event's status, if a final event was observed. */\n finalStatus?: AgentTaskStatus\n /** Last `final` event's reason, if a final event was observed. */\n finalReason?: string\n /** Concatenated `text_delta.text` across the stream, even when payloads are redacted. */\n finalText: string\n}\n\n/** @stable */\nexport interface RuntimeStreamEventCollector {\n onEvent: RuntimeStreamEventSink\n events: Array<Record<string, unknown>>\n /** Snapshot of a small streaming-flavored summary derived from collected events. */\n summary(): RuntimeStreamEventSummary\n}\n\n/** Build an in-memory collector that sanitizes and accumulates `AgentRuntimeEvent`s for inspection. @stable */\nexport function createRuntimeEventCollector<\n TState = unknown,\n TAction = unknown,\n TActionResult = unknown,\n TEval extends ControlEvalResult = ControlEvalResult,\n>(\n options: RuntimeTelemetryOptions = {},\n): RuntimeEventCollector<TState, TAction, TActionResult, TEval> {\n const events: Array<Record<string, unknown>> = []\n return {\n events,\n onEvent: (event) => {\n events.push(sanitizeAgentRuntimeEvent(event, options))\n },\n }\n}\n\n/**\n *\n * Streaming-event counterpart of `createRuntimeEventCollector`. Pass each\n * event yielded by `runAgentTaskStream` through `onEvent` and read the\n * sanitized copies off `events`; the same `RuntimeTelemetryOptions` redaction\n * flags apply. Kept distinct from `createRuntimeEventCollector` because the\n * stream and non-stream event shapes overlap on `type` literals — dispatching\n * on `type` alone would misroute events.\n *\n * @stable\n */\nexport function createRuntimeStreamEventCollector(\n options: RuntimeTelemetryOptions = {},\n): RuntimeStreamEventCollector {\n const events: Array<Record<string, unknown>> = []\n const eventCountsByType: Record<string, number> = {}\n let firstSessionId: string | undefined\n let finalStatus: AgentTaskStatus | undefined\n let finalReason: string | undefined\n let finalText = ''\n return {\n events,\n onEvent: (event) => {\n events.push(sanitizeRuntimeStreamEvent(event, options))\n eventCountsByType[event.type] = (eventCountsByType[event.type] ?? 0) + 1\n if (event.type === 'text_delta') finalText += event.text\n if (\n !firstSessionId &&\n (event.type === 'session_created' || event.type === 'session_resumed')\n ) {\n firstSessionId = event.session.id\n }\n if (event.type === 'final') {\n finalStatus = event.status\n finalReason = event.reason\n }\n },\n summary() {\n return {\n eventCount: events.length,\n eventCountsByType: { ...eventCountsByType },\n firstSessionId,\n finalStatus,\n finalReason,\n finalText,\n }\n },\n }\n}\n","/**\n * OTEL span exporter — streams LoopTraceEvents to an OTLP/HTTP collector.\n *\n * Reads OTEL_EXPORTER_OTLP_ENDPOINT + OTEL_EXPORTER_OTLP_HEADERS from env\n * when no explicit config is given. Keeps the runtime dep-free from\n * @opentelemetry/sdk-trace-base — minimal OTLP/JSON serializer.\n *\n * The exporter accepts both raw OtelSpan objects and LoopTraceEvents\n * (which get converted to OTLP spans automatically).\n */\n\nimport { appendFileSync } from 'node:fs'\n\nimport { deriveHexId, isW3CSpanId, isW3CTraceId } from '@tangle-network/agent-trace-contract'\nimport { type RuntimeTelemetryOptions, sanitizeRuntimeStreamEvent } from './sanitize'\nimport type { RuntimeStreamEvent } from './types'\n\nexport interface OtelExportConfig {\n /** OTLP endpoint. Reads OTEL_EXPORTER_OTLP_ENDPOINT env by default. */\n endpoint?: string\n /** OTLP headers. Reads OTEL_EXPORTER_OTLP_HEADERS env by default. */\n headers?: Record<string, string>\n /** Batch size before flush. Default 64. */\n batchSize?: number\n /** Flush interval ms. Default 5000. */\n flushIntervalMs?: number\n /** Resource attributes stamped on every export. */\n resourceAttributes?: Record<string, string | number | boolean>\n /** Service name. Default 'agent-runtime'. */\n serviceName?: string\n}\n\nexport interface OtelExporter {\n /** Export a span. */\n exportSpan(span: OtelSpan): void\n /** Force flush pending spans. */\n flush(): Promise<void>\n /** Shutdown cleanly. */\n shutdown(): Promise<void>\n}\n\nexport interface OtelSpan {\n traceId: string\n spanId: string\n parentSpanId?: string\n name: string\n kind?: number\n startTimeUnixNano: string\n endTimeUnixNano: string\n attributes?: OtelAttribute[]\n status?: { code: number; message?: string }\n}\n\nexport interface OtelAttribute {\n key: string\n value: { stringValue?: string; intValue?: string; doubleValue?: number; boolValue?: boolean }\n}\n\ninterface OtlpResourceSpans {\n resource: { attributes: OtelAttribute[] }\n scopeSpans: Array<{ scope: { name: string; version: string }; spans: OtelSpan[] }>\n}\n\ninterface OtlpExport {\n resourceSpans: OtlpResourceSpans[]\n}\n\nconst SCOPE = { name: '@tangle-network/agent-runtime', version: '0.83.0' }\n\n/**\n * Current (non-deprecated) OpenTelemetry GenAI semantic-convention keys.\n * Registry: https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/\n * NB: `gen_ai.system` / `gen_ai.usage.prompt_tokens` / `completion_tokens` are\n * DEPRECATED — do not emit them. We use `provider.name` + `input/output_tokens`.\n */\nconst GEN_AI = {\n operation: 'gen_ai.operation.name',\n agentName: 'gen_ai.agent.name',\n conversationId: 'gen_ai.conversation.id',\n inputTokens: 'gen_ai.usage.input_tokens',\n outputTokens: 'gen_ai.usage.output_tokens',\n} as const\n\n/**\n * Create an exporter that APPENDS spans to a local OpenInference-JSONL file, one complete span per\n * line, instead of posting them to a collector.\n *\n * Why this exists beside {@link createOtelExporter}: that one needs an OTLP endpoint, so a run on a\n * laptop, in CI, or inside a sandbox with no collector emits nothing and its per-turn shape is\n * simply lost. The journal records the TREE (who spawned whom, what settled, what it spent); it\n * does not record what happened inside a turn. A run whose tree is readable but whose turns are not\n * is exactly the state that made an observability gap invisible until someone went looking.\n *\n * The line shape is the one `@tangle-network/traces` reads (`spans.otlp.jsonl`) and is a standard\n * OpenInference representation, so the same file feeds any OpenInference tool with no conversion:\n * snake_case identity fields, ISO-8601 times, `parent_span_id` empty at the root, and attributes as\n * a plain object rather than OTLP's key/value array.\n *\n * Appends synchronously per span so a killed process keeps every span it had already finished —\n * matching the spawn journal's durability posture, since a trace that only survives a clean exit is\n * useless for the runs you most want to look at.\n */\nexport function createOpenInferenceFileExporter(filePath: string): OtelExporter {\n const lines: string[] = []\n let failed: Error | undefined\n const append = (line: string): void => {\n try {\n appendFileSync(filePath, `${line}\\n`, 'utf8')\n } catch (error) {\n // Telemetry must never take the run down with it, but a silently dead exporter is how a\n // missing trace gets mistaken for an empty one. Remember the first failure and surface it\n // from flush(), where a caller is already awaiting an answer.\n failed ??= error instanceof Error ? error : new Error(String(error))\n }\n }\n return {\n exportSpan(span: OtelSpan): void {\n append(JSON.stringify(toOpenInferenceLine(span)))\n lines.push('')\n },\n async flush(): Promise<void> {\n if (failed)\n throw new Error(`OpenInference file exporter failed writing ${filePath}: ${failed.message}`)\n },\n async shutdown(): Promise<void> {\n lines.length = 0\n },\n }\n}\n\n/** OTLP's numeric status codes in the NAMES OpenInference requires. */\nconst OTEL_STATUS_NAME: Record<number, string> = { 0: 'UNSET', 1: 'OK', 2: 'ERROR' }\n\n/** Nanosecond string -> ISO-8601, the time format an OpenInference reader parses with `Date.parse`. */\nfunction nanosToIso(nanos: string): string {\n const ms = Number(BigInt(nanos) / 1_000_000n)\n return new Date(ms).toISOString()\n}\n\n/** OTLP's key/value attribute array -> the plain object OpenInference carries. */\nfunction attributesToObject(\n attributes: readonly OtelAttribute[] | undefined,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n for (const a of attributes ?? []) {\n const v = a.value\n out[a.key] =\n v.stringValue ??\n (v.intValue !== undefined ? Number(v.intValue) : undefined) ??\n v.doubleValue ??\n v.boolValue\n }\n return out\n}\n\n/** One `OtelSpan` as the OpenInference JSONL line `traces` and other OpenInference tools read. */\nfunction toOpenInferenceLine(span: OtelSpan): Record<string, unknown> {\n const attributes = attributesToObject(span.attributes)\n const kind = attributes['openinference.span.kind']\n const resource: Record<string, unknown> = {}\n for (const key of ['service.name', 'agent.name']) {\n if (attributes[key] !== undefined) resource[key] = attributes[key]\n }\n return {\n trace_id: span.traceId,\n span_id: span.spanId,\n // Empty string, not null: the root is spelled \"\" in this representation.\n parent_span_id: span.parentSpanId ?? '',\n name: span.name,\n kind: typeof kind === 'string' ? kind : 'CHAIN',\n start_time: nanosToIso(span.startTimeUnixNano),\n end_time: nanosToIso(span.endTimeUnixNano),\n // OpenInference spells status as a NAME, not OTLP's numeric code. Writing the number produced\n // a file a reader found and then refused: \"status.code must be OK, ERROR, UNSET, or its\n // STATUS_CODE_* form\" — the whole run's per-turn detail lost to one field.\n status: {\n code: OTEL_STATUS_NAME[span.status?.code ?? 0] ?? 'UNSET',\n ...(span.status?.message === undefined ? {} : { message: span.status.message }),\n },\n resource: { attributes: resource },\n scope: { name: 'agent-runtime', version: '' },\n attributes,\n }\n}\n\n/**\n * Create an OTEL exporter. Returns undefined when no endpoint is configured.\n */\nexport function createOtelExporter(config?: OtelExportConfig): OtelExporter | undefined {\n const resolvedEndpoint =\n config?.endpoint ??\n (typeof process !== 'undefined' ? process.env.OTEL_EXPORTER_OTLP_ENDPOINT : undefined)\n if (!resolvedEndpoint) return undefined\n const endpoint: string = resolvedEndpoint\n\n const headers = config?.headers ?? parseHeadersFromEnv()\n const batchSize = config?.batchSize ?? 64\n const flushIntervalMs = config?.flushIntervalMs ?? 5000\n const serviceName = config?.serviceName ?? 'agent-runtime'\n const resourceAttrs = config?.resourceAttributes ?? {}\n\n const pending: OtelSpan[] = []\n let timer: ReturnType<typeof setInterval> | undefined\n let stopped = false\n\n const exporter: OtelExporter = {\n exportSpan(span: OtelSpan): void {\n if (stopped) return\n pending.push(span)\n if (pending.length >= batchSize) {\n void doFlush()\n }\n },\n\n async flush(): Promise<void> {\n await doFlush()\n },\n\n async shutdown(): Promise<void> {\n stopped = true\n if (timer !== undefined) {\n clearInterval(timer)\n timer = undefined\n }\n await doFlush()\n },\n }\n\n timer = setInterval(() => {\n if (pending.length > 0) void doFlush()\n }, flushIntervalMs)\n if (typeof timer === 'object' && 'unref' in timer) {\n ;(timer as NodeJS.Timeout).unref()\n }\n\n async function doFlush(): Promise<void> {\n if (pending.length === 0) return\n const batch = pending.splice(0)\n const body: OtlpExport = {\n resourceSpans: [\n {\n resource: {\n attributes: toOtelAttributes({\n 'service.name': serviceName,\n ...resourceAttrs,\n }),\n },\n scopeSpans: [{ scope: SCOPE, spans: batch }],\n },\n ],\n }\n const url = `${endpoint.replace(/\\/+$/, '')}/v1/traces`\n try {\n await fetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...headers },\n body: JSON.stringify(body),\n })\n } catch {\n // Best-effort — telemetry export must not crash the runtime.\n }\n }\n\n return exporter\n}\n\n/**\n * Convert a LoopTraceEvent into an OtelSpan for export.\n */\nexport function loopEventToOtelSpan(\n event: {\n kind: string\n runId: string\n timestamp: number\n payload: object\n },\n traceId: string,\n parentSpanId?: string,\n): OtelSpan {\n const spanId = generateSpanId()\n const attrs: Record<string, string | number | boolean> = {\n 'loop.event_kind': event.kind,\n 'loop.run_id': event.runId,\n }\n for (const [k, v] of Object.entries(event.payload)) {\n if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {\n attrs[`loop.${k}`] = v\n }\n }\n const ts = msToNs(event.timestamp)\n return {\n traceId: padTraceId(traceId),\n spanId,\n parentSpanId: parentSpanId ? padSpanId(parentSpanId) : undefined,\n name: event.kind,\n kind: 1,\n startTimeUnixNano: ts,\n endTimeUnixNano: ts,\n attributes: toOtelAttributes(attrs),\n status: { code: 1 },\n }\n}\n\n/**\n * Build a single flat OtelSpan whose attribute keys are emitted VERBATIM — no\n * `loop.` namespace. Use for non-loop spans (e.g. the intelligence per-run\n * span) whose keys ARE the downstream contract (`gen_ai.request.model`,\n * `tangle.sessionId`) and are exact-matched by readers. `loopEventToOtelSpan`\n * namespaces payload keys because loop payload fields are free-form; do not\n * reuse it for spans with contract keys.\n */\nexport function flatOtelSpan(\n name: string,\n attributes: Record<string, string | number | boolean>,\n traceId: string,\n timestampMs: number,\n parentSpanId?: string,\n endTimestampMs = timestampMs,\n): OtelSpan {\n const start = msToNs(timestampMs)\n const end = msToNs(Math.max(timestampMs, endTimestampMs))\n return {\n traceId: padTraceId(traceId),\n spanId: generateSpanId(),\n parentSpanId: parentSpanId ? padSpanId(parentSpanId) : undefined,\n name,\n kind: 1,\n startTimeUnixNano: start,\n endTimeUnixNano: end,\n attributes: toOtelAttributes(attributes),\n status: { code: 1 },\n }\n}\n\nexport interface RuntimeEventOtelOptions extends RuntimeTelemetryOptions {\n /** Final customer redactor applied after the schema-aware runtime sanitizer. */\n redact?: (value: unknown) => unknown\n}\n\nfunction eventTimestampMs(event: RuntimeStreamEvent): number {\n if ('timestamp' in event && typeof event.timestamp === 'string') {\n const parsed = Date.parse(event.timestamp)\n if (Number.isFinite(parsed)) return parsed\n }\n return Date.now()\n}\n\nfunction serialized(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n\nfunction mcpIdentity(toolName: string): { server?: string; tool?: string } {\n if (!toolName.startsWith('mcp__')) return {}\n const [, server, ...toolParts] = toolName.split('__')\n return {\n ...(server ? { server } : {}),\n ...(toolParts.length > 0 ? { tool: toolParts.join('__') } : {}),\n }\n}\n\n/** Convert normalized runtime events into lossless, redacted child spans. */\nexport function buildRuntimeEventOtelSpans(\n events: ReadonlyArray<RuntimeStreamEvent>,\n traceId: string,\n parentSpanId?: string,\n options: RuntimeEventOtelOptions = {},\n): OtelSpan[] {\n return events.map((event) => {\n const sanitized = sanitizeRuntimeStreamEvent(event, options)\n const safe = options.redact ? options.redact(sanitized) : sanitized\n const record =\n safe && typeof safe === 'object' && !Array.isArray(safe)\n ? (safe as Record<string, unknown>)\n : { value: safe }\n const attrs: Record<string, string | number | boolean> = {\n 'tangle.runtime.event_type': event.type,\n 'tangle.runtime.event': serialized(record),\n }\n let name = `tangle.runtime.${event.type}`\n\n if (event.type === 'tool_call' || event.type === 'tool_result') {\n name = `agent.${event.type}`\n attrs['tool.name'] = event.toolName\n if (event.toolCallId) attrs['tool.call_id'] = event.toolCallId\n const mcp = mcpIdentity(event.toolName)\n if (mcp.server) attrs['mcp.server'] = mcp.server\n if (mcp.tool) attrs['mcp.tool.name'] = mcp.tool\n const payload = event.type === 'tool_call' ? record.args : record.result\n if (payload !== undefined) {\n attrs[event.type === 'tool_call' ? 'tool.input' : 'tool.output'] = serialized(payload)\n }\n } else if (event.type === 'llm_call') {\n name = 'gen_ai.client.inference'\n attrs['gen_ai.request.model'] = event.model\n if (event.tokensIn !== undefined) attrs['gen_ai.usage.input_tokens'] = event.tokensIn\n if (event.tokensOut !== undefined) attrs['gen_ai.usage.output_tokens'] = event.tokensOut\n if (event.costUsd !== undefined) attrs['tangle.cost.usd'] = event.costUsd\n if (event.latencyMs !== undefined) attrs['tangle.latency_ms'] = event.latencyMs\n if (event.finishReason !== undefined)\n attrs['gen_ai.response.finish_reasons'] = event.finishReason\n } else if (event.type === 'backend_error') {\n attrs['error.type'] = event.error?.kind ?? 'backend'\n attrs['error.message'] = event.message\n } else if (event.type === 'final') {\n attrs['tangle.outcome.status'] = event.status\n attrs['tangle.outcome.reason'] = event.reason\n if (event.error) {\n attrs['error.type'] = event.error.kind\n attrs['error.message'] = event.error.message\n }\n }\n\n const startMs = eventTimestampMs(event)\n const endMs =\n event.type === 'llm_call' && event.latencyMs !== undefined && Number.isFinite(event.latencyMs)\n ? startMs + event.latencyMs\n : startMs\n const span = flatOtelSpan(name, attrs, traceId, startMs, parentSpanId, endMs)\n if (\n event.type === 'backend_error' ||\n (event.type === 'final' && event.status !== 'completed')\n ) {\n span.status = { code: 2, message: attrs['error.message']?.toString() ?? event.type }\n }\n return span\n })\n}\n\n/**\n * Sink-neutral node in a reconstructed loop span tree. The root node's\n * `parentSpanId` is `undefined` — sinks decide how to parent it (the OTEL\n * mapper attaches the inherited delegation span; the delegation journal\n * leaves it as the tree root).\n */\nexport interface LoopSpanNode {\n spanId: string\n parentSpanId?: string\n /** `'loop'` | `'loop.round'` | `'loop.iteration'`. */\n name: string\n /** Topology level: loop root, plan round, or iteration branch. */\n kind: 'loop' | 'round' | 'branch'\n startMs: number\n endMs: number\n attrs: Record<string, string | number | boolean>\n /** True when the iteration carried an error — maps to OTEL status code 2. */\n error: boolean\n}\n\n/**\n * Build a nested, real-duration OTLP span tree for ONE loop run from its full\n * ordered `LoopTraceEvent` stream. Unlike `loopEventToOtelSpan` (one flat,\n * zero-duration span per event), this reconstructs the topology hierarchy a\n * GenAI trace viewer renders natively:\n *\n * loop (invoke_workflow)\n * └─ loop.round[k] (invoke_workflow) ← tangle.loop.move.{kind,width,rationale}\n * ├─ loop.iteration[i] (invoke_agent) ← gen_ai.agent.name + usage + verdict + placement\n * └─ …\n *\n * Attributes follow the current GenAI semconv (`gen_ai.*`) where they apply and\n * a namespaced `tangle.loop.*` / `tangle.cost.usd` extension for topology /\n * verdict / placement / cost (not yet standardized). Pure: feed it a buffered\n * per-runId event array (e.g. flushed on `loop.ended`) and export the result.\n */\nexport function buildLoopOtelSpans(\n events: ReadonlyArray<{ kind: string; runId: string; timestamp: number; payload: object }>,\n traceId: string,\n rootParentSpanId?: string,\n): OtelSpan[] {\n const tid = padTraceId(traceId)\n return buildLoopSpanNodes(events).map((node) => ({\n traceId: tid,\n spanId: node.spanId,\n parentSpanId: node.parentSpanId\n ? padSpanId(node.parentSpanId)\n : rootParentSpanId\n ? padSpanId(rootParentSpanId)\n : undefined,\n name: node.name,\n kind: 1,\n startTimeUnixNano: msToNs(node.startMs),\n endTimeUnixNano: msToNs(node.endMs),\n attributes: toOtelAttributes(node.attrs),\n status: { code: node.error ? 2 : 1 },\n }))\n}\n\n/**\n * Sink-neutral core behind {@link buildLoopOtelSpans}: reconstruct the\n * loop → round → branch span tree from one run's ordered `LoopTraceEvent`\n * stream. Consumed by the OTEL mapper above and by the MCP delegation\n * journal's compact trace tee — one topology reconstruction, two sinks.\n * Tolerates partial streams (a run that never reached `loop.ended` closes\n * at the last observed event's timestamp).\n */\nexport function buildLoopSpanNodes(\n events: ReadonlyArray<{ kind: string; runId: string; timestamp: number; payload: object }>,\n): LoopSpanNode[] {\n if (events.length === 0) return []\n const out: LoopSpanNode[] = []\n const num = (v: unknown): number | undefined =>\n typeof v === 'number' && Number.isFinite(v) ? v : undefined\n const str = (v: unknown): string | undefined =>\n typeof v === 'string' && v.length > 0 ? v : undefined\n const rec = (v: unknown): Record<string, unknown> =>\n v && typeof v === 'object' ? (v as Record<string, unknown>) : {}\n\n const started = events.find((e) => e.kind === 'loop.started')\n const ended = events.find((e) => e.kind === 'loop.ended')\n const runId = events[0]?.runId ?? ''\n const rootStart = started?.timestamp ?? events[0]!.timestamp\n const rootEnd = ended?.timestamp ?? events[events.length - 1]!.timestamp\n const rootId = generateSpanId()\n\n const make = (\n spanId: string,\n parentSpanId: string | undefined,\n name: string,\n kind: LoopSpanNode['kind'],\n startMs: number,\n endMs: number,\n attrs: Record<string, string | number | boolean>,\n error = false,\n ): LoopSpanNode => ({\n spanId,\n parentSpanId,\n name,\n kind,\n startMs,\n endMs,\n attrs,\n error,\n })\n\n // root\n const sp = rec(started?.payload)\n const rootAttrs: Record<string, string | number | boolean> = {\n [GEN_AI.operation]: 'invoke_workflow',\n [GEN_AI.conversationId]: runId,\n // Explicit run identity under the tangle namespace so a consuming system of\n // record (Tangle Intelligence's run spine) maps this span tree to one run\n // deterministically, instead of inferring it from the conversation id.\n 'tangle.run.id': runId,\n 'tangle.loop.driver': str(sp.driver) ?? 'driver',\n }\n if (Array.isArray(sp.agentRunNames) && sp.agentRunNames.length > 0) {\n rootAttrs['tangle.loop.agents'] = sp.agentRunNames.map(String).join(',')\n // Subject grain: the primary agent/profile this run drove. Lets the spine\n // group runs under the thing being worked on rather than one service-wide\n // bucket. `agentRunNames[0]` is the lead agent on a fan-out.\n rootAttrs['tangle.subject.key'] = String(sp.agentRunNames[0])\n }\n if (ended) {\n const ep = rec(ended.payload)\n const win = num(ep.winnerIterationIndex)\n if (win !== undefined) rootAttrs['tangle.loop.winner.iteration_index'] = win\n const cost = num(ep.totalCostUsd)\n if (cost !== undefined) rootAttrs['tangle.cost.usd'] = cost\n const dur = num(ep.durationMs)\n if (dur !== undefined) rootAttrs['tangle.loop.duration_ms'] = dur\n const iters = num(ep.iterations)\n if (iters !== undefined) rootAttrs['tangle.loop.iterations'] = iters\n }\n out.push(make(rootId, undefined, 'loop', 'loop', rootStart, rootEnd, rootAttrs))\n\n // rounds + iterations\n const iterStartTs = new Map<number, number>()\n const placementByIdx = new Map<number, Record<string, string>>()\n let currentRoundId: string | undefined\n let pendingRound:\n | { id: string; start: number; attrs: Record<string, string | number | boolean> }\n | undefined\n const flushRound = (endMs: number) => {\n if (!pendingRound) return\n out.push(\n make(\n pendingRound.id,\n rootId,\n 'loop.round',\n 'round',\n pendingRound.start,\n endMs,\n pendingRound.attrs,\n ),\n )\n pendingRound = undefined\n }\n\n for (const e of events) {\n const p = rec(e.payload)\n switch (e.kind) {\n case 'loop.plan': {\n flushRound(e.timestamp)\n const id = generateSpanId()\n const roundIdx = num(p.roundIndex) ?? 0\n const attrs: Record<string, string | number | boolean> = {\n [GEN_AI.operation]: 'invoke_workflow',\n 'tangle.loop.round.index': roundIdx,\n 'tangle.loop.move.kind': str(p.moveKind) ?? 'unknown',\n 'tangle.loop.move.round': roundIdx,\n 'tangle.loop.move.width': num(p.plannedCount) ?? 0,\n }\n const r = str(p.rationale)\n if (r) attrs['tangle.loop.move.rationale'] = r\n const parent = num(p.parentIndex)\n if (parent !== undefined) attrs['tangle.loop.move.parent_index'] = parent\n if (Array.isArray(p.childIndices) && p.childIndices.length > 0) {\n attrs['tangle.loop.move.child_indices'] = p.childIndices.map(String).join(',')\n }\n pendingRound = { id, start: e.timestamp, attrs }\n currentRoundId = id\n break\n }\n case 'loop.iteration.started': {\n const idx = num(p.iterationIndex)\n if (idx !== undefined) iterStartTs.set(idx, e.timestamp)\n break\n }\n case 'loop.iteration.dispatch': {\n const idx = num(p.iterationIndex)\n if (idx === undefined) break\n const place: Record<string, string> = {}\n const kind = str(p.placement)\n if (kind) place['tangle.loop.placement.kind'] = kind\n const sid = str(p.sandboxId)\n if (sid) place['tangle.sandbox.id'] = sid\n const fid = str(p.fleetId)\n if (fid) place['tangle.fleet.id'] = fid\n const mid = str(p.machineId)\n if (mid) place['tangle.machine.id'] = mid\n placementByIdx.set(idx, place)\n break\n }\n case 'loop.iteration.ended': {\n const idx = num(p.iterationIndex) ?? 0\n const start = iterStartTs.get(idx) ?? e.timestamp\n const err = str(p.error)\n const attrs: Record<string, string | number | boolean> = {\n [GEN_AI.operation]: 'invoke_agent',\n 'tangle.loop.iteration.index': idx,\n }\n const agent = str(p.agentRunName)\n if (agent) attrs[GEN_AI.agentName] = agent\n const tu = rec(p.tokenUsage)\n const inTok = num(tu.input)\n if (inTok !== undefined) attrs[GEN_AI.inputTokens] = inTok\n const outTok = num(tu.output)\n if (outTok !== undefined) attrs[GEN_AI.outputTokens] = outTok\n const cost = num(p.costUsd)\n if (cost !== undefined) attrs['tangle.cost.usd'] = cost\n const verdict = rec(p.verdict)\n if (typeof verdict.valid === 'boolean') attrs['tangle.loop.verdict.valid'] = verdict.valid\n const score = num(verdict.score)\n if (score !== undefined) attrs['tangle.loop.verdict.score'] = score\n if (err) attrs['tangle.loop.error'] = err\n const gid = num(p.groupId)\n if (gid !== undefined) attrs['tangle.loop.iteration.group_id'] = gid\n const par = num(p.parentIndex)\n if (par !== undefined) attrs['tangle.loop.iteration.parent_index'] = par\n const dur = num(p.durationMs)\n if (dur !== undefined) attrs['tangle.loop.iteration.duration_ms'] = dur\n const preview = str(p.outputPreview)\n if (preview) attrs['tangle.loop.iteration.output_preview'] = preview\n Object.assign(attrs, placementByIdx.get(idx) ?? {})\n out.push(\n make(\n generateSpanId(),\n currentRoundId ?? rootId,\n 'loop.iteration',\n 'branch',\n start,\n e.timestamp,\n attrs,\n err !== undefined,\n ),\n )\n break\n }\n case 'loop.decision': {\n if (pendingRound) {\n const dec = str(p.decision)\n if (dec) pendingRound.attrs['tangle.loop.decision'] = dec\n flushRound(e.timestamp)\n }\n currentRoundId = undefined\n break\n }\n }\n }\n flushRound(rootEnd)\n return out\n}\n\nfunction parseHeadersFromEnv(): Record<string, string> {\n if (typeof process === 'undefined') return {}\n const raw = process.env.OTEL_EXPORTER_OTLP_HEADERS\n if (!raw) return {}\n const out: Record<string, string> = {}\n for (const pair of raw.split(',')) {\n const eq = pair.indexOf('=')\n if (eq < 0) continue\n const key = pair.slice(0, eq).trim()\n const value = pair.slice(eq + 1).trim()\n if (key) out[key] = value\n }\n return out\n}\n\n/**\n * Convert a flat record into the OTLP attribute list. Non-finite numbers are DROPPED (an OTLP\n * `doubleValue` of `NaN`/`Infinity` is not representable), integers ride as `intValue`. Exported so\n * a producer that mints its own `OtelSpan` (the supervisor span recorder) builds attributes exactly\n * the way every span in this file does, rather than re-deriving the encoding.\n */\nexport function toOtelAttributes(\n record: Record<string, string | number | boolean>,\n): OtelAttribute[] {\n return Object.entries(record).flatMap(([key, value]) => {\n if (typeof value === 'number' && !Number.isFinite(value)) return []\n return [\n {\n key,\n value:\n typeof value === 'number'\n ? Number.isInteger(value)\n ? { intValue: value.toString() }\n : { doubleValue: value }\n : typeof value === 'boolean'\n ? { boolValue: value }\n : { stringValue: value },\n },\n ]\n })\n}\n\nfunction msToNs(ms: number): string {\n const safeMs = Number.isFinite(ms) ? ms : Date.now()\n return (BigInt(Math.floor(safeMs)) * 1_000_000n).toString()\n}\n\n/**\n * Map a caller-supplied span id onto the 16-hex OTLP encoding. An id that is already a valid W3C\n * span id passes through UNCHANGED — that is what lets an inherited `PARENT_SPAN_ID`/`TRACEPARENT`\n * id keep parenting the same trace. A DASHED hex id (a UUID-form id) passes through dash-stripped:\n * that is the exact wire id every earlier release exported for it, so cross-version joins survive\n * the strict-W3C upgrade. Anything else (a human run id) is DERIVED via the zero-dep contract's\n * `deriveHexId`, the one legal derivation: the old slice-and-pad produced ids that embedded the\n * raw input in the wire id and were not even valid hex (the contract's own `non-hex-id` validator\n * rejected what this module exported). Exported as the ONE wire-id normalization every writer\n * shares — `traceContextToEnv` builds the child's `TRACEPARENT` through these same functions, so\n * a parent's exported spans and the context it hands its children always name the same trace.\n */\nexport function padSpanId(id: string): string {\n if (isW3CSpanId(id)) return id\n const dashless = id.replace(/-/g, '')\n return isW3CSpanId(dashless) ? dashless : deriveHexId(id, 8)\n}\n\n/** Trace-id counterpart of {@link padSpanId}: valid W3C trace ids pass through (dash-stripped when\n * UUID-form, preserving the pre-strict-W3C wire id), everything else is derived with\n * `deriveHexId(id, 16)` so every process derives the SAME wire id for the same run. */\nexport function padTraceId(id: string): string {\n if (isW3CTraceId(id)) return id\n const dashless = id.replace(/-/g, '')\n return isW3CTraceId(dashless) ? dashless : deriveHexId(id, 16)\n}\n\n/** Mint a fresh 16-hex-character OTLP span id. Exported so a producer that must know a span's id\n * BEFORE the span closes (a node opened at spawn and parented by its children) uses this one\n * generator instead of a second copy of it. */\nexport function generateSpanId(): string {\n const bytes = new Uint8Array(8)\n if (typeof globalThis.crypto?.getRandomValues === 'function') {\n globalThis.crypto.getRandomValues(bytes)\n } else {\n for (let i = 0; i < 8; i++) bytes[i] = Math.floor(Math.random() * 256)\n }\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n// ─── Eval-run ingest (self-improvement provenance) ───────────────────────────\n//\n// Tangle Intelligence has a first-class, non-trace record for self-improvement\n// runs: POST /v1/ingest/eval-runs (\"Mode D\"). Each generation carries a\n// `surfaceHash` (the proposed-change identity) + arbitrary `surface` provenance;\n// a later `gate-decided` event re-emits the same `runId` (idempotent upsert) with\n// a real `gateDecision` + `holdoutLift`, so proposal→verdict is one diffable\n// record. This is how a consumer's RSI loop records WHAT it changed, WHY, from\n// which evidence — the audit trail behind agentic self-improvement.\n\n/** Wire version the eval-runs ingest enforces (X-Tangle-Wire-Version + body). */\nexport const INTELLIGENCE_WIRE_VERSION = '2026-05-26.v1'\n\nexport interface EvalRunGeneration {\n /** 0-based ordinal of this generation within the run (required by ingest). */\n index: number\n /** Identity of the proposed surface change (content-addressed hash). */\n surfaceHash: string\n /** Arbitrary provenance for this generation (rationale, evidence, source). */\n surface?: unknown\n /** Per-scenario results; empty until the generation is measured. */\n cells?: unknown[]\n /** Mean composite score (0 when unmeasured — pair with labels.measured). */\n compositeMean: number\n costUsd: number\n durationMs: number\n}\n\nexport interface EvalRunEvent {\n runId: string\n runDir: string\n /** ISO timestamp. */\n timestamp: string\n status:\n | 'started'\n | 'baseline-complete'\n | 'generation-complete'\n | 'gate-decided'\n | 'finished'\n | 'errored'\n labels?: Record<string, string>\n baseline?: EvalRunGeneration\n generations?: EvalRunGeneration[]\n gateDecision?: 'ship' | 'hold' | 'need_more_work' | 'model_ceiling' | 'arch_ceiling'\n holdoutLift?: number\n totalCostUsd: number\n totalDurationMs: number\n errorMessage?: string\n}\n\nexport interface EvalRunsExportConfig {\n /** Bearer key — tenant is resolved server-side from it. Reads TANGLE_API_KEY. */\n apiKey?: string\n /** Intelligence base. Reads TANGLE_INTELLIGENCE_URL env, else prod. */\n base?: string\n /** Idempotency-Key header (e.g. the runId) — safe retries + upsert. */\n idempotencyKey?: string\n}\n\nexport interface EvalRunsExportResult {\n ok: boolean\n status: number\n accepted: number\n rejected: Array<{ index: number; reason: string }>\n}\n\nconst DEFAULT_INTELLIGENCE_BASE = 'https://intelligence.tangle.tools'\n\n/**\n * Ship self-improvement eval-run events to Tangle Intelligence. Unlike the\n * best-effort span exporter, this RESOLVES with the ingest verdict (accepted /\n * rejected per event) so a consumer's loop can assert its provenance landed.\n * Throws only on a missing key or network failure.\n */\nexport async function exportEvalRuns(\n events: EvalRunEvent[],\n config?: EvalRunsExportConfig,\n): Promise<EvalRunsExportResult> {\n if (events.length === 0) return { ok: true, status: 0, accepted: 0, rejected: [] }\n const apiKey =\n config?.apiKey ?? (typeof process !== 'undefined' ? process.env.TANGLE_API_KEY : undefined)\n if (!apiKey)\n throw new Error('exportEvalRuns: apiKey required (pass config.apiKey or set TANGLE_API_KEY)')\n const base =\n config?.base ??\n (typeof process !== 'undefined' ? process.env.TANGLE_INTELLIGENCE_URL : undefined) ??\n DEFAULT_INTELLIGENCE_BASE\n const url = `${base.replace(/\\/+$/, '')}/v1/ingest/eval-runs`\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${apiKey}`,\n 'X-Tangle-Wire-Version': INTELLIGENCE_WIRE_VERSION,\n ...(config?.idempotencyKey ? { 'Idempotency-Key': config.idempotencyKey } : {}),\n },\n body: JSON.stringify({ wireVersion: INTELLIGENCE_WIRE_VERSION, events }),\n })\n let parsed: { accepted?: number; rejected?: Array<{ index: number; reason: string }> } = {}\n try {\n parsed = (await res.json()) as typeof parsed\n } catch {\n // non-JSON body (e.g. 5xx HTML) — leave parsed empty\n }\n return {\n ok: res.ok,\n status: res.status,\n accepted: parsed.accepted ?? (res.ok ? events.length : 0),\n rejected: parsed.rejected ?? [],\n }\n}\n","/**\n *\n * Trace context propagation across process-spawn boundaries.\n *\n * CANONICAL WIRE: the W3C `TRACEPARENT` environment variable\n * (`00-<32 hex trace id>-<16 hex span id>-<2 hex flags>`), the convention the wider ecosystem —\n * OTel SDKs, collectors, the Claude Code harness binary — already reads at spawn. The bespoke\n * `TRACE_ID` / `PARENT_SPAN_ID` pair this package shipped first is the FORK, not the standard:\n * it is still read as a fallback and still written alongside `TRACEPARENT` for one release, so\n * a child running either version of this package joins the same trace. The legacy pair is\n * scheduled for removal in the next major.\n *\n * read: TRACEPARENT first, then TRACE_ID / PARENT_SPAN_ID, else a fresh root.\n * write: BOTH — TRACEPARENT (+ TRACESTATE untouched) and TRACE_ID / PARENT_SPAN_ID.\n *\n * A fresh root minted because NO context reached this process is a severed hop, not a normal\n * start: it is marked `unpropagated: true` and every span tree it emits carries\n * `tangle.trace.unpropagated=true`, so a disconnected trace is a queryable fact instead of a\n * silent stranger.\n *\n * @experimental\n */\n\nimport { isW3CSpanId, isW3CTraceId } from '@tangle-network/agent-trace-contract'\nimport type { OtelExporter } from '../otel-export'\nimport { buildLoopOtelSpans, createOtelExporter, padSpanId, padTraceId } from '../otel-export'\nimport type { LoopTraceEmitter, LoopTraceEvent } from '../runtime/types'\n\nexport interface TraceContext {\n /** Trace id inherited from the parent process, or a fresh one. */\n traceId: string\n /** Parent span id from the delegation that launched this MCP server. */\n parentSpanId?: string\n /** True when NO context reached this process and the trace id is a fallback mint — the hop\n * above this process is severed. Span trees emitted under this context are stamped\n * `tangle.trace.unpropagated=true` so the severed hop is queryable. */\n unpropagated?: boolean\n}\n\n/** `00-<traceId>-<spanId>-<flags>`, any version prefix, case-insensitive per the W3C grammar. */\nconst TRACEPARENT_PATTERN = /^[0-9a-f]{2}-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/i\n\n/** Parse a W3C `traceparent` header/env value, or `undefined` when malformed. Fails closed: a\n * half-formed value yields no context rather than an unjoinable id. */\nexport function parseTraceparent(value: unknown): TraceContext | undefined {\n if (typeof value !== 'string') return undefined\n const match = TRACEPARENT_PATTERN.exec(value.trim())\n if (!match) return undefined\n const traceId = (match[1] as string).toLowerCase()\n const parentSpanId = (match[2] as string).toLowerCase()\n if (!isW3CTraceId(traceId) || !isW3CSpanId(parentSpanId)) return undefined\n return { traceId, parentSpanId }\n}\n\n/**\n * Read trace context from a process environment (defaults to `process.env`).\n * `TRACEPARENT` wins; the legacy `TRACE_ID` / `PARENT_SPAN_ID` pair is the fallback; with\n * neither present a fresh root is generated AND marked `unpropagated` — see {@link TraceContext}.\n */\nexport function readTraceContextFromEnv(\n env: Record<string, string | undefined> = process.env,\n): TraceContext {\n const fromTraceparent = parseTraceparent(env.TRACEPARENT)\n if (fromTraceparent) return fromTraceparent\n if (env.TRACE_ID) {\n return {\n traceId: env.TRACE_ID,\n ...(env.PARENT_SPAN_ID ? { parentSpanId: env.PARENT_SPAN_ID } : {}),\n }\n }\n return { traceId: generateTraceId(), unpropagated: true }\n}\n\n/**\n * Create a LoopTraceEmitter that:\n * 1. Parents all spans under the inherited parent span id.\n * 2. Exports spans to OTEL when OTEL_EXPORTER_OTLP_ENDPOINT is set.\n *\n * Returns both the emitter and the optional exporter handle for shutdown.\n */\nexport function createPropagatingTraceEmitter(ctx: TraceContext): {\n emitter: LoopTraceEmitter\n exporter: OtelExporter | undefined\n context: TraceContext\n} {\n const exporter = createOtelExporter()\n\n // Buffer events per loop run, then emit the full nested span tree on\n // `loop.ended` so the topology hierarchy (loop → round → branch) reaches the\n // OTLP collector — not a flat list of zero-duration point spans. A run that\n // never reaches `loop.ended` (hard abort) drops its buffer; acceptable for\n // the short-lived MCP subprocess.\n const buffers = new Map<string, LoopTraceEvent[]>()\n\n const emitter: LoopTraceEmitter = {\n emit(event: LoopTraceEvent) {\n if (!exporter) return\n const buf = buffers.get(event.runId)\n if (buf) buf.push(event)\n else buffers.set(event.runId, [event])\n if (event.kind === 'loop.ended') {\n const events = buffers.get(event.runId) ?? [event]\n buffers.delete(event.runId)\n for (const span of buildLoopOtelSpans(events, ctx.traceId, ctx.parentSpanId)) {\n // The child-side severed-hop marker: a fallback-minted root stamps every span it emits,\n // so a trace with no inbound link SAYS so instead of appearing as a stranger tree. The\n // human run id stays in `loop.run_id` / `tangle.run.id` where it was already searchable.\n exporter.exportSpan(\n ctx.unpropagated === true\n ? {\n ...span,\n attributes: [\n ...(span.attributes ?? []),\n { key: 'tangle.trace.unpropagated', value: { boolValue: true } },\n ],\n }\n : span,\n )\n }\n }\n },\n }\n\n return { emitter, exporter, context: ctx }\n}\n\n/**\n * Build env vars to pass to a child subprocess so it inherits the current trace context.\n *\n * Writes BOTH conventions (see the module doc): `TRACEPARENT` carries the W3C-hex ids — mapped\n * through the exporter's own `padTraceId`/`padSpanId` (dashed hex passes through dash-stripped, a\n * human id is derived through the contract's `deriveHexId`), the SAME normalization every emitted\n * span uses, so both spellings and the parent's own spans all name ONE trace — and the legacy\n * pair carries the caller's ids verbatim. `TRACEPARENT` needs a parent span id by grammar; when\n * the context has none, the legacy pair still propagates the trace id alone.\n */\nexport function traceContextToEnv(ctx: TraceContext): Record<string, string> {\n const env: Record<string, string> = { TRACE_ID: ctx.traceId }\n if (ctx.parentSpanId) env.PARENT_SPAN_ID = ctx.parentSpanId\n if (ctx.parentSpanId) {\n env.TRACEPARENT = `00-${padTraceId(ctx.traceId)}-${padSpanId(ctx.parentSpanId)}-01`\n }\n return env\n}\n\n/**\n * Merge a spawned child's environment from lowest to highest precedence — ambient env, the\n * recorder's stamped trace env, the caller's own overrides — while keeping the ONE cross-key\n * invariant a plain spread cannot: `TRACEPARENT` and the legacy pair must name the SAME trace.\n * A caller override that declares `TRACE_ID` / `PARENT_SPAN_ID` without its own `TRACEPARENT`\n * would otherwise keep the recorder's W3C wire — the child would join the caller's trace on the\n * legacy pair and the RECORDER's on the standard one. The dual-write is performed on the\n * caller's behalf: the merged `TRACEPARENT` is rebuilt from the merged legacy pair through the\n * same {@link traceContextToEnv} derivation (`deriveHexId` for human ids), or dropped when no\n * parent span id survives the merge (the W3C grammar requires one).\n */\nexport function mergeTraceEnv(\n ambient: Record<string, string | undefined>,\n traceEnv: Record<string, string>,\n overrides?: Record<string, string>,\n): Record<string, string | undefined> {\n const merged: Record<string, string | undefined> = {\n ...ambient,\n ...traceEnv,\n ...(overrides ?? {}),\n }\n const overridesIdentity =\n overrides !== undefined &&\n overrides.TRACEPARENT === undefined &&\n (overrides.TRACE_ID !== undefined || overrides.PARENT_SPAN_ID !== undefined)\n if (!overridesIdentity) return merged\n delete merged.TRACEPARENT\n if (merged.TRACE_ID !== undefined) {\n const rewritten = traceContextToEnv({\n traceId: merged.TRACE_ID,\n ...(merged.PARENT_SPAN_ID !== undefined ? { parentSpanId: merged.PARENT_SPAN_ID } : {}),\n })\n if (rewritten.TRACEPARENT !== undefined) merged.TRACEPARENT = rewritten.TRACEPARENT\n }\n return merged\n}\n\nfunction generateTraceId(): string {\n const bytes = new Uint8Array(16)\n if (typeof globalThis.crypto?.getRandomValues === 'function') {\n globalThis.crypto.getRandomValues(bytes)\n } else {\n for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256)\n }\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n","const SNAPSHOT_TOKEN = /^[A-Za-z0-9._-]+$/u\n\ninterface ModelIdentityParts {\n readonly base: string\n readonly snapshot?: string\n}\n\n/** Match equivalent bare and provider-qualified spellings without discarding observed identity. */\nexport function observedModelMatchesDeclared(observed: string, declared: string): boolean {\n const observedIdentity = modelIdentityParts(observed)\n const declaredIdentity = modelIdentityParts(declared)\n if (!observedIdentity || !declaredIdentity) return false\n if (\n declaredIdentity.snapshot !== undefined &&\n observedIdentity.snapshot !== declaredIdentity.snapshot\n ) {\n return false\n }\n return equivalentModelBase(observedIdentity.base, declaredIdentity.base)\n}\n\n/** Merge two observations of one served model while retaining a snapshot-bearing raw identity. */\nexport function mergeObservedModelIdentity(current: string, next: string): string | undefined {\n const currentIdentity = modelIdentityParts(current)\n const nextIdentity = modelIdentityParts(next)\n if (!currentIdentity || !nextIdentity) return undefined\n if (!equivalentModelBase(currentIdentity.base, nextIdentity.base)) return undefined\n if (\n currentIdentity.snapshot !== undefined &&\n nextIdentity.snapshot !== undefined &&\n currentIdentity.snapshot !== nextIdentity.snapshot\n ) {\n return undefined\n }\n return currentIdentity.snapshot === undefined && nextIdentity.snapshot !== undefined\n ? next\n : current\n}\n\n/** Canonicalize a served model for cross-route identity comparisons. */\nexport function canonicalObservedModel(model: string): string | undefined {\n const identity = modelIdentityParts(model)\n if (!identity) return undefined\n const base = identity.base.slice(identity.base.lastIndexOf('/') + 1)\n return identity.snapshot === undefined ? base : `${base}@${identity.snapshot}`\n}\n\nfunction modelIdentityParts(model: string): ModelIdentityParts | null {\n if (model.length === 0) return null\n const at = model.lastIndexOf('@')\n if (at < 0) return modelLeaf(model).length === 0 ? null : { base: model }\n const base = model.slice(0, at)\n const snapshot = model.slice(at + 1)\n if (base.length === 0 || modelLeaf(base).length === 0 || !SNAPSHOT_TOKEN.test(snapshot)) {\n return null\n }\n return { base, snapshot }\n}\n\nfunction equivalentModelBase(observed: string, declared: string): boolean {\n return modelLeaf(observed) === modelLeaf(declared)\n}\n\nfunction modelLeaf(model: string): string {\n return model.slice(model.lastIndexOf('/') + 1)\n}\n","/**\n * THE canonical agentic tool-loop. One inference turn → run any requested tools → fold the\n * results back as `tool` messages → repeat, until the model answers without a tool call or the\n * turn budget is hit. One turn = one inference call (the equal-compute unit vs random@k).\n *\n * The inference is an INJECTABLE seam (`ToolLoopChat`): a router model, a sandboxed CLI\n * harness, or a scripted mock all satisfy it — so the loop is backend-agnostic. The metered /\n * steerable concerns the call sites add (a driver's conserved-pool + deadline bound; an inline\n * executor's inbox flush + abort) attach via optional `hooks`; the skeleton stays one copy.\n */\n\nimport { ValidationError } from '../errors'\nimport type { ToolSpec } from './router-client'\n\n/** Provider-neutral conversation record accepted by a tool-loop brain. */\nexport type ToolLoopMessageRecord = Record<string, unknown>\n\n/** One provider-neutral tool request emitted by a tool-loop model. */\nexport interface ToolLoopToolCall {\n id: string\n name: string\n /** Raw JSON arguments emitted by the model. */\n arguments: string\n}\n\n/** Runtime-owned identity and cancellation for one logical inference call. The wrapper is frozen\n * before dispatch; a transport may observe the signal but cannot replace the authority it names. */\nexport interface ToolLoopCallContext {\n readonly signal: AbortSignal\n readonly callId: string\n readonly correlationId: string\n}\n\n/** One inference turn over the running conversation + the tool specs → the model's text, any\n * tool calls, and token usage. The seam every brain satisfies. */\nexport type ToolLoopChat = (\n messages: ReadonlyArray<ToolLoopMessageRecord>,\n tools: ReadonlyArray<ToolSpec>,\n context?: ToolLoopCallContext,\n) => Promise<{\n content?: string | null\n toolCalls: ToolLoopToolCall[]\n usage?: { input: number; output: number; reasoning?: number }\n /** Dollar value reported for the turn. It is not billed spend unless provenance says so. */\n costUsd?: number\n costProvenance?: 'provider-receipt' | 'billing-receipt' | 'catalog-estimate'\n /** The turn ran but its usage was not reported when the transport EXPECTED one (the streamed\n * router transport asks for usage and this says it never arrived). A metering caller records an\n * unknown turn on it; `runBrainLoop` itself ignores it. */\n usageUnknown?: true\n /** Provider-observed model identity. Profile-bound callers validate it before accepting output. */\n model?: string\n /** Provider-reported prompt-cache evidence; missing fields remain missing. */\n promptCache?: Readonly<Record<string, number | string>>\n /** Physical HTTP/injected-transport attempts spent by this one logical call. */\n transportAttempts?: number\n}>\n\n/** Optional per-loop concerns the metered/steerable call sites attach. The loop is one copy;\n * the budget/deadline bound, the inbox flush, and the metering hook in HERE — not as forks. */\nexport interface ToolLoopHooks {\n /** Run before each inference turn (e.g. flush queued steers into `messages`). */\n beforeTurn?(turn: number, messages: ToolLoopMessageRecord[]): void | Promise<void>\n /** Return true to stop before the next turn (e.g. pool starved / deadline passed / aborted). */\n stopBefore?(turn: number): boolean\n /** Each turn's usage, for metering into a conserved budget pool. */\n onUsage?(usage: { input: number; output: number }): void\n}\n\n/** Self-compaction — bound the loop's OWN context window the way a fresh-respawn (dumb-Ralph) loop\n * does, but in place. A stateless chat API re-sends the WHOLE running conversation every turn, so an\n * agent that accumulates dozens of turns of tool results re-bills its entire transcript on every\n * inference — the context-overflow-one-level-up that the conserved budget pool cannot fix. With\n * compaction set, once the conversation exceeds `thresholdTokens` the accumulated middle (every prior\n * assistant turn + tool result) is distilled into ONE compact progress note and the conversation is\n * reset to `[...head, digest]`: the preserved head (system + the original task) survives, the stale\n * turn-by-turn history does not. The model keeps deciding; it stops re-billing the whole transcript.\n * Fires at a CLEAN turn boundary (after a turn's tool results are folded in, before the next\n * inference) so it never orphans an assistant `tool_calls` from its `tool` replies. */\nexport interface ToolLoopCompaction {\n /** Compact once the estimated token count of the conversation exceeds this. */\n readonly thresholdTokens: number\n /** Distill the conversation into a compact progress note that REPLACES the middle. Receives the\n * full conversation (so it can summarize everything done so far); returns the digest string. */\n readonly distill: (messages: ReadonlyArray<ToolLoopMessageRecord>) => Promise<string> | string\n /** Leading messages preserved verbatim (system + the original task). Default 2. */\n readonly preserveHead?: number\n /** Token estimator over the conversation. Default ≈ chars/4 (incl. tool-call arguments). */\n readonly estimateTokens?: (messages: ReadonlyArray<ToolLoopMessageRecord>) => number\n /** Notified each time a compaction fires — for observability/metering. */\n readonly onCompact?: (info: { turn: number; beforeTokens: number; afterTokens: number }) => void\n}\n\n/** Public supervisor-facing compaction config: same knobs as the primitive, but `distill` is optional\n * because the supervisor has a default digest that combines a brain note with live worker state. */\nexport type ToolLoopCompactionOptions = Omit<ToolLoopCompaction, 'distill'> & {\n readonly distill?: ToolLoopCompaction['distill']\n}\n\n/** ≈ chars/4 over content + any tool-call arguments — a cheap, provider-agnostic size proxy. The\n * exact constant does not matter: it only has to track GROWTH so the threshold trips as history\n * accumulates, which a uniform chars/4 does. */\nfunction estimateConversationTokens(messages: ReadonlyArray<ToolLoopMessageRecord>): number {\n let chars = 0\n for (const m of messages) {\n const content = (m as { content?: unknown }).content\n chars += typeof content === 'string' ? content.length : safeJsonLength(content)\n const calls = (m as { tool_calls?: Array<{ function?: { arguments?: string } }> }).tool_calls\n if (calls) for (const c of calls) chars += c.function?.arguments?.length ?? 0\n }\n return Math.ceil(chars / 4)\n}\n\nfunction safeJsonLength(value: unknown): number {\n if (value === undefined || value === null) return 0\n try {\n return JSON.stringify(value)?.length ?? 0\n } catch {\n return String(value).length\n }\n}\n\n/** Distill the conversation's accumulated middle into one note and splice it in, IF the estimated\n * size exceeds the threshold. Returns true when a compaction fired. The preserved head keeps the\n * system + task verbatim; everything after collapses to a single `user` progress note, so no\n * assistant `tool_calls` is left without its `tool` replies. */\nasync function maybeCompact(\n messages: ToolLoopMessageRecord[],\n c: ToolLoopCompaction,\n turn: number,\n): Promise<boolean> {\n // A negative `preserveHead` would make `splice(head, …)` index from the END and silently preserve\n // the wrong messages; an invalid value falls back to the default (keep system + task) rather than\n // zero (which would splice the system message away). A too-large value is already safe — the length\n // guard below makes it a no-op. (Callers never pass `preserveHead`; this guards the exported primitive.)\n const head = c.preserveHead !== undefined && c.preserveHead > 0 ? c.preserveHead : 2\n // Nothing meaningful to collapse yet (only head + at most one trailing message).\n if (messages.length <= head + 1) return false\n const estimate = c.estimateTokens ?? estimateConversationTokens\n const before = estimate(messages)\n if (before <= c.thresholdTokens) return false\n const digest = await c.distill([...messages])\n messages.splice(head, messages.length - head, {\n role: 'user',\n content: `[earlier work compacted to save context — progress so far]\\n${digest}`,\n })\n c.onCompact?.({ turn, beforeTokens: before, afterTokens: estimate(messages) })\n return true\n}\n\nexport interface ToolLoopResult {\n /** The model's final assistant text (where it stopped calling tools, or the budget turn). */\n final: string\n /** Inference turns spent (≤ maxTurns) — the equal-compute unit. */\n turns: number\n toolCalls: number\n /** The behavior trace: each call + its result, in order — what a trace-analyst steerer reads. */\n toolTrace: Array<{ name: string; args: string; result: string }>\n usage: { input: number; output: number }\n /** False when any completed inference turn omitted token usage. */\n tokensKnown?: false\n /** The full conversation after the loop — lets a caller CARRY the messages into the next shot. */\n messages: ToolLoopMessageRecord[]\n}\n\n/** Resolve one tool-loop turn limit. Zero removes only the turn-count cap; abort, time, and\n * resource budgets remain available to callers. */\nexport function resolveToolLoopMaxTurns(\n value: number | undefined,\n fallback: number,\n context = 'tool loop',\n): number {\n const resolved = value ?? fallback\n if (!Number.isSafeInteger(resolved) || resolved < 0) {\n throw new ValidationError(\n `${context}: maxTurns must be a nonnegative safe integer (0 means unbounded)`,\n )\n }\n return resolved\n}\n\nexport async function runBrainLoop(opts: {\n chat: ToolLoopChat\n tools: ReadonlyArray<ToolSpec>\n execute: (name: string, args: Record<string, unknown>) => Promise<string>\n /** Seed the conversation (a fresh `[system,user]` or a depth continuation). The array is copied. */\n initialMessages: ReadonlyArray<ToolLoopMessageRecord>\n maxTurns?: number\n hooks?: ToolLoopHooks\n /** Bound the loop's own context window in place (the chapter-close a dumb-Ralph respawn gets for\n * free). Off by default — when unset the conversation accumulates exactly as before. */\n compaction?: ToolLoopCompaction\n}): Promise<ToolLoopResult> {\n const maxTurns = resolveToolLoopMaxTurns(opts.maxTurns, 4, 'runBrainLoop')\n const messages: ToolLoopMessageRecord[] = [...opts.initialMessages]\n let toolCalls = 0\n let lastText = ''\n const usage = { input: 0, output: 0 }\n let tokensKnown = true\n let completedTurns = 0\n const toolTrace: Array<{ name: string; args: string; result: string }> = []\n\n for (let turn = 1; maxTurns === 0 || turn <= maxTurns; turn += 1) {\n if (opts.hooks?.stopBefore?.(turn)) break\n await opts.hooks?.beforeTurn?.(turn, messages)\n // Close the chapter BEFORE the inference turn that would otherwise re-bill the whole transcript:\n // distill the accumulated middle to a compact note so this and every later turn pay O(working-set),\n // not O(total-history). A clean boundary — the prior turn's tool replies are already folded in.\n if (opts.compaction) await maybeCompact(messages, opts.compaction, turn)\n const r = await opts.chat(messages, opts.tools)\n completedTurns = turn\n if (r.usage) {\n usage.input += r.usage.input\n usage.output += r.usage.output\n opts.hooks?.onUsage?.(r.usage)\n } else tokensKnown = false\n if (r.content) lastText = r.content\n if (r.toolCalls.length === 0) {\n // The stopping reply is part of the conversation (the contract on `messages`: seed +\n // every assistant/tool turn). Without this push, a shot that answers WITHOUT tools\n // returns a transcript missing its own answer — depth continuation criticizes a\n // solution the model can't see, and candidate extraction (structural-rollout's\n // fenced-code fallback) reads an empty conversation on non-tool-calling models.\n if (r.content) messages.push({ role: 'assistant', content: r.content })\n return {\n final: lastText,\n turns: turn,\n toolCalls,\n toolTrace,\n usage,\n ...(tokensKnown ? {} : { tokensKnown: false }),\n messages,\n }\n }\n\n // Record the assistant turn verbatim (content + the tool_calls it requested), then run each\n // call and fold the result back as a `tool` message.\n messages.push({\n role: 'assistant',\n content: r.content ?? '',\n tool_calls: r.toolCalls.map((tc) => ({\n id: tc.id,\n type: 'function',\n function: { name: tc.name, arguments: tc.arguments },\n })),\n })\n for (const tc of r.toolCalls) {\n toolCalls += 1\n let args: Record<string, unknown> = {}\n try {\n args = JSON.parse(tc.arguments) as Record<string, unknown>\n } catch {\n // Malformed args from the model are a real outcome, not an infra fault — feed the error\n // back so it can correct, rather than throwing the whole loop.\n messages.push({\n role: 'tool',\n tool_call_id: tc.id,\n content: `error: arguments were not valid JSON: ${tc.arguments.slice(0, 200)}`,\n })\n continue\n }\n const out = await opts.execute(tc.name, args)\n messages.push({ role: 'tool', tool_call_id: tc.id, content: out })\n toolTrace.push({ name: tc.name, args: tc.arguments, result: out })\n }\n }\n return {\n final: lastText,\n turns: completedTurns,\n toolCalls,\n toolTrace,\n usage,\n ...(tokensKnown ? {} : { tokensKnown: false }),\n messages,\n }\n}\n","/**\n * The one router chat client: direct OpenAI-compatible completions through the\n * Tangle router — the cheapest dial, no sandbox. Three layers: `routerChatWithUsage`\n * (chat-only), `routerChatWithTools` (one completion with function tools), and\n * `routerToolLoop` (the off-box agentic loop over tool-calling). Shared by the\n * built-in executors and the bench/lab harnesses.\n *\n * Reports REAL token usage so the backend-integrity guard sees a real backend.\n * Returns `undefined` usage when the provider omitted it — never a fabricated 0\n * (a phantom 0 reads as a free call downstream, which the gate would act on).\n */\n\nimport {\n generateIdempotencyKey,\n type RetryConfig,\n SDKError,\n withRetry,\n} from '@tangle-network/agent-core'\nimport { estimateCost, isModelPriced } from '@tangle-network/agent-eval'\nimport type { ReasoningEffort } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../errors'\nimport { type RouterRetryPolicy, resolveRouterRetryPolicy } from './router-retry-policy'\nimport { runBrainLoop, type ToolLoopChat } from './tool-loop'\n\n/**\n * Connection details for Runtime's Router-backed executors.\n *\n * This is deliberately transport-only: model, prompt, tools, generation settings, and retry\n * policy belong to the exact executable `AgentProfile` consumed by `streamAgentTurn`.\n */\nexport interface RouterTransportConfig {\n routerBaseUrl: string\n routerKey: string\n /** Injectable OpenAI-compatible transport for offline execution. */\n complete?: (\n body: Record<string, unknown>,\n request?: {\n readonly headers: Readonly<Record<string, string>>\n readonly signal?: AbortSignal\n },\n ) => Promise<unknown>\n}\n\n/**\n * Private request configuration used by Runtime's Router adapter.\n *\n * Do not export this through a package entry point. Public callers execute a concrete\n * `AgentProfile` through `createExecutor` + `streamAgentTurn`; only Runtime may lower that profile\n * into these provider request fields.\n */\nexport interface RouterConfig extends RouterTransportConfig {\n model: string\n /** Exact retry controls lowered from `AgentProfile.model.metadata.retry`. */\n retry?: RouterRetryPolicy\n /**\n * Optional ceiling for one completion, forwarded as `max_tokens`.\n *\n * A REASONING model spends this budget on hidden thinking BEFORE it emits a visible token, so\n * the default can truncate one mid-thought and return no content at all — observed live with a\n * model that spent 8,188 of the 8,192 on reasoning and answered with nothing. Raise it for a\n * thinking model; the ceiling belongs to the router and model a caller chose, which is why it\n * lives here rather than on one call site.\n */\n maxTokens?: number\n /**\n * Take the tool-calling completion over SSE instead of one buffered POST. Off by default —\n * `routerChatWithTools` never streams, and every existing caller keeps the buffered transport\n * byte for byte.\n *\n * Why it exists: a buffered POST holds one connection idle for the WHOLE completion, and a\n * supervisor turn is the longest completion in the system. An intermediary gateway with an\n * idle-read timeout kills that connection mid-completion (the 524/503 family). A streamed\n * response puts bytes on the wire from the first generated token on, so the connection is only\n * idle through prefill. It does NOT shorten prefill, so a gateway whose deadline is\n * time-to-FIRST-byte is unaffected; only an idle-timeout gateway is.\n *\n * Mutually exclusive with `complete`: the injected transport returns one parsed JSON body and has\n * no stream to read, so setting both throws rather than silently taking the buffered path.\n *\n * WHICH PATHS CAN OPT IN. This flag is read in exactly one place (the private `chatWithTools` transport switch), so\n * every entry point that takes a caller-supplied `RouterConfig` honors it: `routerBrain`,\n * `routerToolLoop`, and `supervisorAgent` (which spreads `deps.router` into the brain's config —\n * the supervisor turn this exists for). Two production call sites build a `RouterConfig` literal\n * from their own options and therefore CANNOT express it today: the bench strategy's\n * `routerToolLoop` config in `strategy.ts` and the local sandbox client's `routerBrain` config in\n * `local-sandbox-client.ts`. Neither drives a supervisor-length turn; setting `stream` on a\n * config handed to either has no path to reach them, and they stay buffered.\n */\n stream?: boolean\n}\n\nexport interface RouterChatResult {\n /** The final answer, with any inline `<think>...</think>` block stripped into `reasoning`. */\n content: string\n /**\n * Thinking-model reasoning, when the provider surfaced it — either as a separate\n * `reasoning`/`reasoning_content` message field (OpenRouter style) or inlined into\n * `content` as a `<think>` block (Groq style). Undefined for non-thinking models.\n * Downstream parsers that match single-token answers must read `content`, which is\n * clean either way; before this split, Groq-style inlining made the same model look\n * broken on one provider and fine on another.\n */\n reasoning?: string\n /** REAL usage, or undefined when the provider reported none. */\n usage?: { input: number; output: number; reasoning?: number }\n /** Local catalog estimate derived from usage; never a provider billing receipt. */\n costUsd?: number\n /** Present with `costUsd` so consumers cannot mistake a catalog estimate for billed spend. */\n costProvenance?: 'catalog-estimate'\n /** Provider-reported billed cost. Absent means dollar spend is unknown. */\n billedCostUsd?: number\n /** Provider-reported prompt-cache fields; missing fields remain missing. */\n cache?: PromptCacheUsage\n /** Provider terminal reason (`stop`, `length`, ...), when reported. */\n finishReason?: string\n /** Exact HTTP/injected-transport calls consumed by this completion. */\n transportAttempts: number\n /** Model identity reported by the provider response. Absent when the provider omitted it. */\n model?: string\n}\n\n/** One OpenAI-compatible chat completion through the Tangle router, returning text + REAL token usage (`undefined` when the provider omits it — never a fabricated 0). */\nexport async function routerChatWithUsage(\n cfg: RouterConfig,\n messages: ReadonlyArray<{ role: string; content: unknown }>,\n opts?: {\n temperature?: number\n signal?: AbortSignal\n maxTokens?: number\n /** OpenAI-compatible deterministic seed. Omit when the provider does not support it. */\n seed?: number\n /**\n * Provider-specific request fields such as Z.AI's `thinking` object.\n * Canonical fields are written after these extras and cannot be overridden here.\n */\n extraBody?: Readonly<Record<string, unknown>>\n /**\n * Reasoning control for thinking models, forwarded as `reasoning_effort`.\n * 'none' is the load-bearing value: binary/single-token decisions (routing,\n * gating) on a thinking model otherwise burn the whole token budget inside\n * the think block — on slow backends (CPU-local) that turns into a client\n * timeout, not just waste. Providers that ignore the field are handled by\n * the reasoning/content split in `parseChatResult`.\n */\n reasoningEffort?: ReasoningEffort\n /** Stable logical-call id reused across transport retries. */\n callId?: string\n /** Caller trace correlation forwarded independently of idempotency. */\n correlationId?: string\n /** Headers inherited from an enclosing conversation or task. */\n propagatedHeaders?: Readonly<Record<string, string>>\n },\n): Promise<RouterChatResult> {\n const url = `${cfg.routerBaseUrl.replace(/\\/$/, '')}/chat/completions`\n const headers = routerRequestHeaders(cfg, opts)\n const temperature = opts?.temperature\n const maxTokens = opts?.maxTokens ?? cfg.maxTokens\n const body = (): Record<string, unknown> => ({\n ...providerRequestExtras(opts?.extraBody, [\n 'model',\n 'messages',\n 'temperature',\n 'max_tokens',\n 'seed',\n 'reasoning_effort',\n 'stream',\n 'stream_options',\n ]),\n model: cfg.model,\n messages,\n ...(temperature !== undefined ? { temperature } : {}),\n ...(maxTokens !== undefined ? { max_tokens: maxTokens } : {}),\n ...(opts?.seed !== undefined ? { seed: opts.seed } : {}),\n ...(opts?.reasoningEffort ? { reasoning_effort: opts.reasoningEffort } : {}),\n })\n const retry = resolveRouterRetryPolicy(cfg.retry, 'RouterConfig.retry')\n // Injected transport short-circuits the network: the offline benchmark seam. It owns its own\n // determinism while sharing the HTTP path's retry, timeout, and cancellation behavior.\n const complete = cfg.complete\n if (complete) {\n const { value, attempts } = await retryRouterOperation(retry, opts?.signal, (signal) =>\n complete(body(), {\n headers,\n signal,\n }),\n )\n return parseChatResult(value, cfg.model, attempts)\n }\n // Retry transient upstream failures (429/5xx) with backoff so a single capacity\n // hiccup does not kill a whole multi-model benchmark run. Provider requests to\n // change temperature fail: generation behavior belongs to the exact profile.\n const { response, attempts } = await fetchRouterResponse(\n url,\n {\n method: 'POST',\n headers,\n body: JSON.stringify(body()),\n },\n opts?.signal,\n retry,\n )\n return parseChatResult(await routerResponseJson(response, attempts), cfg.model, attempts)\n}\n\nfunction parseChatResult(\n json: unknown,\n model: string,\n transportAttempts: number,\n): RouterChatResult {\n const data = json as {\n model?: unknown\n choices?: Array<{\n message?: { content?: string; reasoning?: string; reasoning_content?: string }\n finish_reason?: string\n }>\n usage?: RawUsage\n }\n const { usage, costUsd, costProvenance, billedCostUsd, cache } = meterTurn(data.usage, model)\n const msg = data.choices?.[0]?.message\n if (!msg) throw new ValidationError('router completion: no choices[0].message')\n const { content, reasoning } = splitReasoning(\n msg?.content ?? '',\n msg?.reasoning ?? msg?.reasoning_content,\n )\n return {\n content,\n transportAttempts,\n ...(reportedModel(data.model) ? { model: reportedModel(data.model) } : {}),\n ...(reasoning ? { reasoning } : {}),\n ...(usage ? { usage } : {}),\n ...(costUsd !== undefined ? { costUsd } : {}),\n ...(costProvenance ? { costProvenance } : {}),\n ...(billedCostUsd !== undefined ? { billedCostUsd } : {}),\n ...(cache ? { cache } : {}),\n ...(typeof data.choices?.[0]?.finish_reason === 'string'\n ? { finishReason: data.choices[0].finish_reason }\n : {}),\n }\n}\n\n/**\n * Normalize the two ways providers surface thinking-model reasoning into one shape:\n * a separate field (OpenRouter: `reasoning`, DeepSeek/Kimi: `reasoning_content`) or a\n * `<think>...</think>` block inlined at the head of `content` (Groq, some local runtimes).\n * An UNCLOSED `<think>` (the model hit max_tokens mid-thought) yields empty content and\n * everything as reasoning — which is honest: no final answer was emitted.\n */\nfunction splitReasoning(\n rawContent: string,\n fieldReasoning: string | undefined,\n): { content: string; reasoning?: string } {\n const open = rawContent.indexOf('<think>')\n if (open !== -1) {\n const close = rawContent.indexOf('</think>', open)\n const inline = close !== -1 ? rawContent.slice(open + 7, close) : rawContent.slice(open + 7)\n const rest =\n close !== -1\n ? rawContent.slice(0, open) + rawContent.slice(close + 8)\n : rawContent.slice(0, open)\n const reasoning = [fieldReasoning, inline.trim()].filter(Boolean).join('\\n')\n return { content: rest.trim(), ...(reasoning ? { reasoning } : {}) }\n }\n return { content: rawContent, ...(fieldReasoning ? { reasoning: fieldReasoning } : {}) }\n}\n\n/** A tool-call the model emitted (provider-neutral; mirrors the runtime's ToolCallRequest). */\nexport interface RouterToolCall {\n id: string\n name: string\n /** Raw JSON arguments string as emitted by the model. */\n arguments: string\n}\n\nexport interface RouterChatToolsResult {\n content: string | null\n toolCalls: RouterToolCall[]\n usage?: { input: number; output: number; reasoning?: number }\n costUsd?: number\n /** Present with `costUsd` so consumers cannot mistake a catalog estimate for billed spend. */\n costProvenance?: 'catalog-estimate'\n /** Provider-reported billed cost. Absent means dollar spend is unknown. */\n billedCostUsd?: number\n /** Provider-reported prompt-cache fields; missing fields remain missing. */\n cache?: PromptCacheUsage\n /**\n * Thinking-model reasoning, normalized the way `RouterChatResult.reasoning` is (a separate\n * `reasoning_content`/`reasoning` field, or an inline `<think>` block split out of `content`).\n * Populated by the STREAMED path only — `routerChatWithTools` discards reasoning today and its\n * behavior is preserved unchanged, so a buffered turn still leaves this undefined.\n */\n reasoning?: string\n /**\n * The provider's `finish_reason` for the turn (`'stop'`, `'tool_calls'`, `'length'`, …).\n * Populated by the STREAMED path only. `'length'` is the truncation signal the buffered path\n * cannot surface: it says the turn hit `max_tokens`, not that the model chose to stop.\n */\n finishReason?: string\n /**\n * The turn happened and its token usage is UNKNOWN — not zero, not free. Set by the STREAMED\n * transport when the stream ran to completion without a single usage-bearing chunk, which means\n * the `stream_options.include_usage` contract was not honored upstream.\n *\n * It exists so a bare `usage: undefined` cannot read as a free turn: a metering caller branches\n * on this marker and records an UNKNOWN turn (see the coordination driver's `meteredBrain`),\n * rather than skipping the turn and letting a conserved budget pool believe it cost nothing.\n */\n usageUnknown?: true\n /** Exact HTTP/injected-transport calls consumed by this completion. */\n transportAttempts: number\n /** Model identity reported by the provider response. Absent when the provider omitted it. */\n model?: string\n}\n\n/**\n * A router completion WITH tool-calling — the operator driver's LLM seam. Passes OpenAI-shape\n * `messages` (system/user/assistant-with-tool_calls/tool roles) + function `tools`, and returns the\n * assistant text plus the tool calls the model wants run. Same fail-loud + real-usage discipline as\n * `routerChatWithUsage`. `tool_choice: 'auto'` lets the model decide; the driver loops on the result.\n */\nexport async function routerChatWithTools(\n cfg: RouterConfig,\n messages: ReadonlyArray<Record<string, unknown>>,\n tools: ReadonlyArray<{\n type: 'function'\n function: { name: string; description?: string; parameters: unknown }\n }>,\n opts?: {\n temperature?: number\n signal?: AbortSignal\n toolChoice?: 'auto' | 'required' | 'none'\n maxTokens?: number\n /** OpenAI-compatible deterministic seed. Omit when the provider does not support it. */\n seed?: number\n /** Provider-specific request fields; canonical fields cannot be overridden here. */\n extraBody?: Readonly<Record<string, unknown>>\n reasoningEffort?: ReasoningEffort\n callId?: string\n correlationId?: string\n /** Headers inherited from an enclosing conversation or task. */\n propagatedHeaders?: Readonly<Record<string, string>>\n },\n): Promise<RouterChatToolsResult> {\n const body = toolCompletionBody(cfg, messages, tools, opts)\n const retry = resolveRouterRetryPolicy(cfg.retry, 'RouterConfig.retry')\n // Injected transport short-circuits the network — the offline benchmark seam (see RouterConfig.complete).\n let transportAttempts = 1\n const headers = routerRequestHeaders(cfg, opts)\n const complete = cfg.complete\n const raw = complete\n ? await (async () => {\n const result = await retryRouterOperation(retry, opts?.signal, (signal) =>\n complete(structuredClone(body), { headers, signal }),\n )\n transportAttempts = result.attempts\n return result.value\n })()\n : await (async () => {\n const result = await fetchRouterResponse(\n `${cfg.routerBaseUrl.replace(/\\/$/, '')}/chat/completions`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n },\n opts?.signal,\n retry,\n )\n transportAttempts = result.attempts\n return routerResponseJson(result.response, result.attempts)\n })()\n const data = raw as {\n model?: unknown\n choices?: Array<{\n message?: {\n content?: string | null\n tool_calls?: Array<{ id?: string; function?: { name?: string; arguments?: string } }>\n }\n finish_reason?: string\n }>\n usage?: RawUsage\n }\n const msg = data.choices?.[0]?.message\n if (!msg) throw new ValidationError('router completion: no choices[0].message')\n const toolCalls: RouterToolCall[] = (msg?.tool_calls ?? []).map((tc, i) => ({\n id: tc.id ?? `call_${i}`,\n name: tc.function?.name ?? '',\n arguments: tc.function?.arguments ?? '{}',\n }))\n const { usage, costUsd, costProvenance, billedCostUsd, cache } = meterTurn(data.usage, cfg.model)\n return {\n content: msg?.content ?? null,\n toolCalls,\n transportAttempts,\n ...(reportedModel(data.model) ? { model: reportedModel(data.model) } : {}),\n ...(usage ? { usage } : {}),\n ...(costUsd !== undefined ? { costUsd } : {}),\n ...(costProvenance ? { costProvenance } : {}),\n ...(billedCostUsd !== undefined ? { billedCostUsd } : {}),\n ...(cache ? { cache } : {}),\n ...(typeof data.choices?.[0]?.finish_reason === 'string'\n ? { finishReason: data.choices[0].finish_reason }\n : {}),\n }\n}\n\n/** The OpenAI-shape request body both tool-calling transports send. One builder so the streamed\n * turn cannot drift from the buffered one on model, temperature, tool_choice, or the ceiling. */\nfunction toolCompletionBody(\n cfg: RouterConfig,\n messages: ReadonlyArray<Record<string, unknown>>,\n tools: ReadonlyArray<ToolSpec>,\n opts?: {\n temperature?: number\n toolChoice?: 'auto' | 'required' | 'none'\n maxTokens?: number\n seed?: number\n extraBody?: Readonly<Record<string, unknown>>\n reasoningEffort?: ReasoningEffort\n },\n): Record<string, unknown> {\n return {\n ...providerRequestExtras(opts?.extraBody, [\n 'model',\n 'messages',\n 'tools',\n 'tool_choice',\n 'temperature',\n 'max_tokens',\n 'seed',\n 'reasoning_effort',\n 'stream',\n 'stream_options',\n ]),\n model: cfg.model,\n messages,\n ...(tools.length > 0 ? { tools, tool_choice: opts?.toolChoice ?? 'auto' } : {}),\n ...(opts?.temperature !== undefined ? { temperature: opts.temperature } : {}),\n ...(opts?.maxTokens ? { max_tokens: opts.maxTokens } : {}),\n ...(opts?.seed !== undefined ? { seed: opts.seed } : {}),\n ...(opts?.reasoningEffort ? { reasoning_effort: opts.reasoningEffort } : {}),\n }\n}\n\nfunction providerRequestExtras(\n extraBody: Readonly<Record<string, unknown>> | undefined,\n reservedFields: ReadonlyArray<string>,\n): Record<string, unknown> {\n if (!extraBody) return {}\n const extras = { ...extraBody }\n for (const field of reservedFields) delete extras[field]\n return extras\n}\n\n/**\n * REAL usage → the metered pair, or `undefined` when the provider reported none. Never a\n * fabricated 0: a phantom 0 reads as a free call to the conserved budget pool, which would then\n * over-spend. Shared by the buffered and streamed transports so both meter identically.\n */\nfunction meterTurn(\n raw: RawUsage | undefined,\n model: string,\n): {\n usage?: { input: number; output: number; reasoning?: number }\n costUsd?: number\n costProvenance?: 'catalog-estimate'\n billedCostUsd?: number\n cache?: PromptCacheUsage\n} {\n const reasoning = providerReasoningTokens(raw)\n const usage =\n raw && typeof raw.prompt_tokens === 'number' && typeof raw.completion_tokens === 'number'\n ? {\n input: raw.prompt_tokens,\n output: raw.completion_tokens,\n ...(reasoning !== undefined ? { reasoning } : {}),\n }\n : undefined\n const cache = readPromptCache(raw)\n const billedCostUsd = providerBilledCost(raw)\n if (!usage) {\n return {\n ...(billedCostUsd !== undefined ? { billedCostUsd } : {}),\n ...(cache ? { cache } : {}),\n }\n }\n const localEstimate = isModelPriced(model)\n ? estimateCost(usage.input, usage.output, model)\n : undefined\n // A cached prefix token is billed at a discount the local price table does not know about, so\n // subtract the provider's OWN reported saving rather than re-deriving a discount here. Without\n // this a long supervisor run — which re-sends a growing transcript every turn — is reported at\n // full price for tokens the provider served from cache.\n const costUsd =\n localEstimate !== undefined && cache?.readSavingsUsd !== undefined\n ? Math.max(0, localEstimate - cache.readSavingsUsd)\n : localEstimate\n return {\n usage,\n ...(costUsd !== undefined ? { costUsd, costProvenance: 'catalog-estimate' as const } : {}),\n ...(billedCostUsd !== undefined ? { billedCostUsd } : {}),\n ...(cache ? { cache } : {}),\n }\n}\n\nfunction providerReasoningTokens(raw: RawUsage | undefined): number | undefined {\n if (!raw) return undefined\n for (const value of [raw.completion_tokens_details?.reasoning_tokens, raw.reasoning_tokens]) {\n if (Number.isSafeInteger(value) && (value as number) >= 0) return value as number\n }\n return undefined\n}\n\nfunction providerBilledCost(raw: RawUsage | undefined): number | undefined {\n if (!raw) return undefined\n for (const value of [raw.cost, raw.cost_usd]) {\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return value\n }\n return undefined\n}\n\n/** What the router reports about prefix caching for one completion. Absent when the provider\n * said nothing — an unreported cache is not a miss, and a miss is not a zero saving. */\nexport interface PromptCacheUsage {\n /** Prompt tokens served from a cached prefix. */\n readonly readTokens?: number\n /** Prompt tokens written INTO the cache by this call. */\n readonly writeTokens?: number\n /** Prompt tokens that missed a provider cache. */\n readonly missTokens?: number\n /** Dollars the provider says the cache read saved on this call. */\n readonly readSavingsUsd?: number\n /** The provider's own word for what happened: `hit`, `miss`, `read`, … Kept verbatim rather\n * than normalized, so a new status is visible instead of silently bucketed. */\n readonly status?: string\n}\n\ninterface RawUsage {\n prompt_tokens?: number\n completion_tokens?: number\n cost?: number\n cost_usd?: number\n prompt_cache_hit_tokens?: number\n prompt_cache_miss_tokens?: number\n prompt_tokens_details?: { cached_tokens?: number }\n completion_tokens_details?: { reasoning_tokens?: number }\n reasoning_tokens?: number\n prompt_cache?: unknown\n}\n\nexport function readPromptCache(raw: unknown): PromptCacheUsage | undefined {\n if (!raw || typeof raw !== 'object') return undefined\n const o = raw as Record<string, unknown>\n const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined)\n const nested =\n o.prompt_cache && typeof o.prompt_cache === 'object'\n ? (o.prompt_cache as Record<string, unknown>)\n : o\n const details =\n o.prompt_tokens_details && typeof o.prompt_tokens_details === 'object'\n ? (o.prompt_tokens_details as Record<string, unknown>)\n : undefined\n const readTokens =\n num(nested.read_tokens) ?? num(o.prompt_cache_hit_tokens) ?? num(details?.cached_tokens)\n const writeTokens = num(nested.write_tokens)\n const missTokens = num(o.prompt_cache_miss_tokens)\n const savings = num(nested.read_savings_usd)\n const status = typeof nested.status === 'string' ? nested.status : undefined\n if (\n readTokens === undefined &&\n writeTokens === undefined &&\n missTokens === undefined &&\n savings === undefined &&\n status === undefined\n ) {\n return undefined\n }\n return {\n ...(readTokens !== undefined ? { readTokens } : {}),\n ...(writeTokens !== undefined ? { writeTokens } : {}),\n ...(missTokens !== undefined ? { missTokens } : {}),\n ...(savings !== undefined ? { readSavingsUsd: savings } : {}),\n ...(status !== undefined ? { status } : {}),\n }\n}\n\n// ── Streamed tool-calling transport ──────────────────────────────────────────\n\n/** One OpenAI chat-completion chunk. Every field here is exercised by the pinned SSE fixture the\n * streamed-transport tests read (`tests/kernel/fixtures/router-chat-completion-stream.sse`):\n * `delta.reasoning_content` token-by-token, one `delta.tool_calls` entry carrying\n * `index`/`id`/`function`, then a terminal chunk with `finish_reason` + `usage`. */\ninterface ChatCompletionChunk {\n model?: unknown\n choices?: Array<{\n index?: number\n finish_reason?: string | null\n delta?: {\n content?: string | null\n reasoning?: string | null\n reasoning_content?: string | null\n tool_calls?: Array<{\n index?: number\n id?: string\n function?: { name?: string; arguments?: string }\n }>\n }\n }>\n usage?: RawUsage\n error?: { message?: string; type?: string }\n}\n\n/** A tool call being assembled across chunks: providers may fragment `arguments` arbitrarily. */\ninterface StreamingToolCall {\n id?: string\n name?: string\n arguments: string\n}\n\n/**\n * The SAME completion as `routerChatWithTools`, taken over SSE (`stream: true`) and reassembled\n * into the identical `RouterChatToolsResult`. Opt in with `RouterConfig.stream` — the buffered\n * function is untouched and stays the default for every existing caller.\n *\n * What it buys: a buffered POST holds one connection idle for the whole completion, and that idle\n * window is what an intermediary gateway kills (524/503). Streaming puts bytes on the wire from the\n * first generated token, so the connection is only idle through prefill.\n *\n * Usage accounting is preserved exactly: `stream_options.include_usage` asks the provider for a\n * terminal usage chunk, and those tokens run through the same `meterTurn` the buffered path uses.\n *\n * When NO chunk reported usage, `usage`/`costUsd` stay undefined (never a fabricated 0) AND\n * `usageUnknown: true` is set. A stream that finishes with no usage chunk means the\n * `include_usage` request was not honored upstream, and returning a quiet `undefined` for it is\n * indistinguishable from a free turn — the marker is what lets a metering caller record an UNKNOWN\n * turn instead. Streaming raises the odds of this (one dropped terminal frame is enough), which is\n * why the streamed transport says so explicitly and the buffered one has no equivalent claim to make.\n */\nexport async function streamRouterChatWithTools(\n cfg: RouterConfig,\n messages: ReadonlyArray<Record<string, unknown>>,\n tools: ReadonlyArray<ToolSpec>,\n opts?: {\n temperature?: number\n signal?: AbortSignal\n toolChoice?: 'auto' | 'required' | 'none'\n maxTokens?: number\n seed?: number\n /** Provider-specific request fields; canonical streaming fields cannot be overridden here. */\n extraBody?: Readonly<Record<string, unknown>>\n reasoningEffort?: ReasoningEffort\n callId?: string\n correlationId?: string\n /** Headers inherited from an enclosing conversation or task. */\n propagatedHeaders?: Readonly<Record<string, string>>\n },\n): Promise<RouterChatToolsResult> {\n const retry = resolveRouterRetryPolicy(cfg.retry, 'RouterConfig.retry')\n if (cfg.complete) {\n throw new ValidationError(\n 'streamRouterChatWithTools: RouterConfig.complete is a BUFFERED transport (it returns one ' +\n 'parsed completion body) and cannot serve a stream. Drop `stream` to use the injected ' +\n 'transport, or drop `complete` to stream from the router.',\n )\n }\n const body = {\n ...toolCompletionBody(cfg, messages, tools, opts),\n stream: true,\n // Without this an OpenAI-compatible upstream omits usage from a streamed response entirely,\n // and the turn would meter nothing. An upstream that accepts but ignores it is caught after the\n // fact by `usageUnknown`, not assumed away.\n stream_options: { include_usage: true },\n }\n const { response: res, attempts: transportAttempts } = await fetchRouterResponse(\n `${cfg.routerBaseUrl.replace(/\\/$/, '')}/chat/completions`,\n {\n method: 'POST',\n headers: {\n ...routerRequestHeaders(cfg, opts),\n accept: 'text/event-stream',\n },\n body: JSON.stringify(body),\n },\n opts?.signal,\n retry,\n )\n if (!res.body) {\n throw new ValidationError(\n `router ${res.status}: streamed completion returned no response body to read`,\n )\n }\n\n let content = ''\n let sawContent = false\n let fieldReasoning = ''\n let finishReason: string | undefined\n let rawUsage: RawUsage | undefined\n let observedModel: string | undefined\n const calls = new Map<number, StreamingToolCall>()\n let lastCallIndex = -1\n\n for await (const chunk of readChatCompletionChunksWithAttempts(res.body, transportAttempts)) {\n if (chunk.error) {\n throw new ValidationError(\n `router stream error: ${chunk.error.message ?? chunk.error.type ?? 'unknown'}`,\n )\n }\n const chunkModel = reportedModel(chunk.model)\n if (chunkModel !== undefined) {\n if (observedModel !== undefined && observedModel !== chunkModel) {\n throw new ValidationError(\n `router stream changed reported model from ${JSON.stringify(observedModel)} to ${JSON.stringify(chunkModel)}`,\n )\n }\n observedModel = chunkModel\n }\n // With `include_usage` the terminal chunk may carry usage and an EMPTY choices array.\n if (chunk.usage) rawUsage = chunk.usage\n const choice = chunk.choices?.[0]\n if (!choice) continue\n if (typeof choice.finish_reason === 'string') finishReason = choice.finish_reason\n const delta = choice.delta\n if (!delta) continue\n // An EMPTY content delta still counts as content having been emitted. The buffered path maps\n // `content: \"\"` to `''` and only an ABSENT field to `null` (`msg?.content ?? null`); treating an\n // empty delta as \"no content\" would return `null` where the buffered path returns `''`, so the\n // two transports would disagree on a tool-calls-only turn.\n if (typeof delta.content === 'string') {\n content += delta.content\n sawContent = true\n }\n const reasoningDelta = delta.reasoning_content ?? delta.reasoning\n if (typeof reasoningDelta === 'string') fieldReasoning += reasoningDelta\n for (const tc of delta.tool_calls ?? []) {\n // `index` is the provider's slot for the call. Absent (some proxies drop it), a fragment\n // belongs to the call it is continuing — a NEW `id` opens the next slot, no id continues the\n // current one. Guessing a slot would silently merge two calls' arguments into one.\n const index =\n typeof tc.index === 'number'\n ? tc.index\n : tc.id && !idAlreadyOpen(calls, tc.id)\n ? lastCallIndex + 1\n : Math.max(lastCallIndex, 0)\n lastCallIndex = Math.max(lastCallIndex, index)\n const acc = calls.get(index) ?? { arguments: '' }\n if (tc.id) acc.id = tc.id\n if (tc.function?.name) acc.name = tc.function.name\n if (tc.function?.arguments) acc.arguments += tc.function.arguments\n calls.set(index, acc)\n }\n }\n\n // A model that inlines its thinking as `<think>` in `content` is normalized the same way the\n // chat path normalizes it, so a downstream parser reading `content` gets the clean answer.\n const split = splitReasoning(content, fieldReasoning.length > 0 ? fieldReasoning : undefined)\n const toolCalls: RouterToolCall[] = [...calls.entries()]\n .sort((a, b) => a[0] - b[0])\n .map(([index, call]) => ({\n id: call.id ?? `call_${index}`,\n name: call.name ?? '',\n arguments: call.arguments || '{}',\n }))\n const { usage, costUsd, costProvenance, billedCostUsd, cache } = meterTurn(rawUsage, cfg.model)\n return {\n // `null` only when NO content field was ever sent — the buffered path's `msg?.content ?? null`.\n content: sawContent ? split.content : null,\n toolCalls,\n transportAttempts,\n ...(observedModel !== undefined ? { model: observedModel } : {}),\n ...(split.reasoning ? { reasoning: split.reasoning } : {}),\n ...(finishReason !== undefined ? { finishReason } : {}),\n ...(usage ? { usage } : {}),\n ...(costUsd !== undefined ? { costUsd } : {}),\n ...(costProvenance ? { costProvenance } : {}),\n ...(billedCostUsd !== undefined ? { billedCostUsd } : {}),\n ...(cache ? { cache } : {}),\n // The turn ran; its tokens are unknown. Marked rather than left as a bare `undefined`, which a\n // metering caller cannot tell apart from a turn that genuinely cost nothing.\n ...(usage ? {} : { usageUnknown: true as const }),\n }\n}\n\nfunction routerRequestHeaders(\n cfg: Pick<RouterConfig, 'routerKey'>,\n opts:\n | {\n callId?: string\n correlationId?: string\n propagatedHeaders?: Readonly<Record<string, string>>\n }\n | undefined,\n): Record<string, string> {\n // Every POST is retryable. Mint the logical-call identity once while the request headers are\n // assembled, outside `withRetry`, so an accepted response whose connection dies cannot make a\n // retry look like a new billable completion. A trusted caller identity remains authoritative.\n const suppliedCallId: unknown = opts?.callId\n if (\n suppliedCallId !== undefined &&\n (typeof suppliedCallId !== 'string' || suppliedCallId.trim().length === 0)\n ) {\n throw new ValidationError('router request: callId must be a non-empty, non-whitespace string')\n }\n const callId = typeof suppliedCallId === 'string' ? suppliedCallId : generateIdempotencyKey()\n return {\n ...(opts?.propagatedHeaders ?? {}),\n 'content-type': 'application/json',\n authorization: `Bearer ${cfg.routerKey}`,\n 'idempotency-key': callId,\n ...(opts?.correlationId ? { 'x-correlation-id': opts.correlationId } : {}),\n }\n}\n\nfunction reportedModel(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nasync function fetchRouterResponse(\n url: string,\n init: Omit<RequestInit, 'signal'>,\n callerSignal: AbortSignal | undefined,\n retry: ReturnType<typeof resolveRouterRetryPolicy>,\n): Promise<{ response: Response; attempts: number }> {\n const result = await retryRouterOperation(retry, callerSignal, async (signal) => {\n const candidate = await fetch(url, { ...init, signal })\n if (candidate.ok) return candidate\n const text = await candidate.text().catch(() => '<failed to read response body>')\n throw new SDKError(`router ${candidate.status}: ${text.slice(0, 200)}`, {\n code: 'UNKNOWN',\n status: candidate.status,\n retryable: retry.retryStatuses.includes(candidate.status),\n context: { body: text.slice(0, 200) },\n })\n })\n return { response: result.value, attempts: result.attempts }\n}\n\nasync function retryRouterOperation<T>(\n retry: ReturnType<typeof resolveRouterRetryPolicy>,\n callerSignal: AbortSignal | undefined,\n operation: (signal: AbortSignal) => Promise<T>,\n): Promise<{ value: T; attempts: number }> {\n let attempts = 0\n try {\n const value = await withRetry(\n async (attempt) => {\n attempts = attempt + 1\n const attemptSignal = withRouterRequestTimeout(callerSignal, retry.requestTimeoutMs)\n try {\n return await operation(attemptSignal.signal)\n } catch (error) {\n if (callerSignal?.aborted) throw callerSignal.reason ?? error\n if (attemptSignal.signal.aborted) {\n throw new SDKError(`router request timeout after ${retry.requestTimeoutMs}ms`, {\n code: 'TIMEOUT',\n cause: error instanceof Error ? error : new Error(String(error)),\n })\n }\n if (error instanceof TypeError && error.message.includes('fetch')) {\n throw new SDKError(`router network failure: ${error.message}`, {\n code: 'NETWORK',\n cause: error,\n })\n }\n throw error\n } finally {\n attemptSignal.dispose()\n }\n },\n agentCoreRetryConfig(retry, callerSignal),\n )\n return { value, attempts }\n } catch (error) {\n throwRouterFailureWithAttempts(error, attempts)\n }\n}\n\nconst routerFailureAttempts = new WeakMap<object, number>()\n\n/** Internal evidence carried alongside a failed Router call without replacing the original error.\n * Runtime uses it when an intentional interrupt resumes the worker instead of surfacing the error. */\nexport function routerTransportAttemptsFromError(error: unknown): number | undefined {\n const identity = routerErrorIdentity(error)\n return identity === undefined ? undefined : routerFailureAttempts.get(identity)\n}\n\nfunction throwRouterFailureWithAttempts(error: unknown, attempts: number): never {\n const identity = routerErrorIdentity(error)\n if (identity !== undefined) routerFailureAttempts.set(identity, attempts)\n throw error\n}\n\nfunction routerErrorIdentity(error: unknown): object | undefined {\n return (typeof error === 'object' && error !== null) || typeof error === 'function'\n ? (error as object)\n : undefined\n}\n\nasync function routerResponseJson(response: Response, attempts: number): Promise<unknown> {\n try {\n return await response.json()\n } catch (error) {\n throwRouterFailureWithAttempts(error, attempts)\n }\n}\n\nfunction agentCoreRetryConfig(\n retry: ReturnType<typeof resolveRouterRetryPolicy>,\n callerSignal: AbortSignal | undefined,\n): RetryConfig {\n return {\n maxAttempts: retry.maxAttempts,\n initialDelayMs: retry.initialBackoffMs,\n maxDelayMs: retry.maxBackoffMs,\n multiplier: 2,\n jitter: retry.jitter,\n ...(callerSignal ? { signal: callerSignal } : {}),\n shouldRetry: (error) => {\n if (callerSignal?.aborted) return false\n if (error.status !== undefined) return retry.retryStatuses.includes(error.status)\n return error.code === 'NETWORK' || error.code === 'TIMEOUT'\n },\n }\n}\n\nfunction withRouterRequestTimeout(\n callerSignal: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; dispose: () => void } {\n if (timeoutMs === 0) {\n return { signal: callerSignal ?? new AbortController().signal, dispose: () => undefined }\n }\n const controller = new AbortController()\n const timeout = setTimeout(\n () => controller.abort(new Error(`router request timeout after ${timeoutMs}ms`)),\n timeoutMs,\n )\n const onCallerAbort = () => controller.abort(callerSignal?.reason ?? new Error('aborted'))\n if (callerSignal?.aborted) onCallerAbort()\n else callerSignal?.addEventListener('abort', onCallerAbort, { once: true })\n return {\n signal: controller.signal,\n dispose: () => {\n clearTimeout(timeout)\n callerSignal?.removeEventListener('abort', onCallerAbort)\n },\n }\n}\n\nfunction idAlreadyOpen(calls: Map<number, StreamingToolCall>, id: string): boolean {\n for (const call of calls.values()) if (call.id === id) return true\n return false\n}\n\n/**\n * Decode an SSE body into chat-completion chunks. Frames are blank-line separated; `data:` lines\n * concatenate; `:` comments are keepalives; `[DONE]` ends the stream. The unterminated tail is\n * parsed too — an upstream that dies mid-response routinely sends a last frame with no trailing\n * blank line, and dropping it would turn a real upstream error into a silent empty turn.\n *\n * All three SSE line terminators (CRLF, LF, lone CR) are normalized, and the boundary scan runs\n * over the ACCUMULATED buffer — never over a single read in isolation, because a read may split a\n * CRLF. See `normalizeSseLineEndings`; the split is exercised byte-by-byte by the tests.\n *\n * The generator OWNS the body for its lifetime and releases it on every exit. Stopping early —\n * at `[DONE]`, or because the consumer threw — leaves the HTTP response only partly read, so the\n * body is CANCELLED rather than merely unlocked: releasing the lock alone leaves the connection\n * held open until the socket times out, which under a connection pool starves later turns.\n */\nasync function* readChatCompletionChunks(\n body: ReadableStream<Uint8Array>,\n): AsyncIterable<ChatCompletionChunk> {\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let buf = ''\n // Set only when a read reported EOF: the body is then already exhausted and cancelling it is\n // both unnecessary and a no-op. Any other exit leaves bytes on the wire.\n let drained = false\n try {\n for (;;) {\n const { done, value } = await reader.read()\n buf = normalizeSseLineEndings(\n done ? buf : buf + decoder.decode(value, { stream: true }),\n // While the stream is live a trailing `\\r` is ambiguous; at EOF it is a terminator.\n !done,\n )\n let sep = buf.indexOf('\\n\\n')\n while (sep !== -1) {\n const frame = parseChunkFrame(buf.slice(0, sep))\n buf = buf.slice(sep + 2)\n if (frame === 'done') return\n if (frame) yield frame\n sep = buf.indexOf('\\n\\n')\n }\n if (done) break\n }\n drained = true\n const tail = parseChunkFrame(buf)\n if (tail && tail !== 'done') yield tail\n } finally {\n if (!drained) {\n // `cancel()` REJECTS when the body is already errored (a dead socket). That is cleanup on a\n // path that already carries either a complete result or an error of its own, and letting the\n // rejection escape `finally` would REPLACE that error with a less specific one. The\n // connection is released either way, which is the whole reason cancel is called.\n await reader.cancel().catch(() => undefined)\n }\n reader.releaseLock()\n }\n}\n\nasync function* readChatCompletionChunksWithAttempts(\n body: ReadableStream<Uint8Array>,\n attempts: number,\n): AsyncIterable<ChatCompletionChunk> {\n try {\n yield* readChatCompletionChunks(body)\n } catch (error) {\n throwRouterFailureWithAttempts(error, attempts)\n }\n}\n\n/**\n * Normalize an SSE body's line terminators to `\\n`. The SSE grammar accepts CRLF, LF, AND a lone\n * CR, so a `\\r`-separated body is legal — and left unnormalized it decodes to zero frames, which\n * this transport would report as a turn with no content, no tool calls, and `usageUnknown: true`\n * and no error at all. Losing a whole turn in silence is the one outcome it may not produce.\n *\n * `holdTrailingCr` keeps an ambiguous FINAL `\\r` out of the conversion while more bytes may still\n * arrive: rewriting it to `\\n` before the next byte is seen turns a read-split CRLF into a FALSE\n * frame boundary, splitting one frame into two unparseable halves. At EOF nothing can follow it,\n * so it is converted. Re-running this over the accumulated buffer is idempotent.\n */\nfunction normalizeSseLineEndings(buf: string, holdTrailingCr: boolean): string {\n if (holdTrailingCr && buf.endsWith('\\r')) {\n return `${buf.slice(0, -1).replace(/\\r\\n?/g, '\\n')}\\r`\n }\n return buf.replace(/\\r\\n?/g, '\\n')\n}\n\n/** One SSE frame → a chunk, `'done'`, or undefined for a comment/keepalive/unparseable payload. */\nfunction parseChunkFrame(frame: string): ChatCompletionChunk | 'done' | undefined {\n const dataLines: string[] = []\n for (const line of frame.split('\\n')) {\n if (!line || line.startsWith(':')) continue\n if (line.startsWith('data:')) dataLines.push(line.slice('data:'.length).trimStart())\n }\n if (dataLines.length === 0) return undefined\n const data = dataLines.join('\\n')\n if (data === '[DONE]') return 'done'\n try {\n return JSON.parse(data) as ChatCompletionChunk\n } catch {\n return undefined\n }\n}\n\n/** Pick the tool-calling transport the config asked for. `routerChatWithTools` itself never\n * streams; this is the one place `RouterConfig.stream` is honored, so every router-client entry\n * point (`routerBrain`, `routerToolLoop`) obeys the same switch. */\nfunction chatWithTools(\n cfg: RouterConfig,\n messages: ReadonlyArray<Record<string, unknown>>,\n tools: ReadonlyArray<ToolSpec>,\n opts?: {\n temperature?: number\n signal?: AbortSignal\n toolChoice?: 'auto' | 'required' | 'none'\n maxTokens?: number\n seed?: number\n extraBody?: Readonly<Record<string, unknown>>\n reasoningEffort?: ReasoningEffort\n },\n): Promise<RouterChatToolsResult> {\n return cfg.stream === true\n ? streamRouterChatWithTools(cfg, messages, tools, opts)\n : routerChatWithTools(cfg, messages, tools, opts)\n}\n\nexport interface ToolSpec {\n type: 'function'\n function: { name: string; description?: string; parameters: unknown }\n}\n\nexport interface RouterToolLoopResult {\n /** The model's final assistant text (the turn where it stopped calling tools, or the budget turn). */\n final: string\n /** Inference turns spent (≤ maxTurns) — the equal-budget unit vs random@k. */\n turns: number\n toolCalls: number\n /** The behavior trace: each tool call + its result, in order. What a trace-analyst\n * steerer reads (behavior, never the verdict) to diagnose + redirect the next shot. */\n toolTrace: Array<{ name: string; args: string; result: string }>\n usage: { input: number; output: number }\n /** False when any completed router turn omitted usage. */\n tokensKnown?: false\n /** The full conversation after the loop (seed + every assistant/tool turn). Lets a caller\n * CARRY the messages into the next shot (depth continuation) and read the trajectory. */\n messages: Array<Record<string, unknown>>\n}\n\n/**\n * The tool-using router backend: a real agentic loop OVER the Tangle router (which\n * supports tool-calling), off-box — no sandbox. Each turn is one router completion\n * with `tools`; if the model emits tool_calls, `execute` runs them on the host and\n * their results are folded back as `tool` messages; the loop repeats until the\n * model answers without a tool call or the turn budget is hit. One turn = one\n * inference call, so `maxTurns` is the equal-compute unit against random@k.\n *\n * This is the depth substrate for agentic gates (the worker ACTS, observes the real\n * result, and continues) that the chat-only `routerChatWithUsage` cannot express.\n */\nexport async function routerToolLoop(\n cfg: RouterConfig,\n system: string,\n user: string,\n tools: ReadonlyArray<ToolSpec>,\n execute: (name: string, args: Record<string, unknown>) => Promise<string>,\n opts?: {\n maxTurns?: number\n temperature?: number\n signal?: AbortSignal\n maxTokens?: number\n reasoningEffort?: ReasoningEffort\n /** Seed the loop with an existing conversation (depth continuation) instead of\n * `[system, user]`. When set, `system`/`user` are ignored. The array is copied. */\n initialMessages?: ReadonlyArray<Record<string, unknown>>\n },\n): Promise<RouterToolLoopResult> {\n // The router adapter over the canonical `runBrainLoop`: bind the inference to the router\n // (`routerChatWithTools`), seed the conversation, and let the one shared skeleton drive.\n const initialMessages = opts?.initialMessages ?? [\n { role: 'system', content: system },\n { role: 'user', content: user },\n ]\n return runBrainLoop({\n chat: (messages, toolSpecs) =>\n chatWithTools(cfg, messages, toolSpecs, {\n ...(opts?.temperature !== undefined ? { temperature: opts.temperature } : {}),\n ...(opts?.maxTokens !== undefined ? { maxTokens: opts.maxTokens } : {}),\n ...(opts?.reasoningEffort ? { reasoningEffort: opts.reasoningEffort } : {}),\n ...(opts?.signal ? { signal: opts.signal } : {}),\n }),\n tools,\n execute,\n initialMessages,\n maxTurns: opts?.maxTurns ?? 4,\n })\n}\n\n/**\n * The router as a supervisor BRAIN: the canonical `ToolLoopChat` seam backed by the router's\n * tool-calling. The driver's spawn/observe/steer/await/stop turns become real router tool-calls.\n * The turnkey production brain — tests script a mock `ToolLoopChat`; production passes\n * `routerBrain(cfg)`. No message translation: the loop already speaks the router's OpenAI shape.\n *\n * Transport follows `cfg.stream`: buffered by default, SSE when the caller opts in. A supervisor\n * turn is the longest completion in the system, so it is the call site streaming exists for.\n */\nexport function routerBrain(\n cfg: RouterConfig,\n opts: {\n temperature?: number\n reasoningEffort?: ReasoningEffort\n seed?: number\n toolChoice?: 'auto' | 'required' | 'none'\n extraBody?: Readonly<Record<string, unknown>>\n } = {},\n): ToolLoopChat {\n const temperature = opts.temperature ?? 0.4\n return async (messages, tools, context) => {\n const result = await chatWithTools(cfg, messages, tools, {\n temperature,\n toolChoice: opts.toolChoice ?? 'auto',\n // The config's ceiling reaches the completion, so a caller driving a reasoning model can\n // raise it. Without this a router-brained supervisor is stuck on the 8192 default.\n ...(cfg.maxTokens !== undefined ? { maxTokens: cfg.maxTokens } : {}),\n ...(opts.seed !== undefined ? { seed: opts.seed } : {}),\n ...(opts.extraBody !== undefined ? { extraBody: opts.extraBody } : {}),\n ...(opts.reasoningEffort ? { reasoningEffort: opts.reasoningEffort } : {}),\n ...(context?.signal ? { signal: context.signal } : {}),\n ...(context?.callId ? { callId: context.callId } : {}),\n ...(context?.correlationId ? { correlationId: context.correlationId } : {}),\n })\n const hasBilledCost = result.billedCostUsd !== undefined\n return {\n content: result.content,\n toolCalls: result.toolCalls,\n ...(result.usage !== undefined ? { usage: result.usage } : {}),\n ...(result.usageUnknown === true ? { usageUnknown: true as const } : {}),\n ...(result.model !== undefined ? { model: result.model } : {}),\n ...(result.cache !== undefined ? { promptCache: Object.freeze({ ...result.cache }) } : {}),\n transportAttempts: result.transportAttempts,\n ...(hasBilledCost\n ? { costUsd: result.billedCostUsd, costProvenance: 'billing-receipt' as const }\n : result.costUsd !== undefined\n ? { costUsd: result.costUsd, costProvenance: result.costProvenance }\n : {}),\n }\n }\n}\n","/**\n *\n * `acquireSandbox` — cold-start-resilient sandbox acquisition. Eliminates the\n * \"create timed out at the proxy\" failure mode conceptually by DECOUPLING \"the\n * create HTTP call returned\" from \"the sandbox is ready\":\n *\n * - Create is initiated with a known `name`.\n * - Readiness is observed from the sandbox's own `status` (`refresh()` polls\n * true state), NOT from whether the create call returned in time.\n * - If the create call itself times out at a gateway (502/503/504/522/524 or\n * a transport timeout), provisioning is still running server-side — so we\n * find the named sandbox via `list()` and wait for it to reach `running`.\n *\n * Result: a scale-from-zero cold start (node boot + host-agent registration,\n * minutes) can no longer surface as a create failure behind a ~100s proxy\n * limit. The loop becomes indifferent to whether the host pool is warm or cold.\n *\n * Invariant: an instance reporting no `status` (the minimal test fakes) is\n * treated as ready; only an explicit `pending`/`provisioning` status triggers\n * waiting, and only a retryable THROW triggers the find-by-name path. Real\n * errors (auth, validation, budget) fail loud. A box that is created (or found)\n * but never reaches `running` (abort, terminal status, budget) is torn down\n * before the failure propagates, so an abort storm during cold start does not\n * leak live sandboxes.\n *\n * @experimental\n */\n\nimport type { CreateSandboxOptions, SandboxInstance } from '@tangle-network/sandbox'\nimport { ValidationError } from '../errors'\nimport type { SandboxClient } from './types'\nimport { sleep as abortableSleep, deleteBoxSafe, randomUuid, throwIfAborted } from './util'\n\n/**\n * HTTP statuses where create should be retried — gateway timeouts\n * (502/503/504/522/524) where provisioning may continue server-side, plus\n * request-level retryables (408/425/429).\n */\nconst RETRYABLE_HTTP = new Set([502, 503, 504, 522, 524, 408, 425, 429])\nconst TERMINAL_STATUS = new Set(['failed', 'expired', 'stopped'])\n\n/** @experimental */\nexport interface AcquireOptions {\n /**\n * Total budget for the sandbox to reach `running`, covering on-demand node\n * cold-start. Default 600_000ms — matches the orchestrator's pending-host\n * registration window so we never give up before the platform itself would.\n */\n readyTimeoutMs?: number\n /** Poll interval while waiting for `running` / for the named sandbox to appear. */\n pollIntervalMs?: number\n /** Cancellation (user abort). Distinct from create-call timeouts. */\n signal?: AbortSignal\n /** Stamp a name so a timed-out create is recoverable by lookup. Auto-generated if absent. */\n name?: string\n /** Clock override for deterministic tests. */\n now?: () => number\n /** Sleep override for deterministic tests. */\n sleep?: (ms: number) => Promise<void>\n}\n\n/** Minimal client surface acquire needs beyond `create` (the real SDK satisfies it). */\ninterface PollableClient extends SandboxClient {\n list?: (options?: unknown) => Promise<SandboxInstance[]>\n get?: (id: string) => Promise<SandboxInstance | null>\n}\n\n/**\n * Cold-start-resilient sandbox acquisition: create by name, observe readiness from the sandbox's own status (not the create call), and re-attach after gateway timeouts.\n *\n * @experimental\n */\nexport async function acquireSandbox(\n client: SandboxClient,\n options: CreateSandboxOptions,\n acquire: AcquireOptions = {},\n): Promise<SandboxInstance> {\n if (!client || typeof client.create !== 'function') {\n throw new ValidationError('acquireSandbox: client.create is required')\n }\n const now = acquire.now ?? Date.now\n const sleep = acquire.sleep ?? ((ms: number) => abortableSleep(ms, acquire.signal))\n const pollMs = acquire.pollIntervalMs ?? 3000\n const deadline = now() + (acquire.readyTimeoutMs ?? 600_000)\n // After a retryable create error (commonly a gateway/request timeout on a cold\n // scale-from-zero), the orchestrator has usually ACCEPTED the request and is\n // still provisioning the NAMED box — which appears in list() a few seconds\n // AFTER the create call gave up. Scan list() this many windows for it to\n // appear before re-POSTing: re-creating immediately restarts a fresh cold\n // provision and hits the same wall — that thrash is why a cold acquire never\n // converges within the budget; attaching to the in-flight box does.\n const appearScans = 5\n // crypto.randomUUID is collision-resistant — find-by-name recovery scans\n // list() for this exact name, so two concurrent acquires must never collide.\n const name = options.name ?? acquire.name ?? `loop-sbx-${randomUuid()}`\n const createOpts: CreateSandboxOptions = { ...options, name }\n const c = client as PollableClient\n\n let lastErr: unknown\n let attempt = 0\n while (now() < deadline) {\n throwIfAborted(acquire.signal)\n try {\n const box = await client.create(createOpts)\n // Tear the just-created box down if it never reaches `running` (abort,\n // terminal status, budget) so a failed wait never leaks a live sandbox.\n return await waitReadyOrDestroy(box, deadline, pollMs, acquire.signal, now, sleep)\n } catch (err) {\n throwIfAborted(acquire.signal)\n // Non-retryable (auth/validation/budget) fails loud immediately.\n if (!isRetryable(err)) throw err\n lastErr = err\n // Recovery for a gateway-timed-out create, in order:\n // (a) the orchestrator usually ACCEPTED the create and is provisioning\n // the named box — it appears in list() a few seconds later, so poll\n // for it across `appearScans` windows and attach (this is the cold-\n // start fix: a single scan misses a row not yet written and the loop\n // would otherwise re-POST a fresh cold provision every backoff);\n // (b) only if it never appears did the create truly roll back — retry\n // create with backoff (lands once a warm host exists / autoscaler\n // caught up).\n if (typeof c.list === 'function') {\n for (let scan = 0; scan < appearScans && now() < deadline; scan += 1) {\n const found = (await c.list().catch(() => []))?.find((b) => b.name === name)\n if (found)\n return await waitReadyOrDestroy(found, deadline, pollMs, acquire.signal, now, sleep)\n if (scan < appearScans - 1) await sleep(pollMs)\n }\n }\n attempt += 1\n await sleep(Math.min(pollMs * attempt, 15_000))\n }\n }\n throw new ValidationError(\n `acquireSandbox: could not acquire a running sandbox \"${name}\" within budget`,\n { cause: lastErr instanceof Error ? lastErr : undefined },\n )\n}\n\n/** `waitUntilReady`, tearing the box down (best-effort) on any throw so a box\n * that never reaches `running` (abort, terminal status, budget) does not leak. */\nasync function waitReadyOrDestroy(\n box: SandboxInstance,\n deadline: number,\n pollMs: number,\n signal: AbortSignal | undefined,\n now: () => number,\n sleep: (ms: number) => Promise<void>,\n): Promise<SandboxInstance> {\n try {\n return await waitUntilReady(box, deadline, pollMs, signal, now, sleep)\n } catch (err) {\n await deleteBoxSafe(box)\n throw err\n }\n}\n\n/** Wait for `running`. No status (minimal fakes) = ready. Terminal status throws. */\nasync function waitUntilReady(\n box: SandboxInstance,\n deadline: number,\n pollMs: number,\n signal: AbortSignal | undefined,\n now: () => number,\n sleep: (ms: number) => Promise<void>,\n): Promise<SandboxInstance> {\n for (;;) {\n throwIfAborted(signal)\n const status = readStatus(box)\n if (status === undefined || status === 'running') return box\n if (TERMINAL_STATUS.has(status)) {\n throw new ValidationError(\n `acquireSandbox: sandbox ${box.id ?? '(unknown)'} is ${status}${box.error ? `: ${box.error}` : ''}`,\n )\n }\n if (now() >= deadline) {\n throw new ValidationError(\n `acquireSandbox: sandbox ${box.id ?? '(unknown)'} not running within budget (last status: ${status})`,\n )\n }\n await sleep(pollMs)\n if (typeof box.refresh === 'function') await box.refresh()\n }\n}\n\nfunction readStatus(box: SandboxInstance): string | undefined {\n const s = (box as { status?: unknown }).status\n return typeof s === 'string' ? s : undefined\n}\n\nfunction isRetryable(err: unknown): boolean {\n if (!err || typeof err !== 'object') return false\n const e = err as { status?: number; statusCode?: number; name?: string; message?: string }\n const status = e.status ?? e.statusCode\n if (typeof status === 'number') {\n // An explicit HTTP status is authoritative: retry the known-transient set\n // and server-side faults (>=500, where provisioning may recover), and treat\n // every other status — permanent 4xx like 400/401/403 — as terminal no\n // matter what the message says. A permanent rejection often carries a\n // transient-looking message (\"provision failed\"), and retrying it burns the\n // entire ready budget on an error that cannot heal.\n return RETRYABLE_HTTP.has(status) || status >= 500\n }\n const name = e.name ?? ''\n if (name === 'TimeoutError' || name === 'ServerError' || name === 'NetworkError') return true\n const msg = e.message ?? ''\n // Transient TRANSPORT failures.\n if (\n /\\b(timed out|timeout|gateway|temporarily unavailable|too many requests|ECONNRESET|ETIMEDOUT|EAI_AGAIN)\\b/i.test(\n msg,\n )\n ) {\n return true\n }\n // Transient PLATFORM provisioning failures thrown by `create` itself — edge data\n // plane unreachable, container-phase provision failure, or a rolled-back create.\n // Message signatures classify ONLY status-less errors (transport-level throws);\n // an error that carried a numeric status was already decided above.\n // Retry create onto a FRESH host rather than failing the whole rollout; the loop\n // stays bounded by the ready deadline. A box that booted and then reached a\n // terminal `failed` status with a real error is NOT retried here — that's a genuine\n // fault surfaced by `waitUntilReady`, not a host blip.\n return /provision failed|edge data plane|not reachable|failed to create sandbox/i.test(msg)\n}\n","/**\n *\n * Backend-options assembly shared by the loop kernel's `createSandboxForSpec`\n * and the sandbox planner's box creation, so the worker box and the planner box\n * boot identically. Builds the options only — the acquire path (cold-start\n * recovery) lives in the kernel, the planner calls `client.create` directly.\n *\n * @experimental\n */\n\nimport type { AgentProfile, HarnessType } from '@tangle-network/agent-interface'\nimport type { CreateSandboxOptions } from '@tangle-network/sandbox'\nimport { assertExecutableAgentProfile, concreteProfileModel } from './supervise/model-policy'\n\ntype BackendType = NonNullable<CreateSandboxOptions['backend']>['type']\ntype BackendOverride = NonNullable<CreateSandboxOptions['backend']>\n\n/**\n * Harnesses the sandbox accepts as a `backend.type`. `gemini` is a\n * `HarnessType` with no sandbox backend, so it is absent here and a profile\n * declaring it cannot run through this path.\n *\n * The double `satisfies` pins both directions: an entry the sandbox drops stops\n * compiling, and an entry that is not a harness stops compiling.\n */\nconst harnessBackends = [\n 'claude-code',\n 'nanoclaw',\n 'codex',\n 'opencode',\n 'kimi-code',\n 'pi',\n 'prime',\n 'hermes',\n 'openclaw',\n 'amp',\n 'factory-droids',\n 'acp',\n 'cli-base',\n] as const satisfies readonly HarnessType[] satisfies readonly BackendType[]\n\nfunction harnessAsBackendType(harness: HarnessType): BackendType | undefined {\n return (harnessBackends as readonly string[]).includes(harness)\n ? (harness as BackendType)\n : undefined\n}\n\n/**\n * Resolve the backend `type` from the exact profile's declared `harness`.\n *\n * A declared `harness` the sandbox cannot run throws rather than falling\n * through: silently running a `gemini` profile on opencode returns a result\n * that means something other than it appears to, which is worse than no result.\n */\nfunction resolveBackendType(\n profile: AgentProfile,\n override: Partial<BackendOverride> | undefined,\n): BackendType {\n const declared = profile.harness\n const selected = declared === undefined ? undefined : harnessAsBackendType(declared)\n if (selected === undefined) {\n throw new Error(\n `buildBackendOptions: profile declares harness ${JSON.stringify(declared)}, which the sandbox has no backend for. ` +\n `Runnable harnesses: ${harnessBackends.join(', ')}.`,\n )\n }\n if (override?.type && selected && override.type !== selected) {\n throw new Error(\n `buildBackendOptions: backend override ${JSON.stringify(override.type)} conflicts with AgentProfile backend ${JSON.stringify(selected)}`,\n )\n }\n return selected\n}\n\n/**\n * Build `CreateSandboxOptions` for `profile`, merging `overrides` and setting\n * `backend.profile`. `model`/`server` from an override backend pass through.\n */\nexport function buildBackendOptions(\n profile: AgentProfile,\n overrides: Partial<CreateSandboxOptions> | undefined,\n): CreateSandboxOptions {\n assertExecutableAgentProfile(profile, 'buildBackendOptions')\n const base = overrides ?? {}\n const overrideBackend = base.backend\n const overrideModel = overrideBackend?.model?.model\n const profileModel = concreteProfileModel(profile)\n if (overrideModel !== undefined && overrideModel !== profileModel) {\n throw new Error(\n `buildBackendOptions: backend model ${JSON.stringify(overrideModel)} conflicts with AgentProfile model ${JSON.stringify(profileModel)}`,\n )\n }\n return {\n ...base,\n backend: {\n type: resolveBackendType(profile, overrideBackend),\n profile,\n ...(overrideBackend?.server ? { server: overrideBackend.server } : {}),\n },\n }\n}\n","/**\n *\n * Capability probe for the loop kernel's backend-blind lineage seams. The\n * kernel must NEVER ask \"is this Docker or Firecracker?\"; it asks \"can this\n * platform fork a checkpoint?\" via `client.criuStatus()` and degrades to fresh\n * boxes when the answer is no. CRIU availability is a per-platform fact, so the\n * probe is memoized per client — one network round-trip, reused across every\n * fanout in the run.\n *\n * Invariant: a client with no `criuStatus` method (the loop's test fakes, the\n * raw SDK before it grew the probe) reports `canFork = false`. The seam is\n * fail-CLOSED — never assume forking works, only enable it on a positive probe.\n *\n * @experimental\n */\n\nimport type { SandboxClient } from './types'\n\n/**\n * What the loop kernel is allowed to know about a sandbox backend: a single\n * capability bit, never the backend's identity. `canFork` gates the\n * checkpoint+fork fanout path; everything else (session continuation) is a\n * universal SDK feature that needs no probe.\n *\n * @experimental\n */\nexport interface SandboxCapabilities {\n /**\n * True only when `client.criuStatus()` returned `{ available: true }`. When\n * false, a fork-enabled fanout degrades to independent fresh boxes — same\n * result, no shared context prefix.\n */\n canFork: boolean\n}\n\nconst probeCache = new WeakMap<object, Promise<SandboxCapabilities>>()\n\n/**\n * Probe (and memoize per client) what the loop may rely on. A client without a\n * `criuStatus` method, or whose probe rejects, yields `canFork = false` — a\n * failed probe must never claim a capability the platform may not have. The\n * promise is cached so concurrent fanout branches share one round-trip.\n *\n * @experimental\n */\nexport function probeSandboxCapabilities(client: SandboxClient): Promise<SandboxCapabilities> {\n const key = client as unknown as object\n const cached = probeCache.get(key)\n if (cached) return cached\n const probe = resolveCapabilities(client)\n probeCache.set(key, probe)\n return probe\n}\n\nasync function resolveCapabilities(client: SandboxClient): Promise<SandboxCapabilities> {\n const criuStatus = (client as CriuCapableClient).criuStatus\n if (typeof criuStatus !== 'function') return { canFork: false }\n try {\n const status = await criuStatus.call(client)\n return { canFork: status?.available === true }\n } catch {\n // A probe that throws (transport error, unsupported endpoint) is treated as\n // \"no fork\" — fail closed so a flaky probe degrades to fresh boxes rather\n // than attempting a checkpoint the platform can't honor.\n return { canFork: false }\n }\n}\n\n/**\n * Narrowed view of the optional CRIU probe. The loop-side `SandboxClient`\n * does not require `criuStatus`; this widens it optionally so the probe can be\n * read without importing sandbox-backend specifics. @experimental\n */\nexport interface CriuCapableClient {\n criuStatus?: () => Promise<{ available: boolean; criuVersion?: string; reason?: string }>\n}\n","/**\n *\n * `SandboxLineage` — the backend-blind owner of box + session handles for a\n * single `runAgentRounds` invocation. It exists so `run-loop.ts` never references a\n * backend (Docker / Firecracker): the lineage turns \"continue this session\" and\n * \"fork this branch\" into capability-gated sandbox-SDK calls and degrades to\n * fresh boxes when a capability is absent.\n *\n * Three operations, mirroring the kernel's per-iteration choices:\n * - `start(spec, prompt)` → a fresh box; the FIRST `streamPrompt` carries a\n * minted `sessionId` so later `continue` calls reuse the same server-side\n * conversation instead of re-injecting prior context as prompt text.\n * - `continue(handle, prompt)` → the SAME box, `streamPrompt({ sessionId })`.\n * The context lives in the sandbox; the prompt is only the new turn. Before\n * streaming it ASSERTS the session is still live server-side (via\n * `box.session(id).status()`): if the platform never honored the\n * client-minted id (or reaped it), `status()` is `null` and `continue`\n * fails loud rather than silently re-running the turn without prior context.\n * - `fork(handle, n, ...)` → when `canFork`, `checkpoint({ leaveRunning })` on\n * the parent then `fork(checkpointId)` × n so N branches inherit a shared\n * context prefix; otherwise N independent fresh boxes (same result, no\n * prefix). Either way each branch streams its own turn. Child-box creation\n * is bounded by the lineage's `maxConcurrency` — a 20-way fanout under a\n * concurrency cap of 2 provisions boxes in bounded waves, not all at once.\n *\n * Invariant: the lineage OWNS every box it starts or forks and tears them all\n * down on `teardown()` (or earlier via `prune`). It never tears down a box\n * mid-flight — the kernel decides when a handle is done. Streaming itself stays\n * in `run-loop.ts`; the lineage only hands back the live `streamPrompt` iterable\n * so the kernel keeps ownership of event collection, cost accounting, and trace\n * emission.\n *\n * @experimental\n */\n\nimport type {\n CreateSandboxOptions,\n PromptOptions,\n SandboxEvent,\n SandboxInstance,\n} from '@tangle-network/sandbox'\nimport { ValidationError } from '../errors'\nimport { acquireSandbox } from './sandbox-acquire'\nimport { buildBackendOptions } from './sandbox-backend'\nimport type { SandboxCapabilities } from './sandbox-capabilities'\nimport type { AgentRunSpec, MountRecorder, SandboxClient } from './types'\nimport {\n deleteBoxSafe,\n mapWithConcurrency,\n randomUuid,\n throwAbort,\n throwIfAborted,\n withTimeout,\n} from './util'\n\nconst TEARDOWN_TIMEOUT_MS = 15_000\nconst DEFAULT_FORK_CONCURRENCY = 4\n\n/**\n * One turn's event stream, in the lineage's chosen streaming mode.\n *\n * - `'sse'` (default): live `streamPrompt` — low latency, full per-token trace.\n * Best for interactive chat.\n * - `'poll'`: fire-and-detach via `dispatchPrompt`, await the terminal result by\n * status-polling (NOT a held SSE), then yield the answer as one synthesized\n * event. A long, quiet in-box turn (clone + build + test) never holds a live\n * stream a proxy idle-timeout can drop mid-execution — the failure mode that\n * made batch eval runs lose their stream on both prod and staging. Lower trace\n * fidelity (one terminal event, not per-token), so it is opt-in for batch.\n *\n * Both yield the same `SandboxEvent` vocabulary, so callers are agnostic.\n */\nasync function* pollPromptEvents(\n box: SandboxInstance,\n prompt: string,\n sessionId: string,\n signal: AbortSignal,\n promptOptions?: Omit<PromptOptions, 'signal' | 'sessionId'>,\n): AsyncIterable<SandboxEvent> {\n if (signal.aborted) throwAbort()\n // dispatchPrompt returns the session id the platform actually assigned, which\n // may be one it MINTED rather than the supplied `sessionId`. Polling the\n // supplied id when the platform minted a different one 404s the session-events\n // endpoint (\"Resource not found\"). Always follow the assigned id.\n const dispatched = await box.dispatchPrompt(prompt, {\n ...(promptOptions ?? {}),\n sessionId,\n signal,\n })\n const activeSessionId = dispatched.sessionId\n const result = await box.session(activeSessionId).result()\n if (signal.aborted) throwAbort()\n yield {\n type: 'result',\n id: activeSessionId,\n data: {\n finalText: result.response ?? '',\n success: result.success,\n ...(result.error ? { error: result.error } : {}),\n ...(result.usage ? { usage: result.usage } : {}),\n },\n }\n}\n\nexport function promptEvents(\n streaming: 'sse' | 'poll',\n box: SandboxInstance,\n prompt: string,\n sessionId: string,\n signal: AbortSignal,\n promptOptions?: Omit<PromptOptions, 'signal' | 'sessionId'>,\n): AsyncIterable<SandboxEvent> {\n return streaming === 'poll'\n ? pollPromptEvents(box, prompt, sessionId, signal, promptOptions)\n : box.streamPrompt(prompt, { ...(promptOptions ?? {}), sessionId, signal })\n}\n\n/**\n * A live box plus the session that threads its iterations together. Handed back\n * by `start`/`fork`, passed into `continue`/`fork` to descend from. Opaque to\n * the kernel beyond `box` (for placement/teardown) and `sessionId` (trace).\n *\n * @experimental\n */\nexport interface SandboxLineageHandle {\n /** The owned, running sandbox this handle drives. */\n box: SandboxInstance\n /**\n * Stable session id threaded through this box's `streamPrompt` calls. Minted\n * by the lineage on `start`; reused on `continue` so the server continues the\n * same conversation. A forked handle starts a fresh session on its new box —\n * the shared context comes from the checkpoint, not a shared session id.\n */\n sessionId: string\n}\n\n/**\n * Owns box + session handles for one loop run and offers the three\n * capability-gated lifecycle moves. Construct via `createSandboxLineage`.\n *\n * @experimental\n */\nexport interface SandboxLineage {\n /**\n * Acquire a fresh box and begin a new session on it. Returns the handle and\n * the live `streamPrompt` iterable for the first turn (caller drains it).\n */\n start(\n spec: AgentRunSpec<unknown>,\n prompt: string,\n signal: AbortSignal,\n promptOptions?: Omit<PromptOptions, 'signal' | 'sessionId'>,\n ): Promise<{ handle: SandboxLineageHandle; events: AsyncIterable<SandboxEvent> }>\n /**\n * Continue an existing handle's session with one more turn on the SAME box.\n * The prior context is server-side; `prompt` is only the new turn. Asserts the\n * session is still known to the sandbox first (fail-loud) so a platform that\n * silently dropped the client-minted session id surfaces as an error instead\n * of a contextless turn the caller mistakes for a real continuation.\n */\n continue(\n handle: SandboxLineageHandle,\n prompt: string,\n signal: AbortSignal,\n promptOptions?: Omit<PromptOptions, 'signal' | 'sessionId'>,\n ): Promise<AsyncIterable<SandboxEvent>>\n /**\n * Branch `count` children from `parent`. When the platform can fork, each\n * child inherits `parent`'s checkpoint — and therefore the parent's IMAGE and\n * PROFILE: under a real fork `specs[i]` does NOT re-select a per-branch\n * profile (the SDK forks the running box, it can't swap the image). `specs[i]`\n * picks the per-branch profile ONLY on the degraded fresh-box path (no CRIU).\n * A heterogeneous-profile fanout therefore homogenizes to the parent's profile\n * when fork is available — pass a single shared spec for forked fanouts, or\n * use `random@k` (no fork) when branches must differ. Each child's first turn\n * streams `prompts[i]`. Child-box creation is bounded by `maxConcurrency`.\n */\n fork(\n parent: SandboxLineageHandle,\n prompts: string[],\n specs: AgentRunSpec<unknown>[],\n signal: AbortSignal,\n ): Promise<{ handle: SandboxLineageHandle; events: AsyncIterable<SandboxEvent> }[]>\n /**\n * Destroy every owned box whose handle is NOT in `keep`, freeing it before\n * loop end. The kernel calls this after a round when it can prove no future\n * round will descend from the pruned boxes (deterministic, monotonic branch\n * selection); boxes still reachable as a future branch source are retained.\n * Best-effort, bounded, parallel — a failed delete never throws.\n */\n prune(keep: Iterable<SandboxLineageHandle>): Promise<void>\n /** Destroy every box this lineage owns. Best-effort, bounded, parallel. */\n teardown(): Promise<void>\n}\n\n/**\n * Build a lineage bound to one client + its probed capabilities. The\n * capabilities are passed in (not re-probed) so the kernel probes once per run\n * and the lineage stays a pure function of \"what this platform can do\".\n *\n * @experimental\n */\nexport function createSandboxLineage(\n client: SandboxClient,\n capabilities: SandboxCapabilities,\n options: {\n maxConcurrency?: number\n streaming?: 'sse' | 'poll'\n /** Run provenance recorder forwarded to every `prepareBox` the lineage runs\n * (fresh start, continue, and fork branches). Absent ⇒ mounts go unrecorded\n * (a no-op recorder stands in so the ctx shape is always satisfied). */\n recordMount?: MountRecorder\n } = {},\n): SandboxLineage {\n if (!client || typeof client.create !== 'function') {\n throw new ValidationError('createSandboxLineage: client.create is required')\n }\n // 'sse' (default) preserves the byte-identical live-stream behavior; 'poll' is\n // the drop-resilient fire-and-detach path for long, quiet batch turns.\n const streaming = options.streaming ?? 'sse'\n const recordMount: MountRecorder = options.recordMount ?? (() => {})\n // Bounds the burst of box creation inside `fork` so an N-way fanout doesn't\n // provision N boxes simultaneously regardless of the loop's concurrency cap.\n const forkConcurrency = Math.max(\n 1,\n Math.floor(options.maxConcurrency ?? DEFAULT_FORK_CONCURRENCY),\n )\n const owned: SandboxInstance[] = []\n\n const acquireFresh = async (\n spec: AgentRunSpec<unknown>,\n signal: AbortSignal,\n ): Promise<SandboxInstance> => {\n if (signal.aborted) throwAbort()\n const opts: CreateSandboxOptions = buildBackendOptions(spec.profile, spec.sandboxOverrides)\n const box = await acquireSandbox(client, opts, { signal })\n await spec.prepareBox?.(box, { signal, recordMount })\n owned.push(box)\n return box\n }\n\n return {\n async start(spec, prompt, signal, promptOptions) {\n const box = await acquireFresh(spec, signal)\n const sessionId = mintSessionId()\n const events = promptEvents(streaming, box, prompt, sessionId, signal, promptOptions)\n return { handle: { box, sessionId }, events }\n },\n\n async continue(handle, prompt, signal, promptOptions) {\n if (signal.aborted) throwAbort()\n // Fail loud if the platform did not preserve the client-minted session:\n // continuing a dead/unknown session would silently lose all prior context.\n await assertSessionLive(handle.box, handle.sessionId)\n // Same box, same session id — the server continues the conversation; we do\n // NOT re-acquire and do NOT re-inject prior context as prompt text.\n return promptEvents(streaming, handle.box, prompt, handle.sessionId, signal, promptOptions)\n },\n\n async fork(parent, prompts, specs, signal) {\n if (prompts.length === 0) {\n throw new ValidationError('SandboxLineage.fork: prompts must be non-empty')\n }\n if (signal.aborted) throwAbort()\n const checkpointId = capabilities.canFork\n ? await checkpointForFork(parent.box, signal)\n : undefined\n // checkpointId === undefined ⇒ either the platform can't fork or the\n // checkpoint call yielded nothing usable: degrade to independent fresh\n // boxes. Never silently reuse the parent box for a branch.\n //\n // Bounded by `forkConcurrency`: an N-way fanout creates child boxes in\n // waves of at most `forkConcurrency`, not all N at once. Abort is checked\n // per branch (between waves), since the SDK's `fork`/`create` calls take no\n // signal and cannot be interrupted once in flight.\n return mapWithConcurrency(prompts, forkConcurrency, async (prompt, i) => {\n throwIfAborted(signal)\n const spec = specs[i % specs.length]\n if (!spec) throw new ValidationError('SandboxLineage.fork: no AgentRunSpec for branch')\n if (checkpointId !== undefined) {\n const box = await forkFromCheckpoint(parent.box, checkpointId, signal)\n owned.push(box)\n await spec.prepareBox?.(box, { signal, recordMount })\n const sessionId = mintSessionId()\n return {\n handle: { box, sessionId },\n events: promptEvents(streaming, box, prompt, sessionId, signal),\n }\n }\n const box = await acquireFresh(spec, signal)\n const sessionId = mintSessionId()\n return {\n handle: { box, sessionId },\n events: promptEvents(streaming, box, prompt, sessionId, signal),\n }\n })\n },\n\n async prune(keep) {\n const keepBoxes = new Set<SandboxInstance>()\n for (const handle of keep) keepBoxes.add(handle.box)\n const survivors: SandboxInstance[] = []\n const doomed: SandboxInstance[] = []\n for (const box of owned) (keepBoxes.has(box) ? survivors : doomed).push(box)\n if (doomed.length === 0) return\n owned.length = 0\n owned.push(...survivors)\n await Promise.allSettled(doomed.map((box) => destroyBounded(box)))\n },\n\n async teardown() {\n const boxes = owned.splice(0, owned.length)\n await Promise.allSettled(boxes.map((box) => destroyBounded(box)))\n },\n }\n}\n\n/** Stable, collision-resistant session id minted per box (the caller owns the id). */\nfunction mintSessionId(): string {\n return `loop-sess-${randomUuid()}`\n}\n\n/**\n * Checkpoint the parent leaving it running, returning the checkpoint id to fork\n * from, or `undefined` when the box exposes no `checkpoint` (the loop's fakes)\n * or the call produced no id. `undefined` makes the caller degrade to fresh\n * boxes — a fork that can't checkpoint must not pretend to share context.\n */\nasync function checkpointForFork(\n box: SandboxInstance,\n signal: AbortSignal,\n): Promise<string | undefined> {\n const checkpoint = (box as CheckpointCapableBox).checkpoint\n if (typeof checkpoint !== 'function') return undefined\n if (signal.aborted) throwAbort()\n const result = await checkpoint.call(box, { leaveRunning: true })\n const id = result?.checkpointId\n return typeof id === 'string' && id.length > 0 ? id : undefined\n}\n\n/**\n * Fork a child box from `checkpointId`. The box exposes `fork` whenever the\n * platform advertised `canFork`; a missing `fork` here is a contract violation\n * (probe said yes, box says no) and fails loud rather than silently degrading.\n *\n * `signal` gates entry only: the SDK's `fork(checkpointId, options)` takes no\n * abort signal (`ForkOptions` is name/env/resources/metadata), so an in-flight\n * fork cannot be interrupted. The caller (`fork`) checks abort per branch, so\n * cancellation is responsive at branch boundaries, not mid-fork.\n */\nasync function forkFromCheckpoint(\n box: SandboxInstance,\n checkpointId: string,\n signal: AbortSignal,\n): Promise<SandboxInstance> {\n const fork = (box as ForkCapableBox).fork\n if (typeof fork !== 'function') {\n throw new ValidationError(\n 'SandboxLineage.fork: capabilities report canFork but the box has no fork() method',\n )\n }\n if (signal.aborted) throwAbort()\n return fork.call(box, checkpointId)\n}\n\n/**\n * Fail loud when a handle's session is no longer known to the sandbox. The real\n * SDK box exposes `session(id).status()` which resolves `null` for an unknown /\n * reaped id; a `null` here means a `continue` would run WITHOUT the prior\n * context the caller believes is threaded — so refuse it. Boxes that expose no\n * `session` method (the loop's test fakes, or an SDK without the session API)\n * cannot be verified and are allowed through unchecked.\n */\nasync function assertSessionLive(box: SandboxInstance, sessionId: string): Promise<void> {\n const session = (box as SessionCapableBox).session\n if (typeof session !== 'function') return\n const info = await session.call(box, sessionId).status()\n if (info === null) {\n throw new ValidationError(\n `SandboxLineage.continue: session ${sessionId} is not known to the sandbox — the platform ` +\n 'did not preserve the client-minted session id (or it was reaped). Continuing would run ' +\n 'without prior context; refusing to silently lose conversation continuity.',\n )\n }\n}\n\nasync function destroyBounded(box: SandboxInstance): Promise<void> {\n await withTimeout(deleteBoxSafe(box), TEARDOWN_TIMEOUT_MS)\n}\n\n/**\n * Loop-side widening of the box's optional checkpoint method. The\n * `SandboxClient`/`SandboxInstance` surface the kernel relies on does not\n * require checkpointing; this reads it optionally so the lineage can probe-gate\n * without importing sandbox-backend specifics. @experimental\n */\nexport interface CheckpointCapableBox {\n checkpoint?: (options?: { leaveRunning?: boolean; tags?: string[] }) => Promise<{\n checkpointId: string\n }>\n}\n\n/** Loop-side widening of the box's optional fork method. @experimental */\nexport interface ForkCapableBox {\n fork?: (checkpointId: string, options?: { name?: string }) => Promise<SandboxInstance>\n}\n\n/**\n * Loop-side widening of the box's optional session accessor. The real\n * `SandboxInstance` exposes `session(id).status()`; the loop reads it optionally\n * so `continue` can assert session liveness without requiring it of the test\n * fakes. `status()` resolves `null` when the id is unknown to the sandbox.\n * @experimental\n */\nexport interface SessionCapableBox {\n session?: (id: string) => { status: () => Promise<unknown | null> }\n}\n","/**\n *\n * `runAgentRounds` — the topology-agnostic kernel built atop the sandbox SDK.\n *\n * Each iteration:\n * 1. `driver.plan(task, history)` → N tasks (1 = refine, N = fanout, 0 = stop)\n * 2. For each task (parallel, bounded by `maxConcurrency`):\n * a. round-robin an `AgentRunSpec` from `agentRuns`\n * b. `sandboxClient.create({ backend: { profile }, ...overrides })`\n * c. emit `loop.iteration.dispatch` with the placement\n * (`{ sibling, sandboxId }` or `{ fleet, fleetId, machineId, sandboxId }`)\n * d. iterate `box.streamPrompt(taskToPrompt(task))` and collect events\n * 3. `output.parse(events)` → typed `Output`\n * 4. `validator?.validate(output)` → `DefaultVerdict`\n * 5. Append `Iteration` to history; emit `loop.iteration.ended`\n * 6. `driver.decide(history)` → if terminal, return result + winner\n *\n * The kernel owns: iteration accounting, per-iteration timing, error\n * capture, abort propagation, concurrency cap, cost aggregation, and trace\n * emission. The kernel does NOT own: what the agent runs (sandbox SDK +\n * profile), how outputs are decoded (output adapter), how outputs are\n * scored (validator), or topology (driver).\n *\n * @stable\n */\n\nimport type { SandboxEvent, SandboxInstance } from '@tangle-network/sandbox'\nimport { ValidationError } from '../errors'\nimport { notifyRuntimeHookEvent } from '../runtime-hooks'\nimport { acquireSandbox } from './sandbox-acquire'\nimport { buildBackendOptions } from './sandbox-backend'\nimport { probeSandboxCapabilities } from './sandbox-capabilities'\nimport { extractLlmCallEvent, notifySandboxEventObserver } from './sandbox-events'\nimport {\n createSandboxLineage,\n promptEvents,\n type SandboxLineage,\n type SandboxLineageHandle,\n} from './sandbox-lineage'\nimport { assertExecutableAgentProfile } from './supervise/model-policy'\nimport type {\n AgentRunSpec,\n Driver,\n ExecCtx,\n Iteration,\n LoopLineageOptions,\n LoopResult,\n LoopSandboxPlacement,\n LoopTokenUsage,\n LoopTraceEmitter,\n LoopTraceEvent,\n LoopWinner,\n MountManifestEntry,\n MountRecorder,\n OutputAdapter,\n SandboxClient,\n SelectionReceipt,\n Validator,\n} from './types'\nimport {\n addTokenUsage,\n deleteBoxSafe,\n randomSuffix,\n stringifySafe,\n throwAbort,\n withTimeout,\n zeroTokenUsage,\n} from './util'\n\nconst DEFAULT_MAX_ITERATIONS = 10\nconst DEFAULT_MAX_CONCURRENCY = 4\n\n/** @stable */\nexport interface RunAgentRoundsOptions<Task, Output, Decision> {\n driver: Driver<Task, Output, Decision>\n /**\n * Single agent spec — every iteration uses this profile. Mutually\n * exclusive with `agentRuns`.\n */\n agentRun?: AgentRunSpec<Task>\n /**\n * Multiple specs for heterogeneous fanout. The kernel round-robins\n * through them when the driver plans N tasks. Mutually exclusive with\n * `agentRun`.\n */\n agentRuns?: AgentRunSpec<Task>[]\n output: OutputAdapter<Output>\n validator?: Validator<Output>\n task: Task\n ctx: ExecCtx\n /** Default 10. Hard cap on total iterations across all `plan()` rounds. */\n maxIterations?: number\n /** Default 4. In-flight worker cap within a single `plan()` batch. */\n maxConcurrency?: number\n /**\n * Pre-allocated id for trace correlation. Default = `loop-${random}`.\n * Surfaces as `runId` on every emitted `LoopTraceEvent`.\n */\n runId?: string\n /**\n * Clock override; default `Date.now`. Deterministic tests pass a\n * monotonic counter to stabilize iteration timing fields.\n */\n now?: () => number\n /**\n * Override the default winner selector (highest-valid-score, ties broken\n * by earliest iteration).\n */\n selectWinner?: (iterations: Iteration<Task, Output>[]) => LoopWinner<Task, Output> | undefined\n /**\n * Same-sandbox driver mode — a kernel→caller out-channel, not a value handed\n * in. When set, the kernel keeps each finished worker box alive across the\n * `plan()` boundary and hands it here, so a same-sandbox planner\n * (one that reuses the worker's box) can stream its move INTO the\n * worker's live box — steering from the worker's real filesystem and state,\n * not just a history summary. The kernel owns teardown: every box kept alive\n * this way is destroyed at loop end (and the callback is invoked with\n * `undefined` then as a teardown sentinel). Without it, worker boxes are torn\n * down per-iteration (default) and a same-sandbox planner has nothing to\n * reuse. Intended for single-worker (refine) loops: under fanout every box is\n * still kept for teardown, but only the last-finishing box is handed here, so\n * a planner sees an arbitrary branch's filesystem — pair it with refine.\n */\n onWorkerBox?: (box: SandboxInstance | undefined) => void\n /**\n * Opt-in box-lineage controls. Default OFF — unset means every iteration\n * acquires a fresh box, streams once, and tears it down (today's behavior,\n * byte-identical). With `sessionContinuity` on, a refine round continues the\n * parent iteration's session on its live box; with `forkFanout` on (and a\n * fork-capable platform), a fanout round forks the parent's checkpoint so the\n * branches share a context prefix. The lineage owns every box it starts or\n * forks and tears them all down at loop end — so these paths are mutually\n * exclusive with `onWorkerBox`, which claims the same box-ownership channel.\n * @experimental\n */\n lineage?: LoopLineageOptions\n}\n\n/**\n * The round-synchronous MULTI-AGENT kernel: each round `driver.plan()` fans N tasks\n * out to N sandboxes (bounded concurrency), parses + validates each output, and folds\n * the round's results through `driver.decide` — fanout → validate → vote/select →\n * refine, repeated until the driver says stop. One call spans many agent sessions.\n *\n * Not to be confused with `runToolLoop` / `streamToolLoop` (`/tool-loop`): those\n * run ONE chat turn against ONE model, dispatching the tool calls that turn emits and\n * folding the results back in until the model stops calling tools. No sandboxes, no\n * rounds, no winner selection.\n *\n * @stable\n */\nexport async function runAgentRounds<Task, Output, Decision>(\n options: RunAgentRoundsOptions<Task, Output, Decision>,\n): Promise<LoopResult<Task, Output, Decision>> {\n const specs = resolveAgentRuns(options)\n for (const [index, spec] of specs.entries()) {\n assertExecutableAgentProfile(spec.profile, `runAgentRounds: agent spec ${index}`)\n }\n const maxIterations = options.maxIterations ?? DEFAULT_MAX_ITERATIONS\n if (!Number.isFinite(maxIterations) || maxIterations <= 0) {\n throw new ValidationError('runAgentRounds: maxIterations must be > 0')\n }\n const maxConcurrency = options.maxConcurrency ?? DEFAULT_MAX_CONCURRENCY\n if (!Number.isFinite(maxConcurrency) || maxConcurrency <= 0) {\n throw new ValidationError('runAgentRounds: maxConcurrency must be > 0')\n }\n // Default fresh-box path streaming mode (read regardless of lineage activation,\n // which gates on sessionContinuity/forkFanout — the bench uses neither).\n const sandboxStreaming = options.lineage?.streaming ?? 'sse'\n if (!options.ctx?.sandboxClient || typeof options.ctx.sandboxClient.create !== 'function') {\n throw new ValidationError('runAgentRounds: ctx.sandboxClient.create is required')\n }\n const now = options.now ?? Date.now\n const runId = options.runId ?? `loop-${randomSuffix()}`\n const loopStart = now()\n const driverName = options.driver.name ?? 'driver'\n const iterations: Iteration<Task, Output>[] = []\n // Per-run provenance manifest. `recordMount` is threaded into every box\n // preparation path (fresh + lineage) so a `prepareBox` declares what it\n // mounted. The kernel never inspects box contents — it only collects what the\n // caller records.\n const mounts: MountManifestEntry[] = []\n const recordMount: MountRecorder = (entry) => {\n mounts.push(entry)\n }\n let round = 0\n // Same-sandbox mode: worker boxes are kept alive (not torn down per-iteration)\n // so the planner can stream into the latest; the kernel destroys them at loop end.\n const ownedBoxes: SandboxInstance[] = []\n const collectBox = options.onWorkerBox\n ? (box: SandboxInstance) => {\n ownedBoxes.push(box)\n options.onWorkerBox?.(box)\n }\n : undefined\n\n // Opt-in box lineage: when either flag is set, a backend-blind lineage owns\n // box+session handles so a refine continues the parent session and a fanout\n // forks the parent checkpoint. Both flags off ⇒ lineage stays undefined and\n // the per-iteration acquire/stream/teardown path is byte-identical to today.\n const lineageState = await setUpLineage(options, maxConcurrency, recordMount)\n\n emitRunLoopHook(options, {\n target: 'agent.run',\n phase: 'before',\n runId,\n timestamp: now(),\n payload: {\n driver: driverName,\n agentRunNames: specs.map((spec) => spec.name ?? spec.profile.name ?? 'agent'),\n maxIterations,\n maxConcurrency,\n },\n })\n\n await emitTrace(options.ctx.traceEmitter, {\n kind: 'loop.started',\n runId,\n timestamp: now(),\n payload: {\n driver: driverName,\n agentRunNames: specs.map((spec) => spec.name ?? spec.profile.name ?? 'agent'),\n maxIterations,\n maxConcurrency,\n },\n })\n\n const controller = new AbortController()\n const onOuterAbort = () => controller.abort()\n if (options.ctx.signal) {\n if (options.ctx.signal.aborted) controller.abort()\n else options.ctx.signal.addEventListener('abort', onOuterAbort, { once: true })\n }\n\n try {\n while (iterations.length < maxIterations) {\n if (controller.signal.aborted) throwAbort()\n emitRunLoopHook(options, {\n target: 'agent.plan',\n phase: 'before',\n runId,\n timestamp: now(),\n stepIndex: round,\n payload: { roundIndex: round, historyLength: iterations.length },\n })\n const planned = await options.driver.plan(options.task, iterations)\n // plan() may be a long LLM call (sandbox planner); an abort during it must\n // not launch a fresh batch of workers on an already-cancelled loop.\n if (controller.signal.aborted) throwAbort()\n const planDesc = options.driver.describePlan?.()\n const roundIndex = round\n const baseIndex = iterations.length\n const remaining = maxIterations - iterations.length\n const slice = planned.slice(0, remaining)\n // Edge lineage: a driver may DECLARE the branch source (planner-authored\n // topology); otherwise the kernel infers it — round 0 branches from root\n // (undefined), later rounds from the best-valid (else latest) iteration so\n // far. Either way it's emitted, not guessed by the viewer.\n const parentIndex =\n planDesc?.parentIndex ?? (roundIndex === 0 ? undefined : branchPoint(iterations))\n const childIndices = slice.map((_, i) => baseIndex + i)\n const moveKind =\n planDesc?.kind ??\n (planned.length === 0 ? 'stop' : planned.length === 1 ? 'refine' : 'fanout')\n emitRunLoopHook(options, {\n target: 'agent.plan',\n phase: 'after',\n runId,\n timestamp: now(),\n stepIndex: roundIndex,\n payload: {\n roundIndex,\n plannedCount: planned.length,\n moveKind,\n parentIndex,\n childIndices,\n },\n })\n await emitTrace(options.ctx.traceEmitter, {\n kind: 'loop.plan',\n runId,\n timestamp: now(),\n payload: {\n roundIndex,\n plannedCount: planned.length,\n moveKind,\n rationale: planDesc?.rationale,\n parentIndex,\n childIndices,\n },\n })\n round += 1\n if (planned.length === 0) break\n\n // Reserve slots up front so concurrent workers may mutate by index.\n for (let i = 0; i < slice.length; i += 1) {\n const spec = specs[(baseIndex + i) % specs.length]!\n iterations.push({\n index: baseIndex + i,\n task: slice[i] as Task,\n agentRunName: spec.name ?? spec.profile.name ?? 'agent',\n events: [],\n startedAt: now(),\n endedAt: 0,\n costUsd: 0,\n tokenUsage: zeroTokenUsage(),\n })\n }\n\n // Decide how this round acquires its sandbox streams. Without lineage it's\n // a fresh box per iteration (today's path). With lineage it may continue\n // the parent session (refine) or fork the parent checkpoint (fanout).\n const lineagePlan = lineageState\n ? planLineageRound(lineageState, specs, slice, parentIndex, controller.signal)\n : undefined\n\n await runBatch({\n slice,\n baseIndex,\n iterations,\n specs,\n output: options.output,\n validator: options.validator,\n maxConcurrency,\n streaming: sandboxStreaming,\n signal: controller.signal,\n ctx: options.ctx,\n runId,\n now,\n roundIndex,\n parentIndex,\n collectBox,\n lineagePlan,\n lineageState,\n recordMount,\n })\n\n if (controller.signal.aborted) throwAbort()\n\n emitRunLoopHook(options, {\n target: 'agent.decision',\n phase: 'before',\n runId,\n timestamp: now(),\n stepIndex: roundIndex,\n payload: { historyLength: iterations.length },\n })\n const decision = await options.driver.decide(iterations)\n emitRunLoopHook(options, {\n target: 'agent.decision',\n phase: 'after',\n runId,\n timestamp: now(),\n stepIndex: roundIndex,\n payload: { decision: stringifySafe(decision), historyLength: iterations.length },\n })\n await emitTrace(options.ctx.traceEmitter, {\n kind: 'loop.decision',\n runId,\n timestamp: now(),\n payload: { decision: stringifySafe(decision), historyLength: iterations.length },\n })\n // Terminal decision ends the loop; a non-terminal one falls through to the\n // next plan() round, so this must return rather than continue.\n if (isTerminalDecision(decision)) {\n return await finalizeAndEmitEnded(\n options,\n decision,\n iterations,\n loopStart,\n now,\n runId,\n mounts,\n )\n }\n // The loop continues: free any lineage boxes no future round can descend\n // from, so the live-box set tracks the active frontier instead of growing\n // with every round. No-op unless pruning is provably safe (see canPrune).\n if (lineageState) await pruneLineage(lineageState, iterations)\n }\n\n // Either the cap was reached without a terminal decision, or plan() returned\n // [] first — both ask the driver for its final state and close out identically.\n return await decideAndFinalize(options, iterations, loopStart, now, runId, mounts)\n } finally {\n if (options.ctx.signal) options.ctx.signal.removeEventListener('abort', onOuterAbort)\n // Same-sandbox mode kept worker boxes alive across plan() so the planner could\n // stream into them — the kernel owns their teardown. Destroy in parallel so a\n // large fanout's deletes don't serialize, and bound each so a hung platform\n // delete cannot wedge loop return after the caller aborted.\n await Promise.allSettled(\n ownedBoxes.map((b) => destroySandboxSafe(b, options.ctx.traceEmitter, runId, now)),\n )\n if (options.onWorkerBox) options.onWorkerBox(undefined)\n // The lineage owns every box it started or forked across all rounds; it tears\n // them down at loop end (kept alive between rounds so a later round can\n // continue/fork them).\n if (lineageState) await lineageState.lineage.teardown()\n }\n}\n\n/**\n * Per-loop lineage state: the backend-blind lineage, the caller's opt-in flags,\n * and the live handle for each completed iteration so a later round can continue\n * or fork from it. `undefined` ⇒ no lineage; the kernel uses the fresh-box path.\n */\ninterface LineageState {\n lineage: SandboxLineage\n options: LoopLineageOptions\n /** iteration index → its live box+session handle (kept alive across rounds). */\n handles: Map<number, SandboxLineageHandle>\n /**\n * Whether the kernel may free non-frontier boxes after each round. Safe only\n * when the driver never authors its own branch point (`describePlan` absent),\n * so the kernel-inferred `branchPoint` — which moves monotonically toward\n * higher-scoring iterations — is the only descent source. A driver that\n * declares `parentIndex` may descend from any prior iteration, so no box can\n * be freed before loop end.\n */\n canPrune: boolean\n}\n\n/**\n * Build the lineage when either lineage flag is set. Probes the platform's fork\n * capability once per run (the lineage degrades gracefully when it's absent).\n * Rejects the lineage + `onWorkerBox` combination: both claim the same\n * box-ownership channel, and silently honoring one would leak or double-free.\n */\nasync function setUpLineage<Task, Output, Decision>(\n options: RunAgentRoundsOptions<Task, Output, Decision>,\n maxConcurrency: number,\n recordMount: MountRecorder,\n): Promise<LineageState | undefined> {\n const lineageOpts = options.lineage\n if (!lineageOpts || (!lineageOpts.sessionContinuity && !lineageOpts.forkFanout)) return undefined\n if (options.onWorkerBox) {\n throw new ValidationError(\n 'runAgentRounds: `lineage` and `onWorkerBox` both own worker boxes — pass only one',\n )\n }\n const capabilities = await probeSandboxCapabilities(options.ctx.sandboxClient)\n return {\n lineage: createSandboxLineage(options.ctx.sandboxClient, capabilities, {\n maxConcurrency,\n streaming: lineageOpts.streaming,\n recordMount,\n }),\n options: lineageOpts,\n handles: new Map(),\n canPrune: typeof options.driver.describePlan !== 'function',\n }\n}\n\n/**\n * One iteration's sandbox-stream source for a lineage round. The kernel awaits\n * `acquire()` inside the concurrency-bounded batch (so a fork's per-branch\n * `streamPrompt` and a continue's same-box stream are both rate-limited and\n * abort-checked like a fresh create). Returns the live event stream plus the\n * handle to record for the NEXT round to descend from.\n */\ninterface LineageStreamSource {\n acquire(): Promise<{ events: AsyncIterable<SandboxEvent>; handle: SandboxLineageHandle }>\n}\n\n/** The per-round lineage plan: a stream source per slice offset, or `undefined`\n * for offsets with no lineage source (defensive — never expected). */\ntype LineageRoundPlan = (LineageStreamSource | undefined)[]\n\n/**\n * Decide, for one round, how each iteration acquires its sandbox stream:\n * - refine (1 task) + `sessionContinuity` + a live parent handle ⇒ continue\n * the parent session on its box.\n * - fanout (N tasks) + `forkFanout` + a live parent handle ⇒ fork the parent\n * checkpoint once and stream each branch from a child box (degrades to fresh\n * boxes inside the lineage when the platform can't fork).\n * - otherwise (round 0, no parent, the off flag) ⇒ start a fresh box per\n * iteration THROUGH the lineage so it's owned + a handle is recorded for a\n * later round to descend from.\n * Round 0 (parentIndex undefined) always starts fresh — the independence of the\n * first batch is preserved.\n */\nfunction planLineageRound<Task>(\n state: LineageState,\n specs: AgentRunSpec<Task>[],\n slice: Task[],\n parentIndex: number | undefined,\n signal: AbortSignal,\n): LineageRoundPlan {\n const lineage = state.lineage\n const parent = parentIndex !== undefined ? state.handles.get(parentIndex) : undefined\n const promptFor = (offset: number): string => {\n const spec = specs[offset % specs.length]\n if (!spec)\n throw new ValidationError('runAgentRounds: no AgentRunSpec available for lineage iteration')\n return spec.taskToPrompt(slice[offset] as Task)\n }\n const specAt = (offset: number): AgentRunSpec<unknown> => {\n const spec = specs[offset % specs.length]\n if (!spec)\n throw new ValidationError('runAgentRounds: no AgentRunSpec available for lineage iteration')\n return spec as AgentRunSpec<unknown>\n }\n\n // Continue the parent session: a single-task round descending from a live\n // handle, with the flag on. Reuses the parent's box + session id.\n if (slice.length === 1 && parent && state.options.sessionContinuity) {\n return [\n {\n async acquire() {\n const events = await lineage.continue(parent, promptFor(0), signal)\n // Continuation threads the SAME handle forward — later rounds keep\n // descending from this box's evolving session.\n return { events, handle: parent }\n },\n },\n ]\n }\n\n // Fork the parent checkpoint: a multi-task round descending from a live handle,\n // with the flag on. One checkpoint, N child streams — lazily awaited once and\n // shared across the offsets so the batch checkpoints exactly once.\n if (slice.length > 1 && parent && state.options.forkFanout) {\n const prompts = slice.map((_, offset) => promptFor(offset))\n const childSpecs = slice.map((_, offset) => specAt(offset))\n let forked: Promise<{ handle: SandboxLineageHandle; events: AsyncIterable<SandboxEvent> }[]>\n const ensureForked = () => {\n forked ??= lineage.fork(parent, prompts, childSpecs, signal)\n return forked\n }\n return slice.map((_, offset) => ({\n async acquire() {\n const branches = await ensureForked()\n const branch = branches[offset]\n if (!branch)\n throw new ValidationError('runAgentRounds: lineage fork produced no branch for offset')\n return branch\n },\n }))\n }\n\n // Fresh through the lineage (round 0, no parent, or the relevant flag off):\n // start an owned box per iteration and record a handle for later descent.\n return slice.map((_, offset) => ({\n async acquire() {\n return lineage.start(specAt(offset), promptFor(offset), signal)\n },\n }))\n}\n\n/**\n * After a round, free lineage boxes no future round can descend from. The only\n * descent source for a kernel-inferred topology is `branchPoint`, which moves\n * monotonically toward higher-scoring iterations and never returns to one it has\n * passed — so every box except the current branch point's is unreachable and can\n * be torn down now instead of at loop end. Skipped entirely when the driver\n * authors its own branch point (`canPrune` false): it may descend from any prior\n * iteration. Also skipped when the branch point has no recorded handle (its\n * acquire failed) — that conservative case keeps every box.\n */\nasync function pruneLineage<Task, Output>(\n state: LineageState,\n iterations: ReadonlyArray<Iteration<Task, Output>>,\n): Promise<void> {\n if (!state.canPrune) return\n const keepIndex = branchPoint(iterations)\n if (keepIndex === undefined) return\n const keep = state.handles.get(keepIndex)\n if (!keep) return\n await state.lineage.prune([keep])\n // Drop handle entries pointing at the now-freed boxes so the map never hands a\n // later round a deleted box. Entries sharing the kept box (a refine chain)\n // stay.\n const stale: number[] = []\n for (const [index, handle] of state.handles) {\n if (handle.box !== keep.box) stale.push(index)\n }\n for (const index of stale) state.handles.delete(index)\n}\n\ninterface RunBatchArgs<Task, Output> {\n slice: Task[]\n baseIndex: number\n iterations: Iteration<Task, Output>[]\n specs: AgentRunSpec<Task>[]\n output: OutputAdapter<Output>\n validator: Validator<Output> | undefined\n maxConcurrency: number\n signal: AbortSignal\n ctx: ExecCtx\n runId: string\n now: () => number\n /** Plan round these iterations belong to — stamped as `groupId`. */\n roundIndex: number\n /** Iteration this round branched from — stamped as `parentIndex`. */\n parentIndex?: number\n /**\n * Same-sandbox mode: when set, a finished iteration's box is handed here\n * (kept alive for the planner) instead of being torn down. `undefined` =\n * default per-iteration teardown.\n */\n collectBox?: (box: SandboxInstance) => void\n /**\n * Lineage mode: per-offset stream sources for this round. When set, an\n * iteration acquires its sandbox stream through the lineage (continue / fork /\n * fresh) instead of `createSandboxForSpec`, and the lineage — not the\n * iteration — owns box teardown (deferred to loop end).\n */\n lineagePlan?: LineageRoundPlan\n /** The loop's lineage state; iterations record their handle here for the next\n * round to descend from. Set iff `lineagePlan` is. */\n lineageState?: LineageState\n /** Sandbox streaming mode for the default fresh-box path. 'poll' fire-and-\n * detaches + status-polls the terminal result (drop-resilient for long batch\n * turns); 'sse' streams live (default). */\n streaming: 'sse' | 'poll'\n /** The run's provenance recorder, forwarded to `prepareBox` on the default\n * fresh-box path so a mount declares itself into the manifest. (The lineage\n * path carries its own recorder from `createSandboxLineage`.) */\n recordMount: MountRecorder\n}\n\nasync function runBatch<Task, Output>(args: RunBatchArgs<Task, Output>) {\n const queue = args.slice.map((task, offset) => ({ task, index: args.baseIndex + offset }))\n const inflight = new Set<Promise<void>>()\n // Every started worker, so a rejecting iteration (abort short-circuit, or a\n // throwing trace emitter) cannot orphan its still-running siblings: we always\n // drain ALL of them before propagating the first error.\n const started: Promise<void>[] = []\n let firstError: unknown\n try {\n while (queue.length > 0 || inflight.size > 0) {\n while (inflight.size < args.maxConcurrency && queue.length > 0) {\n const item = queue.shift()!\n const p = executeIteration({ ...args, item }).finally(() => inflight.delete(p))\n started.push(p)\n inflight.add(p)\n }\n if (inflight.size === 0) break\n try {\n await Promise.race(inflight)\n } catch (err) {\n if (firstError === undefined) firstError = err\n // Stop scheduling new work; drain the rest in the finally below.\n queue.length = 0\n break\n }\n }\n } finally {\n const settled = await Promise.allSettled(started)\n if (firstError === undefined) {\n const rejected = settled.find((s) => s.status === 'rejected')\n if (rejected && rejected.status === 'rejected') firstError = rejected.reason\n }\n }\n if (firstError !== undefined) throw firstError\n}\n\ninterface ExecuteIterationArgs<Task, Output> extends RunBatchArgs<Task, Output> {\n item: { task: Task; index: number }\n}\n\nasync function executeIteration<Task, Output>(args: ExecuteIterationArgs<Task, Output>) {\n const slot = args.iterations[args.item.index]\n if (!slot)\n throw new ValidationError(`runAgentRounds: missing iteration slot at index ${args.item.index}`)\n const spec = args.specs[args.item.index % args.specs.length]\n if (!spec) throw new ValidationError('runAgentRounds: no AgentRunSpec available for iteration')\n slot.startedAt = args.now()\n slot.agentRunName = spec.name ?? spec.profile.name ?? 'agent'\n\n await emitTrace(args.ctx.traceEmitter, {\n kind: 'loop.iteration.started',\n runId: args.runId,\n timestamp: args.now(),\n payload: {\n iterationIndex: args.item.index,\n agentRunName: slot.agentRunName,\n taskHash: hashJson(args.item.task),\n groupId: args.roundIndex,\n parentIndex: args.parentIndex,\n },\n })\n\n let box: SandboxInstance | undefined\n // Lineage-owned boxes are torn down by the lineage at loop end, not here. The\n // flag tracks whether THIS iteration's box came from the lineage so the\n // teardown branch below skips it.\n let lineageOwned = false\n try {\n // Stream source: the lineage (continue / fork / fresh) when this round runs\n // under lineage, else a fresh box + a single `streamPrompt` (today's path,\n // byte-identical when no lineage). The lineage path supplies a session id on\n // the stream; the fresh path passes none — preserving N-independent-boxes.\n let stream: AsyncIterable<SandboxEvent>\n const source = args.lineagePlan?.[args.item.index - args.baseIndex]\n if (source) {\n const acquired = await source.acquire()\n box = acquired.handle.box\n lineageOwned = true\n args.lineageState?.handles.set(args.item.index, acquired.handle)\n stream = acquired.events\n } else {\n box = await createSandboxForSpec(args.ctx.sandboxClient, spec, args.signal, args.recordMount)\n const prompt = spec.taskToPrompt(args.item.task)\n // 'poll' (opt-in) fire-and-detaches + status-polls the terminal result so a\n // long, quiet turn never holds a drop-prone live SSE; 'sse' (default)\n // streams live — byte-identical to the prior path.\n stream =\n args.streaming === 'poll'\n ? promptEvents('poll', box, prompt, `${args.runId}-i${args.item.index}`, args.signal)\n : box.streamPrompt(prompt, { signal: args.signal })\n }\n const placement = describeSandboxPlacement(args.ctx.sandboxClient, box)\n await emitTrace(args.ctx.traceEmitter, {\n kind: 'loop.iteration.dispatch',\n runId: args.runId,\n timestamp: args.now(),\n payload: {\n iterationIndex: args.item.index,\n agentRunName: slot.agentRunName,\n placement: placement.kind,\n sandboxId: placement.sandboxId,\n fleetId: placement.fleetId,\n machineId: placement.machineId,\n groupId: args.roundIndex,\n parentIndex: args.parentIndex,\n },\n })\n const events: SandboxEvent[] = []\n let sawLlmCall = false\n for await (const event of stream) {\n events.push(event)\n // Tee each raw event to an optional host observer so a caller can stream\n // the agent's live output. Best-effort + isolated: the observer gets a\n // defensive copy (mutating it cannot corrupt the event the run itself\n // consumes for cost accounting + output parsing below), and a sync throw\n // or a rejected async result is swallowed — it can never break the run.\n notifySandboxEventObserver(event, args.ctx.onSandboxEvent, {\n iterationIndex: args.item.index,\n agentRunName: slot.agentRunName,\n })\n const llmCall = extractLlmCallEvent(event, slot.agentRunName)\n if (llmCall) {\n sawLlmCall = true\n slot.costUsd += llmCall.costUsd ?? 0\n if (llmCall.usdKnown === false) slot.costUsdKnown = false\n if (llmCall.estimatedCostUsd !== undefined) {\n slot.estimatedCostUsd = (slot.estimatedCostUsd ?? 0) + llmCall.estimatedCostUsd\n }\n if (llmCall.promptCache) {\n slot.promptCache ??= {}\n mergeUsageMetadata(slot.promptCache, llmCall.promptCache)\n }\n addTokenUsage(slot.tokenUsage, {\n input: llmCall.tokensIn,\n output: llmCall.tokensOut,\n ...(llmCall.tokensKnown === false ? { tokensKnown: false } : {}),\n })\n args.ctx.runHandle?.observe(llmCall)\n }\n }\n if (!sawLlmCall) {\n slot.tokenUsage.tokensKnown = false\n slot.costUsdKnown = false\n }\n slot.events = events\n slot.output = args.output.parse(events)\n if (args.validator) {\n slot.verdict = await args.validator.validate(slot.output, {\n iteration: args.item.index,\n ...(box ? { box } : {}),\n signal: args.signal,\n traceEmitter: args.ctx.traceEmitter,\n })\n }\n } catch (err) {\n slot.error = err instanceof Error ? err : new Error(String(err))\n } finally {\n slot.endedAt = args.now()\n await emitTrace(args.ctx.traceEmitter, {\n kind: 'loop.iteration.ended',\n runId: args.runId,\n timestamp: args.now(),\n payload: {\n iterationIndex: args.item.index,\n agentRunName: slot.agentRunName,\n outputHash: slot.output !== undefined ? hashJson(slot.output) : undefined,\n verdict: slot.verdict,\n error: slot.error?.message,\n costUsd: slot.costUsd,\n ...(slot.costUsdKnown === false ? { costUsdKnown: false } : {}),\n ...(slot.estimatedCostUsd !== undefined ? { estimatedCostUsd: slot.estimatedCostUsd } : {}),\n ...(slot.promptCache ? { promptCache: slot.promptCache } : {}),\n durationMs: slot.endedAt - slot.startedAt,\n tokenUsage:\n slot.tokenUsage.input || slot.tokenUsage.output ? { ...slot.tokenUsage } : undefined,\n groupId: args.roundIndex,\n parentIndex: args.parentIndex,\n outputPreview:\n slot.output !== undefined ? stringifySafe(slot.output, { max: 280 }) : undefined,\n },\n })\n // The loop owns the per-shot box lifecycle. Default: tear it down now so\n // sandboxes don't leak. Same-sandbox mode: hand it to the kernel to keep\n // alive for the planner. Lineage mode: the lineage owns the box and keeps it\n // alive across rounds (a later round may continue/fork it), tearing it down\n // at loop end — so skip per-iteration teardown here.\n if (lineageOwned) {\n // no-op: lineage.teardown() reaps this box at loop end\n } else if (args.collectBox && box) {\n args.collectBox(box)\n } else {\n await destroySandboxSafe(box, args.ctx.traceEmitter, args.runId, args.now)\n }\n }\n // An abort caught above is NOT a soft per-iteration failure — it must\n // short-circuit the batch, not degrade to a recorded empty iteration. The\n // trace was already emitted in the finally, so re-throw it now.\n if (isAbortError(slot.error) || args.signal.aborted) {\n if (slot.error) throw slot.error\n throwAbort()\n }\n // A structural lineage error (a dropped session, a fork-capability contract\n // violation, a missing spec) is likewise not a soft worker failure: it\n // invalidates the run's continuity/branching guarantee, so propagate it\n // instead of degrading to a recorded empty iteration the driver might ignore.\n if (slot.error instanceof ValidationError) throw slot.error\n}\n\nfunction isAbortError(err: unknown): boolean {\n return err instanceof Error && err.name === 'AbortError'\n}\n\nconst TEARDOWN_TIMEOUT_MS = 15_000\n\n/**\n * Best-effort sandbox teardown. A failed delete must never surface as a loop\n * error, and instances without a `delete` (the loop's test fakes) are skipped.\n * A delete that throws or hangs (bounded by `TEARDOWN_TIMEOUT_MS`) is recorded\n * as a `loop.teardown.failed` trace so a silently-leaking box is observable —\n * distinct from a fake with no `delete`, which is expected and stays silent.\n */\nasync function destroySandboxSafe(\n box: SandboxInstance | undefined,\n trace?: LoopTraceEmitter,\n runId?: string,\n now?: () => number,\n): Promise<void> {\n if (!box || typeof (box as { delete?: unknown }).delete !== 'function') return\n const emitFailed = async (reason: string) => {\n if (!trace || !runId) return\n await emitTrace(trace, {\n kind: 'loop.teardown.failed',\n runId,\n timestamp: (now ?? Date.now)(),\n payload: { sandboxId: readSandboxId(box), reason },\n })\n }\n // Bound the delete so a hung platform delete can't wedge loop return after an\n // abort. `undefined` = timed out; `false` = delete threw; `true` = deleted.\n const outcome = await withTimeout(deleteBoxSafe(box), TEARDOWN_TIMEOUT_MS)\n if (outcome === undefined) await emitFailed('timeout')\n else if (outcome === false) await emitFailed('delete threw')\n}\n\n/**\n * Branch point for a new round — the iteration a later round descends from.\n * Highest-valid-score iteration so far; ties + no-valid fall back to the latest\n * index. Inferred (not driver-declared), so refine renders as a chain and\n * fanout→refine chains off the fanout winner.\n */\nfunction branchPoint<Task, Output>(\n iterations: ReadonlyArray<Iteration<Task, Output>>,\n): number | undefined {\n if (iterations.length === 0) return undefined\n let best = iterations.length - 1\n let bestScore = -Infinity\n for (const iter of iterations) {\n if (iter.verdict?.valid !== true) continue\n const score = iter.verdict.score ?? 0\n if (score > bestScore) {\n bestScore = score\n best = iter.index\n }\n }\n return best\n}\n\nexport function describeSandboxPlacement(\n client: SandboxClient,\n box: SandboxInstance,\n): LoopSandboxPlacement {\n if (typeof client.describePlacement === 'function') {\n try {\n const result = client.describePlacement(box)\n if (\n result &&\n typeof result === 'object' &&\n (result.kind === 'sibling' || result.kind === 'fleet')\n ) {\n return {\n kind: result.kind,\n sandboxId: result.sandboxId ?? readSandboxId(box),\n fleetId: result.fleetId,\n machineId: result.machineId,\n }\n }\n } catch {\n // Adapter bug must not corrupt the iteration; fall through to default.\n }\n }\n return { kind: 'sibling', sandboxId: readSandboxId(box) }\n}\n\nfunction readSandboxId(box: SandboxInstance): string | undefined {\n const raw = (box as unknown as { id?: unknown }).id\n return typeof raw === 'string' && raw.length > 0 ? raw : undefined\n}\n\n/**\n * Instantiate a sandbox for an `AgentRunSpec`: sets `backend.profile` to the\n * spec's profile (inferring the backend type when the spec doesn't override\n * it) and merges `sandboxOverrides`. Shared by the loop kernel and the\n * `AgentRuntime.act` sandbox bridge so both boot the sandbox identically.\n *\n * `recordMount`, when supplied, is forwarded to `prepareBox` so the caller can\n * declare what it mounted into the box for the run's provenance manifest. The\n * loop kernel passes its per-run recorder; other callers (which have no\n * `LoopResult` to attach to) omit it and the prepareBox recorder is a no-op.\n */\nexport async function createSandboxForSpec<Task>(\n client: SandboxClient,\n spec: AgentRunSpec<Task>,\n signal: AbortSignal,\n recordMount?: MountRecorder,\n): Promise<SandboxInstance> {\n const opts = buildBackendOptions(spec.profile, spec.sandboxOverrides)\n // Cold-start-resilient acquire: a slow scale-from-zero create (node boot +\n // host-agent registration) can't surface as a failure — readiness is observed\n // from sandbox status, and a gateway-timed-out create is recovered by lookup.\n if (signal.aborted) throwAbort()\n const box = await acquireSandbox(client, opts, { signal })\n await invokePrepareBox(spec, box, signal, recordMount)\n return box\n}\n\n/**\n * Invoke a spec's `prepareBox` with a complete ctx. `recordMount` is the run's\n * provenance recorder when one is threaded down; absent, a no-op stands in so\n * the ctx shape is always satisfied and a caller that records mounts on a path\n * with no manifest (e.g. the `AgentRuntime.act` bridge) silently drops nothing\n * it cares about — it simply has nowhere to surface a manifest.\n */\nasync function invokePrepareBox<Task>(\n spec: AgentRunSpec<Task>,\n box: SandboxInstance,\n signal: AbortSignal,\n recordMount?: MountRecorder,\n): Promise<void> {\n if (!spec.prepareBox) return\n await spec.prepareBox(box, { signal, recordMount: recordMount ?? noopMountRecorder })\n}\n\n/** Shared no-op recorder for box-preparation paths that have no run manifest. */\nconst noopMountRecorder: MountRecorder = () => {}\n\ninterface FinalizeArgs<Task, Output, Decision> {\n options: RunAgentRoundsOptions<Task, Output, Decision>\n decision: Decision\n iterations: Iteration<Task, Output>[]\n startMs: number\n now: () => number\n runId: string\n /** Provenance mounts recorded across the run's box preparations. */\n mounts: MountManifestEntry[]\n}\n\nfunction finalize<Task, Output, Decision>(\n args: FinalizeArgs<Task, Output, Decision>,\n): LoopResult<Task, Output, Decision> {\n // Precedence: an explicit caller `selectWinner` wins; else a driver-AUTHORED\n // winner (a `select` topology move); else the default argmax. A driver that\n // declares nothing returns undefined and falls through — existing behavior.\n // Track which selector produced the winner so the receipts attribute it.\n let selector: SelectionReceipt['selector']\n let winner: LoopWinner<Task, Output> | undefined\n if (args.options.selectWinner) {\n selector = 'caller'\n winner = args.options.selectWinner(args.iterations)\n } else {\n const authored = args.options.driver.selectWinner?.(args.iterations)\n if (authored) {\n selector = 'driver'\n winner = authored\n } else {\n selector = 'default'\n winner = defaultSelectWinner(args.iterations)\n }\n }\n const costUsd = args.iterations.reduce((sum, iter) => sum + iter.costUsd, 0)\n const costUsdKnown = args.iterations.every((iter) => iter.costUsdKnown !== false)\n const estimatedCostUsd = args.iterations.reduce(\n (sum, iter) => sum + (iter.estimatedCostUsd ?? 0),\n 0,\n )\n const promptCache: Record<string, number | string> = {}\n for (const iteration of args.iterations) {\n if (iteration.promptCache) mergeUsageMetadata(promptCache, iteration.promptCache)\n }\n const tokenUsage = args.iterations.reduce((acc: LoopTokenUsage, iter) => {\n addTokenUsage(acc, iter.tokenUsage)\n return acc\n }, zeroTokenUsage())\n const result: LoopResult<Task, Output, Decision> = {\n decision: args.decision,\n iterations: args.iterations,\n winner,\n durationMs: args.now() - args.startMs,\n costUsd,\n ...(costUsdKnown ? {} : { costUsdKnown: false }),\n ...(estimatedCostUsd > 0 ? { estimatedCostUsd } : {}),\n ...(Object.keys(promptCache).length > 0 ? { promptCache } : {}),\n tokenUsage,\n provenance: {\n mounts: args.mounts,\n selectionReceipts: buildSelectionReceipts(args.iterations, winner, selector),\n },\n }\n return result\n}\n\nfunction mergeUsageMetadata(\n target: Record<string, number | string>,\n source: Readonly<Record<string, number | string>>,\n): void {\n for (const [key, value] of Object.entries(source)) {\n if (typeof value === 'number') target[key] = (Number(target[key]) || 0) + value\n else target[key] = value\n }\n}\n\n/**\n * One receipt per scored candidate — a candidate being an iteration that\n * produced an output without erroring (an errored or output-less iteration was\n * never selectable, so it gets no receipt). The receipt records the candidate's\n * score and whether the selector chose it as the winner, attributed to the\n * selector identity that ran. Domain-free: it states WHAT was selected and its\n * score, never anything about the task or output content.\n */\nfunction buildSelectionReceipts<Task, Output>(\n iterations: Iteration<Task, Output>[],\n winner: LoopWinner<Task, Output> | undefined,\n selector: SelectionReceipt['selector'],\n): SelectionReceipt[] {\n const receipts: SelectionReceipt[] = []\n for (const iter of iterations) {\n if (iter.output === undefined || iter.error) continue\n const selected = winner?.iterationIndex === iter.index\n const receipt: SelectionReceipt = {\n candidateIndex: iter.index,\n selected,\n selector,\n }\n if (iter.verdict?.score !== undefined) receipt.score = iter.verdict.score\n // The kernel can only speak to its OWN selection logic. A caller- or\n // driver-authored winner runs by its own rationale, so the kernel leaves\n // `reason` unset rather than inventing one.\n if (selector === 'default') receipt.reason = defaultSelectorReason(iter, selected)\n receipts.push(receipt)\n }\n return receipts\n}\n\n/** Plain-language reason for the default selector's decision (best-valid-score,\n * earliest-index tiebreak, falling back to best non-errored when none valid). */\nfunction defaultSelectorReason<Task, Output>(\n iter: Iteration<Task, Output>,\n selected: boolean,\n): string {\n const valid = iter.verdict?.valid === true\n if (selected) return valid ? 'best valid score' : 'best non-errored score (no valid candidate)'\n return valid ? 'valid but not top score' : 'not selected'\n}\n\n/**\n * Run `decide`, emit the `loop.decision` trace, then finalize and emit\n * `loop.ended`. The two post-while exits (cap reached / `plan()` returned `[]`)\n * share this exact sequence.\n */\nasync function decideAndFinalize<Task, Output, Decision>(\n options: RunAgentRoundsOptions<Task, Output, Decision>,\n iterations: Iteration<Task, Output>[],\n startMs: number,\n now: () => number,\n runId: string,\n mounts: MountManifestEntry[],\n): Promise<LoopResult<Task, Output, Decision>> {\n emitRunLoopHook(options, {\n target: 'agent.decision',\n phase: 'before',\n runId,\n timestamp: now(),\n payload: { historyLength: iterations.length },\n })\n const decision = await options.driver.decide(iterations)\n emitRunLoopHook(options, {\n target: 'agent.decision',\n phase: 'after',\n runId,\n timestamp: now(),\n payload: { decision: stringifySafe(decision), historyLength: iterations.length },\n })\n await emitTrace(options.ctx.traceEmitter, {\n kind: 'loop.decision',\n runId,\n timestamp: now(),\n payload: { decision: stringifySafe(decision), historyLength: iterations.length },\n })\n return finalizeAndEmitEnded(options, decision, iterations, startMs, now, runId, mounts)\n}\n\n/** Finalize the loop and emit the terminal `loop.ended` span. Used by the\n * in-loop terminal path (decision trace already emitted) and decideAndFinalize. */\nasync function finalizeAndEmitEnded<Task, Output, Decision>(\n options: RunAgentRoundsOptions<Task, Output, Decision>,\n decision: Decision,\n iterations: Iteration<Task, Output>[],\n startMs: number,\n now: () => number,\n runId: string,\n mounts: MountManifestEntry[],\n): Promise<LoopResult<Task, Output, Decision>> {\n const result = finalize({ options, decision, iterations, startMs, now, runId, mounts })\n emitRunLoopHook(options, {\n target: 'agent.run',\n phase: 'after',\n runId,\n timestamp: now(),\n payload: {\n decision: stringifySafe(decision),\n winnerIterationIndex: result.winner?.iterationIndex,\n totalCostUsd: result.costUsd,\n ...(result.costUsdKnown === false ? { costUsdKnown: false } : {}),\n ...(result.estimatedCostUsd !== undefined\n ? { estimatedCostUsd: result.estimatedCostUsd }\n : {}),\n durationMs: result.durationMs,\n iterations: iterations.length,\n },\n })\n // Await the terminal span (unlike a fire-and-forget) so a process exiting\n // right after runAgentRounds resolves (MCP subprocess / CLI dispatch) can't drop it.\n await emitTrace(options.ctx.traceEmitter, {\n kind: 'loop.ended',\n runId,\n timestamp: now(),\n payload: {\n winnerIterationIndex: result.winner?.iterationIndex,\n totalCostUsd: result.costUsd,\n ...(result.costUsdKnown === false ? { costUsdKnown: false } : {}),\n ...(result.estimatedCostUsd !== undefined\n ? { estimatedCostUsd: result.estimatedCostUsd }\n : {}),\n durationMs: result.durationMs,\n iterations: iterations.length,\n },\n })\n return result\n}\n\n/**\n * The kernel's winner argmax — best-valid-score, ties broken by earliest index,\n * falling back to the best-scoring non-errored output when none is valid. Exported\n * so the `runProgram` tree executor selects across merged sub-loop iterations with\n * the SAME semantics the kernel uses at a single loop's finalize (one selector, not\n * a forked copy).\n */\nexport function defaultSelectWinner<Task, Output>(\n iterations: Iteration<Task, Output>[],\n): LoopWinner<Task, Output> | undefined {\n const candidates = iterations.filter((iter) => iter.output !== undefined && !iter.error)\n if (candidates.length === 0) return undefined\n const valid = candidates.filter((iter) => iter.verdict?.valid === true)\n const pool = valid.length > 0 ? valid : candidates\n const sorted = [...pool].sort(\n (a, b) => (b.verdict?.score ?? 0) - (a.verdict?.score ?? 0) || a.index - b.index,\n )\n const top = sorted[0]\n if (!top || top.output === undefined) return undefined\n return {\n task: top.task,\n output: top.output,\n verdict: top.verdict,\n iterationIndex: top.index,\n agentRunName: top.agentRunName,\n }\n}\n\nfunction resolveAgentRuns<Task, Output, Decision>(\n options: RunAgentRoundsOptions<Task, Output, Decision>,\n): AgentRunSpec<Task>[] {\n if (options.agentRun && options.agentRuns) {\n throw new ValidationError('runAgentRounds: pass exactly one of `agentRun` or `agentRuns`')\n }\n if (options.agentRun) return [options.agentRun]\n if (options.agentRuns && options.agentRuns.length > 0) return options.agentRuns\n throw new ValidationError('runAgentRounds: `agentRun` or non-empty `agentRuns` is required')\n}\n\nfunction isTerminalDecision(decision: unknown): boolean {\n return (\n decision === 'stop' || decision === 'pick-winner' || decision === 'fail' || decision === 'done'\n )\n}\n\nfunction emitRunLoopHook<Task, Output, Decision>(\n options: RunAgentRoundsOptions<Task, Output, Decision>,\n event: {\n target: 'agent.run' | 'agent.plan' | 'agent.decision'\n phase: 'before' | 'after' | 'error' | 'event'\n runId: string\n timestamp: number\n stepIndex?: number\n payload?: Record<string, unknown>\n },\n): void {\n notifyRuntimeHookEvent(\n options.ctx.hooks,\n {\n id: `${event.runId}:${event.target}:${event.phase}${\n event.stepIndex === undefined ? '' : `:${event.stepIndex}`\n }`,\n runId: event.runId,\n target: event.target,\n phase: event.phase,\n timestamp: event.timestamp,\n stepIndex: event.stepIndex,\n payload: event.payload,\n metadata: { producer: 'run-loop' },\n },\n { signal: options.ctx.signal },\n )\n}\n\nasync function emitTrace(\n emitter: LoopTraceEmitter | undefined,\n event: LoopTraceEvent,\n): Promise<void> {\n if (!emitter) return\n await emitter.emit(event)\n}\n\n/**\n * Stable hash for the trace payload. Not cryptographic — only used so\n * downstream eval pipelines can group iterations whose task / output is the\n * same. Bare structural hash; non-JSON values stringify via their `toString`.\n */\nfunction hashJson(value: unknown): string {\n let str: string\n try {\n str = JSON.stringify(value) ?? String(value)\n } catch {\n str = String(value)\n }\n // FNV-1a 32-bit — branch-free, dependency-free, good enough for grouping.\n let h = 0x811c9dc5\n for (let i = 0; i < str.length; i += 1) {\n h ^= str.charCodeAt(i)\n h = Math.imul(h, 0x01000193)\n }\n return (h >>> 0).toString(16).padStart(8, '0')\n}\n","/**\n *\n * The worker-side receive end of the down-leg: a per-worker inbox an executor exposes as\n * `Executor.deliver`. The driver's `steer_agent` / `answer_question` land here,\n * and the worker's agent loop drains them at two points (Drew's two delivery modes):\n *\n * - QUEUED (default): the message accumulates and is FLUSHED at the next step boundary — folded\n * into the conversation before the next think. A worker is also forced to flush BEFORE it may\n * settle, so it can never finish while a steer/answer it never read is still pending.\n * - FORCEFUL (`interrupt: true`): trips `freshInterrupt()`'s signal so the loop can abort its\n * in-flight turn immediately, then re-plan with the message folded in — breaking the worker out\n * of a wrong path mid-task instead of waiting for it to finish the step.\n *\n * `deliver` never throws — a malformed message is ignored and returns `false`, so no caller can\n * report delivery for bytes this inbox discarded.\n *\n * @experimental\n */\n\nexport interface InboxMessage {\n readonly kind: 'steer' | 'answer'\n readonly text: string\n /** Forceful messages abort the in-flight turn; queued ones wait for the boundary flush. */\n readonly interrupt: boolean\n /** Present for an `answer` — the question id it resolves. */\n readonly questionId?: string\n}\n\nexport interface Inbox {\n /** The `Executor.deliver` implementation. Returns false when the raw message is malformed and\n * therefore was not queued; callers must not acknowledge a message this inbox discarded. */\n deliver(msg: unknown): boolean\n /** Remove and return all pending messages (the flush). */\n drain(): InboxMessage[]\n pending(): number\n /** Open a fresh per-turn interrupt signal; a later forceful `deliver` aborts it. The loop links\n * this into the signal it passes to its inference call, then re-plans when it fires. */\n freshInterrupt(): AbortSignal\n /** Render drained messages as ONE operator turn to fold into the worker's conversation. */\n fold(messages: ReadonlyArray<InboxMessage>): string\n}\n\nfunction parseDown(msg: unknown): InboxMessage | undefined {\n if (!msg || typeof msg !== 'object') return undefined\n const m = msg as Record<string, unknown>\n const interrupt = m.interrupt === true\n if (typeof m.steer === 'string') return { kind: 'steer', text: m.steer, interrupt }\n if (typeof m.answer === 'string')\n return {\n kind: 'answer',\n text: m.answer,\n interrupt,\n ...(typeof m.questionId === 'string' ? { questionId: m.questionId } : {}),\n }\n return undefined\n}\n\n/** Create the worker-side inbox for the down-leg: the driver's `steer_agent` / `answer_question` messages queue here and the worker's loop drains them at step boundaries and before settle. */\nexport function createInbox(): Inbox {\n const pending: InboxMessage[] = []\n let live: AbortController | null = null\n return {\n deliver(msg) {\n const m = parseDown(msg)\n if (!m) return false\n pending.push(m)\n // A forceful message aborts the turn currently in flight (if any).\n if (m.interrupt && live && !live.signal.aborted) live.abort()\n return true\n },\n drain() {\n return pending.splice(0, pending.length)\n },\n pending: () => pending.length,\n freshInterrupt() {\n live = new AbortController()\n return live.signal\n },\n fold(messages) {\n const lines = messages.map((m) => {\n if (m.kind === 'answer')\n return `- Answer to your question${m.questionId ? ` (${m.questionId})` : ''}: ${m.text}`\n return `- New instruction from your supervisor: ${m.text}`\n })\n return `[SUPERVISOR] Out-of-band message(s) — address these before continuing:\\n${lines.join('\\n')}`\n },\n }\n}\n","/**\n *\n * The LIVE read-model of a still-RUNNING worker — what a driver can see BEFORE the worker settles.\n *\n * Until this existed, `observe_agent` on a running worker returned `{status:'running', spent:{0,0},\n * outRef:null, output:null}`: nothing a brain could act on, so a brain that wanted to steer had no\n * evidence to steer FROM. This is the other half of the steering wire (the first half is\n * `Executor.deliver`): a supervisor cannot correct a worker it cannot watch.\n *\n * Two layers, both pull-based — no timer, no background task, so it is safe to leave on:\n *\n * - The SCOPE layer, available for EVERY executor with no executor cooperation at all: usage\n * events are timestamped as they arrive, so `lastActivityAt` / `idleMs` / `stalled` /\n * `tokens` / `turns` are derived from the stream the conserved pool already meters.\n * - The EXECUTOR layer, optional enrichment via `Executor.progress()`: the tool/file activity\n * the harness exposes, its own turn count, and how many steers are queued but unread.\n *\n * `stalled` is a DERIVED read, computed at observation time against `stallAfterMs` — never a\n * background watchdog. A worker that has produced no metered activity for longer than the\n * threshold reads `stalled: true`; nothing is killed, nothing is retried. The driver decides.\n *\n * @experimental\n */\n\nimport type { NodeStatus } from './types'\n\n/** How long a worker may produce no metered activity before a `progress()` read calls it stalled.\n * Deliberately generous: a coding harness routinely spends minutes inside one tool call, and a\n * false stall that provokes a steer is worse than a late one. */\nexport const DEFAULT_STALL_AFTER_MS = 180_000\n\n/** The most recent activity the executor can name — one tool call, one turn, or a free-form note.\n * `label` is the tool/file/turn name; `detail` is a short, already-truncated descriptor (a path,\n * a command head) that a driver can read without pulling the whole transcript. */\nexport interface ActivityNote {\n readonly at: number\n readonly kind: 'turn' | 'tool' | 'note'\n readonly label: string\n readonly status?: 'ok' | 'error'\n readonly detail?: string\n}\n\n/** What an executor OPTIONALLY adds to the scope-derived progress (`Executor.progress()`). Every\n * field is optional: an executor that knows only its own turn count reports only that. */\nexport interface ExecutorProgress {\n /** The executor's own turn/step count when it is more meaningful than metered iterations. */\n readonly turns?: number\n /** Steers/answers delivered but not yet folded into the worker's conversation. */\n readonly pendingMessages?: number\n /** Newest-last window of what the worker has been doing. */\n readonly recentActivity?: ReadonlyArray<ActivityNote>\n /**\n * What the executor CHANGED about what the caller declared, one short line each — an MCP config\n * it materialized, an extension it had to add for the caller's own servers to mount at all.\n *\n * Deliberately NOT part of `recentActivity`: that is a bounded newest-last ring, so a derived\n * change made before the first turn is evicted by turn 13 and gone by the time anyone looks. And\n * deliberately not only on the settled artifact: a run that fails on turn 40 never produces one,\n * yet \"what was this worker actually given?\" is exactly the question a failure raises. This\n * channel is append-only and readable at any moment, including from a run that never finishes.\n */\n readonly derived?: ReadonlyArray<string>\n /** A one-line human-readable state (\"turn 3, running tests\"). */\n readonly note?: string\n}\n\n/** The full live view of one worker, as `observe_agent` returns it mid-flight. */\nexport interface WorkerProgress {\n readonly id: string\n readonly status: NodeStatus\n /** True while the node is neither done, failed, nor cancelled — i.e. a steer could still land. */\n readonly live: boolean\n /** True when this worker's executor exposes an inbox (`Executor.deliver`) — i.e. `steer_agent`\n * can actually reach it. False means a steer would be recorded and dropped. */\n readonly steerable: boolean\n readonly startedAt: number\n /** Epoch ms of the last metered usage event or executor-reported activity. */\n readonly lastActivityAt: number\n readonly idleMs: number\n readonly stalled: boolean\n readonly stallAfterMs: number\n /** Metered iterations so far (the executor's own count when it reports one). */\n readonly turns: number\n readonly tokens: { readonly input: number; readonly output: number }\n /** False when observed `tokens` is only a known subtotal, not a complete total — the worker did\n * work whose token count its provider never reported. The twin of `usdKnown`, carried for the\n * same reason: a driver reading this over `observe_agent` would otherwise read the subtotal as\n * the measurement and conclude a busy worker was cheap. */\n readonly tokensKnown?: boolean\n readonly usd: number\n /** False when observed dollar spend is only a known subtotal, not a complete total. */\n readonly usdKnown?: boolean\n /** Steers delivered but not yet read by the worker. */\n readonly pendingMessages: number\n /** Newest-last window of tool/turn activity; empty when the executor exposes none. */\n readonly recentActivity: ReadonlyArray<ActivityNote>\n /** What the executor changed about the caller's declaration; absent when it changed nothing.\n * Unlike `recentActivity` this is never evicted, so it still answers on a failed run. */\n readonly derived?: ReadonlyArray<string>\n readonly note?: string\n}\n\n/** A bounded newest-last ring of `ActivityNote`s an executor keeps to answer `progress()`. */\nexport interface ActivityLog {\n push(note: ActivityNote): void\n /** Newest-last, at most `limit` entries. */\n read(): ReadonlyArray<ActivityNote>\n last(): ActivityNote | undefined\n size(): number\n}\n\n/** A short, already-truncated descriptor of a tool call's target — the file/command a driver\n * needs to tell \"editing the right module\" from \"re-reading the same file for the fifth time\",\n * without pulling the worker's transcript across the wire. Shared by every executor that fills an\n * `ActivityLog` (pi RPC, sandbox session parts, cli-bridge tool-call deltas) so one harness's\n * argument naming never reads differently from another's in the same driver's window. */\nexport function describeToolArgs(argsValue: unknown): string | undefined {\n if (!argsValue || typeof argsValue !== 'object') return undefined\n const a = argsValue as Record<string, unknown>\n for (const key of ['filePath', 'file_path', 'path', 'file', 'command', 'cmd', 'pattern']) {\n const v = a[key]\n if (typeof v === 'string' && v.length > 0) return v.length > 120 ? `${v.slice(0, 117)}...` : v\n }\n return undefined\n}\n\n/** Create a bounded activity ring. `limit` caps memory for a worker that runs thousands of tools. */\nexport function createActivityLog(limit = 12): ActivityLog {\n const notes: ActivityNote[] = []\n const cap = Math.max(1, Math.floor(limit))\n return {\n push(note) {\n notes.push(note)\n if (notes.length > cap) notes.splice(0, notes.length - cap)\n },\n read: () => [...notes],\n last: () => notes[notes.length - 1],\n size: () => notes.length,\n }\n}\n\n/** The scope-side facts about a child, independent of whether its executor cooperates. */\nexport interface ScopeProgressInput {\n readonly id: string\n readonly status: NodeStatus\n readonly steerable: boolean\n readonly startedAt: number\n readonly lastActivityAt: number\n readonly turns: number\n readonly tokens: { readonly input: number; readonly output: number }\n readonly tokensKnown?: boolean\n readonly usd: number\n readonly usdKnown?: boolean\n}\n\n/** Fold the scope-derived facts and the executor's optional enrichment into one read. Pure: the\n * caller supplies `now`, so a test can observe a stall without waiting for one. */\nexport function readWorkerProgress(\n scope: ScopeProgressInput,\n executor: ExecutorProgress | undefined,\n now: number,\n stallAfterMs: number = DEFAULT_STALL_AFTER_MS,\n): WorkerProgress {\n const live = scope.status !== 'done' && scope.status !== 'failed' && scope.status !== 'cancelled'\n // An executor-reported activity is newer evidence than the last metered usage event: a harness\n // can run a five-minute tool call without emitting a single token.\n const executorActivityAt = executor?.recentActivity?.length\n ? (executor.recentActivity[executor.recentActivity.length - 1] as ActivityNote).at\n : 0\n const lastActivityAt = Math.max(scope.lastActivityAt, executorActivityAt)\n const idleMs = Math.max(0, now - lastActivityAt)\n const note = executor?.note\n return {\n id: scope.id,\n status: scope.status,\n live,\n steerable: scope.steerable,\n startedAt: scope.startedAt,\n lastActivityAt,\n idleMs,\n // Only a LIVE worker can stall; a settled one is simply finished.\n stalled: live && idleMs > stallAfterMs,\n stallAfterMs,\n turns: executor?.turns ?? scope.turns,\n tokens: scope.tokens,\n // Both markers are carried the same way and only when false, so an unmarked read means the\n // channel is measured — never \"the fold forgot to pass it through\".\n ...(scope.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: scope.usd,\n ...(scope.usdKnown === false ? { usdKnown: false } : {}),\n pendingMessages: executor?.pendingMessages ?? 0,\n recentActivity: executor?.recentActivity ?? [],\n // Absent rather than empty, so \"this executor derived nothing\" and \"this executor does not\n // report derivations\" read the same way — neither is a claim that nothing was changed.\n ...(executor?.derived?.length ? { derived: executor.derived } : {}),\n ...(note ? { note } : {}),\n }\n}\n","/**\n *\n * `TraceSource` — the ONE substrate-agnostic source of a worker's tool-call trace. The online\n * detectors and the settle-time analyzers consume agent-eval `ToolSpan`s from here, regardless of\n * whether the worker is:\n * - an OWNED tool loop (router-tools, cli-bridge tool dispatch) → push spans as we dispatch them;\n * - a SANDBOX / fleet box → read the harness's tool calls off the session (`streamPrompt` parts\n * live, `session.messages()` / `findCompletedTurn` at settle).\n *\n * The common currency is agent-eval's `ToolSpan` (so the same detectors + `buildTrajectory`/\n * `stuckLoopView`/`toolWasteView` run over any source). A source exposes two lanes:\n * - `onSpan` — live spans for ONLINE detection (best-effort; a black-box box may only collect).\n * - `collect` — the full span set at settle for the BATCH analyzers (always available).\n *\n * This module imports NO substrate SDK — it decodes generic message parts / OpenAI tool-call shapes.\n * The sandbox wiring (`sandboxSessionTraceSource`) is the thin adapter that feeds box session parts in.\n *\n * @experimental\n */\n\nimport type { ToolSpan } from '@tangle-network/agent-eval'\nimport type { ToolPart, ToolState } from '@tangle-network/agent-interface'\n\nexport interface ToolStepInput {\n readonly toolName: string\n readonly args: unknown\n /** False when the call was observed but its original arguments were unavailable. */\n readonly argsCaptured?: boolean\n readonly status?: 'ok' | 'error'\n /**\n * False when the source observed the call being MADE but never observed it finishing — so no\n * outcome is knowable, not even by default. Some wires (cli-bridge's OpenAI-shaped `tool_calls`\n * deltas) report the model's DECISION to call a tool and never report the call's result at all.\n * Without this marker such a call would project as `status: 'ok'` and be counted as a success in\n * every downstream error-rate read. Set it and the span carries NO status, which is the truth.\n */\n readonly statusCaptured?: boolean\n readonly result?: unknown\n readonly error?: string\n /** Stable id of the tool call — used to de-duplicate the repeated state transitions a harness\n * streams for one call (opencode emits pending→running→completed, plus a `raw`-wrapped copy). */\n readonly callId?: string\n /** Real per-call wall-clock when the source has it (owned tool-loop; opencode parts with `time`).\n * When omitted the span collapses to a single instant (`at`) — order + counts only, no duration. */\n readonly startedAt?: number\n readonly endedAt?: number\n}\n\nexport interface TraceSource {\n /** Subscribe to tool spans as they are produced (ONLINE). Returns an unsubscribe. A source that\n * only exposes its trace at the end registers nothing and returns a no-op. */\n onSpan(handler: (span: ToolSpan) => void): () => void\n /** The full set of tool spans for the run (SETTLE / batch). Always available. */\n collect(): Promise<ToolSpan[]>\n}\n\n/** Project a normalized tool step into the canonical agent-eval `ToolSpan`. When the step carries\n * real wall-clock (`startedAt`/`endedAt`) the span gets a true duration; otherwise it collapses to\n * the single instant `at` (order + counts only — the historical behavior). A step whose source\n * never saw the call finish (`statusCaptured: false`) gets NO `status` — `ToolSpan.status` is\n * optional precisely so an unobserved outcome can stay unstated rather than defaulting to 'ok'. */\nexport function toToolSpan(input: ToolStepInput, runId: string, seq: number, at: number): ToolSpan {\n const startedAt = typeof input.startedAt === 'number' ? input.startedAt : at\n const endedAt = typeof input.endedAt === 'number' ? input.endedAt : startedAt\n const status = input.statusCaptured === false ? undefined : (input.status ?? 'ok')\n return {\n spanId: `${runId}-t${seq}`,\n runId,\n kind: 'tool',\n name: input.toolName,\n toolName: input.toolName,\n args: input.args,\n ...(input.argsCaptured === false ? { argsCaptured: false } : {}),\n ...(status === undefined ? {} : { status }),\n ...(input.error !== undefined ? { error: input.error } : {}),\n startedAt,\n endedAt,\n ...(input.result !== undefined ? { result: input.result } : {}),\n }\n}\n\n/** Decode one harness message part into a tool step, or `undefined` if it is not a (completed) tool\n * call. ONE adapter per harness family — each owns its real wire shape; the flow downstream is\n * identical. Add a harness = add a decoder + register it; no other code changes. */\nexport type ToolPartDecoder = (part: Record<string, unknown>) => ToolStepInput | undefined\n\nconst obj = (v: unknown): Record<string, unknown> | undefined =>\n v && typeof v === 'object' ? (v as Record<string, unknown>) : undefined\nconst str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined)\n\n/** opencode parts ARE agent-interface's canonical `ToolPart` (`{ type:'tool', tool, callID?,\n * state: ToolState }`) — the shape every adc sdk-provider normalizes its harness output into. We\n * decode against that published type (single source of truth) rather than a re-derived shape; the\n * `ToolState` union drives the status mapping, so a status that adc adds/renames is a compile error\n * here, not a silent miss. The same call streams pending→running→terminal; only a terminal state\n * (`completed` / `error` / `failed`) is a finished call. */\nexport const decodeOpencodePart: ToolPartDecoder = (raw) => {\n if (str(raw.type)?.toLowerCase() !== 'tool' || !str(raw.tool)) return undefined\n const part = raw as Partial<ToolPart>\n const state = obj(part.state) as ToolState | undefined\n const status = state?.status\n if (!status || status === 'pending' || status === 'running') return undefined\n return {\n toolName: part.tool as string,\n args: state?.input ?? {},\n // ToolStateError carries 'error' OR 'failed' — the reverse-engineered decoder missed 'failed'.\n status: status === 'error' || status === 'failed' ? 'error' : 'ok',\n ...(str(part.callID) ? { callId: part.callID as string } : {}),\n }\n}\n\n/** Anthropic / claude-code (also kimi's tool_use variant): a `{ type:'tool_use', id|tool_use_id,\n * name|tool, input }` content block. CONFIRMED against the cli-bridge's authoritative parsers\n * (claude.ts reads `block.type==='tool_use', block.id, block.name, block.input`; kimi.ts adds the\n * `tool_use_id`/`tool` fallbacks) — the canonical readers of these harnesses' real native output. */\nexport const decodeAnthropicPart: ToolPartDecoder = (p) => {\n if (str(p.type)?.toLowerCase() !== 'tool_use') return undefined\n const name = str(p.name) ?? str(p.tool)\n if (!name) return undefined\n const id = str(p.id) ?? str(p.tool_use_id)\n return {\n toolName: name,\n args: p.input ?? {},\n ...(id ? { callId: id } : {}),\n }\n}\n\n/** OpenAI-compatible (router / kimi's top-level form / glm): `{ type:'function'|'tool_call', id,\n * function:{ name, arguments:<JSON string> } }`. CONFIRMED against the cli-bridge (kimi.ts surfaces\n * kimi's top-level `tool_calls:[{type:'function', id, function:{name,arguments}}]` exactly this way).\n * NOTE: codex does NOT emit structured tool calls (the bridge's codex.ts never yields `tool_calls` —\n * it runs shell internally and surfaces only text), so per-tool detection is unavailable for codex\n * from any path — a harness property, not a decoder gap. */\nexport const decodeOpenAiPart: ToolPartDecoder = (p) => {\n const type = str(p.type)?.toLowerCase()\n const fn = obj(p.function)\n // Match on the type OpenAI always sets — not the mere presence of a `.function` field (a\n // `{type:'text', function:{…}}` part must not decode). Name is required below.\n if (type !== 'function' && type !== 'tool_call') return undefined\n const name = str(fn?.name) ?? str(p.name)\n if (!name) return undefined\n const rawArgs = fn?.arguments ?? p.arguments\n return {\n toolName: name,\n args: typeof rawArgs === 'string' ? safeParse(rawArgs) : (rawArgs ?? {}),\n ...(str(p.id) ? { callId: p.id as string } : str(fn?.id) ? { callId: fn?.id as string } : {}),\n }\n}\n\n/** The harness → decoder registry. Add a harness by adding one entry. */\nexport const toolPartDecoders: Record<string, ToolPartDecoder> = {\n opencode: decodeOpencodePart,\n 'claude-code': decodeAnthropicPart,\n anthropic: decodeAnthropicPart,\n codex: decodeOpenAiPart,\n openai: decodeOpenAiPart,\n router: decodeOpenAiPart,\n kimi: decodeOpenAiPart,\n}\n\n/** Decode a part with a specific harness's adapter when known, else try every registered adapter\n * (the composite — robust to mixed/unknown streams). Never throws. */\nexport function decodeToolPart(part: unknown, harness?: string): ToolStepInput | undefined {\n const p = obj(part)\n if (!p) return undefined\n const specific = harness ? toolPartDecoders[harness] : undefined\n if (specific) return specific(p)\n for (const decode of new Set(Object.values(toolPartDecoders))) {\n const step = decode(p)\n if (step) return step\n }\n return undefined\n}\n\nfunction safeParse(s: string): unknown {\n try {\n return JSON.parse(s)\n } catch {\n return s\n }\n}\n\nlet runSeq = 0\n\n/** A push source for OWNED tool loops (router-tools / cli-bridge tool dispatch): the loop calls\n * `record(step)` for each tool call; it becomes a span, fan-out to live subscribers + buffered for\n * `collect`. */\nexport function createPushTraceSource(opts: { runId?: string; now?: () => number } = {}): {\n source: TraceSource\n record: (input: ToolStepInput) => ToolSpan\n} {\n const runId = opts.runId ?? `push-${runSeq++}`\n const now = opts.now ?? Date.now\n const spans: ToolSpan[] = []\n const subs = new Set<(span: ToolSpan) => void>()\n return {\n record(input) {\n const span = toToolSpan(input, runId, spans.length, now())\n spans.push(span)\n for (const fn of subs) {\n try {\n fn(span)\n } catch {\n // a throwing subscriber (e.g. a detector onSignal) must never break the producer loop\n }\n }\n return span\n },\n source: {\n onSpan(handler) {\n subs.add(handler)\n return () => subs.delete(handler)\n },\n collect: () => Promise.resolve([...spans]),\n },\n }\n}\n\n/** A source backed by harness message PARTS (sandbox session, cli-bridge). `collect` reads the full\n * part list and decodes the tool calls; `subscribe`, when given, streams parts live for online\n * detection. The caller supplies how to get parts (e.g. `box.session(id).messages()` flat-mapped to\n * parts) — keeping this module free of any substrate SDK. */\nexport function createPartsTraceSource(opts: {\n collectParts: () => Promise<ReadonlyArray<unknown>>\n subscribeParts?: (onPart: (part: unknown) => void) => () => void\n /** The harness whose decoder to use (e.g. 'opencode'); omit to try every registered adapter. */\n harness?: string\n runId?: string\n now?: () => number\n}): TraceSource {\n const runId = opts.runId ?? `parts-${runSeq++}`\n const now = opts.now ?? Date.now\n const subs = new Set<(span: ToolSpan) => void>()\n // De-dup the repeated transitions a harness streams for one call (pending/running/completed + a\n // `raw`-wrapped copy all decode to the same terminal step) — one span per callId.\n const seenLive = new Set<string>()\n let liveSeq = 0\n let unsub: (() => void) | undefined\n const startLive = () => {\n if (unsub || !opts.subscribeParts) return\n unsub = opts.subscribeParts((part) => {\n const step = decodeToolPart(part, opts.harness)\n if (!step) return\n if (step.callId) {\n if (seenLive.has(step.callId)) return\n seenLive.add(step.callId)\n }\n const span = toToolSpan(step, runId, liveSeq++, now())\n for (const fn of subs) {\n try {\n fn(span)\n } catch {\n // a throwing subscriber (e.g. a detector onSignal) must never break the producer loop\n }\n }\n })\n }\n return {\n onSpan(handler) {\n subs.add(handler)\n startLive()\n return () => {\n subs.delete(handler)\n if (subs.size === 0 && unsub) {\n unsub()\n unsub = undefined\n }\n }\n },\n async collect() {\n const parts = await opts.collectParts()\n const spans: ToolSpan[] = []\n const seen = new Set<string>()\n for (const part of parts) {\n const step = decodeToolPart(part, opts.harness)\n if (!step) continue\n if (step.callId) {\n if (seen.has(step.callId)) continue\n seen.add(step.callId)\n }\n spans.push(toToolSpan(step, runId, spans.length, now()))\n }\n return spans\n },\n }\n}\n\n/** A harness session message carrying parts (the shape `box.messages()` returns). Structurally typed\n * so this works with the real `@tangle-network/sandbox` box AND a test double, no SDK import. */\nexport interface SessionMessageLike {\n readonly parts?: ReadonlyArray<unknown>\n}\n\n/** The minimal box surface this needs: list a session's messages (incl. mid-turn partials). */\nexport interface SessionTraceBox {\n messages(opts: { sessionId: string }): Promise<ReadonlyArray<SessionMessageLike>>\n}\n\n/** The SANDBOX / fleet trace source: read a box session's message parts and decode the harness's tool\n * calls into spans. `collect` (settle) is the solid path — `box.messages({sessionId})` → parts → spans;\n * black-box harnesses aren't mid-step interruptible, so online steering is the owned-loop's job and a\n * live `subscribe` is opt-in (pass `subscribeParts` from `streamPrompt` when the harness streams parts). */\nexport function sandboxSessionTraceSource(\n box: SessionTraceBox,\n sessionId: string,\n opts: {\n /** The box's harness (e.g. 'opencode', 'claude-code') → selects its decoder adapter. */\n harness?: string\n subscribeParts?: (onPart: (part: unknown) => void) => () => void\n runId?: string\n now?: () => number\n } = {},\n): TraceSource {\n return createPartsTraceSource({\n collectParts: async () => {\n const msgs = await box.messages({ sessionId })\n return msgs.flatMap((m) => (m.parts ? [...m.parts] : []))\n },\n ...(opts.harness ? { harness: opts.harness } : {}),\n ...(opts.subscribeParts ? { subscribeParts: opts.subscribeParts } : {}),\n runId: opts.runId ?? `box-${sessionId}`,\n ...(opts.now ? { now: opts.now } : {}),\n })\n}\n","/**\n *\n * The STEERABLE sandbox worker: one box, one server-side session, MANY turns — so a message\n * from the driver has a boundary to be folded into.\n *\n * The default cloud worker was built on `singleShotDriver`: one `runAgentRounds` shot, no turn\n * boundary, and no `Executor.deliver`. `Scope.send` therefore returned `false` for it and\n * `steer_agent` reported `delivered:false` on every call — steering the DEFAULT worker was\n * mechanically impossible, not merely unused. This module is the missing continuation loop.\n *\n * Structure deliberately mirrors `streamBridgeSession` (the cli-bridge equivalent that already\n * works) so both steerable runtimes have ONE shape:\n *\n * - turn 0 sends the task through `SandboxLineage.start` (fresh box, minted session id);\n * - each later turn fires ONLY when the inbox has a steer/answer to fold, and goes through\n * `SandboxLineage.continue` — the SAME box and the SAME server-side session, so the prompt\n * carries only the new instruction and the worker keeps everything it had already learned;\n * - a worker may not settle while a delivered steer is unread: the loop drains once more\n * before breaking, which is what makes `steer_agent` a promise rather than a hint;\n * - a forceful (`interrupt:true`) steer aborts the in-flight turn so the worker re-plans\n * immediately instead of finishing a path the supervisor already rejected.\n *\n * It also produces the LIVE signal a supervisor steers FROM: every sandbox event stamps\n * activity, tool parts are decoded into the shared `ToolSpan` currency for the online detector\n * panel, and `progress()` answers turn / tool / idle / pending-steer questions synchronously.\n *\n * Reports REAL usage only — token and cost numbers come from the sandbox events themselves.\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport type { BackendType, PromptOptions, SandboxEvent } from '@tangle-network/sandbox'\nimport { ValidationError } from '../../errors'\nimport { probeSandboxCapabilities } from '../sandbox-capabilities'\nimport { extractLlmCallEvent } from '../sandbox-events'\nimport { createSandboxLineage, type SandboxLineageHandle } from '../sandbox-lineage'\nimport type { AgentRunSpec, ExecCtx, SandboxClient } from '../types'\nimport { zeroTokenUsage } from '../util'\nimport type { Inbox } from './inbox'\nimport {\n type ActivityLog,\n type ActivityNote,\n createActivityLog,\n describeToolArgs,\n type ExecutorProgress,\n} from './progress'\nimport { createPushTraceSource, decodeToolPart, type TraceSource } from './trace-source'\nimport type { Spend, UsageEvent } from './types'\n\n/** Ceiling on continuation turns. Turn 0 is the task; every later turn is a folded steer, so\n * this bounds how many times a supervisor may redirect ONE worker before it must respawn. */\nexport const DEFAULT_SANDBOX_STEERING_MAX_TURNS = 24\n\n/** Opt-in configuration for the steerable sandbox worker (`SandboxSeam.steering`). Absent, the\n * sandbox executor keeps its historical single-shot `runAgentRounds` composition verbatim. */\nexport interface SandboxSteeringOptions {\n /** Max turns for one worker (turn 0 + folded steers). Default {@link DEFAULT_SANDBOX_STEERING_MAX_TURNS}. */\n readonly maxTurns?: number\n /** How many recent tool/turn notes `progress()` reports. Default 12. */\n readonly activityWindow?: number\n /** Per-turn wall-clock ceiling; the turn's stream is aborted when it elapses. */\n readonly turnTimeoutMs?: number\n}\n\n/** What the steerable session exposes to its executor: the usage stream plus the live reads. */\nexport interface SteerableSandboxSession {\n /** Drive the worker to settlement. `signal` is the spawn-scoped abort handed to `execute`. */\n stream(task: unknown, signal: AbortSignal): AsyncIterable<UsageEvent>\n progress(): ExecutorProgress\n traceSource(): TraceSource\n artifact(): { outRef: string; out: unknown; spent: Spend } | undefined\n teardown(): Promise<void>\n}\n\nexport interface SteerableSandboxArgs {\n readonly controller: AbortController\n readonly profile: AgentProfile\n readonly harness: BackendType\n readonly sandboxClient: SandboxClient\n readonly inbox: Inbox\n readonly taskToPrompt: (task: unknown) => string\n readonly options?: SandboxSteeringOptions\n readonly loopCtx?: Partial<Omit<ExecCtx, 'sandboxClient' | 'signal'>>\n /**\n * Inherited `TRACE_ID` / `PARENT_SPAN_ID` for the box, merged into `CreateSandboxOptions.env` so\n * the remote worker's own spans join the supervisor's trace under the spawning node's span.\n * Absent when the run records no spans — the create options are then untouched.\n */\n readonly traceEnv?: Record<string, string>\n readonly contentRef: (prefix: string, value: unknown) => string\n readonly now?: () => number\n}\n\n/** One steerable sandbox worker. The returned session is inert until `stream()` is drained. */\nexport function createSteerableSandboxSession(args: SteerableSandboxArgs): SteerableSandboxSession {\n const now = args.now ?? Date.now\n const maxTurns = args.options?.maxTurns ?? DEFAULT_SANDBOX_STEERING_MAX_TURNS\n if (!Number.isSafeInteger(maxTurns) || maxTurns < 0) {\n throw new ValidationError(\n 'steerable sandbox worker: maxTurns must be a nonnegative safe integer (0 means unbounded)',\n )\n }\n const activity: ActivityLog = createActivityLog(args.options?.activityWindow ?? 12)\n const trace = createPushTraceSource({ runId: `sandbox-${args.harness}-${now()}`, now })\n\n const state = {\n turns: 0,\n lastText: '',\n seenToolCalls: new Set<string>(),\n artifact: undefined as { outRef: string; out: unknown; spent: Spend } | undefined,\n teardown: undefined as (() => Promise<void>) | undefined,\n note: 'starting',\n }\n\n const recordEvent = (event: SandboxEvent): void => {\n const at = now()\n const data = (event as { data?: unknown }).data\n const part = data && typeof data === 'object' ? (data as { part?: unknown }).part : undefined\n if (part !== undefined) {\n const step = decodeToolPart(part, args.harness)\n if (step) {\n // The same call streams several frames; count it once so the detector panel and the\n // driver's activity window both see ONE entry per real tool call.\n const key = step.callId ?? `${step.toolName}:${activity.size()}`\n if (!state.seenToolCalls.has(key)) {\n state.seenToolCalls.add(key)\n trace.record(step)\n const note: ActivityNote = {\n at,\n kind: 'tool',\n label: step.toolName,\n ...(step.status ? { status: step.status } : {}),\n ...(describeToolArgs(step.args) ? { detail: describeToolArgs(step.args) } : {}),\n }\n activity.push(note)\n }\n }\n }\n const text = readFinalText(event)\n if (text) state.lastText = text\n }\n\n async function* stream(task: unknown, signal: AbortSignal): AsyncIterable<UsageEvent> {\n const capabilities = await probeSandboxCapabilities(args.sandboxClient)\n const lineage = createSandboxLineage(args.sandboxClient, capabilities, { maxConcurrency: 1 })\n state.teardown = () => lineage.teardown()\n\n const spec: AgentRunSpec<unknown> = {\n profile: args.profile,\n taskToPrompt: args.taskToPrompt,\n name: args.profile.name ?? String(args.harness),\n sandboxOverrides: {\n backend: { type: args.harness },\n ...(args.traceEnv && Object.keys(args.traceEnv).length > 0 ? { env: args.traceEnv } : {}),\n },\n }\n const promptOptions = readPromptOptions(args.loopCtx)\n\n const started = now()\n const tokens = zeroTokenUsage()\n let tokensKnown = true\n let usd = 0\n let handle: SandboxLineageHandle | undefined\n let nextPrompt: string | undefined = args.taskToPrompt(task)\n\n try {\n for (let turn = 0; maxTurns === 0 || turn < maxTurns; turn += 1) {\n // Drain the down-leg FIRST. On turn 0 a steer that landed during box acquisition is\n // appended to the task; on later turns the steer IS the whole prompt, because the\n // worker's prior context lives server-side in the session.\n const pending = args.inbox.drain()\n if (pending.length > 0) {\n const folded = args.inbox.fold(pending)\n nextPrompt = turn === 0 && nextPrompt ? `${nextPrompt}\\n\\n${folded}` : folded\n activity.push({\n at: now(),\n kind: 'note',\n label: 'steer-folded',\n detail: `${pending.length} message(s)`,\n })\n }\n if (nextPrompt === undefined) break\n\n const prompt = nextPrompt\n nextPrompt = undefined\n state.note = `turn ${turn}`\n\n const interruptSig = args.inbox.freshInterrupt()\n const turnController = new AbortController()\n const abortTurn = () => turnController.abort()\n if (signal.aborted || args.controller.signal.aborted) turnController.abort()\n else {\n signal.addEventListener('abort', abortTurn)\n args.controller.signal.addEventListener('abort', abortTurn)\n }\n interruptSig.addEventListener('abort', abortTurn, { once: true })\n const timer = args.options?.turnTimeoutMs\n ? setTimeout(abortTurn, args.options.turnTimeoutMs)\n : undefined\n const cleanup = () => {\n signal.removeEventListener('abort', abortTurn)\n args.controller.signal.removeEventListener('abort', abortTurn)\n if (timer) clearTimeout(timer)\n }\n\n let events: AsyncIterable<SandboxEvent>\n let sawLlmCall = false\n try {\n if (!handle) {\n const opened = await lineage.start(spec, prompt, turnController.signal, promptOptions)\n handle = opened.handle\n events = opened.events\n } else {\n events = await lineage.continue(handle, prompt, turnController.signal, promptOptions)\n }\n for await (const event of events) {\n recordEvent(event)\n const call = extractLlmCallEvent(event, spec.name ?? String(args.harness))\n if (!call) continue\n sawLlmCall = true\n const callTokensKnown =\n call.tokensKnown !== false &&\n typeof call.tokensIn === 'number' &&\n typeof call.tokensOut === 'number'\n if (!callTokensKnown) tokensKnown = false\n const input = call.tokensIn ?? 0\n const output = call.tokensOut ?? 0\n if (input || output || !callTokensKnown) {\n tokens.input += input\n tokens.output += output\n yield {\n kind: 'tokens',\n input,\n output,\n ...(callTokensKnown ? {} : { tokensKnown: false }),\n }\n }\n if (typeof call.costUsd === 'number' && call.costUsd > 0) {\n usd += call.costUsd\n // Numeric sandbox cost has no billing-provenance/completeness receipt.\n yield { kind: 'cost', usd: call.costUsd, usdKnown: false }\n }\n }\n } catch (e) {\n cleanup()\n // Re-plan ONLY when a forceful steer (not external teardown) aborted the turn: the\n // steer is already queued, so loop back and fold it. Anything else is fatal.\n if (isInterruptAbort(e, interruptSig, signal, args.controller.signal)) {\n activity.push({ at: now(), kind: 'note', label: 'interrupted', detail: 'replanning' })\n continue\n }\n throw e\n }\n cleanup()\n\n if (!sawLlmCall) {\n tokensKnown = false\n yield { kind: 'tokens', input: 0, output: 0, tokensKnown: false }\n }\n\n state.turns += 1\n activity.push({ at: now(), kind: 'turn', label: `turn ${turn}` })\n yield { kind: 'iteration' }\n\n // A worker may NOT settle while a delivered steer is unread — that is the whole\n // contract `steer_agent` reports back to the driver. Loop instead of breaking.\n if (args.inbox.pending() === 0) break\n }\n } finally {\n state.note = 'settled'\n await lineage.teardown().catch(() => {})\n state.teardown = undefined\n }\n\n // Mark the dollar channel unknown even when no event carried a numeric subtotal: a completed\n // sandbox turn is not proof that the provider billed exactly zero.\n if (state.turns > 0) yield { kind: 'cost', usd: 0, usdKnown: false }\n const spent: Spend = {\n iterations: state.turns,\n tokens,\n ...(tokensKnown ? {} : { tokensKnown: false }),\n usd,\n ...(state.turns > 0 ? { usdKnown: false } : {}),\n ms: now() - started,\n }\n const out = {\n content: state.lastText,\n turns: state.turns,\n toolCalls: activity\n .read()\n .filter((n) => n.kind === 'tool')\n .map((n) => n.label),\n }\n state.artifact = {\n outRef: args.contentRef('sandbox-steerable', { harness: args.harness, out }),\n out,\n spent,\n }\n }\n\n return {\n stream,\n progress: (): ExecutorProgress => ({\n turns: state.turns,\n pendingMessages: args.inbox.pending(),\n recentActivity: activity.read(),\n note: state.note,\n }),\n traceSource: () => trace.source,\n artifact: () => state.artifact,\n async teardown() {\n await state.teardown?.().catch(() => {})\n },\n }\n}\n\n/** A forceful steer aborted this turn (and NOT an external teardown), so the loop re-plans. */\nfunction isInterruptAbort(\n err: unknown,\n interrupt: AbortSignal,\n external: AbortSignal,\n owned: AbortSignal,\n): boolean {\n const aborted =\n (err instanceof DOMException && err.name === 'AbortError') ||\n (typeof err === 'object' && err !== null && (err as { name?: unknown }).name === 'AbortError')\n return aborted && interrupt.aborted && !external.aborted && !owned.aborted\n}\n\n/** The terminal text a sandbox `result` event carries, when it carries one. */\nfunction readFinalText(event: SandboxEvent): string | undefined {\n const data = (event as { data?: unknown }).data\n if (!data || typeof data !== 'object') return undefined\n const text = (data as { finalText?: unknown; text?: unknown }).finalText\n if (typeof text === 'string' && text.length > 0) return text\n const alt = (data as { text?: unknown }).text\n return typeof alt === 'string' && alt.length > 0 ? alt : undefined\n}\n\n/** Prompt options the composed loop context already carries (agent profile / cwd), forwarded so\n * a steerable worker runs with the same box configuration as the single-shot path. */\nfunction readPromptOptions(\n loopCtx: Partial<Omit<ExecCtx, 'sandboxClient' | 'signal'>> | undefined,\n): Omit<PromptOptions, 'signal' | 'sessionId'> | undefined {\n const opts = (loopCtx as { promptOptions?: unknown } | undefined)?.promptOptions\n if (!opts || typeof opts !== 'object') return undefined\n return opts as Omit<PromptOptions, 'signal' | 'sessionId'>\n}\n\n/** Fail loud on a steering config that cannot work, before any box is created. */\nexport function assertSteerable(client: SandboxClient | undefined): void {\n if (!client || typeof client.create !== 'function') {\n throw new ValidationError('steerable sandbox worker: SandboxSeam.sandboxClient.create required')\n }\n}\n","/**\n * Trace context handed DOWN to a spawned worker, so one supervised tree spans machines.\n *\n * WHY. `otel-spans.ts` makes the supervisor's own tree readable by any trace viewer, but it stops at\n * the process boundary: a worker running on a remote sandbox or in a child process opens its OWN\n * trace root, so the viewer shows two unrelated trees for one run. A worker that inherits the\n * parent's trace id and the spawning node's span id emits spans that JOIN the parent's trace, and\n * the viewer assembles the whole cross-machine tree with no viewer change.\n *\n * THE WIRE IS W3C `TRACEPARENT`, dual-written with the legacy pair. `traceContextToEnv`\n * (`src/mcp/trace-propagation.ts`) writes `TRACEPARENT` (the convention the ecosystem — OTel SDKs,\n * collectors, the Claude Code harness binary — reads at spawn) ALONGSIDE the bespoke\n * `TRACE_ID` / `PARENT_SPAN_ID` pair this package shipped first, and `readTraceContextFromEnv()`\n * reads `TRACEPARENT` first with the legacy pair as fallback. The bespoke pair is the fork, not\n * the standard; it is kept for one release so children on the previous package version still join,\n * then removed in the next major.\n *\n * WHICH SPAN. The stamped `PARENT_SPAN_ID` is the span of the node that DID the spawning — the\n * scope's own `parentId` — not the span of the worker's own node. At depth 0 that is the run's root\n * span; inside a driver's nested scope it is that driver child's span, so a depth-2 worker joins\n * under the middle node rather than the root. That is also the only span guaranteed to exist at the\n * moment the child's `ExecutorContext` is built (the worker's own node span is opened by the\n * `agent.spawn` hook that fires just after), so the wire needs no ordering assumption.\n *\n * OFF WHEN TRACING IS OFF. The context reaches an executor only through the `ExecutorContext` seam\n * this module names, and that seam is seeded only when a run configured `SuperviseOptions.otel` AND\n * an exporter resolved. With tracing off there is no seam, {@link workerTraceEnv} returns an empty\n * record, and every spawn environment is byte-identical to what it was before this module existed.\n *\n * TWO SEEDING SITES, because there are two ways a worker's `ExecutorContext` gets built. `Scope`\n * seeds it per child for anything the executor registry resolves — that is the path that knows the\n * spawning node and reaches arbitrary depth. `workerFromBackend` (what `supervise({ backend })`\n * uses) instead builds its leaf executor eagerly and hands it back as a bring-your-own `Executor`,\n * which the registry resolves WITHOUT consulting the scope's context at all; `supervise()` therefore\n * passes the seam to `workerFromBackend` itself, resolved against the run root, which is the node\n * that spawns every front-door worker. Miss that second site and the front door looks wired and\n * stamps nothing.\n *\n * PRECEDENCE, from lowest to highest:\n * 1. the supervisor process's own `process.env` (ambient inheritance),\n * 2. the trace context stamped here,\n * 3. the caller's own seam env (`CliSeam.env`).\n * A caller who sets `TRACE_ID` / `PARENT_SPAN_ID` on a seam wins — theirs is a deliberate\n * declaration about the worker — and the W3C wire follows: a seam that overrides the legacy pair\n * without its own `TRACEPARENT` gets `TRACEPARENT` rebuilt from ITS ids (`mergeTraceEnv` performs\n * the dual-write on the caller's behalf), never left as the recorder's, so both spellings always\n * name the same trace. Ambient `process.env` does NOT win: when the supervisor process was\n * itself launched as someone's worker, its inherited ids describe the SUPERVISOR's place in an\n * outer trace, and reusing them for a child would file the child's spans under the wrong parent.\n * The supported way to join that outer trace is `SupervisorSpanOptions.traceId` / `parentSpanId`\n * (feed them from `readTraceContextFromEnv()`), which makes the recorder's own ids the outer ones\n * and so makes every stamped child inherit them too.\n *\n * WHICH BACKENDS PROPAGATE. Only a backend with a real channel to the worker can carry this, and\n * the ones that have none say so here rather than dropping it silently:\n * - `cli` YES — `CliSeam.env` → the spawned subprocess.\n * - `sandbox` YES — `CreateSandboxOptions.env` on the box the worker runs in (single-shot\n * and steerable). This is the cross-MACHINE case the feature exists for.\n * - `bridge` YES — request headers on the bridge POST (`traceparent` plus the legacy\n * `x-trace-id` / `x-parent-span-id` pair, {@link workerTraceHeaders}); the\n * bridge stamps them into the harness child's environment at spawn.\n * - `router`,\n * `router-tools` NO — a direct model HTTP call. There is no worker process to inherit anything.\n * - `cli-worktree` NO — the work is dispatched through a local harness transport that exposes\n * no environment channel. Wiring it means adding that channel to the transport\n * first; until then it is honestly unpropagated.\n * - `provider` NO — `AgentEnvironmentProvider` has no environment field on its port.\n */\n\nimport { type TraceContext, traceContextToEnv } from '../../mcp/trace-propagation'\nimport type { ExecutorConfig } from './runtime'\n\n/**\n * The census above, as a value the compiler checks. `satisfies` against every `ExecutorConfig`\n * discriminant means an EIGHTH backend arm cannot be added without classifying it here — the prose\n * alone could go stale silently, which is the failure this table exists to prevent.\n *\n * `true` = the arm has a real channel to the worker (environment or transport headers) and stamps\n * the context. `false` = it has none today; it is honestly unpropagated rather than silently\n * dropping.\n */\nexport const WORKER_TRACE_PROPAGATION = {\n cli: true,\n sandbox: true,\n router: false,\n 'router-tools': false,\n bridge: true,\n 'cli-worktree': false,\n provider: false,\n} as const satisfies Record<ExecutorConfig['backend'], boolean>\n\nexport type { TraceContext }\n\n/**\n * Seam key the `Scope` seeds a {@link TraceContext} under on each child's `ExecutorContext.seams`.\n * Single-sourced here so the scope and every backend agree on it without a circular import — the\n * same arrangement `nestedScopeSeamKey` uses.\n */\nexport const workerTraceSeamKey = 'worker-trace'\n\n/**\n * Resolve the trace context a worker spawned BY `spawningNodeId` should inherit. `undefined` means\n * this run records no spans, so nothing is stamped. Supplied by\n * `SupervisorSpanRecorder.workerTrace` and threaded to the scope as `SupervisorOpts.workerTrace`.\n */\nexport type WorkerTraceResolver = (spawningNodeId: string) => TraceContext | undefined\n\n/**\n * What the two readers below need off an `ExecutorContext` — its seam bag, and nothing else.\n * Structural (not an `ExecutorContext` import) so this module stays free of the keystone type\n * surface, and exported because it is part of a public signature.\n */\nexport interface WorkerTraceSeamCarrier {\n readonly seams: Readonly<Record<string, unknown>>\n}\n\n/**\n * Read the inherited trace context off an `ExecutorContext`, or `undefined` when the run records no\n * spans. Fails CLOSED on a malformed seam value (returns `undefined`) rather than stamping a\n * half-formed id that would produce an unjoinable orphan span downstream.\n */\nexport function readWorkerTraceContext(ctx: WorkerTraceSeamCarrier): TraceContext | undefined {\n const seam = ctx.seams[workerTraceSeamKey]\n if (seam === undefined || seam === null || typeof seam !== 'object') return undefined\n const { traceId, parentSpanId } = seam as { traceId?: unknown; parentSpanId?: unknown }\n if (typeof traceId !== 'string' || traceId.length === 0) return undefined\n return {\n traceId,\n ...(typeof parentSpanId === 'string' && parentSpanId.length > 0 ? { parentSpanId } : {}),\n }\n}\n\n/**\n * The trace env to merge into a worker's environment — `TRACEPARENT` plus the legacy\n * `TRACE_ID` / `PARENT_SPAN_ID` pair (dual-written for one release) — EMPTY when the run\n * records no spans, which is what keeps the untraced path byte-identical. Merge it BELOW the\n * caller's own seam env so a deliberately-set id wins (see the precedence note above).\n */\nexport function workerTraceEnv(ctx: WorkerTraceSeamCarrier): Record<string, string> {\n const traceContext = readWorkerTraceContext(ctx)\n return traceContext ? traceContextToEnv(traceContext) : {}\n}\n\n/**\n * The trace request headers for a worker dispatched over the cli-bridge HTTP transport — W3C\n * `traceparent` plus the legacy `x-trace-id` / `x-parent-span-id` pair the bridge also reads —\n * EMPTY when the run records no spans, which keeps the untraced request byte-identical. Derived\n * from the same dual-write the env channel uses ({@link workerTraceEnv}), so the header and env\n * spellings can never name different traces. `traceparent` is present only when a parent span id\n * exists (the W3C grammar requires one); the legacy pair still carries a lone trace id.\n */\nexport function workerTraceHeaders(ctx: WorkerTraceSeamCarrier): Record<string, string> {\n const env = workerTraceEnv(ctx)\n return {\n ...(env.TRACEPARENT !== undefined ? { traceparent: env.TRACEPARENT } : {}),\n ...(env.TRACE_ID !== undefined ? { 'x-trace-id': env.TRACE_ID } : {}),\n ...(env.PARENT_SPAN_ID !== undefined ? { 'x-parent-span-id': env.PARENT_SPAN_ID } : {}),\n }\n}\n","/**\n *\n * The worktree-CLI leaf executor — a supervisor-authored `AgentProfile` driving a local\n * coding-harness CLI (claude / codex / opencode) on its OWN git worktree, surfaced as the open\n * `Executor<Out>` port (`./types`). It is a LEAF executor: it plugs straight into the\n * `Scope`/`Supervisor` recursion and `gateOnDeliverable`, so it IS the canonical recursive path\n * (no `runAgentRounds`/virtual-SandboxInstance shim in between).\n *\n * This is a THIN adapter: the physical act (worktree → profile-aware harness invocation → diff →\n * checks → cleanup) lives ONCE in `runWorktreeHarness` (`../../mcp/worktree-harness`), shared with\n * the `runAgentRounds`/coder-delegate `createInProcessExecutor`. This executor only projects that core's\n * result onto the `Executor` port (artifact + spend) and owns the teardown point. The complete\n * profile delivery — direct prompt/model plus materialized file-backed resources — lives there.\n *\n * Token accounting: ordinary harness CLI runs remain `budgetExempt`, and their `Spend` marks\n * `tokensKnown: false` — the `{0,0}` is a floor, never a measured-free run. Reproducible Codex mode\n * parses the CLI's terminal JSONL usage and is metered by default; an absent usage event fails the\n * run instead of recording fabricated zero tokens. Codex does not report dollar cost, so that\n * channel is explicitly marked unknown on the metered path.\n *\n * @experimental\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { contentAddress } from '../../durable/spawn-journal'\nimport { ValidationError } from '../../errors'\nimport { LOCAL_HARNESSES, type LocalHarness, type runLocalHarness } from '../../mcp/local-harness'\nimport type { GitRunner } from '../../mcp/worktree'\nimport {\n runWorktreeHarness,\n type WorktreeCheckRunner,\n type WorktreeCommandResult,\n type WorktreeHarnessResult,\n type WorktreeHarnessRun,\n type WorktreeProfileMaterializationReceipt,\n worktreeProfileExecutionPlan,\n} from '../../mcp/worktree-harness'\nimport { executableAgentProfileSnapshot } from './executable-spec'\nimport { attestRuntimeOwnedExecutor, newExecutionAttemptId } from './materialization'\nimport { concreteProfileModel } from './model-policy'\nimport type { Executor, ExecutorResult, Spend } from './types'\n\nexport type { WorktreeCommandResult, WorktreeProfileMaterializationReceipt }\n/** Terminal artifact of one worktree-CLI run — the canonical worktree-harness result (the captured\n * diff + the harness's run record + the derived checks). */\nexport type WorktreePatchArtifact = WorktreeHarnessResult\n\n/** @experimental */\nexport interface WorktreeCliExecutorOptions {\n /** Absolute path to the git checkout the worktree is cut from. */\n repoRoot: string\n /**\n * The supervisor-authored prompt/model plus materializable structural resources.\n * `model.default` selects the one-shot model. Routing-only model hints, placement concerns,\n * provider extensions, and `resources.failOnError` fail before execution because this path\n * cannot honor them. Harness-specific values the materializer cannot preserve also fail closed.\n */\n profile: AgentProfile\n /** Default instruction for direct `execute(undefined, signal)` calls. An execution-time task\n * is authoritative. Omit when the caller always supplies the task to `execute`. */\n taskPrompt?: string\n /** Unique id for the worktree path + branch. Defaults to a fresh UUID. */\n runId?: string\n /** Override the base ref the worktree is cut from (default `HEAD`). */\n baseRef?: string\n /** Wall-clock cap per harness subprocess (ms). Default 5 min (the `runLocalHarness` default). */\n harnessTimeoutMs?: number\n /** Run Codex with an ephemeral session, isolated config/instructions, network disabled, and\n * JSONL usage capture. Requires `profile.harness: 'codex'`; metered by default. */\n codexReproducible?: boolean\n /** Absolute host paths denied to reproducible Codex (for benchmark answer copies, credentials,\n * or other task-specific ambient state). */\n codexReadDeniedPaths?: ReadonlyArray<string>\n /**\n * Shell command run in the live worktree to derive the tests-PASS signal (e.g. `pnpm test`).\n * Its exit code becomes `artifact.checks.tests.passed`. Omit to skip (no signal derived).\n */\n testCmd?: string\n /** Shell command run in the live worktree to derive the typecheck-PASS signal (e.g. `pnpm typecheck`). */\n typecheckCmd?: string\n /** Wall-clock cap per verification command (ms). Default = `harnessTimeoutMs` or 5 min. */\n checkTimeoutMs?: number\n /** Cap on each check's captured output. Default 16k. */\n checkOutputCap?: number\n /** Test seam — inject a git runner so unit tests drive the worktree helpers without git. */\n runGit?: GitRunner\n /** Test seam — inject the harness runner so unit tests script a `LocalHarnessResult`. */\n runHarness?: typeof runLocalHarness\n /** Test seam — inject the verification-command runner so unit tests script test/typecheck\n * outcomes without spawning a real shell. Defaults to a `/bin/sh -c` spawn in the worktree. */\n runCommand?: WorktreeCheckRunner\n /**\n * Exclude this leaf's spend from accounting. Defaults to `true` for ordinary CLI runs and\n * `false` for `codexReproducible`, which captures real token usage. A metered custom runner must\n * likewise return `LocalHarnessResult.usage`.\n */\n budgetExempt?: boolean\n /** @internal Kernel-minted attempt identity threaded by the built-in registry. */\n executionAttemptId?: string\n}\n\n/**\n * Build a worktree-CLI leaf `Executor`. Per-spawn (a fresh worktree + abort + teardown each), so a\n * fanout of N profiles = N parallel worktrees that never clobber each other.\n *\n * Fail-loud: an empty `repoRoot`, an incomplete/unsupported profile, a separate harness override,\n * or an explicitly empty `taskPrompt` throws at construction. Calling `execute(undefined, signal)`\n * without a configured prompt throws before a worktree is created. `resultArtifact()` before\n * `execute()` resolves throws.\n *\n * @experimental\n */\nexport function createWorktreeCliExecutor(\n options: WorktreeCliExecutorOptions,\n): Executor<WorktreePatchArtifact> {\n if (!options.repoRoot) {\n throw new ValidationError('createWorktreeCliExecutor: repoRoot required')\n }\n if ('harness' in options) {\n throw new ValidationError(\n 'createWorktreeCliExecutor: separate harness is forbidden; set AgentProfile.harness',\n )\n }\n const profile = executableAgentProfileSnapshot(options.profile, 'createWorktreeCliExecutor')\n const harness = localHarnessFromProfile(profile)\n if (\n options.taskPrompt !== undefined &&\n (typeof options.taskPrompt !== 'string' || options.taskPrompt.length === 0)\n ) {\n throw new ValidationError('createWorktreeCliExecutor: taskPrompt required')\n }\n // KEPT harness-name test: `codexReproducible` is a codex-SPECIFIC public option, so this\n // asserts caller self-consistency and throws loudly instead of varying behavior by name.\n if (options.codexReproducible && harness !== 'codex') {\n throw new ValidationError(\n 'createWorktreeCliExecutor: codexReproducible requires harness \"codex\"',\n )\n }\n if (options.codexReproducible && options.budgetExempt === true) {\n throw new ValidationError('createWorktreeCliExecutor: codexReproducible cannot be budgetExempt')\n }\n if (options.codexReadDeniedPaths !== undefined && !options.codexReproducible) {\n throw new ValidationError(\n 'createWorktreeCliExecutor: codexReadDeniedPaths requires codexReproducible',\n )\n }\n\n const runId = options.runId ?? randomUUID()\n const attemptId = options.executionAttemptId ?? newExecutionAttemptId(runId)\n const controller = new AbortController()\n const budgetExempt = options.budgetExempt ?? !options.codexReproducible\n\n let run: WorktreeHarnessRun | undefined\n let artifact: ExecutorResult<WorktreePatchArtifact> | undefined\n\n const profilePlan = worktreeProfileExecutionPlan(profile, harness)\n const profileModel = concreteProfileModel(profile)\n if (!profileModel) {\n throw new ValidationError('createWorktreeCliExecutor: exact profile model unexpectedly missing')\n }\n return attestRuntimeOwnedExecutor(\n {\n runtime: 'cli',\n budgetExempt,\n async execute(task, signal): Promise<ExecutorResult<WorktreePatchArtifact>> {\n const linked = linkSignals(signal, controller.signal)\n const started = Date.now()\n const taskPrompt = executionTaskPrompt(task, options.taskPrompt)\n\n run = await runWorktreeHarness({\n repoRoot: options.repoRoot,\n profile,\n harness,\n taskPrompt,\n runId,\n ...(options.baseRef ? { baseRef: options.baseRef } : {}),\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.harnessTimeoutMs !== undefined\n ? { harnessTimeoutMs: options.harnessTimeoutMs }\n : {}),\n ...(options.codexReproducible ? { codexReproducible: true } : {}),\n ...(options.codexReadDeniedPaths\n ? { codexReadDeniedPaths: options.codexReadDeniedPaths }\n : {}),\n ...(options.checkTimeoutMs !== undefined\n ? { checkTimeoutMs: options.checkTimeoutMs }\n : {}),\n ...(options.checkOutputCap !== undefined\n ? { checkOutputCap: options.checkOutputCap }\n : {}),\n ...(linked ? { signal: linked } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n\n const usage = run.result.harness.usage\n if (!budgetExempt && !usage) {\n const completed = run\n run = undefined\n await completed.cleanup()\n throw new ValidationError(\n 'createWorktreeCliExecutor: metered harness run returned no token usage',\n )\n }\n // A budget-exempt run has no usage receipt, so its `{0,0}` is a FLOOR, not a measurement.\n // Left unmarked it is byte-identical to a run that truly cost nothing, and a token-priced\n // ceiling over this leaf then reads as enforced while enforcing nothing. `tokensKnown`\n // is the marker; the dollar channel is left alone because `usdKnown: false` under a\n // dollar-capped root is a reconcile REFUSAL in `budget.ts`, which would contradict the\n // exemption this leaf was granted (see `unmeteredSpend` in ./runtime).\n const spent: Spend = {\n iterations: 1,\n tokens: usage\n ? { input: usage.inputTokens, output: usage.outputTokens }\n : { input: 0, output: 0 },\n ...(usage ? {} : { tokensKnown: false }),\n usd: 0,\n ...(usage ? { usdKnown: false } : {}),\n ms: Date.now() - started,\n }\n artifact = { outRef: contentAddress(run.result), out: run.result, spent }\n return artifact\n },\n async teardown(_grace): Promise<{ destroyed: boolean }> {\n controller.abort()\n // The loser of a fanout (or any settled run) is dirty — remove its worktree. A run that\n // THREW already cleaned itself up in the core, so `run` stays undefined and this is a no-op.\n if (run) {\n const r = run\n run = undefined\n await r.cleanup()\n }\n return { destroyed: true }\n },\n resultArtifact() {\n if (!artifact) {\n throw new ValidationError(\n 'createWorktreeCliExecutor: resultArtifact() read before execute() resolved',\n )\n }\n return artifact\n },\n },\n {\n effectiveProfile: profile,\n backend: `cli-worktree:${harness}`,\n model: { status: 'known', id: profileModel },\n execution: { kind: 'worktree-run', id: runId },\n materializer: 'agent-profile-worktree-plan',\n plan: {\n kind: 'worktree-cli',\n profilePlan,\n harness,\n baseRef: options.baseRef ?? 'HEAD',\n harnessTimeoutMs: options.harnessTimeoutMs ?? null,\n codexReproducible: options.codexReproducible === true,\n codexReadDeniedPaths: options.codexReadDeniedPaths ?? [],\n testCmd: options.testCmd ?? null,\n typecheckCmd: options.typecheckCmd ?? null,\n checkTimeoutMs: options.checkTimeoutMs ?? null,\n checkOutputCap: options.checkOutputCap ?? 16_000,\n },\n },\n {\n attemptId,\n binding: {\n repoRoot: options.repoRoot,\n runId,\n harness,\n model: profileModel,\n baseRef: options.baseRef ?? 'HEAD',\n },\n descriptor: {\n kind: 'worktree-cli-run',\n transport: 'process',\n backend: harness,\n },\n },\n )\n}\n\nfunction localHarnessFromProfile(profile: AgentProfile): LocalHarness {\n const harness = profile.harness\n if (LOCAL_HARNESSES.includes(harness as LocalHarness)) return harness as LocalHarness\n throw new ValidationError(\n `createWorktreeCliExecutor: AgentProfile.harness must select ${LOCAL_HARNESSES.join(', ')}`,\n )\n}\n\n/** A scoped execution task is authoritative. The configured prompt remains only as the\n * unambiguous direct-call default for existing `execute(undefined, signal)` consumers. */\nfunction executionTaskPrompt(task: unknown, configuredPrompt: string | undefined): string {\n if (task === undefined) {\n if (configuredPrompt !== undefined) return configuredPrompt\n throw new ValidationError(\n 'createWorktreeCliExecutor: execute task required when taskPrompt is not configured',\n )\n }\n if (typeof task === 'string') return task\n try {\n const encoded = JSON.stringify(task)\n if (encoded !== undefined) return encoded\n } catch (error) {\n throw new ValidationError('createWorktreeCliExecutor: execute task must be JSON-serializable', {\n cause: error,\n })\n }\n throw new ValidationError('createWorktreeCliExecutor: execute task must be JSON-serializable')\n}\n\n/** Link two abort signals into one that fires when either does. Returns `undefined` when neither\n * is present so the harness runner gets no signal at all. */\nfunction linkSignals(a: AbortSignal, b: AbortSignal): AbortSignal | undefined {\n if (a.aborted || b.aborted) {\n const c = new AbortController()\n c.abort()\n return c.signal\n }\n const c = new AbortController()\n const onAbort = () => c.abort()\n a.addEventListener('abort', onAbort, { once: true })\n b.addEventListener('abort', onAbort, { once: true })\n return c.signal\n}\n","/**\n *\n * The leaf runtime — the built-in `Executor` IMPLEMENTATIONS behind the ONE\n * open interface frozen in `./types`, plus the open resolver/registry that maps\n * an `AgentSpec` to one of them OR accepts a bring-your-own executor verbatim.\n *\n * The interface is the extension point, not a closed `inline|sandbox|cli` union:\n * - router/inline : a direct OpenAI-compatible Router call, no box (one-shot).\n * - sandbox : COMPOSES the existing `runAgentRounds` kernel as a single-task\n * leaf and surfaces its token/cost usage as `UsageEvent`s;\n * forwards PR #150's optional `lineage` passthrough WITHOUT\n * reinventing checkpoint/fork (streaming).\n * - cli : a Halo/RLM subprocess; `budgetExempt` (no token accounting),\n * excluded from the equal-k arms by construction (streaming).\n * Every metered runtime reports through the SAME normalized `UsageEvent` channel\n * so the conserved budget pool meters them identically. A user's own agent is\n * first-class the moment it implements `Executor` — register it by name or\n * pass it as `AgentSpec.executor`.\n *\n * Layering: `estimateCost`/`isModelPriced` are substrate primitives from\n * `@tangle-network/agent-eval`; `runAgentRounds`/`acquireSandbox` are runtime kernels\n * from this package. No per-vendor adapters live here.\n *\n * @experimental\n */\n\nimport { spawn } from 'node:child_process'\nimport { randomUUID } from 'node:crypto'\nimport { request as httpRequest } from 'node:http'\nimport { request as httpsRequest } from 'node:https'\nimport { Readable } from 'node:stream'\nimport { estimateCost, isModelPriced } from '@tangle-network/agent-eval'\nimport {\n type AgentProfile,\n type AgentProfileResourceRef,\n agentProfileSchema,\n canonicalAgentProfileDigest,\n profileMaterializationAxes,\n REASONING_EFFORTS,\n type ReasoningEffort,\n} from '@tangle-network/agent-interface'\nimport type { BackendType, SandboxEvent } from '@tangle-network/sandbox'\nimport {\n assertProfileMaterialization,\n defineProfileMaterializationContract,\n} from '../../agent/profile-materialization'\nimport { BackendTransportError, ValidationError } from '../../errors'\nimport { mergeTraceEnv } from '../../mcp/trace-propagation'\nimport {\n captureWorktreeDiff,\n createWorktree,\n type GitRunner,\n removeWorktree,\n type WorktreeHandle,\n} from '../../mcp/worktree'\nimport {\n runWorktreeChecks,\n type WorktreeCheckRunner,\n type WorktreeHarnessResult,\n} from '../../mcp/worktree-harness'\nimport {\n type AgentEnvironmentProvider,\n type AgentEnvironmentProviderRegistry,\n type ProviderExecutorOptions,\n providerAsExecutor,\n providerAsSandboxClient,\n resolveAgentEnvironmentProvider,\n} from '../environment-provider'\nimport { agentHarness } from '../harness-role'\nimport type { KeyProvider } from '../key-provider'\nimport { mergeObservedModelIdentity, observedModelMatchesDeclared } from '../model-identity'\nimport {\n type PromptCacheUsage,\n type RouterChatResult,\n type RouterChatToolsResult,\n type RouterConfig,\n routerChatWithTools,\n routerChatWithUsage,\n routerTransportAttemptsFromError,\n streamRouterChatWithTools,\n type ToolSpec,\n} from '../router-client'\nimport type { RunAgentRoundsOptions } from '../run-loop'\nimport { runAgentRounds } from '../run-loop'\nimport type {\n AgentRunSpec,\n Driver,\n ExecCtx,\n Iteration,\n OutputAdapter,\n SandboxClient,\n} from '../types'\nimport { addTokenUsage, cloneTokenUsage, zeroTokenUsage } from '../util'\nimport { executableAgentProfileSnapshot, executableAgentSpecSnapshot } from './executable-spec'\nimport { createInbox, type Inbox } from './inbox'\nimport {\n attestRuntimeOwnedExecutor,\n attestRuntimeOwnedPendingExecutor,\n finalizeRuntimeOwnedPendingExecutor,\n newExecutionAttemptId,\n recordRuntimeOwnedProviderAttemptStart,\n recordRuntimeOwnedProviderIdentityConflict,\n recordRuntimeOwnedProviderModel,\n runtimeOwnedExecutorExecutionBinding,\n runtimeOwnedExecutorMaterialization,\n} from './materialization'\nimport {\n assertExecutableAgentProfile,\n concreteProfileModel,\n type ProfileModelExecutionSettings,\n profileBridgeWireModel,\n profileModelExecutionSettings,\n} from './model-policy'\nimport {\n type ActivityLog,\n createActivityLog,\n describeToolArgs,\n type ExecutorProgress,\n} from './progress'\nimport { createSteerableSandboxSession, type SandboxSteeringOptions } from './sandbox-session'\nimport { detachedSnapshot } from './snapshot'\nimport {\n createPushTraceSource,\n decodeOpenAiPart,\n type ToolStepInput,\n type TraceSource,\n} from './trace-source'\nimport type {\n AgentSpec,\n DefaultVerdict,\n Executor,\n ExecutorContext,\n ExecutorFactory,\n ExecutorRegistry,\n ExecutorResult,\n Runtime,\n Spend,\n UsageEvent,\n} from './types'\nimport { workerTraceEnv, workerTraceHeaders } from './worker-trace'\nimport { createWorktreeCliExecutor } from './worktree-cli-executor'\n\n// ── Seam contracts (read off ExecutorContext.seams, narrowed per built-in) ─────\n\n/**\n * Router/inline transport seam. The profile owns model, prompt, and generation behavior.\n */\nexport interface RouterSeam {\n routerBaseUrl: string\n routerKey: string\n /** Injectable transport for offline/local execution; still passes through Runtime metering. */\n complete?: RouterConfig['complete']\n /** When present, return one turn's requested tool calls without executing them. */\n tools?: ReadonlyArray<ToolSpec>\n}\n\nconst routerTurnProfileMaterialization = defineProfileMaterializationContract({\n name: 'router-profile-turn',\n axes: [\n 'name',\n 'description',\n 'version',\n 'tags',\n 'systemPrompt',\n 'instructions',\n 'modelDefault',\n 'modelProvider',\n 'modelReasoningEffort',\n 'modelMetadata',\n 'harness',\n 'tools',\n 'files',\n 'resourceTools',\n 'skills',\n 'resourceAgents',\n 'commands',\n 'resourceInstructions',\n 'metadata',\n ],\n})\n\n/**\n * Sandbox executor seam. The `sandboxClient` the composed `runAgentRounds` creates\n * boxes through, plus the optional trace/run/lineage wiring forwarded into the\n * loop. `lineage` is opaque here (PR #150's `RunAgentRoundsOptions.lineage`): forwarded\n * forward-compatibly, never inspected — this executor does NOT reinvent\n * checkpoint/fork.\n */\nexport interface SandboxSeam {\n sandboxClient: SandboxClient\n /** Forwarded into the composed `runAgentRounds`'s `ctx` (trace emitter, run handle, etc.). */\n loopCtx?: Partial<Omit<ExecCtx, 'sandboxClient' | 'signal'>>\n /** PR #150 `RunAgentRoundsOptions.lineage` passthrough — opaque; forwarded, not parsed. */\n lineage?: unknown\n /** Hard cap on the composed loop's iterations. The budget pool reserves against\n * the spawn `Budget.maxIterations`; this is the leaf's own ceiling. Default 1. */\n maxIterations?: number\n /**\n * OPT-IN: run this worker as a multi-turn, STEERABLE session instead of the historical\n * single-shot `runAgentRounds` composition. Setting it gives the sandbox worker an `Executor.deliver`\n * inbox (so `Scope.send` / `steer_agent` actually reach it), a live tool-activity trace, and a\n * `progress()` read — turning the default cloud worker from something a supervisor can only\n * wait on into something it can watch and correct.\n *\n * Absent, nothing changes: the same `runAgentRounds` leaf, no inbox, `steer_agent` still reports\n * `delivered:false`. Opt-in because a steerable worker holds ONE box across several turns,\n * which is a different resource profile from a fire-and-forget shot.\n */\n steering?: SandboxSteeringOptions\n}\n\n/**\n * UNMETERED CLI subprocess seam. `bin` + `args` describe the process to spawn.\n *\n * READ THIS BEFORE CHOOSING `backend: 'cli'`. This backend pipes a prompt to a subprocess's stdin\n * and reads its stdout. It has no usage receipt of any kind, so it reports its spend with\n * `Spend.tokensKnown: false`: the work is recorded, its `{0,0}` tokens and `$0` are a FLOOR rather\n * than a measurement, and a ceiling priced from either is a ceiling that cannot fire. The executor\n * is also `budgetExempt: true`, which is why `driveHarnessFromBackend` refuses it outright rather\n * than pretending to budget it.\n *\n * If you need a metered harness worker, use `backend: 'bridge'` (a cli-bridge session, which\n * reports the harness's real per-turn tokens and cost) or `backend: 'cli-worktree'` with\n * `codexReproducible`. Reach for this seam only when the subprocess genuinely is not an inference\n * agent, or when you have accepted that its cost is invisible.\n *\n * `args` is argv for a LOCAL, in-process spawn under this process's own privileges. It is not a\n * remote channel and nothing forwards it over a wire.\n */\nexport interface CliSeam {\n bin: string\n args?: string[]\n /** Extra environment for the subprocess (merged over `process.env`). */\n env?: Record<string, string>\n /** Working directory for the subprocess. */\n cwd?: string\n}\n\n/**\n * cli-worktree seam. A supervisor-authored `AgentProfile` driving a local coding-harness CLI\n * (claude / codex / opencode) on its own git worktree — the leaf `createWorktreeCliExecutor`\n * named as data. `repoRoot` is transport data; `AgentProfile.harness` selects the CLI.\n * `taskPrompt` remains an optional direct-call fallback for callers that execute with `undefined`.\n * The authored\n * `profile.prompt.systemPrompt` + `profile.model.default` reach the harness via the §1.5\n * `harnessInvocation` mapper. Everything else mirrors `WorktreeCliExecutorOptions`.\n */\nexport interface CliWorktreeSeam {\n repoRoot: string\n taskPrompt?: string\n runId?: string\n baseRef?: string\n harnessTimeoutMs?: number\n /** Isolated, network-off Codex execution with terminal JSONL usage capture. */\n codexReproducible?: boolean\n /** Absolute host paths denied to reproducible Codex. */\n codexReadDeniedPaths?: ReadonlyArray<string>\n testCmd?: string\n typecheckCmd?: string\n checkTimeoutMs?: number\n checkOutputCap?: number\n budgetExempt?: boolean\n /** Live cli-bridge transport inside the worktree. When set, the worktree leaf accepts\n * `deliver()` messages and resumes the same bridge session in this worktree cwd. */\n bridge?: CliWorktreeBridgeSeam\n /** Test seam — forwarded to worktree helpers. */\n runGit?: GitRunner\n /** Test seam — forwarded to verification checks. */\n runCommand?: WorktreeCheckRunner\n}\n\nexport interface CliWorktreeBridgeSeam {\n bridgeUrl: string\n bridgeBearer: string\n /** Caller-owned deadline for each bridge turn. Runtime enforces it locally and sends the\n * same value in `execution.timeoutMs` so cli-bridge cannot substitute its own cutoff. */\n timeoutMs?: number\n /** Stable cli-bridge session id. Defaults to `bridge-worktree-${runId}`. */\n sessionId?: string\n /** Transport reconnects allowed after the first POST. Default 3; set 0 to disable. */\n maxReconnects?: number\n}\n\n/**\n * cli-bridge seam. A local OpenAI-compatible bridge that fronts harness CLIs\n * (claude-code / opencode / kimi / pi) behind one HTTP surface. The spawned\n * `AgentProfile` is the sole harness/provider/model and behavioral authority and\n * is forwarded verbatim per request; this seam carries transport data only.\n *\n * The executor opens a resumable cli-bridge session. `sessionId` identifies the\n * harness conversation across turns; each turn also receives its own durable run id.\n * A dropped HTTP reader reattaches to that exact run and explicit cancel is the only\n * operation allowed to stop it. Omit `sessionId` and the executor mints one per spawn.\n *\n * ── HOW TO CONTROL WHAT THE HARNESS LOADS (there is no argv field, by design) ──\n *\n * A worker often needs the harness started in a KNOWN state — no ambient extensions, skills,\n * context files, or prompt templates — because ambient state is how a paired experiment silently\n * loses its pairing: an installed extension that persists memory across runs carries arm A's state\n * into arm B, and nothing reports it.\n *\n * That is what the spawned `AgentProfile` is FOR. `agent_profile`\n * rides every request verbatim, and cli-bridge maps it onto each harness's own native controls:\n *\n * - Materializing any profile at all already starts the harness isolated from ambient\n * workspace state — for pi that is `--no-context-files --no-skills --no-prompt-templates`,\n * applied to every request that carries an `agent_profile`.\n * - `AgentProfile.extensions.<harness>` is the named, per-harness control channel. An explicit\n * `extensions: { pi: { load: [] } }` disables ambient extension discovery outright\n * (pi's `--no-extensions`); listing package names loads exactly those and nothing else.\n * - `permissions` / `tools` / `mcp` map onto the harness's native tool and server controls.\n *\n * A caller therefore does NOT need to hand-roll an `Executor` to isolate a harness run, and the\n * profile expressing it stays portable: the same declaration means the same thing on a different\n * harness, whereas an argv string means nothing anywhere else.\n *\n * WHY NOT A GENERAL ARGV PASSTHROUGH. `bridgeUrl` addresses a process-spawning server. Forwarding\n * an arbitrary argv array to it would let any caller holding a bearer token choose the flags of a\n * process on the bridge host — which for real harness CLIs includes flags that load code from a\n * path, read a file into the prompt, redirect the working directory, or turn off the isolation the\n * bridge applies. cli-bridge deliberately confines workers (a filesystem jail and deny-by-default\n * network egress), and every one of those confinements is expressed as spawn configuration, so an\n * argv channel is a channel for unwinding them. It would also break this executor's own contract:\n * the durable-run replay protocol, session pinning, and streaming mode are all argv the bridge\n * owns, and a caller-supplied duplicate silently wins or corrupts the parse. The structured profile\n * channel is validated, per-harness, portable, and refuses controls it does not understand — keep\n * new harness capability there.\n */\nexport interface BridgeSeam {\n bridgeUrl: string\n bridgeBearer: string\n /**\n * Optional request-scoped model credential.\n *\n * The key name is portable configuration. The provider is a live service and is intentionally\n * not serialised. Runtime resolves both values immediately before every bridge POST and sends\n * them only to a loopback bridge through private request headers.\n */\n modelCredential?: BridgeModelCredential\n /** Optional working directory forwarded to cli-bridge and persisted with the session. */\n cwd?: string\n /** Caller-owned deadline for each bridge turn. Runtime enforces it locally and sends the\n * same value in `execution.timeoutMs` so the bridge-owned process follows the same policy. */\n timeoutMs?: number\n /** Stable, caller-owned cli-bridge session id for harness-side resume. Defaults\n * to a freshly minted per-spawn id so each worker is its own resumable session. */\n sessionId?: string\n /** Transport reconnects allowed after the first POST. Default 3; set 0 to disable. */\n maxReconnects?: number\n /** Newest-last activity window `progress()` reports. Default 12. */\n activityWindow?: number\n}\n\n/** A live, request-scoped model credential reference for a local cli-bridge. */\nexport interface BridgeModelCredential {\n /** Provider key name for the scoped model token. */\n key: string\n /** Provider key name for the exact scoped HTTPS model gateway URL. */\n baseUrlKey: string\n /** Live credential service. Runtime retains this reference through reusable captures. */\n provider: KeyProvider\n}\n\n/** Generic environment provider executor config. External packages implement\n * `AgentEnvironmentProvider`; this built-in wrapper lets `createExecutor`\n * consume them as backend data while preserving the existing usage channel. */\nexport interface ProviderSeam extends ProviderExecutorOptions {\n provider: AgentEnvironmentProvider | string\n registry?: AgentEnvironmentProviderRegistry\n /**\n * Compose the provider through the existing steerable sandbox session.\n * The exact profile must name its harness, and the provider must expose live\n * continuation plus session controls. The provider still owns environment\n * creation and session semantics.\n */\n steering?: SandboxSteeringOptions\n}\n\nconst routerSeamKey = 'router'\nconst sandboxSeamKey = 'sandbox'\nconst cliSeamKey = 'cli'\nconst bridgeSeamKey = 'bridge'\nconst maxBridgeTimeoutMs = 2_147_483_647\nconst bridgeModelCredentialHeader = 'x-cli-bridge-model-credential'\nconst bridgeModelBaseUrlHeader = 'x-cli-bridge-model-base-url'\nconst bridgeProfileMaterializationSchema = 'cli-bridge.profile-materialization.v2'\nconst bridgeUsageCostSchema = 'cli-bridge.usage-cost.v1'\nconst cliWorktreeSeamKey = 'cli-worktree'\nconst providerSeamKey = 'provider'\n\nfunction isLoopbackBridgeHost(hostname: string): boolean {\n const host = hostname.trim().toLowerCase().replace(/^\\[/, '').replace(/\\]$/, '')\n if (host === 'localhost' || host === '::1' || host === '0:0:0:0:0:0:0:1') return true\n if (host === '::ffff:127.0.0.1') return true\n return /^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/u.test(host)\n}\n\nfunction isLoopbackBridgeUrl(value: string): boolean {\n try {\n const target = new URL(value)\n return (\n (target.protocol === 'http:' || target.protocol === 'https:') &&\n isLoopbackBridgeHost(target.hostname)\n )\n } catch {\n return false\n }\n}\n\n/** Validate and capture the non-serialisable credential service without reading its value. */\nfunction captureBridgeModelCredential(\n value: BridgeModelCredential,\n context: string,\n): BridgeModelCredential {\n if (value === null || typeof value !== 'object') {\n throw new ValidationError(`${context}: modelCredential must be an object`)\n }\n assertExactConfigKeys(\n value as unknown as Readonly<Record<string, unknown>>,\n new Set(['baseUrlKey', 'key', 'provider']),\n `${context} modelCredential`,\n )\n if (typeof value.key !== 'string' || value.key.trim().length === 0) {\n throw new ValidationError(`${context}: modelCredential.key must be a non-empty string`)\n }\n if (typeof value.baseUrlKey !== 'string' || value.baseUrlKey.trim().length === 0) {\n throw new ValidationError(`${context}: modelCredential.baseUrlKey must be a non-empty string`)\n }\n if (value.baseUrlKey === value.key) {\n throw new ValidationError(`${context}: modelCredential.baseUrlKey must differ from key`)\n }\n if (!value.provider || typeof value.provider.get !== 'function') {\n throw new ValidationError(`${context}: modelCredential.provider must implement get(name)`)\n }\n\n // Keep the service live while making JSON/config snapshots contain only the key NAME. The\n // provider may close over a secret, so it must not be an enumerable property of the snapshot.\n const captured = { key: value.key, baseUrlKey: value.baseUrlKey } as BridgeModelCredential\n Object.defineProperty(captured, 'provider', {\n configurable: false,\n enumerable: false,\n value: value.provider,\n writable: false,\n })\n return Object.freeze(captured)\n}\n\nfunction validateBridgeModelCredential(\n value: BridgeModelCredential | undefined,\n bridgeUrl: string,\n context: string,\n): BridgeModelCredential | undefined {\n if (value === undefined) return undefined\n if (!isLoopbackBridgeUrl(bridgeUrl)) {\n throw new ValidationError(\n `${context}: modelCredential is allowed only for a loopback bridge URL`,\n )\n }\n return captureBridgeModelCredential(value, context)\n}\n\ninterface ResolvedBridgeModelCredential {\n token: string\n baseUrl: string\n}\n\nfunction resolveProtectedModelBaseUrl(value: string, context: string): string {\n let target: URL\n try {\n target = new URL(value)\n } catch {\n throw new ValidationError(`${context}: modelCredential.baseUrl must be an absolute HTTPS URL`)\n }\n if (\n target.protocol !== 'https:' ||\n target.username ||\n target.password ||\n target.search ||\n target.hash\n ) {\n throw new ValidationError(\n `${context}: modelCredential.baseUrl must be an HTTPS URL without credentials, query, or fragment`,\n )\n }\n return target.toString().replace(/\\/$/u, '')\n}\n\n/** Resolve only at the outbound boundary. Provider errors are redacted because they may contain\n * the protected value; diagnostics identify key names, never values or provider errors. */\nasync function resolveBridgeModelCredential(\n credential: BridgeModelCredential | undefined,\n context: string,\n): Promise<ResolvedBridgeModelCredential | undefined> {\n if (credential === undefined) return undefined\n const resolveValue = async (key: string): Promise<string> => {\n let value: string | undefined\n try {\n value = await credential.provider.get(key)\n } catch {\n throw new ValidationError(`${context}: modelCredential provider failed for '${key}'`)\n }\n if (typeof value !== 'string' || value.length === 0 || /[\\r\\n\\0]/u.test(value)) {\n throw new ValidationError(\n `${context}: modelCredential provider has no usable value for '${key}'`,\n )\n }\n return value\n }\n const [token, baseUrl] = await Promise.all([\n resolveValue(credential.key),\n resolveValue(credential.baseUrlKey),\n ])\n return { token, baseUrl: resolveProtectedModelBaseUrl(baseUrl, context) }\n}\n\n// ── Content-addressed result pointers (the B1 replay source) ───────────────────\n\n/** Deterministic content hash for an `outRef`. FNV-1a 32-bit over the canonical\n * JSON of the result — not cryptographic, sufficient for content-addressing the\n * replay blob so two identical outputs collapse to one pointer. */\nfunction contentRef(prefix: string, value: unknown): string {\n let str: string\n try {\n str = JSON.stringify(value) ?? String(value)\n } catch {\n str = String(value)\n }\n let h = 0x811c9dc5\n for (let i = 0; i < str.length; i += 1) {\n h ^= str.charCodeAt(i)\n h = Math.imul(h, 0x01000193)\n }\n return `${prefix}:${(h >>> 0).toString(16).padStart(8, '0')}`\n}\n\n/**\n * The spend of work that HAPPENED and reported no usage receipt.\n *\n * Not the same value as a plain zero even though both carry `{0,0}` tokens and `$0`. A bare zero\n * asserts a MEASUREMENT — \"this ran and cost nothing\" — and every consumer downstream reads it that\n * way: the pool keeps reporting `readout().tokensKnown === true`, the journal totals stay clean, the\n * OTEL span records a priced zero, and a caller's token-denominated ceiling can never fire no matter\n * how much the work really burned. A ceiling that cannot fire is worse than no ceiling, because it\n * reads as protection.\n *\n * `Spend.tokensKnown` is the marker the substrate already threads end to end for exactly this case\n * (`budget.ts`, `otel-spans.ts`, `spawn-journal.ts`, `supervisor.ts`): the work is recorded, the\n * zero is labelled a floor rather than a total, and every rollup that touches it reports its balance\n * as a ceiling rather than a measurement. Use this — never a bare zero — whenever a runtime cannot\n * see what its worker spent.\n *\n * The same rule applies to dollars. A dollar-capped run must refuse an executor whose billed spend\n * is unknowable; `budgetExempt` does not authorize Runtime to relabel unknown spend as a measured\n * zero. Callers that require dollar accounting must use a backend with a trusted billing receipt.\n */\nfunction unmeteredSpend(ms: number): Spend {\n return {\n iterations: 0,\n tokens: zeroTokenUsage(),\n tokensKnown: false,\n usd: 0,\n usdKnown: false,\n ms,\n }\n}\n\n// ── router/inline executor (harness === null) ──────────────────────────────────\n\n/**\n * A direct OpenAI-compatible Router chat-completion. One-shot: resolves a\n * `ExecutorResult` and reports its terminal usage as `UsageEvent`s through the\n * conserved pool. Reports REAL token usage — when the provider omits `usage`,\n * the spend records zero tokens but the call still counts one iteration (a\n * phantom fabricated 0 is never emitted as a priced cost).\n *\n * Transport = `routerChatWithUsage` (`../router-client`): transient router\n * failures (429/5xx/Cloudflare-origin) retry with backoff before the executor\n * fails the task.\n */\nexport const routerInlineExecutor: ExecutorFactory<unknown> = (spec, ctx) => {\n const seam = readSeam<RouterSeam>(ctx, routerSeamKey, 'router/inline')\n const model = exactRouterModel(spec.profile, 'routerInlineExecutor')\n if (!seam.routerBaseUrl || !seam.routerKey) {\n throw new ValidationError('routerInlineExecutor: RouterSeam.routerBaseUrl + routerKey required')\n }\n const profileExecution = routerProfileExecution(spec.profile, seam, { multiTurn: false })\n const requestIdentity = routerRequestIdentity(ctx)\n\n const controller = new AbortController()\n const abortIfSignalled = () => {\n if (ctx.signal.aborted) controller.abort()\n }\n abortIfSignalled()\n if (!ctx.signal.aborted) ctx.signal.addEventListener('abort', abortIfSignalled, { once: true })\n\n let artifact: ExecutorResult<unknown> | undefined\n const executionId = ctx.node?.nodeId ?? `router-request-${randomUUID()}`\n const attemptId = ctx.node?.attemptId ?? newExecutionAttemptId(executionId)\n\n let executor!: Executor<unknown>\n executor = attestRuntimeOwnedExecutor(\n {\n runtime: 'router' as Runtime,\n async execute(task, signal): Promise<ExecutorResult<unknown>> {\n const messages = taskToMessages(task, spec, profileExecution.systemPrompt)\n const started = Date.now()\n const linked = linkSignals(signal, controller.signal)\n const extraBody = {\n ...(profileExecution.extraBody ?? {}),\n ...(profileExecution.reasoningEffort\n ? { reasoning_effort: profileExecution.reasoningEffort }\n : {}),\n }\n recordRuntimeOwnedProviderAttemptStart(executor)\n const r = await runRouterTransport<RouterChatResult | RouterChatToolsResult>(\n 'routerInlineExecutor',\n () =>\n seam.tools\n ? (profileExecution.stream === true\n ? streamRouterChatWithTools\n : routerChatWithTools)(\n {\n routerBaseUrl: seam.routerBaseUrl,\n routerKey: seam.routerKey,\n model,\n ...(profileExecution.retry !== undefined\n ? { retry: profileExecution.retry }\n : {}),\n ...(seam.complete ? { complete: seam.complete } : {}),\n },\n messages,\n seam.tools,\n {\n ...(profileExecution.temperature !== undefined\n ? { temperature: profileExecution.temperature }\n : {}),\n ...(linked ? { signal: linked } : {}),\n ...(profileExecution.toolChoice\n ? { toolChoice: profileExecution.toolChoice }\n : {}),\n ...(profileExecution.maxTokens !== undefined\n ? { maxTokens: profileExecution.maxTokens }\n : {}),\n ...(profileExecution.seed !== undefined ? { seed: profileExecution.seed } : {}),\n ...(Object.keys(extraBody).length > 0 ? { extraBody } : {}),\n ...requestIdentity,\n },\n )\n : routerChatWithUsage(\n {\n routerBaseUrl: seam.routerBaseUrl,\n routerKey: seam.routerKey,\n model,\n ...(profileExecution.retry !== undefined\n ? { retry: profileExecution.retry }\n : {}),\n ...(seam.complete ? { complete: seam.complete } : {}),\n },\n messages,\n {\n ...(profileExecution.temperature !== undefined\n ? { temperature: profileExecution.temperature }\n : {}),\n ...(linked ? { signal: linked } : {}),\n ...(profileExecution.maxTokens !== undefined\n ? { maxTokens: profileExecution.maxTokens }\n : {}),\n ...(profileExecution.seed !== undefined ? { seed: profileExecution.seed } : {}),\n ...(profileExecution.reasoningEffort\n ? { reasoningEffort: profileExecution.reasoningEffort }\n : {}),\n ...(profileExecution.extraBody\n ? { extraBody: profileExecution.extraBody }\n : {}),\n ...requestIdentity,\n },\n ),\n )\n if (r.model !== undefined) recordRuntimeOwnedProviderModel(executor, r.model)\n const spent: Spend = {\n iterations: 1,\n tokens: r.usage\n ? cloneTokenUsage({\n input: r.usage.input,\n output: r.usage.output,\n ...routerPromptCacheUsage(r.usage.input, r.cache),\n })\n : zeroTokenUsage(),\n usd: r.billedCostUsd ?? 0,\n ...(r.usage ? {} : { tokensKnown: false }),\n ...(r.billedCostUsd === undefined ? { usdKnown: false } : {}),\n ms: Date.now() - started,\n }\n assertObservedRouterModel(r.model, model, 'routerInlineExecutor')\n const out = {\n content: r.content ?? '',\n ...(r.model !== undefined ? { model: r.model } : {}),\n transportAttempts: r.transportAttempts,\n ...(r.costUsd !== undefined ? { estimatedCostUsd: r.costUsd } : {}),\n ...(r.cache ? { promptCache: r.cache } : {}),\n ...(r.usage?.reasoning !== undefined ? { reasoningTokens: r.usage.reasoning } : {}),\n ...('toolCalls' in r ? { toolCalls: r.toolCalls } : {}),\n ...(r.reasoning ? { reasoning: r.reasoning } : {}),\n ...(r.finishReason\n ? { finishReason: r.finishReason }\n : 'toolCalls' in r && r.toolCalls.length > 0\n ? { finishReason: 'tool_calls' }\n : {}),\n } as unknown\n artifact = { outRef: contentRef('router', { model, out }), out, spent }\n return artifact\n },\n teardown(_grace): Promise<{ destroyed: boolean }> {\n controller.abort('executor torn down')\n return Promise.resolve({ destroyed: true })\n },\n resultArtifact() {\n if (!artifact) {\n throw new ValidationError('routerInlineExecutor: resultArtifact() read before execute()')\n }\n return { ...artifact, spent: artifact.spent }\n },\n },\n {\n effectiveProfile: spec.profile,\n backend: 'router',\n model: { status: 'known', id: model },\n execution: {\n kind: 'request',\n id: executionId,\n },\n materializer: 'router-prompt-model',\n plan: {\n kind: 'openai-chat-completion',\n model,\n provider: spec.profile.model?.provider ?? null,\n temperature: profileExecution.temperature ?? null,\n maxTokens: profileExecution.maxTokens ?? null,\n retry: profileExecution.retry ?? null,\n seed: profileExecution.seed ?? null,\n reasoningEffort: profileExecution.reasoningEffort ?? null,\n extraBody: profileExecution.extraBody ?? null,\n tools: seam.tools ?? null,\n toolChoice: profileExecution.toolChoice ?? null,\n systemPrompt: profileExecution.systemPrompt || null,\n },\n },\n {\n attemptId,\n binding: {\n endpoint: seam.routerBaseUrl,\n executionId,\n model,\n },\n descriptor: { kind: 'router-request', transport: 'http', backend: 'router' },\n },\n )\n return executor\n}\n\nexport type { ToolSpec }\n\n/**\n * Router seam WITH tool use — the tool-using router backend. Same direct\n * OpenAI-compatible endpoint as `RouterSeam`, but each turn passes `tools`; when\n * the model emits tool_calls they run via `executeToolCall` ON THIS HOST and the\n * results fold back as `tool` messages, repeating until the model answers without\n * a tool or `maxTurns` is hit. A real agentic loop, OFF-BOX — no sandbox, so it\n * is unaffected by a box's egress allowlist. One turn = one completion = the\n * equal-compute unit. `executeToolCall` receives the task so per-task tool\n * surfaces (e.g. a gym keyed by task) can dispatch correctly.\n */\nexport interface RouterToolsSeam {\n routerBaseUrl: string\n routerKey: string\n complete?: RouterConfig['complete']\n tools: ReadonlyArray<ToolSpec>\n executeToolCall: (name: string, args: Record<string, unknown>, task: unknown) => Promise<string>\n /** Exact conversation to continue. Runtime validates its system message against the profile. */\n initialMessages?: ReadonlyArray<Readonly<Record<string, unknown>>>\n /** Observe the detached final conversation for session persistence. */\n onMessages?: (messages: ReadonlyArray<Readonly<Record<string, unknown>>>) => void | Promise<void>\n /** Online observer of each tool step — the seam a `DetectorMonitor` taps to watch the live pipe\n * (raise a `finding` when the worker loops/errors). Called after every tool call resolves, with\n * real per-call wall-clock (`startedAt`/`endedAt`/`durationMs`) so a push `TraceSource` can carry\n * non-zero span durations onto the unified timeline. */\n onToolStep?: (step: {\n toolName: string\n args: Record<string, unknown>\n status: 'ok' | 'error'\n // Real per-call wall-clock — the owned-loop executor always supplies these. Optional so an\n // external `RouterToolsSeam` that omits timing still satisfies the type (the span then collapses\n // to order + counts, per `toToolSpan`), keeping this an additive, non-breaking field set.\n startedAt?: number\n endedAt?: number\n durationMs?: number\n }) => void\n}\nconst routerToolsSeamKey = 'router-tools'\n\nfunction mergePromptCache(\n target: Record<string, number | string>,\n cache: PromptCacheUsage | undefined,\n): void {\n if (!cache) return\n for (const key of ['readTokens', 'writeTokens', 'missTokens', 'readSavingsUsd'] as const) {\n const value = cache[key]\n if (value !== undefined) target[key] = (Number(target[key]) || 0) + value\n }\n if (cache.status !== undefined) target.status = cache.status\n}\n\n/** Preserve a complete Router cache split; an incomplete provider receipt stays unknown. */\nfunction routerPromptCacheUsage(\n input: number | undefined,\n cache: PromptCacheUsage | undefined,\n): {\n freshInput?: number\n cacheRead?: number\n cacheWrite?: number\n cacheBreakdownKnown?: false\n} {\n if (cache === undefined) return {}\n const read = cache.readTokens\n const write = cache.writeTokens\n if (read === undefined && write === undefined) return {}\n if (\n input === undefined ||\n !isCacheTokenCount(read) ||\n !isCacheTokenCount(write) ||\n read + write > input\n ) {\n return { cacheBreakdownKnown: false }\n }\n return {\n freshInput: input - read - write,\n cacheRead: read,\n cacheWrite: write,\n }\n}\n\nfunction isCacheTokenCount(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0\n}\n\nasync function runRouterTransport<T>(context: string, call: () => Promise<T>): Promise<T> {\n try {\n return await call()\n } catch (error) {\n throwRouterTransportFailure(context, error)\n }\n}\n\nfunction throwRouterTransportFailure(context: string, error: unknown): never {\n if (\n error instanceof ValidationError ||\n (error && typeof error === 'object' && 'name' in error && error.name === 'AbortError')\n ) {\n throw error\n }\n const message = error instanceof Error ? error.message : String(error)\n throw new ValidationError(`${context}: transport failed: ${message}`)\n}\n\n/**\n * The tool-using router executor. Drives the multi-turn tool loop the single-shot\n * `routerInlineExecutor` cannot express; same fail-loud + real-usage discipline.\n */\nexport const routerToolsInlineExecutor: ExecutorFactory<unknown> = (spec, ctx) => {\n const seam = readSeam<RouterToolsSeam>(ctx, routerToolsSeamKey, 'router-tools')\n const model = exactRouterModel(spec.profile, 'routerToolsInlineExecutor')\n if (!seam.routerBaseUrl || !seam.routerKey) {\n throw new ValidationError(\n 'routerToolsInlineExecutor: RouterToolsSeam.routerBaseUrl + routerKey required',\n )\n }\n const profileExecution = routerProfileExecution(\n spec.profile,\n {\n routerBaseUrl: seam.routerBaseUrl,\n routerKey: seam.routerKey,\n tools: seam.tools,\n },\n { multiTurn: true },\n )\n const enabledToolNames = new Set(seam.tools.map((tool) => tool.function.name))\n const maxTurns = profileExecution.maxTurns ?? 0\n const requestIdentity = routerRequestIdentity(ctx)\n\n const controller = new AbortController()\n const abortIfSignalled = () => {\n if (ctx.signal.aborted) controller.abort()\n }\n abortIfSignalled()\n if (!ctx.signal.aborted) ctx.signal.addEventListener('abort', abortIfSignalled, { once: true })\n\n // The down-leg receive end: the driver's steer/answer/resume land here via `Scope.send`.\n const inbox = createInbox()\n\n let artifact: ExecutorResult<unknown> | undefined\n const executionId = ctx.node?.nodeId ?? `router-tools-run-${randomUUID()}`\n const attemptId = ctx.node?.attemptId ?? newExecutionAttemptId(executionId)\n\n let executor!: Executor<unknown>\n executor = attestRuntimeOwnedExecutor(\n {\n runtime: 'router' as Runtime,\n deliver: (m) => inbox.deliver(m),\n async execute(task, signal): Promise<ExecutorResult<unknown>> {\n const started = Date.now()\n const messages: Array<Record<string, unknown>> = seam.initialMessages\n ? taskToMessages(\n {\n messages: [...seam.initialMessages, { role: 'user', content: taskToPrompt(task) }],\n },\n spec,\n profileExecution.systemPrompt,\n )\n : taskToMessages(task, spec, profileExecution.systemPrompt)\n const tokens = zeroTokenUsage()\n let tokensKnown = true\n let billedUsd = 0\n let usdKnown = true\n let turns = 0\n let transportAttempts = 0\n let observedModel: string | undefined\n let reasoningTokens = 0\n let reasoningKnown = true\n const promptCache: Record<string, number | string> = {}\n let lastText = ''\n // Fold any queued down-messages into the conversation as one operator turn (the boundary flush).\n const flush = () => {\n const pending = inbox.drain()\n if (pending.length) messages.push({ role: 'user', content: inbox.fold(pending) })\n return pending.length > 0\n }\n\n // The external abort sources (caller signal + executor teardown), merged ONCE — so we don't\n // re-register listeners on these long-lived signals every turn.\n const external = mergeAbortSignals(signal, controller.signal)\n\n try {\n for (let t = 0; maxTurns === 0 || t < maxTurns; t += 1) {\n // QUEUED messages flush at the step boundary, before this turn's inference.\n flush()\n // A forceful (interrupt) message aborts THIS turn so the worker re-plans immediately. The\n // per-turn controller fires on `external` OR a fresh interrupt; its listener on `external` is\n // removed after the turn (`cleanup`) so nothing accumulates across turns.\n const interruptSig = inbox.freshInterrupt()\n const turnController = new AbortController()\n const abortTurn = () => turnController.abort()\n if (external.aborted) turnController.abort()\n else external.addEventListener('abort', abortTurn)\n interruptSig.addEventListener('abort', abortTurn, { once: true })\n const cleanup = () => external.removeEventListener('abort', abortTurn)\n let res: Awaited<ReturnType<typeof routerChatWithTools>>\n try {\n recordRuntimeOwnedProviderAttemptStart(executor)\n res = await (profileExecution.stream === true\n ? streamRouterChatWithTools\n : routerChatWithTools)(\n {\n routerBaseUrl: seam.routerBaseUrl,\n routerKey: seam.routerKey,\n model,\n ...(profileExecution.retry !== undefined\n ? { retry: profileExecution.retry }\n : {}),\n ...(seam.complete ? { complete: seam.complete } : {}),\n },\n messages,\n seam.tools,\n {\n ...(profileExecution.temperature !== undefined\n ? { temperature: profileExecution.temperature }\n : {}),\n signal: turnController.signal,\n ...(profileExecution.toolChoice\n ? { toolChoice: profileExecution.toolChoice }\n : {}),\n ...(profileExecution.maxTokens !== undefined\n ? { maxTokens: profileExecution.maxTokens }\n : {}),\n ...(profileExecution.seed !== undefined ? { seed: profileExecution.seed } : {}),\n ...(profileExecution.reasoningEffort\n ? { reasoningEffort: profileExecution.reasoningEffort }\n : {}),\n ...(profileExecution.extraBody ? { extraBody: profileExecution.extraBody } : {}),\n ...routerTurnRequestIdentity(requestIdentity, t),\n },\n )\n } catch (e) {\n cleanup()\n // Re-plan ONLY when a forceful inbox message aborted this turn (a real AbortError, with the\n // interrupt — not the external teardown/budget signal). The request reached the transport,\n // so count its iteration and exact physical attempts. Without a terminal receipt its token,\n // reasoning, and dollar totals are unknown; treating it as free can overspend the pool.\n // Any other error — incl. a network fault coincident with an interrupt — is fatal: rethrow.\n const interruptAbort =\n e instanceof DOMException &&\n e.name === 'AbortError' &&\n interruptSig.aborted &&\n !signal.aborted &&\n !controller.signal.aborted\n if (interruptAbort) {\n turns += 1\n transportAttempts += routerTransportAttemptsFromError(e) ?? 1\n tokensKnown = false\n usdKnown = false\n reasoningKnown = false\n continue\n }\n throwRouterTransportFailure('routerToolsInlineExecutor', e)\n }\n cleanup()\n // The inference completed — count the turn and merge its terminal receipt.\n turns += 1\n transportAttempts += res.transportAttempts\n if (res.model !== undefined) recordRuntimeOwnedProviderModel(executor, res.model)\n assertObservedRouterModel(res.model, model, 'routerToolsInlineExecutor')\n if (res.model !== undefined) observedModel = res.model\n mergePromptCache(promptCache, res.cache)\n if (res.usage) {\n addTokenUsage(tokens, {\n input: res.usage.input,\n output: res.usage.output,\n ...routerPromptCacheUsage(res.usage.input, res.cache),\n })\n if (res.usage.reasoning !== undefined) reasoningTokens += res.usage.reasoning\n else reasoningKnown = false\n } else {\n addTokenUsage(tokens, routerPromptCacheUsage(undefined, res.cache))\n tokensKnown = false\n reasoningKnown = false\n }\n if (res.billedCostUsd !== undefined) billedUsd += res.billedCostUsd\n else usdKnown = false\n if (res.content) lastText = res.content\n const toolCalls = res.toolCalls\n if (toolCalls.length === 0) {\n // Before settling, flush once more — a worker may not finish while a steer/answer it never\n // read is still pending. If anything flushed, keep going; otherwise it is truly done.\n if (flush()) continue\n messages.push({ role: 'assistant', content: res.content ?? '' })\n break\n }\n\n // Record the assistant turn verbatim, then run each call on the host and\n // fold the result back as a `tool` message for the next turn.\n messages.push({\n role: 'assistant',\n content: res.content ?? '',\n tool_calls: toolCalls.map((tc) => ({\n id: tc.id,\n type: 'function',\n function: {\n name: tc.name,\n arguments: tc.arguments,\n },\n })),\n })\n for (let i = 0; i < toolCalls.length; i += 1) {\n const tc = toolCalls[i]\n const id = tc?.id ?? `call_${i}`\n const toolName = tc?.name ?? ''\n if (!enabledToolNames.has(toolName)) {\n messages.push({\n role: 'tool',\n tool_call_id: id,\n content: `error: tool ${JSON.stringify(toolName)} is not enabled by AgentProfile.tools`,\n })\n try {\n seam.onToolStep?.({ toolName, args: {}, status: 'error' })\n } catch {\n // Monitoring cannot authorize or execute a refused tool call.\n }\n continue\n }\n let args: Record<string, unknown> = {}\n try {\n args = JSON.parse(tc?.arguments ?? '{}') as Record<string, unknown>\n } catch {\n // Malformed args are a real outcome, not an infra fault — feed the error\n // back so the model can correct, rather than aborting the whole loop.\n messages.push({\n role: 'tool',\n tool_call_id: id,\n content: 'error: tool arguments were not valid JSON',\n })\n continue\n }\n let result: string\n let status: 'ok' | 'error' = 'ok'\n const toolStartedAt = Date.now()\n try {\n result = await seam.executeToolCall(toolName, args, task)\n } catch (e) {\n status = 'error'\n result = `error: ${e instanceof Error ? e.message : String(e)}`\n }\n const toolEndedAt = Date.now()\n messages.push({ role: 'tool', tool_call_id: id, content: result })\n // Feed the online detector pipe (stuck-loop / error-streak) — a worker repeating the same\n // call or hammering errors is caught mid-run, not only at settle. This is an observability\n // side-channel: a throwing monitor must never crash the production inference loop.\n try {\n seam.onToolStep?.({\n toolName,\n args,\n status,\n startedAt: toolStartedAt,\n endedAt: toolEndedAt,\n durationMs: toolEndedAt - toolStartedAt,\n })\n } catch {\n // ignore — monitoring must not break the worker\n }\n }\n }\n } finally {\n await seam.onMessages?.(\n structuredClone(messages) as ReadonlyArray<Readonly<Record<string, unknown>>>,\n )\n }\n\n const priced = isModelPriced(model)\n const estimatedUsd = priced ? estimateCost(tokens.input, tokens.output, model) : undefined\n const spent: Spend = {\n iterations: turns,\n tokens,\n ...(tokensKnown ? {} : { tokensKnown: false }),\n usd: billedUsd,\n ...(usdKnown ? {} : { usdKnown: false }),\n ms: Date.now() - started,\n }\n const out = {\n content: lastText,\n ...(observedModel !== undefined ? { model: observedModel } : {}),\n messages,\n turns,\n toolCalls: messages.filter((message) => message.role === 'tool').length,\n transportAttempts,\n ...(estimatedUsd !== undefined ? { estimatedCostUsd: estimatedUsd } : {}),\n ...(Object.keys(promptCache).length > 0 ? { promptCache } : {}),\n ...(reasoningKnown && turns > 0 ? { reasoningTokens } : {}),\n } as unknown\n artifact = { outRef: contentRef('router-tools', { model, content: lastText }), out, spent }\n return artifact\n },\n teardown(_grace): Promise<{ destroyed: boolean }> {\n controller.abort('executor torn down')\n return Promise.resolve({ destroyed: true })\n },\n resultArtifact() {\n if (!artifact) {\n throw new ValidationError(\n 'routerToolsInlineExecutor: resultArtifact() read before execute()',\n )\n }\n return { ...artifact, spent: artifact.spent }\n },\n },\n {\n effectiveProfile: spec.profile,\n backend: 'router-tools',\n model: { status: 'known', id: model },\n execution: {\n kind: 'run',\n id: executionId,\n },\n materializer: 'router-tools-prompt-model',\n plan: {\n kind: 'openai-tool-loop',\n model,\n provider: spec.profile.model?.provider ?? null,\n maxTurns,\n tools: seam.tools,\n temperature: profileExecution.temperature ?? null,\n maxTokens: profileExecution.maxTokens ?? null,\n retry: profileExecution.retry ?? null,\n toolChoice: profileExecution.toolChoice ?? null,\n extraBody: profileExecution.extraBody ?? null,\n reasoningEffort: profileExecution.reasoningEffort ?? null,\n systemPrompt: profileExecution.systemPrompt || null,\n },\n },\n {\n attemptId,\n binding: {\n endpoint: seam.routerBaseUrl,\n executionId,\n model,\n },\n descriptor: { kind: 'router-tool-loop', transport: 'http', backend: 'router-tools' },\n },\n )\n return executor\n}\n\nfunction assertObservedRouterModel(\n observed: string | undefined,\n expected: string,\n context: string,\n): void {\n if (observed !== undefined && !observedModelMatchesDeclared(observed, expected)) {\n throw new ValidationError(\n `${context}: provider reported model ${JSON.stringify(observed)} but AgentProfile requires ${JSON.stringify(expected)}`,\n )\n }\n}\n\nfunction routerRequestIdentity(ctx: ExecutorContext): {\n readonly callId?: string\n readonly correlationId?: string\n readonly propagatedHeaders?: Readonly<Record<string, string>>\n} {\n const correlation = ctx.node?.identity?.correlation\n return {\n ...(correlation?.callId ? { callId: correlation.callId } : {}),\n ...(correlation?.correlationId ? { correlationId: correlation.correlationId } : {}),\n ...(ctx.propagatedHeaders ? { propagatedHeaders: ctx.propagatedHeaders } : {}),\n }\n}\n\nfunction routerTurnRequestIdentity(\n identity: {\n readonly callId?: string\n readonly correlationId?: string\n readonly propagatedHeaders?: Readonly<Record<string, string>>\n },\n turnIndex: number,\n): {\n readonly callId?: string\n readonly correlationId?: string\n readonly propagatedHeaders?: Readonly<Record<string, string>>\n} {\n return {\n ...(identity.callId ? { callId: `${identity.callId}:turn:${turnIndex + 1}` } : {}),\n ...(identity.correlationId ? { correlationId: identity.correlationId } : {}),\n ...(identity.propagatedHeaders ? { propagatedHeaders: identity.propagatedHeaders } : {}),\n }\n}\n\n// ── sandbox executor (harness is a BackendType) ────────────────────────────────\n\n/**\n * COMPOSES `runAgentRounds` as a single-task leaf: one box, a refine driver bounded to\n * the seam's `maxIterations` (default 1), the spec's profile as the agent run.\n * Surfaces the loop's aggregated `tokenUsage` + `costUsd` as `UsageEvent`s after\n * it drains, and yields one `iteration` event per loop iteration. Forwards the\n * optional `lineage` passthrough WITHOUT importing sandbox-lineage / reinventing\n * checkpoint/fork.\n *\n * Streaming shape: the loop runs to completion inside the first `next()`, then\n * the recorded usage events are yielded; the terminal artifact is read from\n * `resultArtifact()` after the stream drains.\n */\nexport const sandboxExecutor: ExecutorFactory<unknown> = (spec, ctx) => {\n if (spec.harness === null) {\n throw new ValidationError('sandboxExecutor: harness is null (router/inline) — wrong executor')\n }\n const harness = spec.harness as BackendType\n const seam = readSeam<SandboxSeam>(ctx, sandboxSeamKey, 'sandbox')\n if (!seam.sandboxClient || typeof seam.sandboxClient.create !== 'function') {\n throw new ValidationError('sandboxExecutor: SandboxSeam.sandboxClient.create required')\n }\n const maxIterations = seam.maxIterations ?? 1\n if (!Number.isFinite(maxIterations) || maxIterations <= 0) {\n throw new ValidationError('sandboxExecutor: maxIterations must be > 0')\n }\n // The cross-MACHINE case this exists for: the box gets `TRACE_ID` / `PARENT_SPAN_ID` through\n // `CreateSandboxOptions.env`, so whatever the remote worker emits lands in this run's trace under\n // the spawning node's span. Empty when the run records no spans, and an empty record adds no\n // `env` key to the create options at all.\n const traceEnv = workerTraceEnv(ctx)\n\n const controller = new AbortController()\n const abortIfSignalled = () => {\n if (ctx.signal.aborted) controller.abort()\n }\n abortIfSignalled()\n if (!ctx.signal.aborted) ctx.signal.addEventListener('abort', abortIfSignalled, { once: true })\n\n let artifact: ExecutorResult<unknown> | undefined\n const executionId = ctx.node?.nodeId ?? `sandbox-run-${randomUUID()}`\n const attemptId = ctx.node?.attemptId ?? newExecutionAttemptId(executionId)\n const profileModel = concreteProfileModel(spec.profile)\n const sandboxMaterialization = {\n effectiveProfile: spec.profile,\n backend: harness,\n model: profileModel\n ? ({ status: 'known', id: profileModel } as const)\n : ({ status: 'unknown', reason: 'sandbox harness selected its default model' } as const),\n execution: {\n kind: 'run',\n id: executionId,\n },\n materializer: 'sandbox-agent-profile',\n plan: {\n kind: 'sandbox-agent-rounds',\n harness,\n maxIterations,\n steering: seam.steering !== undefined,\n },\n }\n const sandboxBinding = {\n attemptId,\n binding: {\n executionId,\n harness,\n model: profileModel ?? null,\n },\n descriptor: { kind: 'sandbox-run', transport: 'sandbox', backend: harness },\n }\n\n // STEERABLE mode (opt-in): the worker becomes a multi-turn session on one box, with a real\n // inbox, so a driver's steer has a turn boundary to be folded into. This is the path that\n // makes `Scope.send` return `true` for the DEFAULT cloud worker.\n if (seam.steering) {\n const inbox = createInbox()\n const session = createSteerableSandboxSession({\n controller,\n profile: spec.profile,\n harness,\n sandboxClient: seam.sandboxClient,\n inbox,\n taskToPrompt: (t) => taskToPrompt(t),\n options: seam.steering,\n ...(seam.loopCtx ? { loopCtx: seam.loopCtx } : {}),\n ...(Object.keys(traceEnv).length > 0 ? { traceEnv } : {}),\n contentRef,\n })\n return attestRuntimeOwnedExecutor(\n {\n runtime: 'sandbox' as Runtime,\n deliver: (m) => inbox.deliver(m),\n progress: (): ExecutorProgress => session.progress(),\n traceSource: (): TraceSource => session.traceSource(),\n execute(task, signal): AsyncIterable<UsageEvent> {\n return session.stream(task, signal)\n },\n async teardown(_grace): Promise<{ destroyed: boolean }> {\n controller.abort()\n await session.teardown()\n return { destroyed: true }\n },\n resultArtifact() {\n const a = session.artifact()\n if (!a) {\n throw new ValidationError(\n 'sandboxExecutor(steering): resultArtifact() read before stream drained',\n )\n }\n return a\n },\n },\n sandboxMaterialization,\n sandboxBinding,\n )\n }\n\n // The leaf runs an opaque, self-parallelizing coding harness; the loop just\n // refines once over it. Output is the raw event stream parsed to its tail text.\n const output: OutputAdapter<SandboxLeafOut> = {\n parse(events: SandboxEvent[]): SandboxLeafOut {\n return { events }\n },\n }\n const driver = singleShotDriver<SandboxLeafOut>(maxIterations)\n\n return attestRuntimeOwnedExecutor(\n {\n runtime: 'sandbox' as Runtime,\n execute(task, signal): AsyncIterable<UsageEvent> {\n return streamSandboxLeaf({\n task,\n signal,\n harness,\n spec,\n seam,\n output,\n driver,\n maxIterations,\n controller,\n loopCtx: seam.loopCtx,\n traceEnv,\n onArtifact: (a) => {\n artifact = a\n },\n })\n },\n teardown(_grace): Promise<{ destroyed: boolean }> {\n // The composed runAgentRounds owns its box teardown (finally{allSettled(destroy)});\n // aborting the loop's signal cascades into that barrier.\n controller.abort()\n return Promise.resolve({ destroyed: true })\n },\n resultArtifact() {\n if (!artifact) {\n throw new ValidationError('sandboxExecutor: resultArtifact() read before stream drained')\n }\n return artifact\n },\n },\n sandboxMaterialization,\n sandboxBinding,\n )\n}\n\ninterface SandboxLeafOut {\n events: SandboxEvent[]\n}\n\ninterface StreamSandboxArgs {\n task: unknown\n signal: AbortSignal\n harness: BackendType\n spec: AgentSpec\n seam: SandboxSeam\n output: OutputAdapter<SandboxLeafOut>\n driver: Driver<unknown, SandboxLeafOut, string>\n maxIterations: number\n controller: AbortController\n loopCtx?: Partial<Omit<ExecCtx, 'sandboxClient' | 'signal'>>\n /** Inherited `TRACE_ID` / `PARENT_SPAN_ID` for the box; empty when tracing is off. */\n traceEnv: Record<string, string>\n onArtifact: (a: ExecutorResult<unknown>) => void\n}\n\nasync function* streamSandboxLeaf(args: StreamSandboxArgs): AsyncIterable<UsageEvent> {\n const linked = new AbortController()\n // Stable listener identities: the finally block removes these by reference.\n const cascadeExternal = (): void => linked.abort(abortReasonOf(args.signal))\n const cascadeScope = (): void => linked.abort(abortReasonOf(args.controller.signal))\n if (args.signal.aborted || args.controller.signal.aborted) {\n linked.abort(abortReasonOf(args.signal.aborted ? args.signal : args.controller.signal))\n } else {\n args.signal.addEventListener('abort', cascadeExternal, { once: true })\n args.controller.signal.addEventListener('abort', cascadeScope, { once: true })\n }\n\n const agentRun: AgentRunSpec<unknown> = {\n profile: args.spec.profile,\n taskToPrompt: (t) => taskToPrompt(t),\n name: args.spec.profile.name ?? args.harness,\n sandboxOverrides: {\n backend: { type: args.harness },\n // Absent entirely when tracing is off, so the create options are byte-identical to before.\n ...(Object.keys(args.traceEnv).length > 0 ? { env: args.traceEnv } : {}),\n },\n }\n const started = Date.now()\n\n // `lineage` is a PR #150 RunAgentRoundsOptions field absent on this branch — forwarded\n // forward-compatibly without coupling to its (not-yet-present) static type.\n const loopOptions = {\n driver: args.driver,\n agentRun,\n output: args.output,\n task: args.task,\n maxIterations: args.maxIterations,\n maxConcurrency: 1,\n ctx: {\n ...(args.loopCtx ?? {}),\n sandboxClient: args.seam.sandboxClient,\n signal: linked.signal,\n } as ExecCtx,\n ...(args.seam.lineage !== undefined ? { lineage: args.seam.lineage } : {}),\n } as RunAgentRoundsOptions<unknown, SandboxLeafOut, string>\n\n try {\n const result = await runAgentRounds(loopOptions)\n // Fail loud on a round that produced nothing: the worker settles `down`\n // carrying the loop's own reason (a rejected profile, a box that would not\n // provision) rather than an artifact it never produced.\n const failure = failedRound(result)\n if (failure) throw failure\n const out = result.winner?.output ?? { events: [] }\n const verdict = result.winner?.verdict ?? leafVerdict(result)\n const tokensKnown = result.tokenUsage.tokensKnown !== false\n const usdKnown = result.costUsdKnown !== false\n const outWithUsage = {\n ...out,\n ...(result.estimatedCostUsd !== undefined\n ? { estimatedCostUsd: result.estimatedCostUsd }\n : {}),\n ...(result.promptCache ? { promptCache: result.promptCache } : {}),\n }\n const spent: Spend = {\n iterations: result.iterations.length,\n tokens: cloneTokenUsage(result.tokenUsage),\n ...(tokensKnown ? {} : { tokensKnown: false }),\n usd: result.costUsd,\n ...(usdKnown ? {} : { usdKnown: false }),\n ms: Date.now() - started,\n }\n args.onArtifact({\n outRef: contentRef('sandbox', { harness: args.harness, out: outWithUsage }),\n out: outWithUsage,\n ...(verdict ? { verdict } : {}),\n spent,\n })\n for (let i = 0; i < result.iterations.length; i += 1) yield { kind: 'iteration' }\n if (result.iterations.length > 0 || result.tokenUsage.input || result.tokenUsage.output) {\n yield {\n kind: 'tokens',\n input: result.tokenUsage.input,\n output: result.tokenUsage.output,\n ...(tokensKnown ? {} : { tokensKnown: false }),\n ...(result.tokenUsage.freshInput !== undefined\n ? { freshInput: result.tokenUsage.freshInput }\n : {}),\n ...(result.tokenUsage.cacheRead !== undefined\n ? { cacheRead: result.tokenUsage.cacheRead }\n : {}),\n ...(result.tokenUsage.cacheWrite !== undefined\n ? { cacheWrite: result.tokenUsage.cacheWrite }\n : {}),\n ...(result.tokenUsage.cacheBreakdownKnown === false\n ? { cacheBreakdownKnown: false as const }\n : {}),\n }\n }\n if (result.iterations.length > 0 || result.costUsd) {\n yield { kind: 'cost', usd: result.costUsd, ...(usdKnown ? {} : { usdKnown: false }) }\n }\n } finally {\n args.signal.removeEventListener('abort', cascadeExternal)\n args.controller.signal.removeEventListener('abort', cascadeScope)\n }\n}\n\n/** The loop's own failure, when NO iteration produced an output: the first error it\n * recorded, renamed so the settled worker names the leaf it died in. `undefined`\n * when any iteration produced an output — a partly-failed round still has material\n * to settle on. */\nfunction failedRound(result: {\n iterations: ReadonlyArray<{ output?: unknown; error?: Error }>\n}): Error | undefined {\n if (result.iterations.length === 0) return undefined\n if (result.iterations.some((iteration) => iteration.output !== undefined)) return undefined\n const first = result.iterations.find((iteration) => iteration.error)?.error\n if (!first) return undefined\n return new Error(`sandboxExecutor: agent round failed — ${first.message}`, { cause: first })\n}\n\n/**\n * The leaf's OWN verdict, for a round the loop scored no validator against.\n *\n * `settled ⟺ delivered` is written by the completion oracle, and a caller that\n * passes one keeps it: `gateOnDeliverable` wraps this executor and overrides\n * `valid` from its check. This is the sandbox backend's structural answer for a\n * run with no oracle at all — without it nothing ever writes `valid`, no settled\n * child is ever DELIVERED, and the finalizer has nothing to select no matter how\n * well the worker ran. Structural, never self-reported: the harness completed a\n * round and returned an output artifact, or it did not.\n */\nfunction leafVerdict(result: { winner?: { output?: unknown } }): DefaultVerdict | undefined {\n if (result.winner?.output === undefined) return undefined\n return { valid: true, score: 1 }\n}\n\n// ── cli executor (Halo / external RLM subprocess) ──────────────────────────────\n\n/**\n * Spawns a subprocess (`bin` + `args`). It cannot account tokens, so it is\n * `budgetExempt: true`: it remains usable as a direct executor, while budgeted supervision\n * refuses it before process execution because the CLI exposes no usage receipt. teardown is SIGTERM → SIGKILL\n * with a grace window. Streaming: yields one `iteration` event on clean exit.\n *\n * Its terminal spend is `unmeteredSpend`, NOT a zero: an unmetered runtime that reports a plain\n * `0` is indistinguishable from one that measured zero, and every ceiling downstream then reads\n * as enforced while enforcing nothing.\n */\nexport const cliExecutor: ExecutorFactory<unknown> = (_spec, ctx) => {\n const seam = readSeam<CliSeam>(ctx, cliSeamKey, 'cli')\n if (!seam.bin) throw new ValidationError('cliExecutor: CliSeam.bin required')\n // `TRACE_ID` / `PARENT_SPAN_ID` for this worker when the run records spans; `{}` otherwise.\n const traceEnv = workerTraceEnv(ctx)\n\n const controller = new AbortController()\n const abortIfSignalled = () => {\n if (ctx.signal.aborted) controller.abort()\n }\n abortIfSignalled()\n if (!ctx.signal.aborted) ctx.signal.addEventListener('abort', abortIfSignalled, { once: true })\n\n let proc: ReturnType<typeof spawn> | undefined\n let artifact: ExecutorResult<unknown> | undefined\n const executionId = ctx.node?.nodeId ?? `cli-process-${randomUUID()}`\n const attemptId = ctx.node?.attemptId ?? newExecutionAttemptId(executionId)\n\n return attestRuntimeOwnedExecutor(\n {\n runtime: 'cli' as Runtime,\n budgetExempt: true,\n execute(task, signal): AsyncIterable<UsageEvent> {\n return streamCliLeaf({\n task,\n signal,\n traceEnv,\n seam,\n controller,\n onProc: (p) => {\n proc = p\n },\n onArtifact: (a) => {\n artifact = a\n },\n })\n },\n async teardown(grace): Promise<{ destroyed: boolean }> {\n controller.abort()\n if (!proc || proc.exitCode !== null || proc.killed) return { destroyed: true }\n return killWithGrace(proc, grace)\n },\n resultArtifact() {\n if (!artifact) {\n throw new ValidationError('cliExecutor: resultArtifact() read before stream drained')\n }\n return artifact\n },\n },\n {\n effectiveProfile: _spec.profile,\n backend: 'cli',\n model: { status: 'unknown', reason: 'raw subprocess has no model identity contract' },\n execution: { kind: 'process-attempt', id: executionId },\n materializer: 'raw-cli-stdin',\n plan: {\n kind: 'raw-cli-process',\n bin: seam.bin,\n args: seam.args ?? [],\n cwd: seam.cwd ?? null,\n envOverrides: seam.env ?? {},\n ambientEnvironment: 'inherited',\n },\n },\n {\n attemptId,\n binding: {\n executionId,\n bin: seam.bin,\n cwd: seam.cwd ?? null,\n },\n descriptor: { kind: 'cli-process', transport: 'process', backend: 'cli' },\n },\n )\n}\n\ninterface StreamCliArgs {\n task: unknown\n signal: AbortSignal\n seam: CliSeam\n /** Inherited `TRACE_ID` / `PARENT_SPAN_ID` for the subprocess; empty when tracing is off. */\n traceEnv: Record<string, string>\n controller: AbortController\n onProc: (p: ReturnType<typeof spawn>) => void\n onArtifact: (a: ExecutorResult<unknown>) => void\n}\n\nasync function* streamCliLeaf(args: StreamCliArgs): AsyncIterable<UsageEvent> {\n const started = Date.now()\n const prompt = taskToPrompt(args.task)\n const proc = spawn(args.seam.bin, args.seam.args ?? [], {\n ...(args.seam.cwd ? { cwd: args.seam.cwd } : {}),\n // Trace context above ambient `process.env` (whose ids describe the SUPERVISOR's place in an\n // outer trace, not this child's) and below `seam.env` (a deliberate operator declaration).\n // `mergeTraceEnv`, not a plain spread: a seam that overrides the legacy pair without its own\n // `TRACEPARENT` gets the W3C wire rebuilt from ITS ids, never left as the recorder's.\n env: mergeTraceEnv(process.env, args.traceEnv, args.seam.env),\n stdio: ['pipe', 'pipe', 'pipe'],\n })\n args.onProc(proc)\n\n const onAbort = () => killWithGrace(proc, 'brutalKill')\n if (args.signal.aborted || args.controller.signal.aborted) onAbort()\n else {\n args.signal.addEventListener('abort', onAbort, { once: true })\n args.controller.signal.addEventListener('abort', onAbort, { once: true })\n }\n\n // Feed the task on stdin; the subprocess owns its own tool/agent loop.\n if (proc.stdin) {\n proc.stdin.write(prompt)\n proc.stdin.end()\n }\n const chunks: string[] = []\n const errChunks: string[] = []\n if (proc.stdout) proc.stdout.on('data', (d: Buffer) => chunks.push(d.toString('utf8')))\n if (proc.stderr) proc.stderr.on('data', (d: Buffer) => errChunks.push(d.toString('utf8')))\n\n const exit = await new Promise<{ code: number | null; error?: Error }>((resolve) => {\n proc.once('error', (err) => resolve({ code: null, error: err }))\n proc.once('close', (code) => resolve({ code }))\n })\n args.signal.removeEventListener('abort', onAbort)\n args.controller.signal.removeEventListener('abort', onAbort)\n\n if (exit.error) {\n throw new ValidationError(`cliExecutor: spawn failed: ${exit.error.message}`, {\n cause: exit.error,\n })\n }\n if (exit.code !== 0) {\n throw new ValidationError(\n `cliExecutor: ${args.seam.bin} exited ${exit.code}: ${errChunks.join('').slice(0, 200)}`,\n )\n }\n const out = { content: chunks.join('') } as unknown\n // A raw subprocess exposes no usage receipt, so its spend is UNKNOWN — not zero. Wall-clock is\n // the one thing this runtime did measure, so that is the one field reported as measured.\n args.onArtifact({\n outRef: contentRef('cli', out),\n out,\n spent: unmeteredSpend(Date.now() - started),\n })\n yield { kind: 'iteration' }\n}\n\n/** SIGTERM, then SIGKILL after `grace` ms (`'brutalKill'` = immediate SIGKILL,\n * `'infinity'` = await clean exit, never escalate). */\nfunction killWithGrace(\n proc: ReturnType<typeof spawn>,\n grace: number | 'brutalKill' | 'infinity',\n): Promise<{ destroyed: boolean }> {\n if (proc.exitCode !== null || proc.killed) return Promise.resolve({ destroyed: true })\n return new Promise((resolve) => {\n let timer: ReturnType<typeof setTimeout> | undefined\n proc.once('close', () => {\n if (timer) clearTimeout(timer)\n resolve({ destroyed: true })\n })\n if (grace === 'brutalKill') {\n proc.kill('SIGKILL')\n return\n }\n proc.kill('SIGTERM')\n if (grace === 'infinity') return\n timer = setTimeout(() => {\n if (proc.exitCode === null && !proc.killed) proc.kill('SIGKILL')\n }, grace)\n })\n}\n\n// ── bridge executor (harness CLIs behind the local cli-bridge) ──────────────────\n\n/**\n * A worker as a RESUMABLE cli-bridge harness session — the local twin of the\n * sandbox executor. Both are a persistent, streamed agent session the driver\n * spawns, watches stream `UsageEvent`s, then STEERS/RESUMES out-of-band; the only\n * difference is where the harness runs (local cli-bridge vs a cloud box).\n *\n * Structure mirrors `streamSandboxLeaf` + `routerToolsInlineExecutor`:\n * - STREAMED: `execute` returns an `AsyncIterable<UsageEvent>`; the SSE chunks\n * cli-bridge emits (`stream:true`) are parsed into incremental usage + a tail\n * artifact read via `resultArtifact()` after the stream drains.\n * - RESUMABLE: every turn carries a stable `session_id`. cli-bridge maps it to the\n * harness's internal conversation id (SQLite `SessionStore`), so a steer delivered\n * via `deliver` re-calls the SAME session id — opencode `-s <id>`, claude\n * `--resume`, … — continuing the SAME harness session, not a fresh one.\n * - STEERABLE: the down-leg `inbox` is drained at each turn boundary; a queued\n * steer becomes the next turn's prompt on the same session, and the worker can't\n * settle while a steer it never read is pending (the sandbox/router contract).\n * - ABORT: reader abort only detaches HTTP. Interrupt/teardown then call the\n * bridge's explicit cancel operation and wait for the owned run to terminate.\n *\n * Reports REAL usage when the bridge surfaces it, never a fabricated cost.\n */\ninterface ResolvedBridgeSeam extends BridgeSeam {\n /** Derived once from the exact AgentProfile; never accepted as backend configuration. */\n readonly model: string\n /** Provider response model after removing the harness-only wire prefix. */\n readonly providerModel: string\n /** Profile-owned ceiling for one completion, forwarded as `max_tokens` when present. */\n readonly maxTokens?: number\n}\n\n/** Resolve the exact bridge wire id from the profile and nowhere else. */\nfunction bridgeProfileModel(profile: AgentProfile, context: string): string {\n assertExecutableAgentProfile(profile, context)\n if (!agentHarness(profile.harness)) {\n throw new ValidationError(`${context}: AgentProfile.harness must select a coding-agent harness`)\n }\n const model = profileBridgeWireModel(profile)\n if (!model) {\n throw new ValidationError(`${context}: AgentProfile did not resolve a bridge wire model`)\n }\n return model\n}\n\nexport const bridgeExecutor: ExecutorFactory<unknown> = (spec, ctx) => {\n const base = readSeam<BridgeSeam>(ctx, bridgeSeamKey, 'bridge')\n const modelCredential = validateBridgeModelCredential(\n base.modelCredential,\n base.bridgeUrl,\n 'bridgeExecutor',\n )\n const effectiveProfile = agentProfileSchema.parse(spec.profile)\n const model = bridgeProfileModel(effectiveProfile, 'bridgeExecutor')\n const harness = agentHarness(effectiveProfile.harness)\n const providerModel =\n harness !== undefined && model.startsWith(`${harness}/`)\n ? model.slice(harness.length + 1)\n : model\n const profileExecution = profileModelExecutionSettings(effectiveProfile, 'bridgeExecutor')\n const seam: ResolvedBridgeSeam = {\n ...base,\n ...(modelCredential === undefined ? {} : { modelCredential }),\n model,\n providerModel,\n ...(profileExecution.maxTokens !== undefined ? { maxTokens: profileExecution.maxTokens } : {}),\n }\n if (!seam.bridgeUrl || !seam.bridgeBearer) {\n throw new ValidationError('bridgeExecutor: bridgeUrl + bridgeBearer are required')\n }\n if (\n seam.timeoutMs !== undefined &&\n (!Number.isSafeInteger(seam.timeoutMs) ||\n seam.timeoutMs < 1 ||\n seam.timeoutMs > maxBridgeTimeoutMs)\n ) {\n throw new ValidationError(\n `bridgeExecutor: timeoutMs must be an integer from 1 to ${maxBridgeTimeoutMs}`,\n )\n }\n if (\n seam.maxReconnects !== undefined &&\n (!Number.isSafeInteger(seam.maxReconnects) || seam.maxReconnects < 0)\n ) {\n throw new ValidationError('bridgeExecutor: maxReconnects must be a nonnegative safe integer')\n }\n const maxTurns = profileExecution.maxTurns ?? 0\n const maxReconnects = seam.maxReconnects ?? 3\n // A stable per-spawn session id (caller can pin one) — cli-bridge keys harness\n // resume off this exactly as a box id keys a sandbox session.\n const sessionId = seam.sessionId ?? `bridge-${spec.profile.name ?? 'worker'}-${randomUUID()}`\n const attemptId = ctx.node?.attemptId ?? newExecutionAttemptId(sessionId)\n // The bridge's trace channel is the request, not an env field: the `traceparent` (+ legacy\n // pair) headers ride every turn POST, and the bridge stamps them into the harness child's\n // environment at spawn. Empty when the run records no spans, adding no header at all.\n const traceHeaders = workerTraceHeaders(ctx)\n\n const controller = new AbortController()\n const abortIfSignalled = () => {\n if (ctx.signal.aborted) controller.abort()\n }\n abortIfSignalled()\n if (!ctx.signal.aborted) ctx.signal.addEventListener('abort', abortIfSignalled, { once: true })\n\n // The down-leg receive end: the driver's steer/answer/resume land here via `Scope.send`.\n const inbox = createInbox()\n let artifact: ExecutorResult<unknown> | undefined\n // One spawn owns one resumable session and, at most, one live durable run per\n // turn. Keep the server-owned run identities until the bridge proves each job\n // terminal; closing a response body is deliberately not terminal evidence.\n const activeRuns = new Map<string, ActiveBridgeRun>()\n // The live read-model behind `progress()`, filled as the SSE stream is consumed.\n const observation: BridgeObservation = {\n turns: 0,\n note: 'starting',\n activity: createActivityLog(seam.activityWindow ?? 12),\n derived: [],\n refreshedAt: 0,\n refreshing: false,\n closed: false,\n }\n // One push source per SPAWN, not per turn: a steered worker's turn 4 tool calls belong to the\n // same trace as its turn 0 calls, and `collect()` must still answer after the stream drains.\n const trace = createPushTraceSource({ runId: sessionId })\n\n // Interface's AgentExecutionPreparationReceipt cannot be reused here yet: it is a pre-compute\n // contract requiring an execution-bound workspace lease, source/prepared workspace digests,\n // profile-activation evidence, and full per-axis ownership. cli-bridge currently has only its\n // terminal applied WorkspacePlan acknowledgement. Keep that acknowledgement explicitly terminal,\n // bind it into Runtime's existing declaration, and never present this planned declaration as\n // evidence that the remote process actually used it.\n const plannedDeclaration = {\n effectiveProfile,\n backend: 'bridge',\n model: { status: 'known' as const, id: seam.model },\n execution: { kind: 'session', id: sessionId },\n materializer: 'cli-bridge-agent-profile',\n plan: {\n kind: 'cli-bridge-session',\n cwd: seam.cwd ?? null,\n maxTurns,\n maxReconnects,\n timeoutMs: seam.timeoutMs ?? null,\n streaming: true,\n ...(seam.maxTokens !== undefined ? { maxTokens: seam.maxTokens } : {}),\n terminalAcknowledgement: null,\n },\n }\n const plannedBinding = {\n attemptId,\n binding: {\n bridgeUrl: seam.bridgeUrl,\n cwd: seam.cwd ?? null,\n effectiveProfile,\n model: seam.model,\n sessionId,\n },\n descriptor: { kind: 'bridge-session', transport: 'http', backend: 'bridge' },\n }\n let acknowledged: BridgeProfileMaterializationReceipt | undefined\n let executor!: Executor<unknown>\n executor = {\n runtime: 'cli' as Runtime,\n deliver: (m) => inbox.deliver(m),\n /**\n * The LIVE read of this worker, answered entirely from local mirrors so it is synchronous\n * and cannot block or fail the run. The bridge's own run state is refreshed OUT OF BAND —\n * a read schedules a fetch whose answer lands for the NEXT read — because the executor\n * cannot know from its own stream whether a silent run is thinking, detached mid-reconnect,\n * or already cancelled server-side, and that is exactly the distinction a supervisor's\n * respawn decision turns on.\n */\n progress: (): ExecutorProgress | undefined => {\n try {\n scheduleBridgeRunStateRefresh(seam, activeRuns, observation)\n return {\n turns: observation.turns,\n pendingMessages: inbox.pending(),\n recentActivity: observation.activity.read(),\n ...(observation.derived.length > 0 ? { derived: [...observation.derived] } : {}),\n note: bridgeProgressNote(observation, liveBridgeRunId(activeRuns)),\n }\n } catch {\n return undefined\n }\n },\n traceSource: (): TraceSource => trace.source,\n execute(task, signal): AsyncIterable<UsageEvent> {\n return streamBridgeSession({\n task,\n signal,\n profile: effectiveProfile,\n seam,\n sessionId,\n maxTurns,\n maxReconnects,\n traceHeaders,\n inbox,\n controller,\n activeRuns,\n observation,\n record: (step: ToolStepInput) => {\n trace.record(step)\n },\n onProviderAttemptStart: () => recordRuntimeOwnedProviderAttemptStart(executor),\n onProviderModel: (model) => recordRuntimeOwnedProviderModel(executor, model),\n onProviderIdentityConflict: () => recordRuntimeOwnedProviderIdentityConflict(executor),\n onArtifact: (a) => {\n artifact = a\n },\n onProfileMaterialization: (receipt) => {\n if (acknowledged !== undefined) {\n if (JSON.stringify(acknowledged) !== JSON.stringify(receipt)) {\n throw new ValidationError(\n 'bridgeExecutor: profile materialization changed across session turns',\n )\n }\n return\n }\n acknowledged = receipt\n finalizeRuntimeOwnedPendingExecutor(\n executor,\n {\n ...plannedDeclaration,\n plan: { ...plannedDeclaration.plan, terminalAcknowledgement: receipt },\n },\n plannedBinding,\n )\n },\n })\n },\n async teardown(grace): Promise<{ destroyed: boolean }> {\n controller.abort()\n const remaining = [...activeRuns.values()].filter((run) => !run.terminal)\n if (remaining.length === 0) return { destroyed: true }\n const terminal = await Promise.all(\n remaining.map((run) => cancelBridgeRunToTerminal(seam, run, grace)),\n )\n return { destroyed: terminal.every(Boolean) }\n },\n resultArtifact() {\n if (!artifact) {\n throw new ValidationError('bridgeExecutor: resultArtifact() read before stream drained')\n }\n return { ...artifact, spent: artifact.spent }\n },\n }\n return attestRuntimeOwnedPendingExecutor(executor, 'cli', plannedDeclaration, plannedBinding)\n}\n\ninterface StreamBridgeArgs {\n task: unknown\n signal: AbortSignal\n profile: AgentProfile\n seam: ResolvedBridgeSeam\n sessionId: string\n maxTurns: number\n maxReconnects: number\n /** Trace request headers ({@link workerTraceHeaders}); empty when the run records no spans. */\n traceHeaders: Readonly<Record<string, string>>\n inbox: Inbox\n controller: AbortController\n activeRuns: Map<string, ActiveBridgeRun>\n /** The live read-model `progress()` answers from; the turn loop is its only writer. */\n observation: BridgeObservation\n record: (step: ToolStepInput) => void\n onProviderAttemptStart: () => void\n onProviderModel: (model: string) => void\n onProviderIdentityConflict: () => void\n onArtifact: (a: ExecutorResult<unknown>) => void\n onProfileMaterialization: (receipt: BridgeProfileMaterializationReceipt) => void\n}\n\n/** Everything `bridgeExecutor.progress()` answers from. Every field is written by the turn loop as\n * the stream is consumed, so the read itself touches no I/O and cannot block the run. */\ninterface BridgeObservation {\n turns: number\n note: string\n readonly activity: ActivityLog\n /** Append-only record of what this executor changed about the caller's declaration. */\n readonly derived: string[]\n /** Newest bridge-side run snapshot; written by the out-of-band refresh, never awaited. */\n runState?: BridgeRunStateRead\n /** When the last refresh was STARTED — the rate limit, so a hot observe loop can't hammer. */\n refreshedAt: number\n refreshing: boolean\n /** Set once the bridge reports the run terminal, or the stream ends. Stops all further reads. */\n closed: boolean\n}\n\n/** The bridge's own view of the durable run, as `GET /v1/runs/:id` reports it. `at` is when this\n * executor read it, so a stale snapshot is presented as stale rather than as current truth. */\ninterface BridgeRunStateRead {\n readonly runId: string\n readonly status: string\n readonly state: string\n readonly terminal: boolean\n readonly lastSeq: number\n readonly at: number\n}\n\n/** Minimum spacing between out-of-band run-state reads. A driver polling `observe_agent` in a\n * tight loop must not turn an observability read into load on the bridge. */\nconst BRIDGE_RUN_STATE_REFRESH_MS = 1_000\n/** Ceiling on one run-state read. A bridge that hangs must not pin `refreshing` forever and\n * silently stop every later refresh. */\nconst BRIDGE_RUN_STATE_TIMEOUT_MS = 2_000\n\n/** One human-readable line: the local turn phase, plus the bridge's own run state when a snapshot\n * has been read for a run that is still live. The snapshot's AGE is stated because a driver\n * reading \"running\" must be able to tell a fresh read from a 40-second-old one; and once this\n * executor holds terminal proof the line is DROPPED rather than left repeating a last-known\n * \"running\" that stopped being true the moment the run ended. */\nfunction bridgeProgressNote(observation: BridgeObservation, liveRunId: string | undefined): string {\n const run = observation.runState\n if (!run || run.runId !== liveRunId) return observation.note\n const age = Math.max(0, Date.now() - run.at)\n return `${observation.note} · bridge run ${run.state} (status ${run.status}, seq ${run.lastSeq}, read ${age}ms ago)`\n}\n\n/** The run this executor still believes live, if any — the one worth reporting on and the only one\n * worth asking the bridge about. */\nfunction liveBridgeRunId(activeRuns: Map<string, ActiveBridgeRun>): string | undefined {\n for (const run of activeRuns.values()) {\n if (!run.terminal) return run.id\n }\n return undefined\n}\n\n/**\n * Start a NON-BLOCKING read of the bridge's run state; the answer lands on `observation` for a\n * later `progress()` call. Nothing here is awaited by the caller and no failure escapes: a bridge\n * that is down, slow, or has forgotten the run leaves the previous snapshot in place, and\n * `progress()` still returns the local mirror.\n */\nfunction scheduleBridgeRunStateRefresh(\n seam: BridgeSeam,\n activeRuns: Map<string, ActiveBridgeRun>,\n observation: BridgeObservation,\n): void {\n // A terminal answer is the end of the question. Local run state is NOT proof: `run.terminal`\n // stays false forever when a session dies without it (a failed teardown), so keying only on that\n // polls a dead worker for the life of the process.\n if (observation.closed) return\n if (observation.refreshing) return\n const now = Date.now()\n if (now - observation.refreshedAt < BRIDGE_RUN_STATE_REFRESH_MS) return\n // Only a run this executor still believes live is worth asking about; a terminal one is already\n // known, and there is nothing to steer.\n const runId = liveBridgeRunId(activeRuns)\n if (runId === undefined) return\n observation.refreshedAt = now\n observation.refreshing = true\n void (async () => {\n try {\n const snapshot = await bridgeRunStateGet(seam, runId)\n if (snapshot) {\n observation.runState = snapshot\n // Never write `run.terminal` from an observability read: `teardown` treats that field as\n // terminal proof and would skip the cancel.\n if (snapshot.terminal) observation.closed = true\n }\n } catch {\n // Keep the previous snapshot. An unreadable run state is not evidence about the run.\n } finally {\n observation.refreshing = false\n }\n })()\n}\n\n/** `GET /v1/runs/:id` — the bridge's durable-run registry read. Resolves `undefined` for any\n * non-200 or non-conforming body rather than throwing: this is only ever an observability read. */\nfunction bridgeRunStateGet(\n seam: BridgeSeam,\n runId: string,\n): Promise<BridgeRunStateRead | undefined> {\n const target = new URL(\n `${seam.bridgeUrl.replace(/\\/$/, '')}/v1/runs/${encodeURIComponent(runId)}`,\n )\n target.searchParams.set('wait_ms', '0')\n const requestFn = target.protocol === 'https:' ? httpsRequest : httpRequest\n return new Promise<BridgeRunStateRead | undefined>((resolve, reject) => {\n const req = requestFn(\n target,\n {\n method: 'GET',\n headers: { authorization: `Bearer ${seam.bridgeBearer}` },\n timeout: BRIDGE_RUN_STATE_TIMEOUT_MS,\n },\n (res) => {\n void (async () => {\n const chunks: Buffer[] = []\n for await (const chunk of res) chunks.push(Buffer.from(chunk))\n if (res.statusCode !== 200) {\n resolve(undefined)\n return\n }\n resolve(readBridgeRunState(runId, Buffer.concat(chunks).toString('utf8')))\n })().catch(reject)\n },\n )\n req.on('timeout', () => req.destroy(new Error('bridgeExecutor: run state read timed out')))\n req.on('error', reject)\n req.end()\n })\n}\n\n/** Decode one run snapshot. A body that does not carry the fields we report is `undefined`, never\n * a partially-invented snapshot. */\nfunction readBridgeRunState(runId: string, body: string): BridgeRunStateRead | undefined {\n let parsed: {\n id?: unknown\n status?: unknown\n state?: unknown\n terminal?: unknown\n lastSeq?: unknown\n }\n try {\n parsed = JSON.parse(body) as typeof parsed\n } catch {\n return undefined\n }\n if (parsed.id !== runId) return undefined\n if (typeof parsed.status !== 'string' || typeof parsed.state !== 'string') return undefined\n if (typeof parsed.terminal !== 'boolean' || typeof parsed.lastSeq !== 'number') return undefined\n return {\n runId,\n status: parsed.status,\n state: parsed.state,\n terminal: parsed.terminal,\n lastSeq: parsed.lastSeq,\n at: Date.now(),\n }\n}\n\ninterface ActiveBridgeRun {\n readonly id: string\n requestDigest?: string\n profileMaterialization?: BridgeProfileMaterializationReceipt\n transportAttempts: number\n lastEventId: number\n terminal: boolean\n cancelInFlight?: Promise<boolean>\n}\n\ninterface BridgeProfileMaterializationReceipt {\n readonly schema: typeof bridgeProfileMaterializationSchema\n readonly effectiveProfileDigest: string\n readonly harness: string\n readonly provider: string | null\n /** Exact full bridge wire id, for example `pi/tangle-router/deepseek-v4-flash`. */\n readonly model: string\n readonly reasoningEffort: {\n readonly requested: ReasoningEffort | null\n /** Exact native argv/config value after the bridge's backend mapping. */\n readonly applied: string | null\n }\n /** Exact model transport selected by cli-bridge before the harness process started. */\n readonly inference?: BridgeInferenceReceipt\n readonly workspacePlanDigest: string\n readonly files: ReadonlyArray<{ path: string; mode: number }>\n readonly unsupported: ReadonlyArray<{ dimension: string; reason: string }>\n}\n\ninterface BridgeInferenceReceipt {\n readonly effectiveEndpoint: string\n readonly apiMode: string\n readonly transport: 'scoped-loopback'\n /** Exact positive completion-token cap applied to the isolated model config. */\n readonly appliedMaxTokens?: number\n readonly observation?: BridgeInferenceObservation\n}\n\ninterface BridgeInferenceObservation {\n readonly requests: number\n readonly generationRequests: number\n readonly auxiliaryRequests: number\n readonly usageReceipts: number\n readonly rejectedRequests: number\n readonly failedRequests: number\n readonly inFlightRequests: number\n readonly accountingMatched: boolean\n readonly usage: BridgeInferenceUsage\n}\n\ninterface BridgeInferenceUsage {\n readonly inputTokens?: number\n readonly freshInputTokens?: number\n readonly cacheReadInputTokens?: number\n readonly cacheWriteInputTokens?: number\n readonly outputTokens?: number\n readonly costKnown: false\n readonly estimatedCost?: number\n}\n\n/**\n * One resumable cli-bridge session, run as a streamed turn loop. Turn 0 sends the\n * task; each subsequent turn fires ONLY when the inbox has a steer/answer to fold —\n * re-calling the SAME `session_id` so cli-bridge resumes the harness conversation.\n * Mirrors `routerToolsInlineExecutor`'s drain→turn→settle loop, but each turn is a\n * full streamed harness session call rather than a single chat round.\n */\nasync function* streamBridgeSession(args: StreamBridgeArgs): AsyncIterable<UsageEvent> {\n const { seam, inbox, observation } = args\n const started = Date.now()\n const external = mergeAbortSignals(args.signal, args.controller.signal)\n const tokens = zeroTokenUsage()\n let tokensKnown = true\n let usd = 0\n let usdKnown = true\n let estimatedUsd = 0\n let sawEstimatedUsd = false\n let turns = 0\n let transportAttempts = 0\n let lastText = ''\n let observedModel: string | undefined\n let observedSystemFingerprint: string | undefined\n const toolCalls: string[] = []\n const promptCache: { freshInput?: number; readInput?: number; writeInput?: number } = {}\n\n // Turn 0 is the task; later turns carry the folded steer/answer as the next prompt\n // on the SAME session. `nextPrompt` is undefined once there's nothing pending.\n let nextPrompt: string | undefined = taskToPrompt(args.task)\n for (let t = 0; args.maxTurns === 0 || t < args.maxTurns; t += 1) {\n // Drain queued down-messages; on turns > 0 they ARE the prompt (resume content).\n const pending = inbox.drain()\n if (pending.length) {\n const folded = inbox.fold(pending)\n nextPrompt = t === 0 && nextPrompt ? `${nextPrompt}\\n\\n${folded}` : folded\n for (const m of pending) {\n observation.activity.push({\n at: Date.now(),\n kind: 'note',\n label: m.interrupt ? 'steer' : 'follow-up',\n detail: m.text.length > 80 ? `${m.text.slice(0, 77)}...` : m.text,\n })\n }\n }\n if (nextPrompt === undefined) break\n observation.note = `turn ${t}`\n\n // Each turn sends ONLY the new task/steer. The full canonical profile carries the standing\n // prompt, and cli-bridge materializes it once; duplicating it as a system message changes the\n // instructions and makes profile-vs-message precedence backend-dependent.\n const messages: Array<{ role: string; content: string }> = []\n messages.push({ role: 'user', content: nextPrompt })\n nextPrompt = undefined\n\n // Per-turn signal: external teardown/abort OR a forceful interrupt steer.\n const interruptSig = inbox.freshInterrupt()\n const turnController = new AbortController()\n const abortTurn = () => turnController.abort()\n if (external.aborted) turnController.abort()\n else external.addEventListener('abort', abortTurn)\n interruptSig.addEventListener('abort', abortTurn, { once: true })\n let timedOut = false\n const timer =\n seam.timeoutMs !== undefined\n ? setTimeout(() => {\n timedOut = true\n abortTurn()\n }, seam.timeoutMs)\n : undefined\n const cleanup = () => {\n external.removeEventListener('abort', abortTurn)\n if (timer) clearTimeout(timer)\n }\n\n const activeRun: ActiveBridgeRun = {\n id: `bridge-run-${randomUUID()}`,\n transportAttempts: 0,\n lastEventId: 0,\n terminal: false,\n }\n args.activeRuns.set(activeRun.id, activeRun)\n const requestBody = {\n model: seam.model,\n stream: true,\n run_id: activeRun.id,\n session_id: args.sessionId,\n ...(seam.cwd ? { cwd: seam.cwd } : {}),\n ...(seam.maxTokens !== undefined ? { max_tokens: seam.maxTokens } : {}),\n execution: {\n kind: 'host' as const,\n ...(seam.timeoutMs !== undefined ? { timeoutMs: seam.timeoutMs } : {}),\n },\n agent_profile: args.profile,\n messages,\n }\n\n let turnText = ''\n let sawTurnTokenUsage = false\n let turnTokensKnown = true\n let sawTurnCostStatus = false\n let turnUsdKnown = true\n let turnKnownCostSubtotal = 0\n let turnEstimatedCostSubtotal = 0\n let interrupted = false\n try {\n args.onProviderAttemptStart()\n for await (const chunk of streamDurableBridgeRun({\n seam,\n profile: args.profile,\n sessionId: args.sessionId,\n body: requestBody,\n signal: turnController.signal,\n run: activeRun,\n maxReconnects: args.maxReconnects,\n traceHeaders: args.traceHeaders,\n })) {\n if (chunk.model !== undefined) {\n args.onProviderModel(chunk.model)\n try {\n if (!observedModelMatchesDeclared(chunk.model, seam.providerModel)) {\n args.onProviderIdentityConflict()\n throw new ValidationError(\n `bridgeExecutor: bridge reported model ${JSON.stringify(chunk.model)} but the profile requires ${JSON.stringify(seam.providerModel)}`,\n )\n }\n observedModel = mergeBridgeObservedModel(observedModel, chunk.model)\n } catch (error) {\n args.onProviderIdentityConflict()\n throw error\n }\n }\n if (chunk.systemFingerprint !== undefined) {\n if (\n observedSystemFingerprint !== undefined &&\n observedSystemFingerprint !== chunk.systemFingerprint\n ) {\n args.onProviderIdentityConflict()\n throw new ValidationError(\n `bridgeExecutor: bridge changed system fingerprint from ${JSON.stringify(observedSystemFingerprint)} to ${JSON.stringify(chunk.systemFingerprint)}`,\n )\n }\n observedSystemFingerprint = chunk.systemFingerprint\n }\n if (chunk.content) {\n turnText += chunk.content\n }\n for (const step of chunk.toolCalls ?? []) {\n toolCalls.push(step.toolName)\n observation.activity.push({\n at: Date.now(),\n kind: 'tool',\n label: step.toolName,\n // No `status`: the bridge reported the DECISION to call this tool, and nothing on\n // this wire ever reports the call finishing. An 'ok' here would be invented.\n ...(describeToolArgs(step.args) ? { detail: describeToolArgs(step.args) } : {}),\n })\n args.record(step)\n }\n if (chunk.usage) {\n sawTurnTokenUsage = true\n if (!chunk.usage.known) turnTokensKnown = false\n const usageEvent: Extract<UsageEvent, { kind: 'tokens' }> = {\n kind: 'tokens',\n input: chunk.usage.input,\n output: chunk.usage.output,\n ...(chunk.usage.known ? {} : { tokensKnown: false }),\n ...(chunk.usage.promptCache?.freshInput !== undefined\n ? { freshInput: chunk.usage.promptCache.freshInput }\n : {}),\n ...(chunk.usage.promptCache?.readInput !== undefined\n ? { cacheRead: chunk.usage.promptCache.readInput }\n : {}),\n ...(chunk.usage.promptCache?.writeInput !== undefined\n ? { cacheWrite: chunk.usage.promptCache.writeInput }\n : {}),\n }\n addTokenUsage(tokens, usageEvent)\n yield usageEvent\n if (chunk.usage.promptCache) {\n if (chunk.usage.promptCache.freshInput !== undefined) {\n promptCache.freshInput =\n (promptCache.freshInput ?? 0) + chunk.usage.promptCache.freshInput\n }\n if (chunk.usage.promptCache.readInput !== undefined) {\n promptCache.readInput =\n (promptCache.readInput ?? 0) + chunk.usage.promptCache.readInput\n }\n if (chunk.usage.promptCache.writeInput !== undefined) {\n promptCache.writeInput =\n (promptCache.writeInput ?? 0) + chunk.usage.promptCache.writeInput\n }\n }\n }\n if (chunk.costKnown !== undefined) {\n sawTurnCostStatus = true\n if (!chunk.costKnown) turnUsdKnown = false\n // A trusted total is the complete charge for the turn. It supersedes earlier\n // incremental chunks that correctly reported that their subtotal was incomplete.\n if (chunk.costKnown && chunk.costScope === 'total') turnUsdKnown = true\n }\n if (typeof chunk.cost === 'number') {\n const increment =\n chunk.costScope === 'total' ? chunk.cost - turnKnownCostSubtotal : chunk.cost\n if (increment < 0) {\n throw new ValidationError('bridgeExecutor: total billed cost decreased within a turn')\n }\n turnKnownCostSubtotal += increment\n if (increment > 0) {\n usd += increment\n yield { kind: 'cost', usd: increment }\n }\n }\n if (typeof chunk.estimatedCost === 'number') {\n const increment =\n chunk.costScope === 'total'\n ? chunk.estimatedCost - turnEstimatedCostSubtotal\n : chunk.estimatedCost\n if (increment < 0) {\n throw new ValidationError(\n 'bridgeExecutor: total estimated cost decreased within a turn',\n )\n }\n turnEstimatedCostSubtotal += increment\n estimatedUsd += increment\n sawEstimatedUsd = true\n }\n }\n args.onProfileMaterialization(activeRun.profileMaterialization!)\n } catch (error) {\n // A forceful steer first detaches this HTTP reader, then explicitly cancels\n // the durable run and waits for terminal proof. Starting the resume turn\n // before that acknowledgement would race two harness processes against one\n // resumable session.\n const interruptAbort =\n interruptSig.aborted && !args.signal.aborted && !args.controller.signal.aborted\n if (interruptAbort) {\n const terminal = await cancelBridgeRunToTerminal(seam, activeRun, 'infinity', external)\n if (!terminal) {\n throw new ValidationError(\n `bridgeExecutor: interrupted run ${activeRun.id} did not reach terminal state`,\n )\n }\n interrupted = true\n } else {\n // A per-turn timeout is owned here, not by the HTTP socket. Request\n // explicit cancellation before surfacing it; external scope teardown\n // performs the same operation under its own grace budget.\n if (timedOut && !activeRun.terminal) {\n await requestBridgeRunCancellation(seam, activeRun, 0)\n }\n throw error\n }\n } finally {\n transportAttempts += activeRun.transportAttempts\n cleanup()\n }\n // Some transports can finish a buffered body normally after their signal fires. The forceful\n // steer still wins and must become a new turn rather than letting this response settle.\n if (interruptSig.aborted && !args.signal.aborted && !args.controller.signal.aborted) {\n interrupted = true\n }\n turns += 1\n observation.turns = turns\n observation.activity.push({ at: Date.now(), kind: 'turn', label: `turn ${turns}` })\n if (!sawTurnTokenUsage || !turnTokensKnown) tokensKnown = false\n if (!sawTurnCostStatus || !turnUsdKnown) usdKnown = false\n yield { kind: 'iteration' }\n if (!interrupted && turnText) lastText = turnText\n\n if (interrupted) {\n observation.note = `turn ${turns} interrupted, resuming`\n continue\n }\n\n // Before settling, drain once more — the worker can't finish while a steer it\n // never read is pending (the sandbox/router settle contract). A pending steer\n // becomes the next resume turn; otherwise the session is truly done.\n if (inbox.pending() === 0) break\n }\n\n observation.note = 'settled'\n const spent: Spend = {\n iterations: turns,\n tokens,\n ...(tokensKnown ? {} : { tokensKnown: false }),\n usd,\n ...(usdKnown ? {} : { usdKnown: false }),\n ms: Date.now() - started,\n }\n const out = {\n content: lastText,\n ...(observedModel !== undefined ? { model: observedModel } : {}),\n ...(observedSystemFingerprint ? { system_fingerprint: observedSystemFingerprint } : {}),\n toolCalls,\n transportAttempts,\n ...(Object.keys(promptCache).length > 0 ? { promptCache } : {}),\n ...(sawEstimatedUsd ? { estimatedCostUsd: estimatedUsd } : {}),\n } as unknown\n args.onArtifact({\n outRef: contentRef('bridge', {\n model: observedModel ?? null,\n session: args.sessionId,\n content: lastText,\n }),\n out,\n spent,\n })\n}\n\nconst BRIDGE_CANCEL_LONG_POLL_MS = 30_000\nconst BRIDGE_BRUTAL_KILL_WAIT_MS = 150\n\ninterface StreamDurableBridgeRunArgs {\n seam: ResolvedBridgeSeam\n profile: AgentProfile\n sessionId: string\n body: unknown\n signal: AbortSignal\n run: ActiveBridgeRun\n maxReconnects: number\n /** Trace request headers ({@link workerTraceHeaders}); empty when the run records no spans. */\n traceHeaders: Readonly<Record<string, string>>\n}\n\n/**\n * Drain one server-owned bridge run. A transport loss replays from the last\n * contiguous event id under the SAME run id and request bytes. No unnumbered,\n * duplicate, or skipped event is accepted: an exact replay contract that\n * cannot prove continuity fails instead of returning a plausible partial answer.\n */\nasync function* streamDurableBridgeRun(\n args: StreamDurableBridgeRunArgs,\n): AsyncIterable<BridgeStreamChunk> {\n await assertBridgeExecutionCapabilities(args.seam, args.signal)\n let reconnects = 0\n let pendingUpstreamError: ValidationError | undefined\n\n for (;;) {\n let res: BridgeResponse\n try {\n args.run.transportAttempts += 1\n res = await bridgeStreamPost(args.seam.bridgeUrl, {\n bearer: args.seam.bridgeBearer,\n modelCredential: args.seam.modelCredential,\n sessionId: args.sessionId,\n runId: args.run.id,\n afterEventId: args.run.lastEventId,\n body: args.body,\n signal: args.signal,\n traceHeaders: args.traceHeaders,\n })\n } catch (error) {\n if (args.signal.aborted) throw error\n if (error instanceof ValidationError) throw error\n if (reconnects >= args.maxReconnects) {\n throw new ValidationError(\n `bridgeExecutor: run ${args.run.id} disconnected before terminal acknowledgement after ${reconnects + 1} attempts: ${errorMessage(error)}`,\n )\n }\n reconnects += 1\n continue\n }\n\n if (!res.ok) {\n // A remote status is a TRANSPORT fact, not a caller mistake: the package's taxonomy has\n // `BackendTransportError` precisely so a consumer (and the root-driver retry) can branch on\n // the upstream status — a 502 from a dying harness is recoverable, a 401 is not. Typing this\n // as a validation failure made every bridge fault look like a deliberate refusal.\n const body = (await res.text()).slice(0, 300)\n throw new BackendTransportError('bridge', `bridgeExecutor: bridge ${res.status}: ${body}`, {\n status: res.status,\n body,\n })\n }\n if (!res.body) {\n throw new ValidationError('bridgeExecutor: bridge response had no body to stream')\n }\n assertBridgeResponseIdentity(res, args.run)\n\n let sawDone = false\n try {\n for await (const event of parseSseChatStream(res.body)) {\n if (event.kind === 'done') {\n sawDone = true\n break\n }\n const expected = args.run.lastEventId + 1\n if (event.id !== expected) {\n throw new ValidationError(\n `bridgeExecutor: run ${args.run.id} replay gap: expected event ${expected}, received ${event.id}`,\n )\n }\n args.run.lastEventId = event.id\n if (event.error) pendingUpstreamError = event.error\n if (event.chunk?.profileMaterialization) {\n const receipt = assertBridgeProfileMaterialization(\n event.chunk.profileMaterialization,\n args.profile,\n args.seam.model,\n )\n if (\n args.run.profileMaterialization !== undefined &&\n JSON.stringify(args.run.profileMaterialization) !== JSON.stringify(receipt)\n ) {\n throw new ValidationError(\n `bridgeExecutor: run ${args.run.id} profile materialization changed across replay`,\n )\n }\n args.run.profileMaterialization = receipt\n }\n if (event.chunk) yield event.chunk\n }\n } catch (error) {\n if (args.signal.aborted) throw error\n if (error instanceof ValidationError) throw error\n if (reconnects >= args.maxReconnects) {\n throw new ValidationError(\n `bridgeExecutor: run ${args.run.id} stream disconnected before terminal acknowledgement after ${reconnects + 1} attempts: ${errorMessage(error)}`,\n )\n }\n reconnects += 1\n continue\n }\n\n if (sawDone) {\n if (args.run.profileMaterialization === undefined) {\n // Also TRANSPORT: a bridge that advertises the capability emits this receipt on every\n // healthy turn, so its absence means the turn did not survive to send it — the same\n // mid-stream death as above, arriving as a missing field instead of an error frame.\n // Typed as validation it read as a permanently broken bridge and the root-driver retry\n // refused to re-enter; one arm of a six-arm wave was lost to exactly this.\n throw new BackendTransportError(\n 'bridge',\n `bridgeExecutor: run ${args.run.id} completed without ${bridgeProfileMaterializationSchema}`,\n )\n }\n args.run.terminal = true\n if (pendingUpstreamError) throw pendingUpstreamError\n return\n }\n // Preserve the provider's actual diagnostic even when a non-conforming\n // bridge drops the final [DONE]. The run remains nonterminal in our local\n // state, so teardown still has to cancel and obtain real terminal proof.\n if (pendingUpstreamError) throw pendingUpstreamError\n if (args.signal.aborted) {\n throw new DOMException('bridgeExecutor: turn aborted', 'AbortError')\n }\n if (reconnects >= args.maxReconnects) {\n throw new ValidationError(\n `bridgeExecutor: run ${args.run.id} ended without terminal acknowledgement after ${reconnects + 1} attempts`,\n )\n }\n reconnects += 1\n }\n}\n\n/** Refuse an old bridge before it can start a paid harness turn. This is intentionally uncached:\n * a process may restart behind the same URL, and a remembered capability from the prior process\n * is not evidence about the process that will receive the next POST. The terminal receipt remains\n * mandatory because the bridge can still restart between this GET and the run request. */\nasync function assertBridgeExecutionCapabilities(\n seam: BridgeSeam,\n signal: AbortSignal,\n): Promise<void> {\n const target = new URL(`${seam.bridgeUrl.replace(/\\/$/, '')}/`)\n const requestFn = target.protocol === 'https:' ? httpsRequest : httpRequest\n const response = await new Promise<BridgeBufferedResponse>((resolve, reject) => {\n if (signal.aborted) {\n reject(new DOMException('bridgeExecutor: aborted before capability preflight', 'AbortError'))\n return\n }\n const req = requestFn(\n target,\n {\n method: 'GET',\n headers: { authorization: `Bearer ${seam.bridgeBearer}` },\n timeout: 0,\n },\n (res) => {\n void (async () => {\n const chunks: Buffer[] = []\n for await (const chunk of res) chunks.push(Buffer.from(chunk))\n resolve({\n status: res.statusCode ?? 0,\n headers: res.headers,\n text: Buffer.concat(chunks).toString('utf8'),\n })\n })().catch(reject)\n },\n )\n const abort = () =>\n req.destroy(new DOMException('bridgeExecutor: preflight aborted', 'AbortError'))\n signal.addEventListener('abort', abort, { once: true })\n req.on('error', reject)\n req.on('close', () => signal.removeEventListener('abort', abort))\n req.end()\n })\n if (response.status < 200 || response.status >= 300) {\n throw new BackendTransportError(\n 'bridge',\n `bridgeExecutor: capability preflight returned ${response.status}: ${response.text.slice(0, 200)}`,\n { status: response.status, body: response.text.slice(0, 200) },\n )\n }\n let body: { capabilities?: Record<string, unknown> }\n try {\n body = JSON.parse(response.text) as typeof body\n } catch {\n throw new ValidationError('bridgeExecutor: capability preflight returned invalid JSON')\n }\n if (body.capabilities?.profileMaterialization !== bridgeProfileMaterializationSchema) {\n throw new ValidationError(\n `bridgeExecutor: bridge does not advertise ${bridgeProfileMaterializationSchema}`,\n )\n }\n if (body.capabilities?.usageCostProvenance !== bridgeUsageCostSchema) {\n throw new ValidationError(`bridgeExecutor: bridge does not advertise ${bridgeUsageCostSchema}`)\n }\n}\n\n/** The subset of `Response` `streamBridgeSession` consumes: status gate, an error\n * body reader, and a web `ReadableStream` the SSE parser drains. */\ninterface BridgeResponse {\n ok: boolean\n status: number\n headers: Readonly<Record<string, string | string[] | undefined>>\n text: () => Promise<string>\n body: ReadableStream<Uint8Array> | null\n}\n\ninterface BridgeStreamPostArgs {\n bearer: string\n modelCredential?: BridgeModelCredential\n sessionId: string\n runId: string\n afterEventId: number\n body: unknown\n signal: AbortSignal\n /** Trace request headers ({@link workerTraceHeaders}); empty when the run records no spans. */\n traceHeaders: Readonly<Record<string, string>>\n}\n\n/**\n * POST one streamed turn to the cli-bridge over the `node:http(s)` core client\n * instead of global `fetch`. The bridge runs a harness CLI and streams SSE only\n * once that harness starts producing — first byte routinely arrives >5 min into a\n * heavy turn. `fetch` (undici) caps the wait for response headers at a fixed\n * `headersTimeout` (~300s) that no per-request option or `AbortSignal` overrides,\n * so it aborts a live-but-slow bridge with an opaque \"Headers Timeout Error\". The\n * core client has no such cap; the turn's `AbortSignal` (external teardown, a\n * forceful steer, or `seam.timeoutMs`) is the sole deadline. The response's\n * `IncomingMessage` (a Node `Readable`) is adapted to a web `ReadableStream` so the\n * shared `parseSseChatStream` consumes it unchanged.\n */\nasync function bridgeStreamPost(url: string, args: BridgeStreamPostArgs): Promise<BridgeResponse> {\n const modelCredential = await resolveBridgeModelCredential(args.modelCredential, 'bridgeExecutor')\n const target = new URL(`${url.replace(/\\/$/, '')}/v1/chat/completions`)\n const payload = JSON.stringify(args.body)\n const requestFn = target.protocol === 'https:' ? httpsRequest : httpRequest\n return new Promise<BridgeResponse>((resolve, reject) => {\n if (args.signal.aborted) {\n reject(new DOMException('bridgeExecutor: aborted before request', 'AbortError'))\n return\n }\n const req = requestFn(\n target,\n {\n method: 'POST',\n headers: {\n // Trace context first, so a malformed caller value can never shadow the fixed\n // transport headers below.\n ...args.traceHeaders,\n 'content-type': 'application/json',\n authorization: `Bearer ${args.bearer}`,\n ...(modelCredential === undefined\n ? {}\n : {\n [bridgeModelCredentialHeader]: modelCredential.token,\n [bridgeModelBaseUrlHeader]: modelCredential.baseUrl,\n }),\n 'x-session-id': args.sessionId,\n 'x-run-id': args.runId,\n ...(args.afterEventId > 0 ? { 'last-event-id': String(args.afterEventId) } : {}),\n 'content-length': Buffer.byteLength(payload),\n },\n // No header/body idle timeout: a slow bridge is a live bridge; the abort\n // signal is the sole deadline.\n timeout: 0,\n },\n (res) => {\n response = res\n res.once('close', () => args.signal.removeEventListener('abort', onAbort))\n const status = res.statusCode ?? 0\n const ok = status >= 200 && status < 300\n const body = Readable.toWeb(res) as ReadableStream<Uint8Array>\n resolve({\n ok,\n status,\n headers: res.headers,\n body,\n text: async () => {\n const chunks: Buffer[] = []\n for await (const c of res) chunks.push(c as Buffer)\n return Buffer.concat(chunks).toString('utf8')\n },\n })\n },\n )\n let response: Parameters<typeof Readable.toWeb>[0] | undefined\n const onAbort = (): void => {\n req.destroy(new DOMException('bridgeExecutor: turn aborted', 'AbortError'))\n if (response && 'destroy' in response && typeof response.destroy === 'function') {\n response.destroy(new DOMException('bridgeExecutor: turn aborted', 'AbortError'))\n }\n }\n if (args.signal.aborted) onAbort()\n else args.signal.addEventListener('abort', onAbort, { once: true })\n req.on('error', (e) => {\n args.signal.removeEventListener('abort', onAbort)\n reject(e)\n })\n req.on('close', () => {\n if (!response) args.signal.removeEventListener('abort', onAbort)\n })\n req.write(payload)\n req.end()\n })\n}\n\ninterface BridgeBufferedResponse {\n status: number\n headers: Readonly<Record<string, string | string[] | undefined>>\n text: string\n}\n\nfunction bridgeHeader(\n headers: Readonly<Record<string, string | string[] | undefined>>,\n name: string,\n): string | undefined {\n const raw = headers[name.toLowerCase()]\n if (Array.isArray(raw)) return raw.length === 1 ? raw[0] : undefined\n return raw\n}\n\nfunction assertBridgeResponseIdentity(response: BridgeResponse, run: ActiveBridgeRun): void {\n assertBridgeIdentityHeaders(response.headers, run)\n}\n\nfunction assertBridgeIdentityHeaders(\n headers: Readonly<Record<string, string | string[] | undefined>>,\n run: ActiveBridgeRun,\n): void {\n const responseRunId = bridgeHeader(headers, 'x-run-id')\n if (responseRunId !== run.id) {\n throw new ValidationError(\n `bridgeExecutor: bridge run identity mismatch: expected ${run.id}, received ${responseRunId ?? 'missing'}`,\n )\n }\n const digest = bridgeHeader(headers, 'x-run-request-digest')\n if (!digest || !/^sha256:[a-f0-9]{64}$/u.test(digest)) {\n throw new ValidationError('bridgeExecutor: bridge response omitted a valid request digest')\n }\n if (run.requestDigest !== undefined && run.requestDigest !== digest) {\n throw new ValidationError(\n `bridgeExecutor: bridge request digest changed for run ${run.id}: expected ${run.requestDigest}, received ${digest}`,\n )\n }\n run.requestDigest = digest\n}\n\n/** Explicitly cancel one server-owned run and long-poll for its terminal snapshot. */\nfunction bridgeCancelPost(\n seam: BridgeSeam,\n run: ActiveBridgeRun,\n waitMs: number,\n): Promise<BridgeBufferedResponse> {\n const target = new URL(\n `${seam.bridgeUrl.replace(/\\/$/, '')}/v1/runs/${encodeURIComponent(run.id)}/cancel`,\n )\n target.searchParams.set('wait_ms', String(waitMs))\n const requestFn = target.protocol === 'https:' ? httpsRequest : httpRequest\n return new Promise<BridgeBufferedResponse>((resolve, reject) => {\n const req = requestFn(\n target,\n {\n method: 'POST',\n headers: {\n authorization: `Bearer ${seam.bridgeBearer}`,\n 'x-run-id': run.id,\n 'content-length': '0',\n },\n timeout: 0,\n },\n (res) => {\n void (async () => {\n const chunks: Buffer[] = []\n for await (const chunk of res) chunks.push(Buffer.from(chunk))\n resolve({\n status: res.statusCode ?? 0,\n headers: res.headers,\n text: Buffer.concat(chunks).toString('utf8'),\n })\n })().catch(reject)\n },\n )\n req.on('error', reject)\n req.end()\n })\n}\n\nasync function requestBridgeRunCancellation(\n seam: BridgeSeam,\n run: ActiveBridgeRun,\n waitMs: number,\n): Promise<boolean> {\n if (run.terminal) return true\n if (run.cancelInFlight) return run.cancelInFlight\n const work = (async (): Promise<boolean> => {\n const response = await bridgeCancelPost(seam, run, waitMs)\n if (response.status === 404) {\n throw new ValidationError(\n `bridgeExecutor: bridge no longer knows run ${run.id}; terminal state is unproven`,\n )\n }\n if (response.status !== 200 && response.status !== 202) {\n throw new ValidationError(\n `bridgeExecutor: cancel ${run.id} returned ${response.status}: ${response.text.slice(0, 300)}`,\n )\n }\n assertBridgeIdentityHeaders(response.headers, run)\n let parsed: {\n terminal?: unknown\n run?: { id?: unknown; requestDigest?: unknown; terminal?: unknown }\n }\n try {\n parsed = JSON.parse(response.text) as typeof parsed\n } catch {\n throw new ValidationError(`bridgeExecutor: cancel ${run.id} returned invalid JSON`)\n }\n if (\n parsed.run?.id !== run.id ||\n parsed.run.requestDigest !== run.requestDigest ||\n typeof parsed.terminal !== 'boolean' ||\n typeof parsed.run.terminal !== 'boolean' ||\n parsed.terminal !== parsed.run.terminal\n ) {\n throw new ValidationError(\n `bridgeExecutor: cancel ${run.id} returned an inconsistent terminal snapshot`,\n )\n }\n if (response.status === 200 && parsed.terminal === true) {\n run.terminal = true\n return true\n }\n if (response.status === 202 && parsed.terminal === false) return false\n throw new ValidationError(\n `bridgeExecutor: cancel ${run.id} status ${response.status} disagreed with terminal=${String(parsed.terminal)}`,\n )\n })()\n run.cancelInFlight = work\n try {\n return await work\n } finally {\n if (run.cancelInFlight === work) run.cancelInFlight = undefined\n }\n}\n\nasync function cancelBridgeRunToTerminal(\n seam: BridgeSeam,\n run: ActiveBridgeRun,\n grace: number | 'brutalKill' | 'infinity',\n stopSignal?: AbortSignal,\n): Promise<boolean> {\n if (run.terminal) return true\n const deadline =\n grace === 'infinity'\n ? undefined\n : Date.now() + (grace === 'brutalKill' ? BRIDGE_BRUTAL_KILL_WAIT_MS : Math.max(0, grace))\n let first = true\n for (;;) {\n const remaining = deadline === undefined ? BRIDGE_CANCEL_LONG_POLL_MS : deadline - Date.now()\n if (!first && remaining <= 0) return false\n if (!first && stopSignal?.aborted) return false\n const waitMs = Math.max(\n 0,\n Math.min(\n stopSignal ? 1_000 : BRIDGE_CANCEL_LONG_POLL_MS,\n deadline === undefined ? remaining : Math.max(0, remaining),\n ),\n )\n const terminal = await requestBridgeRunCancellation(seam, run, waitMs)\n if (terminal) return true\n first = false\n if (deadline !== undefined && Date.now() >= deadline) return false\n await new Promise<void>((resolve) => setTimeout(resolve, 10))\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\ninterface BridgeStreamChunk {\n content?: string\n /** Provider-reported response model, not the bridge request model. */\n model?: string\n /** Provider response fingerprint carried alongside the response model. */\n systemFingerprint?: string\n /** Every tool call the delta carried, decoded into the shared tool-step currency. */\n toolCalls?: ReadonlyArray<ToolStepInput>\n usage?: {\n input: number\n output: number\n known: boolean\n promptCache?: { freshInput?: number; readInput?: number; writeInput?: number }\n }\n cost?: number\n costKnown?: boolean\n estimatedCost?: number\n costScope?: 'incremental' | 'total'\n profileMaterialization?: BridgeProfileMaterializationReceipt\n}\n\nfunction mergeBridgeObservedModel(current: string | undefined, next: string): string {\n if (current === undefined || current === next) return next\n const merged = mergeObservedModelIdentity(current, next)\n if (merged === undefined) {\n throw new ValidationError(\n `bridgeExecutor: bridge changed response model from ${JSON.stringify(current)} to ${JSON.stringify(next)}`,\n )\n }\n return merged\n}\n\nfunction assertBridgeProfileMaterialization(\n value: unknown,\n profile: AgentProfile,\n wireModel: string | undefined,\n): BridgeProfileMaterializationReceipt {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new ValidationError('bridgeExecutor: profile materialization receipt must be an object')\n }\n const raw = value as Record<string, unknown>\n const requiredKeys = [\n 'effectiveProfileDigest',\n 'files',\n 'harness',\n 'model',\n 'provider',\n 'reasoningEffort',\n 'schema',\n 'unsupported',\n 'workspacePlanDigest',\n ]\n // `inference` is part of the SAME v2 schema, not an extension of it: cli-bridge added it to\n // describe the bridge-owned model transport a jailed harness is pinned to (pi reaches its model\n // only through that loopback endpoint), and its own `ProfileMaterializationReceipt` type declares\n // it optional under `cli-bridge.profile-materialization.v2`. Comparing the key set EXACTLY made\n // this executor refuse a conformant receipt — every jailed pi run through a current bridge\n // settled `down` with \"receipt has missing or unknown fields\", which reads as a malformed bridge\n // rather than a validator that pinned an older spelling of the same version. Required keys stay\n // required and every value is still checked; the optional block is validated when present.\n const optionalKeys = ['inference']\n const presentKeys = Object.keys(raw)\n const missing = requiredKeys.filter((key) => !presentKeys.includes(key))\n const unknown = presentKeys.filter(\n (key) => !requiredKeys.includes(key) && !optionalKeys.includes(key),\n )\n if (missing.length > 0 || unknown.length > 0) {\n throw new ValidationError(\n 'bridgeExecutor: profile materialization receipt has missing or unknown fields' +\n (missing.length > 0 ? ` (missing: ${missing.sort().join(', ')})` : '') +\n (unknown.length > 0 ? ` (unknown: ${unknown.sort().join(', ')})` : ''),\n )\n }\n const inference =\n raw.inference === undefined ? undefined : parseBridgeInferenceReceipt(raw.inference)\n if (raw.schema !== bridgeProfileMaterializationSchema) {\n throw new ValidationError(\n `bridgeExecutor: profile materialization receipt is not ${bridgeProfileMaterializationSchema}`,\n )\n }\n const effectiveProfileDigest = raw.effectiveProfileDigest\n if (\n typeof effectiveProfileDigest !== 'string' ||\n !/^sha256:[a-f0-9]{64}$/u.test(effectiveProfileDigest)\n ) {\n throw new ValidationError(\n 'bridgeExecutor: profile materialization receipt has an invalid effectiveProfileDigest',\n )\n }\n const expectedDigest = canonicalAgentProfileDigest(profile)\n if (effectiveProfileDigest !== expectedDigest) {\n throw new ValidationError(\n `bridgeExecutor: bridge materialized profile ${effectiveProfileDigest}, expected ${expectedDigest}`,\n )\n }\n if (typeof raw.harness !== 'string' || raw.harness.length === 0) {\n throw new ValidationError('bridgeExecutor: profile materialization receipt has no harness')\n }\n if (raw.provider !== null && (typeof raw.provider !== 'string' || raw.provider.length === 0)) {\n throw new ValidationError(\n 'bridgeExecutor: profile materialization receipt has invalid provider',\n )\n }\n if (typeof raw.model !== 'string' || raw.model.length === 0 || raw.model !== wireModel) {\n throw new ValidationError(\n `bridgeExecutor: bridge materialized model ${JSON.stringify(raw.model)}, expected ${JSON.stringify(wireModel)}`,\n )\n }\n const expectedHarness = agentHarness(profile.harness) ?? wireModel?.split('/')[0]\n if (!expectedHarness || raw.harness !== expectedHarness) {\n throw new ValidationError(\n `bridgeExecutor: bridge materialized harness ${JSON.stringify(raw.harness)}, expected ${JSON.stringify(expectedHarness)}`,\n )\n }\n const expectedProvider = profile.model?.provider ?? null\n if (expectedProvider !== null && raw.provider !== expectedProvider) {\n throw new ValidationError(\n `bridgeExecutor: bridge materialized provider ${JSON.stringify(raw.provider)}, expected ${JSON.stringify(expectedProvider)}`,\n )\n }\n if (\n !raw.reasoningEffort ||\n typeof raw.reasoningEffort !== 'object' ||\n Array.isArray(raw.reasoningEffort)\n ) {\n throw new ValidationError(\n 'bridgeExecutor: profile materialization receipt has invalid reasoningEffort',\n )\n }\n const reasoningEffort = raw.reasoningEffort as Record<string, unknown>\n if (Object.keys(reasoningEffort).sort().join(',') !== 'applied,requested') {\n throw new ValidationError(\n 'bridgeExecutor: profile materialization receipt reasoningEffort has missing or unknown fields',\n )\n }\n const requested = reasoningEffort.requested\n const applied = reasoningEffort.applied\n if (\n (requested !== null &&\n (typeof requested !== 'string' ||\n !REASONING_EFFORTS.includes(requested as ReasoningEffort))) ||\n (applied !== null && (typeof applied !== 'string' || applied.length === 0))\n ) {\n throw new ValidationError(\n 'bridgeExecutor: profile materialization receipt has invalid reasoning effort values',\n )\n }\n const expectedRequested = profile.model?.reasoningEffort ?? null\n const expectedApplied = expectedBridgeAppliedReasoning(raw.harness, expectedRequested)\n if (requested !== expectedRequested || applied !== expectedApplied) {\n throw new ValidationError(\n `bridgeExecutor: bridge materialized reasoning effort ${JSON.stringify({ requested, applied })}, expected ${JSON.stringify({ requested: expectedRequested, applied: expectedApplied })}`,\n )\n }\n if (\n typeof raw.workspacePlanDigest !== 'string' ||\n !/^sha256:[a-f0-9]{64}$/u.test(raw.workspacePlanDigest)\n ) {\n throw new ValidationError(\n 'bridgeExecutor: profile materialization receipt has invalid workspacePlanDigest',\n )\n }\n if (!Array.isArray(raw.files) || !Array.isArray(raw.unsupported)) {\n throw new ValidationError(\n 'bridgeExecutor: profile materialization receipt files/unsupported must be arrays',\n )\n }\n const files = raw.files.map((entry) => {\n if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {\n throw new ValidationError('bridgeExecutor: profile materialization receipt has invalid file')\n }\n const file = entry as Record<string, unknown>\n if (\n Object.keys(file).sort().join(',') !== 'mode,path' ||\n typeof file.path !== 'string' ||\n file.path.length === 0 ||\n !Number.isSafeInteger(file.mode) ||\n (file.mode as number) < 0\n ) {\n throw new ValidationError('bridgeExecutor: profile materialization receipt has invalid file')\n }\n return { path: file.path, mode: file.mode as number }\n })\n const unsupported = raw.unsupported.map((entry) => {\n if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {\n throw new ValidationError(\n 'bridgeExecutor: profile materialization receipt has invalid unsupported entry',\n )\n }\n const item = entry as Record<string, unknown>\n if (\n Object.keys(item).sort().join(',') !== 'dimension,reason' ||\n typeof item.dimension !== 'string' ||\n item.dimension.length === 0 ||\n typeof item.reason !== 'string' ||\n item.reason.length === 0\n ) {\n throw new ValidationError(\n 'bridgeExecutor: profile materialization receipt has invalid unsupported entry',\n )\n }\n return { dimension: item.dimension, reason: item.reason }\n })\n if (unsupported.length > 0) {\n throw new ValidationError(\n `bridgeExecutor: bridge did not materialize profile dimensions: ${unsupported.map((item) => item.dimension).join(', ')}`,\n )\n }\n return Object.freeze({\n schema: bridgeProfileMaterializationSchema,\n effectiveProfileDigest,\n harness: raw.harness,\n provider: raw.provider as string | null,\n model: raw.model,\n reasoningEffort: {\n requested: requested as ReasoningEffort | null,\n applied: applied as string | null,\n },\n ...(inference === undefined ? {} : { inference }),\n workspacePlanDigest: raw.workspacePlanDigest,\n files: Object.freeze(files),\n unsupported: Object.freeze(unsupported),\n })\n}\n\nfunction parseBridgeInferenceReceipt(value: unknown): BridgeInferenceReceipt {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError(\n 'bridgeExecutor: profile materialization receipt has an invalid inference block',\n )\n }\n const raw = value as Record<string, unknown>\n assertBridgeReceiptKeys(\n raw,\n ['apiMode', 'effectiveEndpoint', 'transport'],\n ['appliedMaxTokens', 'observation'],\n 'profile materialization inference block',\n )\n const effectiveEndpoint = raw.effectiveEndpoint\n if (typeof effectiveEndpoint !== 'string' || effectiveEndpoint.length === 0) {\n throw new ValidationError(\n 'bridgeExecutor: profile materialization inference block has no effectiveEndpoint',\n )\n }\n const apiMode = raw.apiMode\n if (typeof apiMode !== 'string' || apiMode.length === 0) {\n throw new ValidationError(\n 'bridgeExecutor: profile materialization inference block has no apiMode',\n )\n }\n if (raw.transport !== 'scoped-loopback') {\n throw new ValidationError(\n 'bridgeExecutor: profile materialization inference block has invalid transport',\n )\n }\n const observation =\n raw.observation === undefined ? undefined : parseBridgeInferenceObservation(raw.observation)\n const appliedMaxTokens =\n raw.appliedMaxTokens === undefined\n ? undefined\n : bridgeInferencePositiveCount(raw.appliedMaxTokens, 'appliedMaxTokens')\n return detachedSnapshot(\n {\n effectiveEndpoint,\n apiMode,\n transport: 'scoped-loopback' as const,\n ...(appliedMaxTokens === undefined ? {} : { appliedMaxTokens }),\n ...(observation === undefined ? {} : { observation }),\n },\n 'bridgeExecutor: profile materialization inference block',\n )\n}\n\nfunction parseBridgeInferenceObservation(value: unknown): BridgeInferenceObservation {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError(\n 'bridgeExecutor: profile materialization inference observation must be an object',\n )\n }\n const raw = value as Record<string, unknown>\n assertBridgeReceiptKeys(\n raw,\n [\n 'accountingMatched',\n 'auxiliaryRequests',\n 'failedRequests',\n 'generationRequests',\n 'inFlightRequests',\n 'rejectedRequests',\n 'requests',\n 'usage',\n 'usageReceipts',\n ],\n [],\n 'profile materialization inference observation',\n )\n const observation = {\n requests: bridgeInferenceCount(raw.requests, 'requests'),\n generationRequests: bridgeInferenceCount(raw.generationRequests, 'generationRequests'),\n auxiliaryRequests: bridgeInferenceCount(raw.auxiliaryRequests, 'auxiliaryRequests'),\n usageReceipts: bridgeInferenceCount(raw.usageReceipts, 'usageReceipts'),\n rejectedRequests: bridgeInferenceCount(raw.rejectedRequests, 'rejectedRequests'),\n failedRequests: bridgeInferenceCount(raw.failedRequests, 'failedRequests'),\n inFlightRequests: bridgeInferenceCount(raw.inFlightRequests, 'inFlightRequests'),\n accountingMatched: bridgeInferenceBoolean(raw.accountingMatched, 'accountingMatched'),\n usage: parseBridgeInferenceUsage(raw.usage),\n }\n return detachedSnapshot(\n observation,\n 'bridgeExecutor: profile materialization inference observation',\n )\n}\n\nfunction parseBridgeInferenceUsage(value: unknown): BridgeInferenceUsage {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError(\n 'bridgeExecutor: profile materialization inference usage must be an object',\n )\n }\n const raw = value as Record<string, unknown>\n assertBridgeReceiptKeys(\n raw,\n ['costKnown'],\n [\n 'cacheReadInputTokens',\n 'cacheWriteInputTokens',\n 'estimatedCost',\n 'freshInputTokens',\n 'inputTokens',\n 'outputTokens',\n ],\n 'profile materialization inference usage',\n )\n if (raw.costKnown !== false) {\n throw new ValidationError(\n 'bridgeExecutor: profile materialization inference usage must report costKnown=false',\n )\n }\n const usage = {\n ...(raw.inputTokens === undefined\n ? {}\n : { inputTokens: bridgeInferenceCount(raw.inputTokens, 'usage.inputTokens') }),\n ...(raw.freshInputTokens === undefined\n ? {}\n : { freshInputTokens: bridgeInferenceCount(raw.freshInputTokens, 'usage.freshInputTokens') }),\n ...(raw.cacheReadInputTokens === undefined\n ? {}\n : {\n cacheReadInputTokens: bridgeInferenceCount(\n raw.cacheReadInputTokens,\n 'usage.cacheReadInputTokens',\n ),\n }),\n ...(raw.cacheWriteInputTokens === undefined\n ? {}\n : {\n cacheWriteInputTokens: bridgeInferenceCount(\n raw.cacheWriteInputTokens,\n 'usage.cacheWriteInputTokens',\n ),\n }),\n ...(raw.outputTokens === undefined\n ? {}\n : { outputTokens: bridgeInferenceCount(raw.outputTokens, 'usage.outputTokens') }),\n costKnown: false as const,\n ...(raw.estimatedCost === undefined\n ? {}\n : { estimatedCost: bridgeInferenceMoney(raw.estimatedCost, 'usage.estimatedCost') }),\n }\n return detachedSnapshot(usage, 'bridgeExecutor: profile materialization inference usage')\n}\n\nfunction assertBridgeReceiptKeys(\n value: Record<string, unknown>,\n required: readonly string[],\n optional: readonly string[],\n context: string,\n): void {\n const requiredSet = new Set(required)\n const optionalSet = new Set(optional)\n const missing = required.filter((key) => !Object.hasOwn(value, key))\n const unknown = Object.keys(value).filter((key) => !requiredSet.has(key) && !optionalSet.has(key))\n if (missing.length > 0 || unknown.length > 0) {\n throw new ValidationError(\n `bridgeExecutor: ${context} has missing or unknown fields` +\n (missing.length > 0 ? ` (missing: ${missing.sort().join(', ')})` : '') +\n (unknown.length > 0 ? ` (unknown: ${unknown.sort().join(', ')})` : ''),\n )\n }\n}\n\nfunction bridgeInferenceCount(value: unknown, field: string): number {\n if (!Number.isSafeInteger(value) || (value as number) < 0) {\n throw new ValidationError(\n `bridgeExecutor: profile materialization inference ${field} must be a nonnegative safe integer`,\n )\n }\n return value as number\n}\n\nfunction bridgeInferencePositiveCount(value: unknown, field: string): number {\n if (!Number.isSafeInteger(value) || (value as number) <= 0) {\n throw new ValidationError(\n `bridgeExecutor: profile materialization inference ${field} must be a positive safe integer`,\n )\n }\n return value as number\n}\n\nfunction bridgeInferenceBoolean(value: unknown, field: string): boolean {\n if (typeof value !== 'boolean') {\n throw new ValidationError(\n `bridgeExecutor: profile materialization inference ${field} must be boolean`,\n )\n }\n return value\n}\n\nfunction bridgeInferenceMoney(value: unknown, field: string): number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {\n throw new ValidationError(\n `bridgeExecutor: profile materialization inference ${field} must be finite and nonnegative`,\n )\n }\n return value\n}\n\n/** Expected native control for the bridge backends that can emit the v2 acknowledgement. These\n * mappings mirror the actual cli-bridge argv functions, so the acknowledgement is checked against\n * what the process must have received rather than merely echoing the canonical request. */\nfunction expectedBridgeAppliedReasoning(\n harness: string,\n requested: ReasoningEffort | null,\n): string | null {\n if (requested === null) return null\n switch (harness) {\n case 'pi':\n if (requested === 'none') return 'off'\n return requested === 'ultracode' ? 'xhigh' : requested\n case 'claude-code':\n if (requested === 'none' || requested === 'minimal') return 'low'\n return requested === 'ultracode' ? 'max' : requested\n case 'codex':\n if (requested === 'none') return 'minimal'\n return requested === 'xhigh' || requested === 'ultracode' ? 'high' : requested\n case 'kimi-code':\n if (requested === 'medium') return null\n return requested === 'none' || requested === 'minimal' || requested === 'low'\n ? '--no-thinking'\n : '--thinking'\n case 'gemini':\n return null\n default:\n // OpenCode and bridge backends with direct reasoning variants preserve the canonical label.\n return requested\n }\n}\n\n/**\n * Decode the OpenAI-shaped `tool_calls` of one delta into the shared `ToolStepInput` currency,\n * through the SAME `decodeOpenAiPart` adapter the sandbox/parts trace source uses — the wire shape\n * cli-bridge emits (`{index, id, type:'function', function:{name, arguments}}`) is exactly the one\n * that decoder owns, so there is no second mapping to drift.\n *\n * FIDELITY, stated once: this wire carries the model's DECISION to call a tool. cli-bridge's\n * backends surface the call the moment the harness announces it and NEVER report the call\n * finishing, so no outcome, result, or duration exists to read. Each step is therefore marked\n * `statusCaptured: false` and carries no `startedAt`/`endedAt` — its span is an instant with no\n * status. Synthesising an end time would inject a fabricated 0ms latency, and defaulting to 'ok'\n * would count an unobserved call as a success; both would silently corrupt any downstream latency\n * or error-rate analysis. An honest lower-fidelity span beats a fabricated one. A harness whose\n * native protocol reports tool completion could carry true durations; this wire does not.\n *\n * cli-bridge emits each call complete in ONE delta (`{id, name, arguments}` together), so no\n * cross-delta argument-fragment assembly is needed; a frame that carries argument bytes without a\n * name decodes to nothing rather than to a nameless call.\n */\nfunction decodeBridgeToolCalls(raw: unknown): ToolStepInput[] {\n if (!Array.isArray(raw)) return []\n const steps: ToolStepInput[] = []\n for (const call of raw) {\n if (!call || typeof call !== 'object') continue\n const record = call as Record<string, unknown>\n const fn = record.function as Record<string, unknown> | undefined\n // `type` is what `decodeOpenAiPart` matches on. A named function is a tool call whatever the\n // entry calls itself, and the previous parser keyed only on `function.name` — so normalize on\n // the name and never let an unrecognized `type` narrow what this executor observes. Dropping\n // one here also drops it from the public `out.toolCalls`.\n const named = typeof fn?.name === 'string' && fn.name.length > 0\n const step = decodeOpenAiPart(named ? { ...record, type: 'function' } : record)\n if (!step) continue\n const rawArgs = fn?.arguments ?? record.arguments\n const argsCaptured =\n typeof rawArgs === 'string' ? rawArgs.trim().length > 0 : rawArgs !== undefined\n steps.push({\n ...step,\n // An empty/absent `arguments` is an uncaptured argument list, not an empty one.\n ...(argsCaptured ? {} : { args: {}, argsCaptured: false }),\n statusCaptured: false,\n })\n }\n return steps\n}\n\ntype BridgeSseEvent =\n | { kind: 'event'; id: number; chunk?: BridgeStreamChunk; error?: ValidationError }\n | { kind: 'done' }\n\n/**\n * Parse cli-bridge's OpenAI-compatible SSE stream into normalized chunks. Each\n * `data:` line is an OpenAI chat-completion chunk (`choices[].delta`). Every\n * run-owned frame, including an id-only comment, is returned so the caller can\n * prove a contiguous replay sequence. Transport keepalives have no id and are ignored.\n */\nasync function* parseSseChatStream(\n body: ReadableStream<Uint8Array>,\n): AsyncIterable<BridgeSseEvent> {\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let buf = ''\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n buf += decoder.decode(value, { stream: true })\n // SSE frames are separated by a blank line; split on it and keep the tail.\n let separator = /\\r?\\n\\r?\\n/u.exec(buf)\n while (separator) {\n const frame = buf.slice(0, separator.index)\n buf = buf.slice(separator.index + separator[0].length)\n const event = parseSseFrame(frame)\n if (event) yield event\n separator = /\\r?\\n\\r?\\n/u.exec(buf)\n }\n }\n buf += decoder.decode()\n // Upstream failures routinely arrive UNTERMINATED: a final `data:` frame\n // with no trailing blank line, or a bare JSON error body with no SSE\n // framing at all (kimi's access_terminated_error). Dropping the tail here\n // ends the stream as one empty zero-token turn — the integrity guard still\n // fails the run, but the diagnostic dies with the buffer. Parse the tail so\n // the upstream error message rides the thrown event instead.\n const tail = parseSseStreamTail(buf)\n if (tail !== undefined) yield tail\n } finally {\n reader.releaseLock()\n }\n}\n\n/** Parse the stream's unterminated tail: an SSE frame missing its trailing\n * blank line, or a bare (non-SSE) JSON body — the shape bridge upstreams use\n * for terminal failures. Throws `ValidationError` on an error payload; returns\n * `undefined` for keepalive noise or non-JSON leftovers. */\nfunction parseSseStreamTail(buf: string): BridgeSseEvent | undefined {\n const tail = buf.trim()\n if (!tail) return undefined\n const framed = parseSseFrame(tail)\n if (framed !== undefined) return framed\n let parsed: { error?: { message?: string; type?: string } }\n try {\n parsed = JSON.parse(tail)\n } catch {\n return undefined\n }\n if (parsed.error) {\n throw new ValidationError(\n `bridgeExecutor: bridge upstream error: ${parsed.error.message ?? parsed.error.type ?? 'unknown'}`,\n )\n }\n return undefined\n}\n\n/** Parse one SSE frame into a numbered run event, terminal marker, or unnumbered keepalive. */\nfunction parseSseFrame(frame: string): BridgeSseEvent | undefined {\n const dataLines: string[] = []\n let id: number | undefined\n for (const rawLine of frame.split('\\n')) {\n const line = rawLine.replace(/\\r$/, '')\n if (!line || line.startsWith(':')) continue\n if (line.startsWith('id:')) {\n const rawId = line.slice('id:'.length).trim()\n if (!/^[1-9][0-9]*$/u.test(rawId)) {\n throw new ValidationError(`bridgeExecutor: invalid SSE event id ${JSON.stringify(rawId)}`)\n }\n const parsedId = Number(rawId)\n if (!Number.isSafeInteger(parsedId)) {\n throw new ValidationError(`bridgeExecutor: SSE event id exceeds safe integer range`)\n }\n id = parsedId\n continue\n }\n if (line.startsWith('data:')) dataLines.push(line.slice('data:'.length).trimStart())\n }\n if (dataLines.length === 0) {\n return id === undefined ? undefined : { kind: 'event', id }\n }\n const data = dataLines.join('\\n')\n if (data === '[DONE]') return { kind: 'done' }\n let parsed: {\n model?: unknown\n system_fingerprint?: unknown\n choices?: Array<{\n delta?: {\n content?: string | null\n tool_calls?: unknown\n }\n message?: { content?: string | null }\n }>\n error?: { message?: string; type?: string }\n usage?: {\n prompt_tokens?: unknown\n completion_tokens?: unknown\n fresh_input_tokens?: unknown\n cache_read_input_tokens?: unknown\n cache_write_input_tokens?: unknown\n prompt_cache_hit_tokens?: unknown\n prompt_tokens_details?: { cached_tokens?: unknown }\n prompt_cache?: { read_tokens?: unknown; write_tokens?: unknown }\n cost?: unknown\n estimated_cost?: unknown\n cost_known?: unknown\n cost_provenance?: unknown\n cost_scope?: unknown\n estimated?: unknown\n }\n profile_materialization?: unknown\n }\n try {\n parsed = JSON.parse(data)\n } catch {\n throw new ValidationError('bridgeExecutor: bridge emitted a non-JSON SSE data frame')\n }\n if (id === undefined) {\n throw new ValidationError('bridgeExecutor: bridge emitted an unnumbered run event')\n }\n if (parsed.error) {\n // `type` is the upstream's error class (e.g. kimi's access_terminated_error)\n // — carry it when the payload has no message, never collapse to 'unknown'.\n //\n // TRANSPORT, not validation. What arrives here is the harness's or the provider's failure\n // relayed mid-stream — a turn that ended without emitting anything, a dropped upstream, a\n // provider 5xx. Typing it as a validation error made it read as Runtime's own deliberate\n // refusal, which is precisely what the root-driver retry treats as terminal: measured on a\n // six-arm wave, three arms died on `pi assistant turn failed: The model finished\n // (finish_reason=stop) without emitting any visible output — Retry the request`, and the\n // retry declined to retry a message that asked to be retried.\n return {\n kind: 'event',\n id,\n error: new BackendTransportError(\n 'bridge',\n `bridgeExecutor: bridge stream error: ${parsed.error.message ?? parsed.error.type ?? 'unknown'}`,\n ),\n }\n }\n const out: BridgeStreamChunk = {}\n if (parsed.model !== undefined) {\n if (typeof parsed.model !== 'string' || parsed.model.length === 0) {\n throw new ValidationError('bridgeExecutor: bridge response model must be a non-empty string')\n }\n out.model = parsed.model\n }\n if (parsed.system_fingerprint !== undefined) {\n if (typeof parsed.system_fingerprint !== 'string' || parsed.system_fingerprint.length === 0) {\n throw new ValidationError(\n 'bridgeExecutor: bridge system_fingerprint must be a non-empty string',\n )\n }\n out.systemFingerprint = parsed.system_fingerprint\n }\n const choice = parsed.choices?.[0]\n const content = choice?.delta?.content ?? choice?.message?.content\n if (typeof content === 'string' && content.length > 0) out.content = content\n const toolCalls = decodeBridgeToolCalls(choice?.delta?.tool_calls)\n if (toolCalls.length > 0) out.toolCalls = toolCalls\n const u = parsed.usage\n if (u) {\n const input = optionalBridgeTokenCount(u.prompt_tokens, 'prompt_tokens')\n const output = optionalBridgeTokenCount(u.completion_tokens, 'completion_tokens')\n const readInput = optionalBridgeTokenCount(\n u.cache_read_input_tokens ??\n u.prompt_cache?.read_tokens ??\n u.prompt_cache_hit_tokens ??\n u.prompt_tokens_details?.cached_tokens,\n 'cache read input tokens',\n )\n const writeInput = optionalBridgeTokenCount(\n u.cache_write_input_tokens ?? u.prompt_cache?.write_tokens,\n 'cache write input tokens',\n )\n const explicitFreshInput = optionalBridgeTokenCount(u.fresh_input_tokens, 'fresh_input_tokens')\n const freshInput =\n explicitFreshInput ??\n (input !== undefined &&\n readInput !== undefined &&\n writeInput !== undefined &&\n input >= readInput + writeInput\n ? input - readInput - writeInput\n : undefined)\n if (\n input !== undefined ||\n output !== undefined ||\n freshInput !== undefined ||\n readInput !== undefined ||\n writeInput !== undefined\n ) {\n out.usage = {\n input: input ?? 0,\n output: output ?? 0,\n known: input !== undefined && output !== undefined && u.estimated !== true,\n ...(freshInput !== undefined || readInput !== undefined || writeInput !== undefined\n ? {\n promptCache: {\n ...(freshInput !== undefined ? { freshInput } : {}),\n ...(readInput !== undefined ? { readInput } : {}),\n ...(writeInput !== undefined ? { writeInput } : {}),\n },\n }\n : {}),\n }\n }\n if (u.estimated !== undefined && typeof u.estimated !== 'boolean') {\n throw new ValidationError('bridgeExecutor: usage.estimated must be boolean')\n }\n if (u.cost_scope !== undefined && u.cost_scope !== 'incremental' && u.cost_scope !== 'total') {\n throw new ValidationError(\"bridgeExecutor: usage.cost_scope must be 'incremental' or 'total'\")\n }\n out.costScope = u.cost_scope === 'total' ? 'total' : 'incremental'\n applyBridgeCostReceipt(out, u)\n }\n if (parsed.profile_materialization !== undefined) {\n out.profileMaterialization =\n parsed.profile_materialization as BridgeProfileMaterializationReceipt\n }\n return {\n kind: 'event',\n id,\n ...(Object.keys(out).length > 0 ? { chunk: out } : {}),\n }\n}\n\nfunction optionalBridgeTokenCount(value: unknown, field: string): number | undefined {\n if (value === undefined) return undefined\n if (!Number.isSafeInteger(value) || (value as number) < 0) {\n throw new ValidationError(`bridgeExecutor: usage.${field} must be a nonnegative safe integer`)\n }\n return value as number\n}\n\nfunction optionalBridgeMoney(value: unknown, field: string): number | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {\n throw new ValidationError(`bridgeExecutor: usage.${field} must be a finite nonnegative number`)\n }\n return value\n}\n\n/** Admit billed spend only with explicit trusted provenance. A catalog estimate remains visible on\n * the result but can never debit a dollar budget or turn unknown dollars into a known zero. */\nfunction applyBridgeCostReceipt(\n out: BridgeStreamChunk,\n usage: {\n cost?: unknown\n estimated_cost?: unknown\n cost_known?: unknown\n cost_provenance?: unknown\n },\n): void {\n const cost = optionalBridgeMoney(usage.cost, 'cost')\n const estimatedCost = optionalBridgeMoney(usage.estimated_cost, 'estimated_cost')\n const provenance = usage.cost_provenance\n if (usage.cost_known !== true && usage.cost_known !== false) {\n throw new ValidationError('bridgeExecutor: usage.cost_known must be an explicit boolean')\n }\n if (usage.cost_known) {\n if (\n cost === undefined ||\n (provenance !== 'provider-receipt' && provenance !== 'billing-receipt') ||\n estimatedCost !== undefined\n ) {\n throw new ValidationError(\n 'bridgeExecutor: known cost requires cost plus provider-receipt or billing-receipt provenance',\n )\n }\n out.costKnown = true\n out.cost = cost\n return\n }\n if (cost !== undefined) {\n throw new ValidationError('bridgeExecutor: unknown cost cannot carry billed cost')\n }\n if (estimatedCost !== undefined && provenance !== 'catalog-estimate') {\n throw new ValidationError('bridgeExecutor: estimated cost requires catalog-estimate provenance')\n }\n if (\n estimatedCost === undefined &&\n provenance !== undefined &&\n provenance !== 'catalog-estimate'\n ) {\n throw new ValidationError('bridgeExecutor: unknown cost has invalid provenance')\n }\n out.costKnown = false\n if (estimatedCost !== undefined) out.estimatedCost = estimatedCost\n}\n\nfunction bridgeWorktreeExecutor(\n spec: AgentSpec,\n ctx: ExecutorContext,\n seam: CliWorktreeSeam,\n): Executor<WorktreeHarnessResult> {\n const bridge = seam.bridge\n if (!bridge) {\n throw new ValidationError('cliWorktreeExecutor: bridge transport missing')\n }\n if (!bridge.bridgeUrl || !bridge.bridgeBearer) {\n throw new ValidationError(\n 'cliWorktreeExecutor: bridge.bridgeUrl + bridge.bridgeBearer required',\n )\n }\n\n const runId = seam.runId ?? randomUUID()\n const sessionId = bridge.sessionId ?? `bridge-worktree-${runId}`\n const attemptId = ctx.node?.attemptId ?? newExecutionAttemptId(runId)\n const effectiveProfile = agentProfileSchema.parse(spec.profile)\n const model = bridgeProfileModel(effectiveProfile, 'cliWorktreeExecutor bridge')\n const controller = new AbortController()\n const pending: unknown[] = []\n let inner: Executor<unknown> | undefined\n let worktree: WorktreeHandle | undefined\n let removed = false\n let artifact: ExecutorResult<WorktreeHarnessResult> | undefined\n\n const cleanupWorktree = async (): Promise<void> => {\n if (!worktree || removed) return\n const target = worktree\n removed = true\n worktree = undefined\n await removeWorktree({\n worktree: target,\n repoRoot: seam.repoRoot,\n ...(seam.runGit ? { runGit: seam.runGit } : {}),\n }).catch(() => undefined)\n }\n\n const deliver = (msg: unknown): void => {\n if (inner?.deliver) {\n inner.deliver(msg)\n return\n }\n pending.push(msg)\n }\n\n const plannedDeclaration = {\n effectiveProfile,\n backend: 'bridge-worktree',\n model: { status: 'known' as const, id: model },\n execution: { kind: 'worktree-session', id: `${runId}:${sessionId}` },\n materializer: 'bridge-worktree-agent-profile',\n plan: {\n kind: 'bridge-worktree-session',\n runId,\n sessionId,\n baseRef: seam.baseRef ?? 'HEAD',\n model,\n testCmd: seam.testCmd ?? null,\n typecheckCmd: seam.typecheckCmd ?? null,\n checkTimeoutMs:\n seam.checkTimeoutMs ?? seam.harnessTimeoutMs ?? bridge.timeoutMs ?? 5 * 60 * 1000,\n checkOutputCap: seam.checkOutputCap ?? 16_000,\n bridgeAcknowledgement: null,\n },\n }\n const plannedBinding = {\n attemptId,\n binding: {\n bridgeUrl: bridge.bridgeUrl,\n effectiveProfile,\n model,\n repoRoot: seam.repoRoot,\n runId,\n sessionId,\n },\n descriptor: {\n kind: 'bridge-worktree-session',\n transport: 'http',\n backend: 'bridge-worktree',\n },\n }\n let executor!: Executor<WorktreeHarnessResult>\n executor = {\n runtime: 'cli' as Runtime,\n budgetExempt: seam.budgetExempt ?? false,\n deliver,\n execute(task, signal): AsyncIterable<UsageEvent> {\n return (async function* bridgeWorktreeStream() {\n const started = Date.now()\n const linked = mergeAbortSignals(signal, controller.signal)\n let bridgeArtifact: ExecutorResult<unknown> | undefined\n\n try {\n worktree = await createWorktree({\n repoRoot: seam.repoRoot,\n runId,\n ...(seam.baseRef ? { baseRef: seam.baseRef } : {}),\n ...(seam.runGit ? { runGit: seam.runGit } : {}),\n })\n removed = false\n\n const bridgeSeam: BridgeSeam = {\n bridgeUrl: bridge.bridgeUrl,\n bridgeBearer: bridge.bridgeBearer,\n cwd: worktree.path,\n sessionId,\n ...(bridge.timeoutMs !== undefined ? { timeoutMs: bridge.timeoutMs } : {}),\n ...(bridge.maxReconnects !== undefined ? { maxReconnects: bridge.maxReconnects } : {}),\n }\n const bridgeCtx: ExecutorContext = {\n ...ctx,\n signal: linked,\n seams: { ...ctx.seams, [bridgeSeamKey]: bridgeSeam },\n }\n inner = bridgeExecutor(spec, bridgeCtx)\n for (const msg of pending.splice(0)) inner.deliver?.(msg)\n\n const run = inner.execute(task, linked)\n if (isAsyncIterable<UsageEvent>(run)) {\n for await (const event of run) yield event\n bridgeArtifact = inner.resultArtifact()\n } else {\n bridgeArtifact = await run\n }\n\n const bridgeDeclaration = runtimeOwnedExecutorMaterialization(inner)\n const bridgeBinding = runtimeOwnedExecutorExecutionBinding(inner)\n if (bridgeDeclaration === undefined || bridgeBinding === undefined) {\n throw new ValidationError(\n 'cliWorktreeExecutor: bridge completed without a terminal materialization acknowledgement',\n )\n }\n finalizeRuntimeOwnedPendingExecutor(\n executor,\n {\n ...plannedDeclaration,\n plan: {\n ...plannedDeclaration.plan,\n bridgeAcknowledgement: bridgeDeclaration.plan,\n },\n },\n {\n ...plannedBinding,\n binding: {\n ...plannedBinding.binding,\n worktreePath: worktree.path,\n bridgeBinding: bridgeBinding.binding,\n },\n },\n )\n\n const diff = await captureWorktreeDiff({\n worktree,\n ...(seam.runGit ? { runGit: seam.runGit } : {}),\n })\n const checks = await runWorktreeChecks({\n worktreePath: worktree.path,\n ...(seam.testCmd !== undefined ? { testCmd: seam.testCmd } : {}),\n ...(seam.typecheckCmd !== undefined ? { typecheckCmd: seam.typecheckCmd } : {}),\n timeoutMs:\n seam.checkTimeoutMs ?? seam.harnessTimeoutMs ?? bridge.timeoutMs ?? 5 * 60 * 1000,\n cap: seam.checkOutputCap ?? 16_000,\n ...(seam.runCommand ? { runCommand: seam.runCommand } : {}),\n signal: linked,\n })\n\n const result: WorktreeHarnessResult = {\n branch: worktree.branch,\n patch: diff.patch,\n stats: diff.stats,\n harness: {\n name: 'bridge',\n exitCode: null,\n timedOut: false,\n killedBySignal: null,\n durationMs: bridgeArtifact.spent.ms || Date.now() - started,\n stdout: bridgeOutputText(bridgeArtifact.out),\n stderr: '',\n },\n ...(checks ? { checks } : {}),\n }\n const spent: Spend = {\n ...bridgeArtifact.spent,\n ms: bridgeArtifact.spent.ms || Date.now() - started,\n }\n artifact = {\n outRef: contentRef('bridge-worktree', { sessionId, result }),\n out: result,\n spent,\n }\n } catch (err) {\n controller.abort()\n await inner?.teardown('brutalKill').catch(() => undefined)\n await cleanupWorktree()\n throw err\n }\n })()\n },\n async teardown(grace): Promise<{ destroyed: boolean }> {\n controller.abort()\n let destroyed = true\n try {\n if (inner) {\n destroyed = (await inner.teardown(grace)).destroyed\n }\n } finally {\n await cleanupWorktree()\n }\n return { destroyed }\n },\n resultArtifact() {\n if (!artifact) {\n throw new ValidationError(\n 'cliWorktreeExecutor: bridge resultArtifact() read before stream drained',\n )\n }\n return artifact\n },\n }\n return attestRuntimeOwnedPendingExecutor(executor, 'cli', plannedDeclaration, plannedBinding)\n}\n\nfunction bridgeOutputText(out: unknown): string {\n if (typeof out === 'string') return out\n if (out && typeof out === 'object') {\n const content = (out as { content?: unknown }).content\n if (typeof content === 'string') return content\n }\n try {\n return JSON.stringify(out) ?? String(out)\n } catch {\n return String(out)\n }\n}\n\nfunction isAsyncIterable<T>(value: unknown): value is AsyncIterable<T> {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function'\n )\n}\n\n// ── cli-worktree executor (authored profile → harness CLI on a git worktree) ────\n\n/**\n * The leaf `createWorktreeCliExecutor` as a backend-as-data factory: a supervisor-authored\n * `AgentProfile` driving claude / codex / opencode on its own worktree. `budgetExempt` like\n * the other CLI leaves; the authored systemPrompt + model reach the harness via §1.5.\n */\nexport const cliWorktreeExecutor: ExecutorFactory<unknown> = (spec, ctx) => {\n const seam = readSeam<CliWorktreeSeam>(ctx, cliWorktreeSeamKey, 'cli-worktree')\n if (!seam.repoRoot) {\n throw new ValidationError('cliWorktreeExecutor: CliWorktreeSeam.repoRoot required')\n }\n if (seam.bridge) return bridgeWorktreeExecutor(spec, ctx, seam)\n const effectiveProfile = agentProfileSchema.parse(spec.profile)\n assertExecutableAgentProfile(effectiveProfile, 'cliWorktreeExecutor')\n return createWorktreeCliExecutor({\n repoRoot: seam.repoRoot,\n profile: effectiveProfile,\n ...(seam.taskPrompt !== undefined ? { taskPrompt: seam.taskPrompt } : {}),\n ...(seam.runId ? { runId: seam.runId } : {}),\n ...(seam.baseRef ? { baseRef: seam.baseRef } : {}),\n ...(seam.harnessTimeoutMs !== undefined ? { harnessTimeoutMs: seam.harnessTimeoutMs } : {}),\n ...(seam.codexReproducible ? { codexReproducible: true } : {}),\n ...(seam.codexReadDeniedPaths ? { codexReadDeniedPaths: seam.codexReadDeniedPaths } : {}),\n ...(seam.testCmd !== undefined ? { testCmd: seam.testCmd } : {}),\n ...(seam.typecheckCmd !== undefined ? { typecheckCmd: seam.typecheckCmd } : {}),\n ...(seam.checkTimeoutMs !== undefined ? { checkTimeoutMs: seam.checkTimeoutMs } : {}),\n ...(seam.checkOutputCap !== undefined ? { checkOutputCap: seam.checkOutputCap } : {}),\n ...(seam.runGit ? { runGit: seam.runGit } : {}),\n ...(seam.runCommand ? { runCommand: seam.runCommand } : {}),\n ...(seam.budgetExempt !== undefined ? { budgetExempt: seam.budgetExempt } : {}),\n ...(ctx.node?.attemptId !== undefined ? { executionAttemptId: ctx.node.attemptId } : {}),\n }) as Executor<unknown>\n}\n\n// ── createExecutor: the ONE built-in factory (backend as data) ──────────────────\n\n/**\n * Config for {@link createExecutor}: the backend is DATA — the cost dial a profile,\n * an experiment config, or a replay journal can name — not an import choice. Each\n * variant carries its backend's seam (router/router-tools/bridge/cli/cli-worktree/sandbox).\n */\nexport type ExecutorConfig =\n | ({ backend: 'router' } & RouterSeam)\n | ({ backend: 'router-tools' } & RouterToolsSeam)\n | ({ backend: 'bridge' } & BridgeSeam)\n | ({ backend: 'cli' } & CliSeam)\n | ({ backend: 'cli-worktree' } & CliWorktreeSeam)\n | ({ backend: 'provider' } & ProviderSeam)\n | ({ backend: 'sandbox' } & SandboxSeam)\n\nfunction assertExactConfigKeys(\n value: Readonly<Record<string, unknown>>,\n allowed: ReadonlySet<string>,\n context: string,\n): void {\n const unknown = Object.keys(value).filter((key) => !allowed.has(key))\n if (unknown.length > 0) {\n throw new ValidationError(\n `${context}: unknown fields ${unknown.sort().join(', ')}; execution behavior belongs in AgentProfile`,\n )\n }\n}\n\n/** Capture one public executor configuration at its call boundary. All data that selects policy,\n * model, process, limits, or backend behavior is detached and deeply frozen.\n * Explicit service/function fields remain live by reference because they are executable ports,\n * not portable configuration. */\nexport function snapshotExecutorConfig(config: ExecutorConfig): ExecutorConfig {\n switch (config.backend) {\n case 'router-tools': {\n const { complete, executeToolCall, onMessages, onToolStep, ...decisionData } = config\n const snapshot = detachedSnapshot(decisionData, 'createExecutor router-tools config')\n return Object.freeze({\n ...snapshot,\n ...(complete === undefined ? {} : { complete }),\n executeToolCall,\n ...(onMessages === undefined ? {} : { onMessages }),\n ...(onToolStep === undefined ? {} : { onToolStep }),\n })\n }\n case 'router': {\n const { complete, ...decisionData } = config\n const snapshot = detachedSnapshot(decisionData, 'createExecutor router config')\n return Object.freeze({\n ...snapshot,\n ...(complete === undefined ? {} : { complete }),\n })\n }\n case 'cli-worktree': {\n if (config.bridge) {\n assertExactConfigKeys(\n config.bridge as unknown as Readonly<Record<string, unknown>>,\n new Set(['bridgeBearer', 'bridgeUrl', 'maxReconnects', 'sessionId', 'timeoutMs']),\n 'createExecutor cli-worktree bridge config',\n )\n }\n const { runGit, runCommand, ...decisionData } = config\n const snapshot = detachedSnapshot(decisionData, 'createExecutor cli-worktree config')\n return Object.freeze({\n ...snapshot,\n ...(runGit === undefined ? {} : { runGit }),\n ...(runCommand === undefined ? {} : { runCommand }),\n })\n }\n case 'provider': {\n const { provider, registry, profileForCreate, taskToTurn, ...decisionData } = config\n const snapshot = detachedSnapshot(decisionData, 'createExecutor provider config')\n // A registry is a live service. Resolve its mutable name mapping exactly once at intake and\n // retain the resulting provider instance, never the registry lookup for later execution.\n const resolvedProvider = resolveAgentEnvironmentProvider(provider, registry)\n return Object.freeze({\n ...snapshot,\n provider: resolvedProvider,\n ...(profileForCreate === undefined ? {} : { profileForCreate }),\n ...(taskToTurn === undefined ? {} : { taskToTurn }),\n })\n }\n case 'sandbox': {\n assertExactConfigKeys(\n config as unknown as Readonly<Record<string, unknown>>,\n new Set(['backend', 'lineage', 'loopCtx', 'maxIterations', 'sandboxClient', 'steering']),\n 'createExecutor sandbox config',\n )\n const { sandboxClient, loopCtx, ...decisionData } = config\n if (loopCtx === undefined) {\n const snapshot = detachedSnapshot(decisionData, 'createExecutor sandbox config')\n return Object.freeze({ ...snapshot, sandboxClient })\n }\n const { hooks, traceEmitter, onSandboxEvent, runHandle, ...loopDecisionData } = loopCtx\n const snapshot = detachedSnapshot(\n { ...decisionData, loopCtx: loopDecisionData },\n 'createExecutor sandbox config',\n )\n const loopSnapshot = snapshot.loopCtx\n return Object.freeze({\n ...snapshot,\n sandboxClient,\n loopCtx: Object.freeze({\n ...loopSnapshot,\n ...(hooks === undefined ? {} : { hooks }),\n ...(traceEmitter === undefined ? {} : { traceEmitter }),\n ...(onSandboxEvent === undefined ? {} : { onSandboxEvent }),\n ...(runHandle === undefined ? {} : { runHandle }),\n }),\n })\n }\n case 'bridge': {\n assertExactConfigKeys(\n config as unknown as Readonly<Record<string, unknown>>,\n new Set([\n 'activityWindow',\n 'backend',\n 'bridgeBearer',\n 'bridgeUrl',\n 'cwd',\n 'maxReconnects',\n 'modelCredential',\n 'sessionId',\n 'timeoutMs',\n ]),\n 'createExecutor bridge config',\n )\n const { modelCredential, ...decisionData } = config\n const snapshot = detachedSnapshot(decisionData, 'createExecutor bridge config')\n const capturedCredential = validateBridgeModelCredential(\n modelCredential,\n config.bridgeUrl,\n 'createExecutor bridge config',\n )\n return Object.freeze({\n ...snapshot,\n ...(capturedCredential === undefined ? {} : { modelCredential: capturedCredential }),\n })\n }\n case 'cli':\n return detachedSnapshot(config, `createExecutor ${config.backend} config`)\n }\n}\n\n/** A backend config reused for multiple workers/managers cannot pin execution identity. */\nexport function captureReusableExecutorConfig(\n config: ExecutorConfig,\n context: string,\n): ExecutorConfig {\n const captured = snapshotExecutorConfig(config)\n const fixedIdentity =\n captured.backend === 'bridge' && captured.sessionId !== undefined\n ? 'sessionId'\n : captured.backend === 'cli-worktree' && captured.runId !== undefined\n ? 'runId'\n : captured.backend === 'cli-worktree' && captured.bridge?.sessionId !== undefined\n ? 'bridge.sessionId'\n : undefined\n if (fixedIdentity !== undefined) {\n throw new ValidationError(\n `${context}: fixed ${fixedIdentity} is not allowed on a reusable backend; let each execution derive an isolated id`,\n )\n }\n return captured\n}\n\n/** Bind one already-captured reusable backend to the durable identity of the execution that will\n * use it. Stateful bridge backends need an explicit external id: a random default isolates two\n * siblings but cannot reconnect a replacement process to the same harness session. Non-stateful\n * backends carry no external execution id and are returned unchanged. */\nexport function bindReusableExecutorExecutionId(\n captured: ExecutorConfig,\n executionId: string,\n): ExecutorConfig {\n if (typeof executionId !== 'string' || executionId.length === 0) {\n throw new ValidationError(\n 'bindReusableExecutorExecutionId: executionId must be a non-empty string',\n )\n }\n switch (captured.backend) {\n case 'bridge':\n return Object.freeze({ ...captured, sessionId: executionId })\n case 'cli-worktree':\n // The bridged worktree derives `bridge-worktree-${runId}` when no inner session id is set,\n // so this one durable value binds both the worktree and its resumed harness conversation.\n return Object.freeze({ ...captured, runId: executionId })\n case 'router':\n case 'router-tools':\n case 'cli':\n case 'provider':\n case 'sandbox':\n return captured\n }\n}\n\n/**\n * The single built-in executor factory. Picks a leaf backend by data (`config.backend`),\n * injects the matching seam, and delegates to that backend's built-in implementation.\n * The `Executor` port stays OPEN: bring-your-own agents implement `Executor` directly, while Scope\n * or `createExecutorRegistry` still parses and seals their exact profile before use. Use this instead of a\n * per-vendor adapter or a closed `inline|sandbox|cli` switch — those bypass the\n * `UsageEvent` reporting channel.\n */\nexport function createExecutor(config: ExecutorConfig): ExecutorFactory<unknown> {\n const captured = snapshotExecutorConfig(config)\n return (rawSpec, ctx) => {\n const spec = executableAgentSpecSnapshot(rawSpec, `createExecutor(${captured.backend})`)\n const { backend, ...seamData } = captured as ExecutorConfig & Record<string, unknown>\n const seam = Object.freeze(seamData)\n const seamed: ExecutorContext = { ...ctx, seams: { ...ctx.seams, [backend]: seam } }\n switch (captured.backend) {\n case 'router':\n return routerInlineExecutor(spec, seamed)\n case 'router-tools':\n return routerToolsInlineExecutor(spec, seamed)\n case 'bridge':\n return bridgeExecutor(spec, seamed)\n case 'cli':\n return cliExecutor(spec, seamed)\n case 'cli-worktree':\n return cliWorktreeExecutor(spec, seamed)\n case 'provider': {\n const providerSeam = readSeam<ProviderSeam>(seamed, providerSeamKey, 'provider')\n const provider = resolveAgentEnvironmentProvider(\n providerSeam.provider,\n providerSeam.registry,\n )\n if (providerSeam.steering) {\n if (providerSeam.taskToTurn) {\n throw new ValidationError(\n 'createExecutor(provider, steering): taskToTurn is not representable by the text-only steerable session',\n )\n }\n if (providerSeam.destroyOnSettle === false) {\n throw new ValidationError(\n 'createExecutor(provider, steering): destroyOnSettle=false conflicts with the session-owned environment lifecycle',\n )\n }\n const harness = requiredProviderProfileHarness(spec, providerSeam)\n const sandboxClient = providerAsSandboxClient(provider, {\n defaults: {\n ...(providerSeam.defaults ?? {}),\n signal: seamed.signal,\n },\n requireTerminalEvent: providerSeam.requireTerminalEvent,\n requireSession: true,\n })\n const providerCtx: ExecutorContext = {\n ...seamed,\n seams: {\n ...seamed.seams,\n [sandboxSeamKey]: {\n sandboxClient,\n steering: providerSeam.steering,\n } satisfies SandboxSeam,\n },\n }\n const executor = sandboxExecutor({ ...spec, harness }, providerCtx)\n return {\n ...executor,\n runtime: providerSeam.runtime ?? (provider.name as Runtime),\n }\n }\n const profileForCreate = providerSeam.profileForCreate\n return providerAsExecutor(provider, {\n ...providerSeam,\n profileForCreate: (profile) => {\n const prepared = executableAgentProfileSnapshot(\n profileForCreate?.(profile) ?? profile,\n 'createExecutor(provider)',\n )\n if (canonicalAgentProfileDigest(prepared) !== canonicalAgentProfileDigest(profile)) {\n throw new ValidationError(\n 'createExecutor(provider): profileForCreate changed the exact AgentProfile; execution overlays are not allowed',\n )\n }\n return prepared\n },\n })(spec, seamed)\n }\n case 'sandbox': {\n const harness = spec.profile.harness as BackendType\n if (spec.harness != null && spec.harness !== harness) {\n throw new ValidationError(\n `createExecutor(sandbox): AgentSpec.harness ${JSON.stringify(spec.harness)} conflicts with AgentProfile.harness ${JSON.stringify(harness)}`,\n )\n }\n return sandboxExecutor({ ...spec, harness }, seamed)\n }\n }\n }\n}\n\nfunction requiredProviderProfileHarness(spec: AgentSpec, seam: ProviderSeam): BackendType {\n const harness = spec.profile.harness\n if (harness === undefined) {\n throw new ValidationError(\n 'createExecutor(provider, steering): AgentProfile.harness is required',\n )\n }\n if (spec.harness != null && spec.harness !== harness) {\n throw new ValidationError(\n `createExecutor(provider, steering): AgentSpec.harness \"${spec.harness}\" conflicts with AgentProfile.harness \"${harness}\"`,\n )\n }\n if (seam.defaults?.backend !== undefined && seam.defaults.backend !== harness) {\n throw new ValidationError(\n `createExecutor(provider, steering): provider default backend \"${seam.defaults.backend}\" conflicts with AgentProfile.harness \"${harness}\"`,\n )\n }\n return harness as BackendType\n}\n\n// ── The open registry ──────────────────────────────────────────────────────────\n\n/**\n * The open resolver/registry. Pre-registers the three built-ins under their\n * runtime tags (`'router'`, `'sandbox'`, `'cli'`) and accepts `register(name,\n * factory)` for any additional runtime. A BYO `AgentSpec.executor` has highest routing precedence\n * after the same exact-profile intake validation. Registration + BYO remain open extension points.\n *\n * `resolve` precedence (frozen in `ExecutorRegistry`): a BYO `spec.executorFactory` →\n * `spec.executor` → `harness === null` → the `'router'` factory; else a registered factory for the\n * harness-derived runtime (`'sandbox'` for any `BackendType`); else fail loud.\n */\nexport function createExecutorRegistry(): ExecutorRegistry {\n const factories = new Map<Runtime, ExecutorFactory<unknown>>()\n factories.set('router', routerInlineExecutor)\n factories.set('inline', routerInlineExecutor)\n factories.set('sandbox', sandboxExecutor)\n factories.set('cli', cliExecutor)\n\n return {\n register<Out>(runtime: Runtime, factory: ExecutorFactory<Out>): void {\n if (factories.has(runtime)) {\n throw new ValidationError(`executor registry: runtime \"${runtime}\" already registered`)\n }\n factories.set(runtime, factory as ExecutorFactory<unknown>)\n },\n resolve<Out>(\n rawSpec: AgentSpec,\n ): { succeeded: true; value: ExecutorFactory<Out> } | { succeeded: false; error: string } {\n const spec = executableAgentSpecSnapshot(rawSpec, 'executor registry')\n const bind =\n (factory: ExecutorFactory<Out>): ExecutorFactory<Out> =>\n (_ignored, context) =>\n factory(spec, context)\n // BYO factory: constructed only after Scope admission with the real signal/context.\n if (spec.executorFactory) {\n return {\n succeeded: true,\n value: bind(spec.executorFactory as ExecutorFactory<Out>),\n }\n }\n // BYO: a caller-supplied executor wins, wrapped in a trivial per-spawn factory.\n if (spec.executor) {\n const byo = spec.executor\n return { succeeded: true, value: bind(() => byo as Executor<Out>) }\n }\n // router/inline: an agent with no harness is a direct Router call.\n if (spec.harness === null) {\n const f = factories.get('router')\n if (!f) return { succeeded: false, error: 'executor registry: no \"router\" factory' }\n return { succeeded: true, value: bind(f as ExecutorFactory<Out>) }\n }\n // sandbox: any BackendType maps to the sandbox-composing-runAgentRounds executor.\n const runtimeTag: Runtime = 'sandbox'\n const f = factories.get(runtimeTag)\n if (!f) {\n return {\n succeeded: false,\n error: `executor registry: no factory for runtime \"${runtimeTag}\" (harness \"${spec.harness}\") and no BYO executor`,\n }\n }\n return { succeeded: true, value: bind(f as ExecutorFactory<Out>) }\n },\n }\n}\n\n// ── Shared helpers ──────────────────────────────────────────────────────────────\n\n/** Narrow a named seam off the `ExecutorContext`, failing loud when absent — no\n * silent default for a required external-boundary seam. */\nfunction readSeam<T>(ctx: ExecutorContext, key: string, who: string): T {\n const seam = ctx.seams[key]\n if (seam === undefined || seam === null) {\n throw new ValidationError(`${who} executor: missing required seam \"${key}\" on ExecutorContext`)\n }\n return seam as T\n}\n\n/** A leaf task is opaque (`unknown`). A string is the prompt verbatim; an object\n * with a `prompt`/`content`/`task` string field uses it; otherwise it serializes.\n * Module-exported (not package surface) so sibling leaf executors read a task\n * identically instead of re-deriving the rule. */\nexport function taskToPrompt(task: unknown): string {\n if (typeof task === 'string') return task\n if (task && typeof task === 'object') {\n const obj = task as Record<string, unknown>\n for (const k of ['prompt', 'content', 'task', 'message']) {\n if (typeof obj[k] === 'string') return obj[k] as string\n }\n }\n return JSON.stringify(task)\n}\n\ninterface RouterProfileExecution {\n systemPrompt: string\n reasoningEffort?: ReasoningEffort\n temperature?: number\n maxTokens?: number\n retry?: ProfileModelExecutionSettings['retry']\n seed?: number\n toolChoice?: 'auto' | 'required' | 'none'\n extraBody?: Readonly<Record<string, unknown>>\n maxTurns?: number\n stream?: boolean\n}\n\n/** Validate and render every AgentProfile axis the direct Router path claims to carry.\n * Unsupported behavioral axes fail before the HTTP request; inline resources become\n * named system-prompt attachments because this executor has no workspace to mount. */\nfunction routerProfileExecution(\n profile: AgentProfile,\n seam: RouterSeam,\n mode: { multiTurn: boolean },\n): RouterProfileExecution {\n assertProfileMaterialization({\n contract: routerTurnProfileMaterialization,\n changedAxes: profileMaterializationAxes(profile),\n context: 'routerInlineExecutor',\n })\n\n if (agentHarness(profile.harness) !== undefined) {\n throw new ValidationError(\n `routerInlineExecutor: AgentProfile.harness ${JSON.stringify(profile.harness)} requires a harness executor; the direct Router executor cannot materialize it`,\n )\n }\n\n const profileEffort = profile.model?.reasoningEffort\n const settings = profileModelExecutionSettings(profile, 'routerInlineExecutor')\n\n if (!mode.multiTurn && settings.maxTurns !== undefined) {\n throw new ValidationError(\n 'routerInlineExecutor: AgentProfile.model.metadata.maxTurns requires the router-tools backend',\n )\n }\n if (settings.stream === true && seam.tools === undefined) {\n throw new ValidationError(\n 'routerInlineExecutor: streamed chat without tool schemas is not supported; omit stream or use a harness executor',\n )\n }\n\n const declaredTools = profile.tools ?? {}\n const suppliedTools = seam.tools ?? []\n if (settings.toolChoice !== undefined && suppliedTools.length === 0) {\n throw new ValidationError(\n 'routerInlineExecutor: AgentProfile.model.metadata.toolChoice requires at least one enabled tool',\n )\n }\n const suppliedNames = new Set<string>()\n for (const tool of suppliedTools) {\n const name = tool.function.name\n if (!name || suppliedNames.has(name)) {\n throw new ValidationError(\n `routerInlineExecutor: caller tool names must be non-empty and unique (${JSON.stringify(name)})`,\n )\n }\n suppliedNames.add(name)\n if (declaredTools[name] !== true) {\n throw new ValidationError(\n `routerInlineExecutor: caller tool ${JSON.stringify(name)} is not enabled by AgentProfile.tools`,\n )\n }\n }\n for (const [name, enabled] of Object.entries(declaredTools)) {\n if (enabled && !suppliedNames.has(name)) {\n throw new ValidationError(\n `routerInlineExecutor: AgentProfile enables tool ${JSON.stringify(name)} but the caller supplied no matching schema`,\n )\n }\n if (!enabled && suppliedNames.has(name)) {\n throw new ValidationError(\n `routerInlineExecutor: AgentProfile disables tool ${JSON.stringify(name)}`,\n )\n }\n }\n\n return {\n systemPrompt: renderRouterProfilePrompt(profile),\n ...(profileEffort ? { reasoningEffort: profileEffort } : {}),\n ...settings,\n }\n}\n\n/** Resolve the one model id that will cross the Router boundary from the exact profile only. */\nfunction exactRouterModel(profile: AgentProfile, context: string): string {\n assertExecutableAgentProfile(profile, context)\n if (agentHarness(profile.harness) !== undefined) {\n throw new ValidationError(\n `${context}: AgentProfile.harness ${JSON.stringify(profile.harness)} conflicts with direct Router execution; use \"cli-base\"`,\n )\n }\n return concreteProfileModel(profile)!\n}\n\nfunction renderRouterProfilePrompt(profile: AgentProfile): string {\n const sections: string[] = [\n profile.prompt?.systemPrompt,\n ...(profile.prompt?.instructions ?? []),\n ].filter((value): value is string => typeof value === 'string' && value.trim().length > 0)\n const resources = profile.resources\n if (!resources) return sections.join('\\n')\n\n if (typeof resources.instructions === 'string') {\n if (resources.instructions.trim()) sections.push(resources.instructions)\n } else if (resources.instructions) {\n sections.push(renderRouterResource('instructions', resources.instructions))\n }\n for (const file of resources.files ?? []) {\n if (file.executable === true) {\n throw new ValidationError(\n `routerInlineExecutor: executable resource ${JSON.stringify(file.path)} requires a workspace backend`,\n )\n }\n sections.push(renderRouterResource(`file ${file.path}`, file.resource))\n }\n for (const [kind, refs] of [\n ['tool', resources.tools],\n ['skill', resources.skills],\n ['agent', resources.agents],\n ['command', resources.commands],\n ] as const) {\n for (const ref of refs ?? []) sections.push(renderRouterResource(kind, ref))\n }\n return sections.join('\\n\\n')\n}\n\nfunction renderRouterResource(kind: string, resource: AgentProfileResourceRef): string {\n if (resource.kind !== 'inline') {\n throw new ValidationError(\n `routerInlineExecutor: ${kind} resource ${JSON.stringify(resource.name ?? resource.path)} is not inline and cannot be resolved by the direct Router executor`,\n )\n }\n return `## Attached ${kind}: ${resource.name}\\n${resource.content}`\n}\n\n/** Router messages from the opaque task + every portable profile prompt instruction.\n * The profile prompt is always the immutable first message. Later system-role messages are\n * preserved as per-call task context; they cannot replace or precede the profile policy. */\nfunction taskToMessages(\n task: unknown,\n spec: AgentSpec,\n resolvedSystem?: string,\n): Array<{ role: string; content: unknown } & Record<string, unknown>> {\n const system =\n resolvedSystem ??\n [spec.profile.prompt?.systemPrompt, ...(spec.profile.prompt?.instructions ?? [])]\n .filter((line): line is string => typeof line === 'string' && line.trim().length > 0)\n .join('\\n')\n\n if (\n task &&\n typeof task === 'object' &&\n Array.isArray((task as { messages?: unknown }).messages)\n ) {\n const supplied = (task as { messages: unknown[] }).messages.map((value, index) => {\n if (!value || typeof value !== 'object') {\n throw new ValidationError(`routerInlineExecutor: messages[${index}] must be an object`)\n }\n const message = { ...(value as Record<string, unknown>) }\n if (typeof message.role !== 'string' || !('content' in message)) {\n throw new ValidationError(\n `routerInlineExecutor: messages[${index}] requires role and content`,\n )\n }\n return message as { role: string; content: unknown } & Record<string, unknown>\n })\n if (system.length > 0 && !(supplied[0]?.role === 'system' && supplied[0].content === system)) {\n return [{ role: 'system', content: system }, ...supplied]\n }\n return supplied\n }\n\n return [\n ...(system.length > 0 ? [{ role: 'system', content: system }] : []),\n { role: 'user', content: taskToPrompt(task) },\n ]\n}\n\n/** A driver that refines a single task up to `maxIterations` times then stops —\n * the minimal policy that lets the sandbox executor run `runAgentRounds` as one leaf. */\nfunction singleShotDriver<Out>(maxIterations: number): Driver<unknown, Out, string> {\n return {\n name: 'leaf',\n plan(task, history): Promise<unknown[]> {\n return Promise.resolve(history.length >= maxIterations ? [] : [task])\n },\n decide(history: ReadonlyArray<Iteration<unknown, Out>>): string {\n return history.length >= maxIterations ? 'stop' : 'continue'\n },\n }\n}\n\n/** Link two abort signals into one that fires when either does. Returns\n * `undefined` when neither is present so `fetch` gets no signal at all. */\nfunction linkSignals(a: AbortSignal, b: AbortSignal): AbortSignal | undefined {\n if (a.aborted || b.aborted) {\n const c = new AbortController()\n c.abort(abortReasonOf(a.aborted ? a : b))\n return c.signal\n }\n const c = new AbortController()\n a.addEventListener('abort', () => c.abort(abortReasonOf(a)), { once: true })\n b.addEventListener('abort', () => c.abort(abortReasonOf(b)), { once: true })\n return c.signal\n}\n\n/** The reason a signal carries, or a named fallback. A cascade that drops the upstream reason\n * turns every downstream death into the generic \"execution aborted\": the worker's `down`\n * record then says nothing about WHY, which is what makes a whole class of child mortality\n * undiagnosable from the journal alone. */\nfunction abortReasonOf(signal: AbortSignal, fallback = 'aborted by parent scope'): unknown {\n const reason = signal.reason\n if (typeof reason === 'string' && reason.length > 0) return reason\n // `controller.abort()` with no argument sets a DOMException whose message is the platform\n // placeholder (\"This operation was aborted\"), which carries no more information than the\n // generic death it replaces — treat it as reasonless and name the scope instead.\n if (reason instanceof Error && reason.name !== 'AbortError' && reason.message.length > 0) {\n return reason.message\n }\n return fallback\n}\n\n/** Combine N abort signals into one that fires when ANY does. Node-portable (no `AbortSignal.any`,\n * which needs >=20.3 — the package floor is >=20). Module-exported (not package surface) so\n * sibling leaf executors share the one portable implementation. */\nexport function mergeAbortSignals(...signals: AbortSignal[]): AbortSignal {\n const c = new AbortController()\n const onAbort = () => c.abort()\n for (const s of signals) {\n if (s.aborted) {\n c.abort()\n break\n }\n s.addEventListener('abort', onAbort, { once: true })\n }\n return c.signal\n}\n\n// Re-export the verdict + spend surface so a consumer importing the runtime\n// built-ins gets the budget vocabulary from one place.\nexport type { DefaultVerdict, Executor, ExecutorResult, Spend, UsageEvent }\n","/**\n *\n * The conserved budget reservation pool — the invariant the whole instrument\n * rests on (critique M5/B3). One root `Budget` becomes a conserved pool of three\n * quantities (tokens, usd, iterations) plus an absolute deadline. Children reserve\n * atomically at spawn and reconcile at settle:\n *\n * total ≡ free + reserved + committed (for every known quantity)\n *\n * `reserve` moves a child's whole ceiling from `free` → `reserved` and fails closed\n * when `free` can't cover it (never read-then-spawn overcommit, so `Σk(treatment) ≡\n * Σk(blind)` by construction). `reconcile` releases the reservation, commits ACTUAL\n * spend, and refunds the unspent remainder to `free`. Tokens and usd are separate\n * channels (`LoopTokenUsage` has no `usd`); iterations are conserved alongside them.\n *\n * Pure and deterministic: `now()` is injected, there is no I/O, and no wall-clock or\n * RNG read. A `reserve`/`reconcile` ticket is single-use (fail-loud on double or\n * unknown reconcile) so a child can never refund twice. Reconciling an OPEN ticket always\n * closes it: a fail-loud condition settles the reservation first and throws afterwards, so no\n * error path can strand a reservation past the join barrier's `assertNoOpenTickets`.\n * A child that declared no `maxUsd` reserved no dollar allocation, so its real dollars are\n * committed as observed spend and debited from the root's balance rather than treated as an\n * overspend of a $0 ceiling it never asked for. If dollar cost is unknowable under a\n * dollar limit, reconciliation closes the known token/iteration work, marks the dollar channel\n * unusable, and refuses later reservations; inventing a numeric dollar total would be worse.\n * If a TOKEN count is unknowable (a provider that reported no usage for work that ran), the pool\n * records the work, debits what it knows, and marks `readout().tokensKnown` false — the balance is\n * then a ceiling, not a measurement. It does not close admission the way the dollar channel does:\n * tokens are always capped, so one unreported turn must not end the run.\n *\n * A pool can be RESTORED from a prior process's durable record (same-host restart): measured\n * committed spend is debited exactly once, and each child journaled as started but never settled\n * is charged at its full declared ceiling — restart never mints capacity, and the unknown flags\n * stay visible in every later readout. The original absolute deadline never slides.\n *\n * @experimental\n */\n\nimport { ValidationError } from '../../errors'\nimport { addTokenUsage, zeroTokenUsage } from '../util'\nimport type { Budget, LoopTokenUsage, Spend, UsageEvent } from './types'\n\nexport type { Budget, Spend, UsageEvent }\n\n/** Opaque, single-use reservation handle returned by `reserve` and consumed by\n * `reconcile`. Carries the reserved ceilings so reconciliation needs no lookup. */\nexport interface ReservationTicket {\n readonly id: number\n readonly reserved: {\n readonly tokens: number\n readonly usd: number\n readonly iterations: number\n /**\n * Whether the child's `Budget` actually declared `maxUsd`. `reserved.usd` is `0` for BOTH a\n * child that named no dollar ceiling and one that named `$0`, and the two settle differently:\n * an undeclared ceiling cannot be exceeded, so the child's real dollars are committed as\n * OBSERVED spend, while a declared ceiling of `$0` is a limit whose breach is fail-loud.\n * Optional so an externally constructed ticket stays valid; an absent flag is read as\n * `true` — the strict, fail-closed reading.\n */\n readonly usdBudgeted?: boolean\n }\n}\n\n/** Post-reservation pool readout — the shape `Scope.budget` exposes. `tokensLeft`,\n * `usdLeft`, and `reservedTokens` reflect committed-but-unsettled reservations;\n * `deadlineMs` is the ABSOLUTE wall-clock deadline (0 when the root set none).\n * `iterationsLeft` is the remaining iteration capacity.\n * `usdCapped` distinguishes a real `usdLeft <= 0` exhaustion from an uncapped pool (which always\n * reads `usdLeft: 0`) — the in-loop guard needs it to bound a usd-capped driver. */\nexport type BudgetReadout = Readonly<{\n tokensLeft: number\n /**\n * False once the pool has recorded work whose token count was UNREPORTED (a `Spend` with\n * `tokensKnown: false`). `tokensLeft` is then a ceiling on what remains, not a measurement: real\n * consumption is at least the debited amount and possibly more. Reading `tokensLeft` without this\n * flag would present an under-count as an exact balance.\n */\n tokensKnown: boolean\n usdLeft: number\n usdCapped: boolean\n /** False once any recorded work reported an unknown dollar cost; the dollar totals are then a\n * lower bound on real spend, not a measurement. */\n usdKnown: boolean\n iterationsLeft: number\n deadlineMs: number\n reservedTokens: number\n}>\n/** Why a reservation was refused. `budget-exhausted` means the pool ran out of a channel it\n * budgets; `usd-unbudgeted` means the root declared no dollar ceiling, so a dollar request is\n * unsatisfiable at any amount and the fix is to budget the root, not to ask for less. */\nexport type ReservationRejection = 'budget-exhausted' | 'usd-unbudgeted'\n\n/** State recovered from a prior process before new work is admitted. `committed` is measured spend\n * already present in the durable journal. Each `uncertainReservation` is a child that was recorded\n * as started but never recorded as settled: its full declared ceiling is charged conservatively,\n * while the public readout remains explicitly unknown. */\nexport interface BudgetPoolRestore {\n readonly committed?: Spend\n readonly uncertainReservations?: ReadonlyArray<Budget>\n /** Original absolute deadline from the first process. It may never slide on restart. */\n readonly absoluteDeadlineMs?: number\n}\n\n/** Reject malformed ceilings before they can mint capacity through negative reservations. */\nexport function assertValidBudget(budget: Budget, label = 'budget'): void {\n const safeInteger = (value: number, field: string) => {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`${label}.${field} must be a non-negative safe integer`)\n }\n }\n const finiteNonNegative = (value: number, field: string) => {\n if (!Number.isFinite(value) || value < 0) {\n throw new Error(`${label}.${field} must be a non-negative finite number`)\n }\n }\n safeInteger(budget.maxIterations, 'maxIterations')\n safeInteger(budget.maxTokens, 'maxTokens')\n if (budget.maxUsd !== undefined) finiteNonNegative(budget.maxUsd, 'maxUsd')\n if (budget.deadlineMs !== undefined) finiteNonNegative(budget.deadlineMs, 'deadlineMs')\n}\n\nfunction assertValidSpend(spend: Spend, label: string): void {\n if (!Number.isSafeInteger(spend.iterations) || spend.iterations < 0) {\n throw new Error(`${label}.iterations must be a non-negative safe integer`)\n }\n for (const [field, value] of [\n ['input', spend.tokens.input],\n ['output', spend.tokens.output],\n ['freshInput', spend.tokens.freshInput],\n ['cacheRead', spend.tokens.cacheRead],\n ['cacheWrite', spend.tokens.cacheWrite],\n ] as const) {\n if (value === undefined) continue\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`${label}.tokens.${field} must be a non-negative safe integer`)\n }\n }\n for (const [field, value] of [\n ['tokensKnown', spend.tokens.tokensKnown],\n ['cacheBreakdownKnown', spend.tokens.cacheBreakdownKnown],\n ] as const) {\n if (value !== undefined && value !== false) {\n throw new Error(`${label}.tokens.${field} must be false when present`)\n }\n }\n const { freshInput, cacheRead, cacheWrite } = spend.tokens\n if (\n freshInput !== undefined &&\n cacheRead !== undefined &&\n cacheWrite !== undefined &&\n freshInput + cacheRead + cacheWrite !== spend.tokens.input\n ) {\n throw new Error(`${label}.tokens cache classes must sum to input`)\n }\n for (const [field, value] of [\n ['usd', spend.usd],\n ['ms', spend.ms],\n ] as const) {\n if (!Number.isFinite(value) || value < 0) {\n throw new Error(`${label}.${field} must be a non-negative finite number`)\n }\n }\n}\n\nexport interface BudgetPool {\n /**\n * Atomically reserve a child's full ceiling from the free balance. Fails closed\n * ({ ok: false }) when the pool can't cover tokens, usd, or iterations — the\n * caller inspects `ok` before `ticket`.\n */\n reserve(\n b: Budget,\n ): { ok: true; ticket: ReservationTicket } | { ok: false; reason: ReservationRejection }\n /**\n * Release a reservation: commit the actual `spent`, refund the unspent remainder\n * to the free pool. Throws on an unknown or already-reconciled ticket (fail loud —\n * a double refund would silently break conservation).\n */\n reconcile(ticket: ReservationTicket, spent: Spend): void\n /** Fold a normalized `UsageEvent` stream (or array) into a `Spend`. Tokens via\n * `addTokenUsage`, usd on its own channel, iterations from `'iteration'` events.\n * `ms` is left zero — wall-clock duration is the caller's to record, not the pool's. */\n spendFrom(events: AsyncIterable<UsageEvent> | UsageEvent[]): Promise<Spend>\n /** The current readout, reflecting all outstanding reservations. */\n readout(): BudgetReadout\n /**\n * Record OBSERVED spend that did NOT go through reserve/reconcile — the driver's OWN inference\n * (its chat turns), which is real compute but not a spawned child. A direct `free → committed`\n * debit, so `total ≡ free + reserved + committed` is preserved: equal-k counts the driver's\n * tokens and the in-loop budget guard (`readout().tokensLeft`) sees them. `free` may go negative\n * when a run overspends — that is honest (the readout then signals exhaustion). It never throws:\n * the spend already happened, so accounting records reality; the in-loop guard prevents MORE.\n * The DURABLE record is the journal's `metered` event (written by `Scope.meter`); this debit\n * only makes the live `readout()` reflect driver inference for the in-loop guard.\n */\n observe(spend: Spend): void\n /** Fail loud if any reservation is still open — the conserved-pool leak detector. Called at the\n * supervisor's join barrier: once every child has settled, no ticket may remain (a leaked\n * reservation would silently break `total ≡ free + reserved + committed`). */\n assertNoOpenTickets(): void\n}\n\n/** Fold a normalized `UsageEvent` array into a `Spend`. Tokens and usd are separate\n * channels; iterations come from `'iteration'` events. Pure; `ms` stays zero (the\n * pool does not read wall-clock). */\nexport function spendFromUsageEvents(events: UsageEvent[]): Spend {\n const tokens = zeroTokenUsage()\n let tokensKnown = true\n let usd = 0\n let usdKnown = true\n let iterations = 0\n for (const ev of events) {\n if (ev.kind === 'tokens') {\n addTokenUsage(tokens, ev)\n if (ev.tokensKnown === false) tokensKnown = false\n } else if (ev.kind === 'cost') {\n usd += ev.usd\n if (ev.usdKnown === false) usdKnown = false\n } else {\n iterations += 1\n }\n }\n return {\n iterations,\n tokens,\n ...(tokensKnown ? {} : { tokensKnown: false }),\n usd,\n ...(usdKnown ? {} : { usdKnown: false }),\n ms: 0,\n }\n}\n\nasync function foldUsage(events: AsyncIterable<UsageEvent> | UsageEvent[]): Promise<Spend> {\n if (Array.isArray(events)) return spendFromUsageEvents(events)\n const tokens = zeroTokenUsage()\n let tokensKnown = true\n let usd = 0\n let usdKnown = true\n let iterations = 0\n for await (const ev of events) {\n if (ev.kind === 'tokens') {\n addTokenUsage(tokens, ev)\n if (ev.tokensKnown === false) tokensKnown = false\n } else if (ev.kind === 'cost') {\n usd += ev.usd\n if (ev.usdKnown === false) usdKnown = false\n } else {\n iterations += 1\n }\n }\n return {\n iterations,\n tokens,\n ...(tokensKnown ? {} : { tokensKnown: false }),\n usd,\n ...(usdKnown ? {} : { usdKnown: false }),\n ms: 0,\n }\n}\n\nfunction totalTokens(usage: LoopTokenUsage): number {\n return usage.input + usage.output\n}\n\n/**\n * Create a conserved reservation pool from a root `Budget`. `now()` is injected so the\n * deadline readout is deterministic; defaults to `Date.now` for non-test callers. The\n * absolute deadline for a fresh pool is fixed at construction (`now() + budget.deadlineMs`). A\n * restored pool instead retains `restore.absoluteDeadlineMs`, so restart never slides the original\n * wall-clock limit. The readout is an absolute instant, not a shrinking remainder.\n */\nexport function createBudgetPool(\n root: Budget,\n now: () => number = Date.now,\n restore: BudgetPoolRestore = {},\n): BudgetPool {\n assertValidBudget(root, 'root budget')\n if (\n restore.absoluteDeadlineMs !== undefined &&\n (!Number.isFinite(restore.absoluteDeadlineMs) || restore.absoluteDeadlineMs < 0)\n ) {\n throw new Error('budget restore.absoluteDeadlineMs must be a non-negative finite number')\n }\n // free + reserved + committed ≡ root totals, per channel, always.\n let freeTokens = root.maxTokens\n let reservedTokens = 0\n let committedTokens = 0\n // Set once the pool records work with an unreported token count, and never cleared. Unlike\n // `usdTainted` it does NOT close admission: the token channel is always capped, so refusing every\n // later reservation would turn one provider that skipped a usage report into a dead run. The pool\n // keeps enforcing the cap on what it knows and reports, via `readout().tokensKnown`, that the\n // balance is an under-count rather than a measurement.\n let tokensTainted = false\n\n const usdCapped = root.maxUsd !== undefined\n let freeUsd = root.maxUsd ?? 0\n let reservedUsd = 0\n let committedUsd = 0\n // Closes dollar admission: set when unknown dollar cost lands under a dollar-capped root.\n let usdTainted = false\n // Reporting only: set whenever ANY recorded work carried `usdKnown: false`, capped or not, so\n // the readout never presents a lower bound as a measured dollar total.\n let usdMeasured = true\n\n let freeIterations = root.maxIterations\n let reservedIterations = 0\n let committedIterations = 0\n\n const absoluteDeadlineMs =\n restore.absoluteDeadlineMs ?? (root.deadlineMs !== undefined ? now() + root.deadlineMs : 0)\n\n let nextTicketId = 0\n const open = new Set<number>()\n\n function reserve(\n b: Budget,\n ): { ok: true; ticket: ReservationTicket } | { ok: false; reason: ReservationRejection } {\n assertValidBudget(b, 'reservation budget')\n const wantTokens = b.maxTokens\n const wantUsd = b.maxUsd ?? 0\n const wantIterations = b.maxIterations\n if (usdCapped && usdTainted) return { ok: false, reason: 'budget-exhausted' }\n // Fail-closed admission: every requested channel must fit the free balance. A\n // usd request against an uncapped root is unsatisfiable (the root declared no $).\n if (wantTokens > freeTokens) return { ok: false, reason: 'budget-exhausted' }\n if (wantIterations > freeIterations) return { ok: false, reason: 'budget-exhausted' }\n // A dollar request against a root that declared no dollar ceiling can never be satisfied at\n // ANY amount, which is a different fact from an exhausted balance and calls for a different\n // fix: budget the root, do not retry smaller. Reporting both as `budget-exhausted` invites a\n // caller to shrink its request forever — observed live, a driver walked its child budget down\n // to $0.01 and spent 68k tokens before asking for help.\n if (wantUsd > 0 && !usdCapped) return { ok: false, reason: 'usd-unbudgeted' }\n if (wantUsd > freeUsd) return { ok: false, reason: 'budget-exhausted' }\n\n freeTokens -= wantTokens\n reservedTokens += wantTokens\n freeIterations -= wantIterations\n reservedIterations += wantIterations\n if (wantUsd > 0) {\n freeUsd -= wantUsd\n reservedUsd += wantUsd\n }\n\n const id = nextTicketId++\n open.add(id)\n return {\n ok: true,\n ticket: {\n id,\n reserved: {\n tokens: wantTokens,\n usd: wantUsd,\n iterations: wantIterations,\n usdBudgeted: b.maxUsd !== undefined,\n },\n },\n }\n }\n\n function reconcile(ticket: ReservationTicket, spent: Spend): void {\n if (!open.has(ticket.id)) {\n throw new Error(`budget pool: reconcile of unknown or already-settled ticket ${ticket.id}`)\n }\n assertValidSpend(spent, `budget pool ticket ${ticket.id} spend`)\n const { tokens: rTokens, usd: rUsd, iterations: rIterations } = ticket.reserved\n const unknownUnderCap = usdCapped && spent.usdKnown === false\n const spentTokens = totalTokens(spent.tokens)\n // A child whose `Budget` named no `maxUsd` reserved NO dollar allocation, so it has no\n // dollar ceiling to exceed: under a capped root its real dollars are OBSERVED spend, and\n // the settlement below commits them and debits them from `free` (the same treatment\n // `observe` gives driver inference). Only a child that DECLARED a ceiling can overspend\n // one. Conflating the two made a successful priced child fail its own reconcile.\n const usdBudgeted = ticket.reserved.usdBudgeted !== false\n\n // Fail-loud conditions are DECIDED here and thrown at the very END, after the reservation\n // has been settled. A throw placed before settlement is how a ticket escapes the pool:\n // `Scope.runChild` marks the child reconciled before calling, so nothing retries, the\n // ticket stays open forever, and `assertNoOpenTickets` fails the whole run at the join\n // barrier — on the SUCCESS path. Everything between here and the throw is unconditional\n // pure arithmetic that cannot skip the settlement.\n let violation: string | undefined\n if (spentTokens > rTokens) {\n // A child must never commit more than it reserved (that would overdraw the conserved\n // pool). The settlement still commits the ACTUAL spend and lets `free` go negative,\n // which keeps `total ≡ free + reserved + committed` exact and reports the overdraw\n // through the readout instead of stranding the reservation.\n violation = `ticket ${ticket.id} spent ${spentTokens} tokens > reserved ${rTokens}`\n } else if (spent.iterations > rIterations) {\n violation = `ticket ${ticket.id} spent ${spent.iterations} iterations > reserved ${rIterations}`\n } else if (usdCapped && usdBudgeted && spent.usd > rUsd) {\n // USD is conserved ONLY when the root declared a ceiling AND the child declared one to\n // be measured against. `maxUsd` is optional on both: when either is unset, usd is an\n // OBSERVED quantity (committed for accounting), never a budgeted constraint — an unset\n // ceiling must not behave as a hard $0 limit that fail-closes a real priced spend.\n violation = `ticket ${ticket.id} spent $${spent.usd} > reserved $${rUsd}`\n } else if (unknownUnderCap) {\n // The known channels still settle, then the dollar channel is permanently tainted and\n // admission closes.\n violation = `ticket ${ticket.id} reported unknown dollar cost under a dollar-capped budget`\n }\n\n // ── Settlement: unconditional, and the only place the ticket closes ───────────────\n open.delete(ticket.id)\n\n // Release the whole reservation, then commit actual spend; the difference is the\n // refund that flows back to `free`.\n if (spent.tokensKnown === false) tokensTainted = true\n if (spent.usdKnown === false) usdMeasured = false\n reservedTokens -= rTokens\n committedTokens += spentTokens\n freeTokens += rTokens - spentTokens\n\n reservedIterations -= rIterations\n committedIterations += spent.iterations\n freeIterations += rIterations - spent.iterations\n\n if (usdCapped) {\n reservedUsd -= rUsd\n committedUsd += spent.usd\n if (unknownUnderCap) {\n usdTainted = true\n freeUsd = 0\n } else {\n // `rUsd` is 0 for a child that declared no ceiling, so this debits its observed\n // dollars straight out of the capped root's free balance — the root's `usdLeft`\n // shrinks by what the child really spent and admission closes when it runs out.\n freeUsd += rUsd - spent.usd\n }\n } else {\n // With no root dollar limit, record observed spend without a reservation channel.\n committedUsd += spent.usd\n }\n\n if (violation !== undefined) throw new Error(`budget pool: ${violation}`)\n }\n\n function observe(spend: Spend): void {\n assertValidSpend(spend, 'observed spend')\n // Unknown dollars under a dollar cap are REFUSED before any balance mutates: unlike a\n // reconciled child (whose reservation must settle), an observation has no ticket to strand,\n // so the honest reading is a fail-loud refusal the caller surfaces — `driver-failed` carrying\n // this reason — rather than an invented figure or a silently consumed cap.\n if (usdCapped && spend.usdKnown === false) {\n // A typed refusal, not a bare invariant guard: this is a contract failure the caller sees on\n // the `driver-failed` arm, and a driver retry must be able to tell it apart from a foreign\n // accident it could recover from.\n throw new ValidationError(\n 'budget pool: cannot observe unknown dollar cost under a dollar-capped budget',\n )\n }\n // Work whose token count was never reported still debits what IS known (usually nothing) and\n // marks the balance incomplete. The alternative — refusing to record it — is the \"free turn\"\n // the pool must never see.\n if (spend.tokensKnown === false) tokensTainted = true\n if (spend.usdKnown === false) usdMeasured = false\n const tokens = totalTokens(spend.tokens)\n // Direct free → committed debit (no reservation ticket). `free` may go negative on overspend —\n // that is honest; the readout then reports exhaustion and the in-loop guard halts the driver.\n // The DURABLE record of this spend is the journal's `metered` event (the twin written by\n // `Scope.meter`); this debit exists only to make the live `readout()` reflect driver inference.\n freeTokens -= tokens\n committedTokens += tokens\n freeIterations -= spend.iterations\n committedIterations += spend.iterations\n committedUsd += spend.usd\n if (usdCapped) freeUsd -= spend.usd\n }\n\n function readout(): BudgetReadout {\n return {\n tokensLeft: freeTokens,\n tokensKnown: !tokensTainted,\n usdLeft: usdCapped ? (usdTainted ? 0 : freeUsd) : 0,\n usdCapped,\n usdKnown: usdMeasured && !usdTainted,\n iterationsLeft: freeIterations,\n deadlineMs: absoluteDeadlineMs,\n reservedTokens,\n }\n }\n\n function assertNoOpenTickets(): void {\n if (open.size > 0) {\n throw new Error(\n `budget pool: ${open.size} reservation(s) still open at join barrier (leaked ticket ids: ${[...open].join(', ')}) — conserved-pool invariant violated`,\n )\n }\n }\n\n // Reconstruct the conserved balances before exposing the pool. Measured prior spend is debited\n // exactly once. A started-without-terminal child is charged at its entire reservation: this\n // never mints capacity on restart, but unlike treating unknown as zero it can leave unrelated\n // capacity usable. The false known flags remain visible in every later report. Restore uses\n // direct arithmetic rather than `observe`, because the prior process's spend ALREADY happened:\n // refusing to record it would be the zero-cost restart the pool must never allow.\n if (restore.committed !== undefined) {\n assertValidSpend(restore.committed, 'budget restore committed')\n const committed = restore.committed\n if (committed.tokensKnown === false) tokensTainted = true\n if (committed.usdKnown === false) usdMeasured = false\n const tokens = totalTokens(committed.tokens)\n freeTokens -= tokens\n committedTokens += tokens\n freeIterations -= committed.iterations\n committedIterations += committed.iterations\n committedUsd += committed.usd\n if (usdCapped) {\n freeUsd -= committed.usd\n if (committed.usdKnown === false) {\n // The prior process spent dollars it could not measure under a dollar cap: the remaining\n // balance is not a sound bound, so consume it and close dollar admission.\n usdTainted = true\n if (freeUsd > 0) committedUsd += freeUsd\n freeUsd = 0\n }\n }\n }\n for (const [index, uncertain] of (restore.uncertainReservations ?? []).entries()) {\n assertValidBudget(uncertain, `budget restore uncertainReservations[${index}]`)\n // The child ran (or may have run) without a settle record: its telemetry is unknown, so the\n // pool charges the full declared ceiling and reports the balance as a ceiling, never a\n // measurement.\n tokensTainted = true\n usdMeasured = false\n freeTokens -= uncertain.maxTokens\n committedTokens += uncertain.maxTokens\n freeIterations -= uncertain.maxIterations\n committedIterations += uncertain.maxIterations\n if (usdCapped) {\n if (uncertain.maxUsd === undefined) {\n // No child dollar ceiling existed, so the root's remaining dollar capacity is not safe.\n usdTainted = true\n committedUsd += freeUsd > 0 ? freeUsd : 0\n freeUsd = 0\n } else {\n freeUsd -= uncertain.maxUsd\n committedUsd += uncertain.maxUsd\n }\n }\n }\n\n return {\n reserve,\n reconcile,\n spendFrom: foldUsage,\n readout,\n observe,\n assertNoOpenTickets,\n }\n}\n","import { ValidationError } from '../../errors'\nimport type { Executor } from './types'\n\n// Node clamps larger delays to 1 ms instead of waiting, so long budgets must be armed in chunks.\nconst MAX_TIMER_DELAY_MS = 2_147_483_647\n\nexport const DEFAULT_SUCCESSFUL_SHUTDOWN_MS = 5_000\nconst TEARDOWN_ACKNOWLEDGEMENT_MS = 250\n\n/** Arm one wall-clock deadline without keeping the Node.js process alive. */\nexport function armDeadlineTimer(delayMs: number, onDeadline: () => void): () => void {\n const deadlineAtMs = Date.now() + Math.max(0, delayMs)\n let cleared = false\n let timer: ReturnType<typeof setTimeout> | undefined\n\n const arm = (): void => {\n if (cleared) return\n const remainingMs = Math.max(0, deadlineAtMs - Date.now())\n timer = setTimeout(\n () => {\n if (cleared) return\n if (Date.now() >= deadlineAtMs) onDeadline()\n else arm()\n },\n Math.min(remainingMs, MAX_TIMER_DELAY_MS),\n )\n if (typeof timer.unref === 'function') timer.unref()\n }\n\n arm()\n return () => {\n cleared = true\n if (timer !== undefined) clearTimeout(timer)\n }\n}\n\n/**\n * Resolve a spawned child's duration into one absolute cutoff. An omitted child deadline inherits\n * the parent cutoff; an explicit child duration may shorten, but never extend, that cutoff.\n */\nexport function boundedChildDeadlineAt(\n parentDeadlineAtMs: number,\n childDeadlineMs: number | undefined,\n nowMs: number,\n): number | undefined {\n const parent = parentDeadlineAtMs > 0 ? parentDeadlineAtMs : undefined\n const child = childDeadlineMs === undefined ? undefined : nowMs + childDeadlineMs\n if (parent === undefined) return child\n if (child === undefined) return parent\n return Math.min(parent, child)\n}\n\n/** Invoke teardown once and bound how long the runtime waits for its acknowledgement. A hard\n * execution deadline always wins; without one, numeric grace gets a short acknowledgement\n * allowance and a brutal kill gets only that allowance. Explicit `infinity` remains unbounded\n * only when no execution deadline exists. The losing promise stays observed. */\nexport async function teardownExecutor<Out>(\n executor: Executor<Out>,\n grace: number | 'brutalKill' | 'infinity',\n deadlineAtMs: number | undefined,\n now: () => number,\n): Promise<void> {\n const work = Promise.resolve(executor.teardown(grace))\n\n const requestedWaitMs =\n grace === 'infinity'\n ? undefined\n : grace === 'brutalKill'\n ? TEARDOWN_ACKNOWLEDGEMENT_MS\n : grace + TEARDOWN_ACKNOWLEDGEMENT_MS\n // The execution cutoff stops new work; cleanup still gets a small, bounded acknowledgement\n // window after that cutoff. Otherwise an already-resolved brutal kill invoked exactly at the\n // deadline would be mislabeled as a cleanup failure without receiving one microtask.\n const deadlineWaitMs =\n deadlineAtMs === undefined\n ? undefined\n : Math.max(0, deadlineAtMs - now()) + TEARDOWN_ACKNOWLEDGEMENT_MS\n const waitMs =\n requestedWaitMs === undefined\n ? deadlineWaitMs\n : deadlineWaitMs === undefined\n ? requestedWaitMs\n : Math.min(requestedWaitMs, deadlineWaitMs)\n\n let receipt: { destroyed: boolean }\n if (waitMs === undefined) {\n receipt = await work\n } else if (waitMs <= 0) {\n void work.catch(() => undefined)\n throw new ValidationError('executor teardown did not acknowledge before its deadline')\n } else {\n let timer: ReturnType<typeof setTimeout> | undefined\n const timedOut = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(\n () =>\n reject(new ValidationError(`executor teardown did not acknowledge within ${waitMs}ms`)),\n waitMs,\n )\n })\n try {\n receipt = await Promise.race([work, timedOut])\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n }\n }\n\n if (!receipt.destroyed) {\n throw new ValidationError('executor teardown reported destroyed=false')\n }\n}\n","/**\n *\n * `rollingDispatch` — the REFILLING dispatch policy over a `Scope`. It keeps `width` children in\n * flight and admits the next queued unit of work the instant one settles, instead of waiting for\n * a whole round to drain (`fanout`) or for a driver to decide again (`spawn → await → spawn`).\n *\n * The gap it closes: `fanout` opens every item at once and then drains — one round, no refill —\n * and a driver brain's manual loop opens one worker per model turn. Between those two there was\n * nothing that holds N slots full, which is why a 5-worker run can peak at 2 live workers and sit\n * ~50% idle. This is a policy over the EXISTING `Scope.spawn` / `Scope.next` primitives: it adds\n * no second admission path, so the conserved budget pool stays the only fence on total work and\n * `width` is only a fence on simultaneous work.\n *\n * Fail-closed by construction: an admission rejection (`budget-exhausted` / `depth-exceeded`) is\n * recorded and STOPS further admission — the loop then drains what is already live and returns.\n * It never retries a rejected spawn against the same pool, and it never spawns past `width`.\n *\n * ── The concurrency-cap ledger (read this before adding a fourth cap) ──────────────────────────\n *\n * Three unrelated caps bound \"how much runs at once\" in this stack, at three different layers.\n * They are NOT aware of each other, and the smallest one silently wins:\n *\n * 1. `SuperviseOptions.maxLiveWorkers` (`src/runtime/supervise/supervise.ts`) — supervised-tree\n * level. One shared Scope counter bounds every spawned manager and leaf in the recursive tree;\n * `spawn_agent` fails closed with `error: 'max-live-workers'` past it. Unset ⇒ NO tree cap.\n * `CoordinationToolsOptions.maxLiveWorkers` remains the local form for a toolbox mounted on a\n * caller-owned Scope that has no tree limit.\n * 2. `SandboxLineage`'s `maxConcurrency` / `DEFAULT_FORK_CONCURRENCY = 4`\n * (`src/runtime/sandbox-lineage.ts`) — kernel level. How many BOXES one `runAgentRounds` fork wave\n * provisions at once. It bounds a single leaf's fanout, not the supervisor's worker count.\n * 3. A host's own live-box governor (e.g. the kernel's `ComputeGovernor`, `maxSandboxes = 4`) — fleet\n * level. How many sandboxes may exist across the whole host process.\n *\n * The honest effective limit on simultaneous WORKERS is the minimum of the caps that apply to the\n * worker layer — (1) and (3). (2) is a different unit (boxes per fork wave inside one leaf) and\n * must not be min'd into it, or a 4-way fork inside one worker reads as a 4-worker ceiling.\n * `effectiveConcurrency` computes that minimum in one place so a host derives ONE number and\n * passes it to BOTH `maxLiveWorkers` and this dispatcher's `width`, instead of leaving a fleet\n * governor of 4 and an unset worker fence as unrelated numbers.\n *\n * ── Why this is not a copy of the kernel's batch loop ──────────────────────────────────────────\n *\n * `runBatch` (`src/runtime/run-loop.ts`) runs the same hold-N-slots-full shape over the KERNEL's\n * substrate: bare promises in a `Set`, raced with `Promise.race`, bounded by `maxConcurrency`.\n * This one runs it over the SUPERVISOR's substrate — `Scope.spawn`'s atomic reservation against\n * the conserved pool, `Scope.next`'s journaled settlement cursor, and the blob store behind each\n * result. Neither can be expressed in the other's terms without dragging its whole substrate\n * along: the kernel loop has no budget to reserve and no cursor to order settlements by, and this\n * one cannot race raw promises because a settlement is only real once it is journaled. The shape\n * repeating across the two deliberate layers is resonance, not duplication — do not \"unify\" them\n * into a shared helper that would have to know about both.\n *\n * @experimental\n */\n\nimport { ValidationError } from '../../errors'\nimport type { Agent, Budget, NodeId, Scope, Settled, SpawnOpts } from './types'\n\n/** One unit of queued work: the agent to run, its task, and the spawn options (budget + label).\n * `nextUnit` mints these lazily so a queue can be generated, re-ordered, or grown while the\n * dispatcher runs. */\nexport interface DispatchUnit<Out> {\n readonly agent: Agent<unknown, Out>\n readonly task: unknown\n readonly opts: SpawnOpts\n}\n\n/** Why the dispatcher stopped admitting work. `drained` = the queue ran dry (the ordinary end);\n * `not-admitted` = the conserved pool or the depth ceiling refused a spawn; `stopped` = the\n * caller's `shouldStop` returned true; `aborted` = the scope's signal fired. */\nexport type DispatchStopReason = 'drained' | 'not-admitted' | 'stopped' | 'aborted'\n\nexport interface RollingDispatchOptions<Out> {\n /**\n * How many children to hold in flight. Must be a positive integer. This is a SIMULTANEITY fence\n * only — the conserved pool still bounds total work, and a `width` larger than the pool can\n * afford simply hits `not-admitted` sooner. Derive it with `effectiveConcurrency` when the host\n * also runs a fleet-level box governor.\n */\n readonly width: number\n /**\n * Produce the next unit of work, or `undefined` when the queue is dry. Called only when a slot\n * is free, so a caller may compute the next unit from what has already settled (the point of a\n * refilling dispatcher: the queue is allowed to react). Never called after a stop.\n */\n nextUnit(): DispatchUnit<Out> | undefined | Promise<DispatchUnit<Out> | undefined>\n /**\n * Called once per settlement, in cursor order, BEFORE the freed slot is refilled — so an\n * `onSettled` that appends to the caller's queue is visible to the very next `nextUnit`.\n */\n onSettled?(settled: Settled<Out>): void | Promise<void>\n /**\n * Consulted before each admission. `true` stops admitting; the already-live children are still\n * drained to completion (no orphan, no lost settlement). Use it for a progress/plateau rule.\n */\n shouldStop?(): boolean\n}\n\nexport interface DispatchReport<Out> {\n /** Every settlement, in the order `scope.next()` yielded them. */\n readonly settled: ReadonlyArray<Settled<Out>>\n /** How many children this dispatcher admitted. */\n readonly admitted: number\n /** Admission rejections, in order — `label: reason`. Non-empty ⇒ the pool or depth fenced. */\n readonly rejected: ReadonlyArray<string>\n readonly stopReason: DispatchStopReason\n /** The highest simultaneous live count actually reached — the number to compare against\n * `width` when asking \"did the slots really stay full?\" */\n readonly peakLive: number\n}\n\n/**\n * Run the refilling dispatch loop over `scope` until the queue is dry (or a stop fires) and every\n * admitted child has settled. Returns the settlements in cursor order plus the admission ledger.\n *\n * The loop is: fill free slots from `nextUnit` → `await scope.next()` → deliver the settlement →\n * refill → repeat. Because the refill happens immediately after each settlement rather than after\n * a whole round, a slow child never idles the other slots.\n */\nexport async function rollingDispatch<Out>(\n scope: Scope<Out>,\n opts: RollingDispatchOptions<Out>,\n): Promise<DispatchReport<Out>> {\n if (!Number.isInteger(opts.width) || opts.width < 1) {\n throw new ValidationError(\n `rollingDispatch: width must be a positive integer, got ${String(opts.width)}`,\n )\n }\n\n const settled: Settled<Out>[] = []\n const rejected: string[] = []\n const live = new Set<NodeId>()\n let admitted = 0\n let peakLive = 0\n let queueDry = false\n let stopReason: DispatchStopReason = 'drained'\n\n // Fill every free slot from the queue. Returns false when nothing further may be admitted\n // (queue dry, caller stop, pool/depth rejection, or abort) — the caller then only drains.\n const fill = async (): Promise<void> => {\n while (live.size < opts.width) {\n if (queueDry) return\n if (scope.signal.aborted) {\n stopReason = 'aborted'\n queueDry = true\n return\n }\n if (opts.shouldStop?.() === true) {\n stopReason = 'stopped'\n queueDry = true\n return\n }\n const unit = await opts.nextUnit()\n if (unit === undefined) {\n queueDry = true\n return\n }\n // The ONE admission path: the scope's own atomic reservation. A rejection is terminal for\n // this dispatcher — the pool is conserved, so retrying the same spawn cannot succeed until\n // a live child refunds, and admitting a DIFFERENT unit past a rejection would silently\n // reorder the caller's queue.\n const res = scope.spawn(unit.agent, unit.task, unit.opts)\n if (!res.ok) {\n rejected.push(`${unit.opts.label}: ${res.reason}`)\n stopReason = 'not-admitted'\n queueDry = true\n return\n }\n live.add(res.handle.id)\n admitted += 1\n if (live.size > peakLive) peakLive = live.size\n }\n }\n\n await fill()\n while (live.size > 0) {\n const s = await scope.next()\n // `next()` is null only when the scope's live set is empty; this dispatcher may share the\n // scope with children it did not admit, so treat null as \"nothing of ours left to await\".\n if (s === null) break\n live.delete(s.handle.id)\n settled.push(s)\n await opts.onSettled?.(s)\n await fill()\n }\n\n return { settled, admitted, rejected, stopReason, peakLive }\n}\n\n/**\n * Free worker slots under a simultaneity cap: `cap - live`, floored at 0, or `null` when there is\n * no cap (the conserved pool is then the only fence and \"free slots\" is not a finite number).\n * The one place the answer is computed, so the driver-facing tool payload and a dispatcher agree.\n */\nexport function freeSlots(liveCount: number, cap: number | undefined): number | null {\n if (cap === undefined || cap <= 0) return null\n return Math.max(0, cap - liveCount)\n}\n\n/** The caps a host can set on simultaneous work. See the ledger in this module's header for what\n * each one actually bounds. */\nexport interface ConcurrencyCaps {\n /** Supervisor level: max spawned-but-unsettled workers. */\n readonly maxLiveWorkers?: number\n /** Fleet level: max live sandboxes/boxes across the host process (a `ComputeGovernor`-style\n * cap). Applies to the worker layer, so it participates in the minimum. */\n readonly maxSandboxes?: number\n}\n\n/**\n * The ONE honest effective limit on simultaneous workers: the minimum of the caps that actually\n * bound the worker layer. Ignores unset/non-positive caps; returns `undefined` when no cap applies\n * (uncapped — the conserved pool remains the only fence).\n *\n * Deliberately does NOT fold in `SandboxLineage`'s fork concurrency: that bounds boxes inside ONE\n * leaf's fork wave, a different unit. Folding it in would report a 4-worker ceiling for what is\n * really a 4-box fanout inside a single worker.\n *\n * Use it once, at the top of a run, and pass the result to BOTH `maxLiveWorkers` and a\n * dispatcher's `width` — that is what turns three unrelated numbers into one.\n */\nexport function effectiveConcurrency(caps: ConcurrencyCaps): number | undefined {\n const applicable = [caps.maxLiveWorkers, caps.maxSandboxes].filter(\n (c): c is number => typeof c === 'number' && c > 0,\n )\n if (applicable.length === 0) return undefined\n return Math.min(...applicable)\n}\n\n/** Convenience: a `DispatchUnit` factory over a fixed array of tasks, for the common case where\n * the queue is known up front and only the refill behavior is wanted. */\nexport function queueOf<Out>(\n units: ReadonlyArray<{ agent: Agent<unknown, Out>; task: unknown; label: string }>,\n budget: Budget,\n): () => DispatchUnit<Out> | undefined {\n let i = 0\n return () => {\n const u = units[i]\n if (u === undefined) return undefined\n i += 1\n return { agent: u.agent, task: u.task, opts: { budget, label: u.label } }\n }\n}\n","/**\n *\n * WAIT-STATES — a supervision-tree node that waits on wall-clock time or an external condition\n * without holding a worker, an executor, a sandbox, or a single LLM turn.\n *\n * A long-horizon run spends most of its wall-clock NOT computing: waiting for CI to finish,\n * for a nightly job to land, for a human to reply, for a rate-limit window to reopen. Before\n * this, the only way to express that was to keep something alive and re-ask — which spends\n * driver tokens per re-ask and pins a process to the wait.\n *\n * Two node kinds, both first-class:\n * - `timer` — wake at an ABSOLUTE wall-clock instant (`untilMs`).\n * - `poll` — re-run a named predicate every `intervalMs` until it returns true, or until an\n * absolute `timeoutAtMs` passes (CI status, file existence, an HTTP probe, an\n * inbox message).\n *\n * ── How this differs from `await_event`'s 15s poll fence (`DEFAULT_AWAIT_EVENT_TIMEOUT_MS`) ──\n *\n * They look similar and are not the same mechanism. `await_event` is an IN-RUN RENDEZVOUS: the\n * driver blocks on the coordination bus for the next event from a live worker, and the 15s fence\n * exists only so a remote MCP request does not exceed the client's timeout — the caller re-polls.\n * Every re-poll is another driver inference turn (real tokens) against a process that must stay\n * up, and nothing about that wait is recorded: kill the process and the wait is simply gone.\n *\n * A wait-state is a NODE, not a call. It has a node id in the tree, a journal record carrying its\n * ABSOLUTE deadline, and it settles through the same `Scope.next()` cursor as any worker. Nobody\n * is blocked on it — the driver can stop reasoning entirely, and the process can die. Cost while\n * waiting: zero LLM calls, zero executor, zero sandbox, zero conserved budget (a wait reserves\n * nothing from the pool). The only in-process residue is one timer entry.\n *\n * ── Why probes are NAMED, not passed as closures ────────────────────────────────────────────\n *\n * A wait must survive a process restart with its original deadline intact, and a closure cannot\n * be journaled. So a `poll` names its predicate (`probe: 'ci-green'`) and the run resolves it\n * through a `WaitProbeRegistry`. A brand-new process re-resolves the SAME name against its own\n * registry and re-arms the wait — which is what makes \"kill the box, the wait keeps waiting\"\n * true rather than aspirational.\n *\n * Absolute instants for the same reason: `untilMs` / `timeoutAtMs` are epoch ms, not durations,\n * so a resumed wait counts down from the original arm, not from the restart. `timerAt`/`pollFor`\n * build them from a duration when that is what the caller has.\n *\n * @experimental\n */\n\nimport { ValidationError } from '../../errors'\n\n/** What a wait node is waiting for. Both variants carry ABSOLUTE epoch-ms instants so a wait\n * re-armed by a later process keeps the deadline the first process set. */\nexport type WaitSpec =\n | {\n readonly kind: 'timer'\n /** Absolute epoch ms to wake at. A past instant fires immediately. */\n readonly untilMs: number\n }\n | {\n readonly kind: 'poll'\n /** Name of the predicate in the run's `WaitProbeRegistry`. Named (not a closure) so a\n * resumed process can re-resolve it — see the module header. */\n readonly probe: string\n /** How often to re-run the predicate, in ms. Must be > 0. */\n readonly intervalMs: number\n /** Absolute epoch ms after which an unfired poll settles `timeout`. Omit = no timeout\n * (then the run's own deadline is the only bound, and a run WITH a deadline refuses an\n * unbounded poll — see `assertWaitWithinDeadline`). */\n readonly timeoutAtMs?: number\n /** Opaque JSON handed to the probe on every check. Journaled with the spec, so a resumed\n * probe gets the same arguments. */\n readonly args?: Record<string, unknown>\n }\n\n/** Build a `timer` spec from a DURATION. The instant is resolved once, at arm time — a resumed\n * wait re-uses the journaled instant, never a fresh `now + ms`. */\nexport function timerAt(ms: number, now: number): WaitSpec {\n return { kind: 'timer', untilMs: now + ms }\n}\n\n/** Build a bounded `poll` spec from a duration. */\nexport function pollFor(\n probe: string,\n opts: {\n readonly intervalMs: number\n readonly timeoutMs?: number\n readonly args?: Record<string, unknown>\n },\n now: number,\n): WaitSpec {\n return {\n kind: 'poll',\n probe,\n intervalMs: opts.intervalMs,\n ...(opts.timeoutMs !== undefined ? { timeoutAtMs: now + opts.timeoutMs } : {}),\n ...(opts.args ? { args: opts.args } : {}),\n }\n}\n\n/**\n * A named predicate a `poll` node re-checks. Returns true when the condition it watches has\n * flipped. A throw is treated as \"not yet\" (an unreachable CI endpoint is not a settled answer),\n * and is counted in the outcome's `probeErrors` so a probe that never works is visible rather\n * than silently polling forever.\n */\nexport type WaitProbe = (\n args: Record<string, unknown> | undefined,\n signal: AbortSignal,\n) => boolean | Promise<boolean>\n\n/** Resolves a `poll` spec's `probe` name to its predicate. Threaded through `SupervisorOpts` so\n * the SAME registry a fresh run used is what a resumed run re-resolves against. */\nexport interface WaitProbeRegistry {\n resolve(name: string): WaitProbe | undefined\n}\n\n/** Registry over a plain name→predicate record. */\nexport function createWaitProbes(entries: Record<string, WaitProbe>): WaitProbeRegistry {\n const map = new Map(Object.entries(entries))\n return { resolve: (name) => map.get(name) }\n}\n\n/** The `out` a settled wait node delivers through `Scope.next()`. `settled` is the outcome the\n * caller branches on: `'fired'` = the timer reached its instant or the predicate flipped;\n * `'timeout'` = a bounded poll gave up. A timeout is a first-class ANSWER, not a failure — a\n * wait only settles `down` when it is cancelled or aborted. */\nexport interface WaitOutcome {\n /** Tag for `isWaitOutcome` — a wait outcome arrives on the same cursor as worker outputs. */\n readonly waitOutcome: true\n readonly kind: WaitSpec['kind']\n readonly settled: 'fired' | 'timeout'\n readonly label: string\n /** The absolute instant this wait was armed for (timer `untilMs` / poll `timeoutAtMs`); absent\n * for an unbounded poll. */\n readonly untilMs?: number\n /** Epoch ms the wait was FIRST armed — preserved across a resume, so `wokenAt - armedAt` is\n * the true end-to-end wait even when it spanned several processes. */\n readonly armedAt: number\n readonly wokenAt: number\n /** Predicate checks performed in the process that settled it (a resume restarts this count). */\n readonly polls: number\n /** Probe checks that threw (counted, not fatal). */\n readonly probeErrors: number\n /** True when a later process re-armed this wait from the journal instead of creating it. */\n readonly resumed: boolean\n}\n\n/** Narrow a settlement's `out` to a wait outcome — a wait settles on the SAME cursor as workers,\n * so a driver that mixes them tags them apart with this. */\nexport function isWaitOutcome(value: unknown): value is WaitOutcome {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { waitOutcome?: unknown }).waitOutcome === true\n )\n}\n\n/** A wait recorded in the journal that never woke — what a resumed run re-arms. */\nexport interface PendingWait {\n readonly id: string\n readonly label: string\n readonly spec: WaitSpec\n /** The ORIGINAL arm instant. A re-armed wait keeps it, so its deadline never slides. */\n readonly armedAt: number\n /** The wait ordinal in its parent scope, so a resumed scope continues past it. */\n readonly ordinal: number\n}\n\n/** Reject reasons for `Scope.wait`, mirroring `Scope.spawn`'s fail-closed admission shape. */\nexport type WaitRejection = 'invalid-spec' | 'unknown-probe' | 'deadline-exceeded'\n\n/** The absolute instant a spec is bounded by, or `undefined` for an unbounded poll. */\nexport function waitUntil(spec: WaitSpec): number | undefined {\n return spec.kind === 'timer' ? spec.untilMs : spec.timeoutAtMs\n}\n\n/** Structural validation, independent of the run. Returns null when the spec is usable. */\nexport function validateWaitSpec(spec: WaitSpec): string | null {\n if (spec.kind === 'timer') {\n return Number.isFinite(spec.untilMs) ? null : 'timer.untilMs must be a finite epoch-ms instant'\n }\n if (typeof spec.probe !== 'string' || spec.probe.length === 0) {\n return 'poll.probe must be a non-empty probe name'\n }\n if (!Number.isFinite(spec.intervalMs) || spec.intervalMs <= 0) {\n return 'poll.intervalMs must be > 0'\n }\n if (spec.timeoutAtMs !== undefined && !Number.isFinite(spec.timeoutAtMs)) {\n return 'poll.timeoutAtMs must be a finite epoch-ms instant'\n }\n return null\n}\n\n/**\n * A wait must not silently outlive the run's HARD wall-clock ceiling. When the conserved pool\n * carries an absolute `deadlineMs`, a wait bounded past it — or an unbounded poll — is REFUSED at\n * arm time (`deadline-exceeded`) rather than sleeping through a ceiling the caller already set.\n * The alternative (extending the pool's deadline to cover the wait) would let a wait override a\n * hard budget guard, which is exactly what mechanic D forbids; a run that intends week-long waits\n * either sets a deadline that covers them or sets none.\n */\nexport function assertWaitWithinDeadline(spec: WaitSpec, deadlineMs: number): boolean {\n if (deadlineMs <= 0) return true\n const until = waitUntil(spec)\n if (until === undefined) return false\n return until <= deadlineMs\n}\n\n/** How a wait finished, as the scope's settle path sees it. */\nexport type WaitResolution =\n | { readonly kind: 'woke'; readonly outcome: WaitOutcome }\n | { readonly kind: 'cancelled'; readonly reason: string }\n\nexport interface RunWaitArgs {\n readonly spec: WaitSpec\n readonly label: string\n readonly armedAt: number\n readonly resumed: boolean\n readonly signal: AbortSignal\n readonly probes?: WaitProbeRegistry\n readonly now: () => number\n /** Injected sleeper so a test drives a week-long wait in microseconds. Defaults to\n * `setTimeout`, cleared on abort so a cancelled wait never keeps the event loop alive. */\n readonly sleep?: (ms: number, signal: AbortSignal) => Promise<void>\n}\n\n/**\n * Drive one wait to its resolution. Spends nothing: a `timer` is one sleep, a `poll` is a sleep\n * between predicate checks. No LLM call, no executor, no box, no budget reservation.\n */\nexport async function runWait(args: RunWaitArgs): Promise<WaitResolution> {\n const { spec, label, armedAt, resumed, signal, now } = args\n const sleep = args.sleep ?? defaultSleep\n if (signal.aborted) return { kind: 'cancelled', reason: 'aborted before arming' }\n\n if (spec.kind === 'timer') {\n const remaining = spec.untilMs - now()\n if (remaining > 0) await sleep(remaining, signal)\n if (signal.aborted) return { kind: 'cancelled', reason: 'wait aborted' }\n return {\n kind: 'woke',\n outcome: outcome('timer', 'fired', label, spec.untilMs, armedAt, now(), 0, 0, resumed),\n }\n }\n\n const probe = args.probes?.resolve(spec.probe)\n if (!probe) {\n // Unresolvable at RUN time (it passed admission, so this is a registry that changed under a\n // resumed run). Fail loud rather than polling a predicate that can never answer.\n throw new ValidationError(\n `wait '${label}': poll probe '${spec.probe}' is not registered in this run's WaitProbeRegistry`,\n )\n }\n let polls = 0\n let probeErrors = 0\n for (;;) {\n if (signal.aborted) return { kind: 'cancelled', reason: 'wait aborted' }\n polls += 1\n let fired = false\n try {\n fired = await probe(spec.args, signal)\n } catch {\n probeErrors += 1\n }\n if (fired) {\n return {\n kind: 'woke',\n outcome: outcome(\n 'poll',\n 'fired',\n label,\n spec.timeoutAtMs,\n armedAt,\n now(),\n polls,\n probeErrors,\n resumed,\n ),\n }\n }\n if (spec.timeoutAtMs !== undefined && now() >= spec.timeoutAtMs) {\n return {\n kind: 'woke',\n outcome: outcome(\n 'poll',\n 'timeout',\n label,\n spec.timeoutAtMs,\n armedAt,\n now(),\n polls,\n probeErrors,\n resumed,\n ),\n }\n }\n const nextCheck =\n spec.timeoutAtMs === undefined\n ? spec.intervalMs\n : Math.min(spec.intervalMs, Math.max(0, spec.timeoutAtMs - now()))\n await sleep(nextCheck, signal)\n }\n}\n\nfunction outcome(\n kind: WaitSpec['kind'],\n settled: 'fired' | 'timeout',\n label: string,\n untilMs: number | undefined,\n armedAt: number,\n wokenAt: number,\n polls: number,\n probeErrors: number,\n resumed: boolean,\n): WaitOutcome {\n return {\n waitOutcome: true,\n kind,\n settled,\n label,\n ...(untilMs !== undefined ? { untilMs } : {}),\n armedAt,\n wokenAt,\n polls,\n probeErrors,\n resumed,\n }\n}\n\n/** `setTimeout` that resolves early (and clears) when the scope aborts, so a cancelled wait\n * releases the event loop immediately instead of holding the process to its deadline. */\nfunction defaultSleep(ms: number, signal: AbortSignal): Promise<void> {\n if (ms <= 0 || signal.aborted) return Promise.resolve()\n return new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n function onAbort(): void {\n clearTimeout(timer)\n resolve()\n }\n signal.addEventListener('abort', onAbort, { once: true })\n })\n}\n","/**\n *\n * The reactive `Scope` impl (KEYSTONE, build step 4 + the step-8 adapter).\n *\n * An `Agent.act` runs inside a `Scope`. It `spawn`s children dynamically and reacts to\n * them via `next()`. The scope owns ONE in-memory nursery — the authoritative live set —\n * and is the single place that drives a child's lifecycle: reserve budget atomically,\n * resolve a `Executor` through the open registry, run it (one-shot OR streaming),\n * fold its normalized `UsageEvent`s into a conserved `Spend`, reconcile the reservation\n * (refunding the unspent remainder), persist the result blob + journal records, and\n * deliver the `Settled` through the `next()` cursor.\n *\n * Three invariants this impl enforces by construction:\n * - `next()` is a ray.wait n=1 cursor over THIS scope's live set; it assigns the\n * monotonic `seq` (the recorded cursor order) at the moment it yields a settlement, so\n * replay re-delivers in the identical order — `seq` is never wall-clock.\n * - Budget is reserved at spawn and reconciled at settle through the shared `BudgetPool`,\n * so `spawn` fails CLOSED on an exhausted pool and total ≡ free + reserved + committed.\n * - `view` reads the in-memory nursery, never the journal — O(live), synchronous.\n *\n * The settle path is the only writer of journal `settled` events; the spawn path the only\n * writer of `spawned` events. The result blob is `put` BEFORE the journal `settled` record\n * references its `outRef`, so a crash can never leave a journaled ref with no blob.\n *\n * @stable\n */\n\nimport {\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n type Sha256Digest,\n sha256DigestSchema,\n} from '@tangle-network/agent-interface'\nimport { contentAddress } from '../../durable/spawn-journal'\nimport { ValidationError } from '../../errors'\nimport { notifyRuntimeHookEvent, type RuntimeHooks } from '../../runtime-hooks'\nimport type { Iteration } from '../types'\nimport { addTokenUsage, cloneTokenUsage, zeroTokenUsage } from '../util'\nimport { type BudgetPool, createBudgetPool, type ReservationTicket } from './budget'\nimport {\n armDeadlineTimer,\n boundedChildDeadlineAt,\n DEFAULT_SUCCESSFUL_SHUTDOWN_MS,\n teardownExecutor,\n} from './deadline'\nimport { freeSlots } from './dispatch'\nimport { executableAgentSpecSnapshot } from './executable-spec'\nimport {\n authoredProfileDigest,\n knownExecutionBindingReceipt,\n knownMaterializationReceipt,\n newExecutionAttemptId,\n runtimeOwnedDeferredExecutorRuntime,\n runtimeOwnedExecutorExecutionBinding,\n runtimeOwnedExecutorMaterialization,\n runtimeOwnedExecutorProviderEvidence,\n runtimeOwnedPendingExecutorMaterialization,\n unknownExecutionBindingReceipt,\n unknownMaterializationReceipt,\n} from './materialization'\nimport {\n DEFAULT_STALL_AFTER_MS,\n type ExecutorProgress,\n readWorkerProgress,\n type WorkerProgress,\n} from './progress'\nimport { detachedSnapshot } from './snapshot'\nimport { captureWorkerTraceEvidence } from './trace-evidence'\nimport type { TraceSource } from './trace-source'\nimport { runtimeOwnedNestedDriverTreeRoot } from './tree-key'\nimport type {\n Agent,\n AgentSpec,\n Budget,\n DefaultVerdict,\n ExecutionBindingReceipt,\n Executor,\n ExecutorContext,\n ExecutorExecutionBinding,\n ExecutorNodeContext,\n ExecutorRegistry,\n ExecutorResult,\n Handle,\n NodeExecutionIdentity,\n NodeId,\n NodeSnapshot,\n NodeStatus,\n ProfileMaterializationReceipt,\n ProviderModelExecutionEvidence,\n ResultBlobStore,\n ResumedKeyState,\n ResumedWork,\n Scope,\n Settled,\n SpawnJournal,\n SpawnOpts,\n SpawnPrior,\n SpawnRejection,\n Spend,\n TreeView,\n UsageEvent,\n WaitOpts,\n WorkerTraceEvidence,\n} from './types'\nimport {\n assertWaitWithinDeadline,\n type PendingWait,\n runWait,\n validateWaitSpec,\n type WaitOutcome,\n type WaitProbeRegistry,\n type WaitRejection,\n type WaitSpec,\n} from './wait'\nimport { type WorkerTraceResolver, workerTraceSeamKey } from './worker-trace'\n\n/** Construction args for `createScope`. The supervisor threads the shared pool, journal,\n * blob store, and executor registry through; `depth`/`maxDepth` pair the runtime\n * recursion ceiling with the conserved pool (R3). */\nexport interface ScopeArgs {\n /** This scope's owning node id — children get `${parentId}:s${seq}` ids. */\n readonly parentId: NodeId\n /** Journal/blob root key the supervisor `beginTree`'d. */\n readonly root: NodeId\n /** The reservation pool for this scope: the root total or one nested allocated partition. */\n readonly pool: BudgetPool\n /** Append-only spawn journal; this scope writes `spawned` + `settled` records. */\n readonly journal: SpawnJournal\n /** Content-addressed result store backing `outRef` rehydration. */\n readonly blobs: ResultBlobStore\n /** The open executor resolver (BYO → router/inline → registered harness factory). */\n readonly executors: ExecutorRegistry\n /** Predicate resolver for `poll` wait-states. Absent ⇒ `wait` refuses a `poll` with\n * `unknown-probe`; `timer` waits never touch it. */\n readonly probes?: WaitProbeRegistry\n /** Injected sleeper for wait-states — a test drives a week-long timer in microseconds. */\n readonly waitSleep?: (ms: number, signal: AbortSignal) => Promise<void>\n /** Per-spawn executor-construction seams (sandbox client, router config, cli bin). */\n readonly seams: Readonly<Record<string, unknown>>\n /** This scope's recursion depth (root = 0). */\n readonly depth: number\n /** Runtime recursion-depth ceiling — a spawn past it fails closed `depth-exceeded`. */\n readonly maxDepth?: number\n /** Root-owned limit on live spawned workers across this scope and every nested scope. */\n readonly maxLiveWorkers?: number\n /** @internal Shared counter inherited by nested scopes. Callers set `maxLiveWorkers`; the root\n * scope creates this state once and passes the same object through its recursion seam. */\n readonly liveWorkerCapacity?: LiveWorkerCapacityState\n /** Abort signal for this scope; an abort cascades into every live child's executor. */\n readonly signal: AbortSignal\n /** Injected clock — keeps the journal `at` timestamp deterministic in tests. */\n readonly now?: () => number\n /** Lifecycle stream sink. `spawn` emits `agent.spawn`, `next` emits `agent.child` — the\n * SAME stream `runAgentRounds`/`tool-loop` feed, so the recursive tree is ONE observable stream\n * (the topology viewer reads it). Undefined ⇒ the journal stays the only record. */\n readonly hooks?: RuntimeHooks\n /**\n * Trace context to hand down to each spawned worker (`SupervisorOpts.workerTrace`). Called with\n * THIS scope's own `parentId` — the node doing the spawning — and the resolved context is seeded\n * onto each child's `ExecutorContext` under `workerTraceSeamKey`. Absent (the untraced default)\n * ⇒ no seam is seeded and no worker environment is touched.\n */\n readonly workerTrace?: WorkerTraceResolver\n /**\n * Present when this run RECORDS spans but the worker backend has NO channel to carry the trace\n * context (`WORKER_TRACE_PROPAGATION[backend] === false` — cli-worktree has no env\n * channel; router / router-tools / provider have no worker process). Each spawn then journals a\n * `trace-unpropagated` event naming the severed hop, so a child whose trace shows up as a\n * disconnected root is a recorded fact rather than a silent stranger. Absent ⇒ either the run\n * is untraced or the backend propagates; nothing is journaled.\n */\n readonly workerTraceUnpropagated?: {\n readonly backend: string\n readonly reason: 'no-env-channel' | 'no-worker-process' | 'caller-omitted'\n }\n /** @internal Trusted root-adapter publication channel. It is never exposed as a Scope method. */\n readonly ownerMaterialization?: {\n readonly runtime: NodeSnapshot['runtime']\n readonly authoredProfile?: unknown\n readonly attemptId: string\n readonly prior?: ProfileMaterializationReceipt\n readonly journalRoot?: NodeId\n readonly nodeId?: NodeId\n readonly requiredKnown?: boolean\n readonly onReceipt?: (\n materialization: ProfileMaterializationReceipt,\n binding: ExecutionBindingReceipt,\n ) => void\n }\n /**\n * Resume seam — set ONLY by the supervisor when `SupervisorOpts.resume` is on AND a non-empty\n * journal tree exists for this root. It carries the replayed committed work (so `scope.resume`\n * exposes it to a resume-aware `act`) and the recorded ordinal/cursor maxima the new counters\n * continue past, so a freshly-spawned child never reuses a journaled `seq`. Absent ⇒ fresh run.\n */\n readonly resumeFrom?: {\n readonly settled: ReadonlyArray<Settled<unknown>>\n readonly view: TreeView\n /** Highest `spawned` ordinal already journaled; new spawns start at `+1`. */\n readonly maxSpawnOrdinal: number\n /** Highest cursor `seq` already journaled; new settlements start at `+1`. */\n readonly maxCursorSeq: number\n /** Highest `waiting` ordinal already journaled; new waits start at `+1`. */\n readonly maxWaitOrdinal: number\n /** Waits journaled as armed but never woken — re-armed (same node id, same absolute deadline)\n * when `wait` is called again with the SAME label. */\n readonly waits: ReadonlyArray<PendingWait>\n /** Keyed assignments from the prior journal — what a keyed re-spawn resolves against. */\n readonly keys: ReadonlyMap<string, ResumedKeyState<unknown>>\n /** Prior committed spend summed off the journal (settled child work + metered inference). */\n readonly priorSpend: { readonly childWork: Spend; readonly driverInference: Spend }\n }\n}\n\ntype RuntimeOwnedProviderMeter = (\n spend: Spend,\n providerModel: ProviderModelExecutionEvidence,\n detail?: Record<string, unknown>,\n) => Promise<void>\n\n/** Runtime-owned provider evidence is written through this private scope capability. */\nconst runtimeOwnedProviderMeters = new WeakMap<object, RuntimeOwnedProviderMeter>()\n\n/** Mutable only inside Scope admission/release. Every nested scope receives this exact object. */\nexport interface LiveWorkerCapacityState {\n readonly max: number | undefined\n live: number\n}\n\n/**\n * Internal live-set entry. `settled` resolves once the child's executor has fully drained,\n * its reservation reconciled, and its result blob persisted; `next()` awaits these to drive\n * the cursor. `resolved` mirrors that terminal value synchronously so a concurrent `next()`\n * can pick the next undelivered settlement without re-racing. `delivered` guards exactly-once\n * delivery; `seq` is stamped by `next()`, never here.\n */\ninterface LiveChild {\n readonly id: NodeId\n status: NodeStatus\n runtime: NodeSnapshot['runtime']\n readonly ownedTreeRoot?: NodeId\n readonly budget: Budget\n readonly label: string\n readonly assignmentId?: string\n readonly identity?: NodeExecutionIdentity\n /** The semantic spawn key, when this child was spawned with one — the settle path folds the\n * terminal state back into the scope's key registry under it. */\n readonly key?: string\n spent: Spend\n outRef?: string\n /** Durable structured tool evidence once this executor is terminal. */\n trace?: WorkerTraceEvidence\n /** Provider-served model evidence once this executor has attempted inference. */\n providerModel?: import('./types').ProviderModelExecutionEvidence\n /** Exact terminal timestamp committed to the journal. */\n settledAt?: number\n /** Resolves with the terminal settlement WITHOUT a `seq` — `next()` stamps the seq. */\n readonly settled: Promise<PreSeqSettled>\n /** Synchronous mirror of `settled`'s value once it has resolved (else `undefined`). */\n resolved?: PreSeqSettled\n /** True once the EXECUTOR's own work is finished (artifact read or throw caught) — from then\n * on `settled` resolves without further executor progress (only persistence/teardown), so a\n * non-blocking drain may await it without waiting on live work. */\n executorDone: boolean\n /** True only after executor teardown returned `{ destroyed: true }`. A failed/unknown cleanup\n * retains the shared capacity slot so replacement work cannot exceed the physical live count. */\n cleanupConfirmed: boolean\n /** True once `next()` has yielded this child's settlement. */\n delivered: boolean\n /** The executor's out-of-band inbox, captured at spawn — backs `scope.send`. */\n readonly deliver?: (msg: unknown) => boolean\n /** The executor's optional live progress read, captured at spawn — backs `scope.progress`. */\n readonly readProgress?: () => ExecutorProgress | undefined\n /** The executor's optional live tool trace, captured at spawn — backs `scope.traceSource`. */\n readonly readTraceSource?: () => TraceSource | undefined\n /** Kernel-owned declaration of the exact execution plan, durable before `execute` starts. */\n materialization?: ProfileMaterializationReceipt\n /** One immutable record per concrete execution attempt. */\n executionBindings: ExecutionBindingReceipt[]\n /** Wall-clock of the spawn, and of the last metered usage event this child produced. Both are\n * stamped by the scope from the stream the conserved pool already meters, so EVERY executor —\n * including one that implements no progress read at all — has an observable liveness signal. */\n readonly startedAt: number\n lastActivityAt: number\n /** Present ONLY on a wait-state node. Its presence is what routes the settle path to the\n * `woken` journal event instead of `settled`, and what keeps a wait out of `inFlight`. */\n readonly wait?: {\n readonly spec: WaitSpec\n readonly armedAt: number\n readonly label: string\n armCommitted: boolean\n }\n}\n\n/** A child's terminal settlement before the cursor stamps the monotonic `seq`. A wait-state's\n * `done` carries a `WaitOutcome` as its `out` and a zero `spent` — waiting is free by type, not\n * by measurement. */\ntype PreSeqSettled =\n | {\n kind: 'done'\n out: unknown\n outRef: string\n verdict?: DefaultVerdict\n spent: Spend\n providerModel?: import('./types').ProviderModelExecutionEvidence\n trace: WorkerTraceEvidence\n /** A driver child's OWN-inference subtree total (from `Executor.metered()`) — journaled as a\n * `metered` event for this node, NOT reconciled (already debited live via `observe`). */\n metered?: Spend\n }\n | {\n kind: 'down'\n reason: string\n infra: boolean\n restartCount: number\n trace: WorkerTraceEvidence\n providerModel?: import('./types').ProviderModelExecutionEvidence\n /** A CRASHED driver child's partial OWN-inference subtree total — re-homed on the down path\n * too, so the journal matches the pool (which already debited it via `observe`). */\n metered?: Spend\n }\n\n/**\n * The recursion seam key. A `Scope` seeds a value of this on each child's\n * `ExecutorContext.seams` so a child whose executor is a DRIVER can mount a NESTED `Scope`\n * over the driver's reserved child allocation at `depth+1`. A leaf executor never reads it. Single-sourced\n * here so the scope and the driver-executor agree on the seam without a circular import.\n */\nexport const nestedScopeSeamKey = 'nested-scope'\n\n/**\n * The recursion seam value: mount a nested `Scope` for a driver child. `parentId` is the\n * driver child's own node id (so its children get `${nodeId}:s${ordinal}` ids and its\n * nested journal tree is namespaced under it); `root` is the journal tree key for the\n * nested tree (distinct from the parent's so cursor seqs never collide in the per-tree\n * guard). `depth` is `parent.depth + 1`. The nested scope spends from a child pool backed by\n * the driver's already-reserved allocation; it shares the parent's `journal`/`blobs` and\n * `executors` (a nested child resolves to leaf-or-driver through the same open registry).\n */\nexport interface NestedScopeSeam {\n /** Durable id of the driver child that owns the nested tree. */\n readonly nodeId: NodeId\n /** This scope's recursion depth — a nested scope runs at `depth + 1`. */\n readonly depth: number\n /** The runtime recursion-depth ceiling, paired with the conserved pool (R3). */\n readonly maxDepth?: number\n /** The journal tree key the parent scope writes to (used to namespace nested trees). */\n readonly journalRoot: NodeId\n /** Mount a nested scope rooted at `nestedRoot`, parented at this driver child's node id. */\n mount(nestedRoot: NodeId, signal: AbortSignal): Scope<unknown>\n}\n\ninterface DeferredOwnerSlot {\n ownerMaterialization?: NonNullable<ScopeArgs['ownerMaterialization']>\n}\n\nfunction makeNestedScopeSeam(\n args: ScopeArgs,\n liveWorkerCapacity: LiveWorkerCapacityState,\n childNodeId: NodeId,\n childBudget: Budget,\n childDeadlineAtMs: number | undefined,\n deferredOwner: DeferredOwnerSlot,\n): NestedScopeSeam {\n const now = args.now ?? Date.now\n return {\n nodeId: childNodeId,\n depth: args.depth,\n ...(args.maxDepth !== undefined ? { maxDepth: args.maxDepth } : {}),\n journalRoot: args.root,\n mount(nestedRoot: NodeId, signal: AbortSignal): Scope<unknown> {\n const deadlineMs =\n childDeadlineAtMs === undefined ? undefined : Math.max(0, childDeadlineAtMs - now())\n const nestedBudget = {\n ...childBudget,\n ...(deadlineMs !== undefined ? { deadlineMs } : {}),\n }\n return createScope<unknown>({\n parentId: childNodeId,\n root: nestedRoot,\n pool: createBudgetPool(nestedBudget, now),\n journal: args.journal,\n blobs: args.blobs,\n executors: args.executors,\n // Re-seed the parent's NON-recursion seams (sandbox/router for leaf grandchildren);\n // the nested scope adds its OWN nested-scope seam per child in `spawn`.\n seams: args.seams,\n depth: args.depth + 1,\n ...(args.maxDepth !== undefined ? { maxDepth: args.maxDepth } : {}),\n liveWorkerCapacity,\n signal,\n ...(args.now ? { now: args.now } : {}),\n ...(args.hooks ? { hooks: args.hooks } : {}),\n // The nested scope resolves the trace context against ITS OWN `parentId` (this driver\n // child), so a grandchild worker joins under the middle node's span, not the run root's.\n ...(args.workerTrace ? { workerTrace: args.workerTrace } : {}),\n ...(args.workerTraceUnpropagated\n ? { workerTraceUnpropagated: args.workerTraceUnpropagated }\n : {}),\n ...(deferredOwner.ownerMaterialization === undefined\n ? {}\n : { ownerMaterialization: deferredOwner.ownerMaterialization }),\n })\n },\n }\n}\n\n/** Create the reactive `Scope` a driver's `Agent.act` runs inside: spawn children on an atomically reserved conserved budget, settle via the `next()` cursor, journal for replay. */\nexport function createScope<Out>(args: ScopeArgs): Scope<Out> {\n const children = new Map<NodeId, LiveChild>()\n const liveWorkerCapacity: LiveWorkerCapacityState = args.liveWorkerCapacity ?? {\n max: normalizeLiveWorkerLimit(args.maxLiveWorkers),\n live: 0,\n }\n // Two distinct monotonic counters in two namespaces:\n // - `spawnOrdinal` is the spawn order (0,1,2,…); it mints the deterministic node id\n // `${parent}:s${ordinal}` and stamps the `spawned` event's `seq`. Known at spawn.\n // - `cursorSeq` is the order `next()` yields settlements (B2); it stamps the\n // `settled`/`cancelled` event's `seq` and the `Settled.seq` the driver branches on.\n // They are separate so a `spawned` event never collides with a `settled` event in the\n // journal's per-tree uniqueness guard (which is scoped to the cursor namespace).\n // On a resumed scope, continue both monotonic namespaces PAST the recorded maxima so a\n // freshly-spawned child or settlement never reuses a journaled `seq` (the per-tree\n // uniqueness guard would otherwise fail loud). On a fresh scope both start at 0.\n // - `waitOrdinal` is a THIRD namespace for wait-states (`${parent}:w${ordinal}`, stamping the\n // `waiting` event's `seq`), separate from the spawn ordinal so a wait and a worker can never\n // mint the same node id.\n let spawnOrdinal = args.resumeFrom ? args.resumeFrom.maxSpawnOrdinal + 1 : 0\n let cursorSeq = args.resumeFrom ? args.resumeFrom.maxCursorSeq + 1 : 0\n let waitOrdinal = args.resumeFrom ? args.resumeFrom.maxWaitOrdinal + 1 : 0\n let meterSeq = 0\n const now = args.now ?? Date.now\n // Waits the journal shows as armed but never woken, keyed by label. `wait` RE-ADOPTS one instead\n // of arming a fresh countdown — that is what makes a resumed deadline the ORIGINAL deadline.\n const unclaimedWaits = new Map<string, PendingWait>(\n (args.resumeFrom?.waits ?? []).map((w) => [w.label, w]),\n )\n\n // The semantic-key registry (`SpawnOpts.key`): every keyed assignment's current state, seeded\n // from the prior journal on resume and updated live as keyed children spawn and settle. This is\n // what makes a keyed spawn idempotent per key across process lifetimes: `done` returns the\n // committed result, `live` refuses a concurrent duplicate, `down`/`in-doubt` spawn fresh but\n // say so explicitly.\n type KeyState =\n | { readonly state: 'live'; readonly id: NodeId; readonly identity: NodeExecutionIdentity }\n | {\n readonly state: 'done'\n readonly id: NodeId\n readonly identity: NodeExecutionIdentity\n readonly settled: Settled<Out> & { kind: 'done' }\n }\n | {\n readonly state: 'down'\n readonly id: NodeId\n readonly identity: NodeExecutionIdentity\n readonly reason: string\n }\n | { readonly state: 'in-doubt'; readonly id: NodeId; readonly identity: NodeExecutionIdentity }\n const keyed = new Map<string, KeyState>()\n for (const [key, prior] of args.resumeFrom?.keys ?? []) {\n if (prior.state === 'completed' && prior.settled?.kind === 'done') {\n if (prior.identity === undefined) continue\n keyed.set(key, {\n state: 'done',\n id: prior.id,\n identity: prior.identity,\n settled: prior.settled as Settled<Out> & { kind: 'done' },\n })\n } else if (prior.state === 'down' && prior.settled?.kind === 'down') {\n if (prior.identity === undefined) continue\n keyed.set(key, {\n state: 'down',\n id: prior.id,\n identity: prior.identity,\n reason: prior.settled.reason,\n })\n } else if (prior.identity !== undefined) {\n keyed.set(key, { state: 'in-doubt', id: prior.id, identity: prior.identity })\n }\n }\n /** Fold a keyed child's terminal settlement back into the registry, so a later spawn with the\n * same key resolves to it (done → committed result; down → explicit retry). */\n const recordKeyedSettlement = (key: string, settled: Settled<Out>): void => {\n const identity = settled.handle.identity\n if (identity === undefined) {\n throw new ValidationError(`scope: keyed settlement '${key}' lost its execution identity`)\n }\n if (settled.kind === 'done') {\n keyed.set(key, { state: 'done', id: settled.handle.id, identity, settled })\n } else {\n keyed.set(key, { state: 'down', id: settled.handle.id, identity, reason: settled.reason })\n }\n }\n\n function spawn<C extends Out>(\n agentOrFactory: Agent<unknown, C> | (() => Agent<unknown, C>),\n rawTask: unknown,\n rawOpts: SpawnOpts,\n ):\n | { ok: true; handle: Handle<C>; prior?: SpawnPrior<C> }\n | { ok: false; reason: SpawnRejection } {\n if (args.signal.aborted) return { ok: false, reason: 'scope-aborted' }\n const task = detachedSnapshot(rawTask, 'scope.spawn task')\n const opts = detachedSnapshot(rawOpts, 'scope.spawn options')\n\n // A key is an identity claim, not merely a cache label. On every reuse, prepare the requested\n // agent far enough to derive the authorized profile/task identity, then compare it with the\n // journal before returning an old result or retrying old work. No executor is resolved,\n // constructed, reserved, or run on the completed path.\n let prior: SpawnPrior<C> | undefined\n let prepared:\n | {\n readonly agent: Agent<unknown, C>\n readonly spec: AgentSpec\n readonly identity: NodeExecutionIdentity | undefined\n }\n | undefined\n const prepare = () => {\n const agent = typeof agentOrFactory === 'function' ? agentOrFactory() : agentOrFactory\n const rawSpec = (agent as unknown as { executorSpec?: unknown }).executorSpec\n if (!isAgentSpec(rawSpec)) {\n throw new ValidationError(\n `scope.spawn: agent \"${agent.name}\" exposes no \\`executorSpec\\` (AgentSpec) to resolve a Executor`,\n )\n }\n const spec = executableAgentSpecSnapshot(rawSpec, 'scope.spawn')\n return { agent, spec, identity: deriveNodeExecutionIdentity(spec, task) }\n }\n if (opts.key !== undefined) {\n const existing = keyed.get(opts.key)\n if (existing !== undefined) {\n prepared = prepare()\n if (!isCompleteIdentity(prepared.identity)) {\n return { ok: false, reason: 'invalid-identity' }\n }\n if (!sameNodeExecutionIdentity(existing.identity, prepared.identity)) {\n return { ok: false, reason: 'key-conflict' }\n }\n }\n if (existing?.state === 'live') return { ok: false, reason: 'duplicate-key' }\n if (existing?.state === 'done') {\n return {\n ok: true,\n handle: existing.settled.handle as Handle<C>,\n prior: { state: 'completed', settled: existing.settled as Settled<C> & { kind: 'done' } },\n }\n }\n if (existing?.state === 'down') {\n prior = { state: 'retried', priorId: existing.id, reason: existing.reason }\n } else if (existing?.state === 'in-doubt') {\n prior = { state: 'lost', priorId: existing.id }\n }\n }\n\n if (args.maxDepth !== undefined && args.depth >= args.maxDepth) {\n return { ok: false, reason: 'depth-exceeded' }\n }\n\n // A concrete child exposes its profile now, so parse and seal it before capacity or budget\n // admission. A lazy agent factory cannot reveal a profile without being constructed; preserve\n // the refusal invariant for those factories and validate the result immediately after the\n // reservation, before registry resolution or any executor code.\n if (typeof agentOrFactory !== 'function') prepared ??= prepare()\n\n // ONE admission counter is shared by the root scope and every recursive scope it mounts.\n // Acquire before calling a lazy worker factory, resolving/constructing its executor, or\n // reserving budget. A completed keyed assignment returned above never touches the counter.\n const permit = acquireLiveWorker(liveWorkerCapacity)\n if (!permit.ok) return { ok: false, reason: 'max-live-workers' }\n\n // Reserve the child's whole ceiling atomically; fail CLOSED when the pool can't cover\n // it (never read-then-spawn overcommit, so Σk is conserved by construction). This happens\n // before a fresh lazy agent factory is called: refused work constructs nothing.\n let reservation: ReturnType<BudgetPool['reserve']>\n try {\n reservation = args.pool.reserve(opts.budget)\n } catch (error) {\n permit.release()\n throw error\n }\n if (!reservation.ok) {\n permit.release()\n return { ok: false, reason: reservation.reason }\n }\n\n // Resolve the leaf executor through the open registry after both worker and budget admission.\n // If preparation fails, refund the reservation here because runChild never receives it.\n let spec: AgentSpec\n let resolved: { succeeded: true; value: (spec: AgentSpec, ctx: ExecutorContext) => Executor<C> }\n let identity: NodeExecutionIdentity | undefined\n try {\n prepared ??= prepare()\n spec = prepared.spec\n identity = prepared.identity\n if (opts.key !== undefined && !isCompleteIdentity(identity)) {\n args.pool.reconcile(reservation.ticket, zeroSpend())\n permit.release()\n return { ok: false, reason: 'invalid-identity' }\n }\n const outcome = args.executors.resolve<C>(spec)\n if (!outcome.succeeded) throw new ValidationError(`scope.spawn: ${outcome.error}`)\n resolved = outcome\n } catch (error) {\n args.pool.reconcile(reservation.ticket, zeroSpend())\n permit.release()\n throw error\n }\n\n // Everything between reserve and runChild's hand-off owns the reservation. A SYNCHRONOUS\n // throw here (most likely the executor factory `resolved.value(spec, ctx)`) would otherwise\n // leak the reservation — runChild, which reconciles the ticket, is never reached. Release it\n // with zero spend on throw, then rethrow, so `total ≡ free + reserved + committed` holds.\n // (runChild is the last statement and never sync-throws, so there is no double-reconcile.)\n let cascadeAbort: (() => void) | undefined\n let clearChildDeadline: (() => void) | undefined\n try {\n const ordinal = spawnOrdinal++\n const id: NodeId = `${args.parentId}:s${ordinal}`\n const attemptId = newExecutionAttemptId(id)\n const startedAt = now()\n const childDeadlineAtMs = boundedChildDeadlineAt(\n args.pool.readout().deadlineMs,\n opts.budget.deadlineMs,\n startedAt,\n )\n\n // The child's abort chains off this scope's signal (a scope abort reaps every child)\n // AND off its own handle.abort() or bounded deadline. Aborting mid-acquire cascades through\n // the executor's signal into its acquireSandbox find-by-name reap, so an acquiring node\n // never leaks.\n const controller = new AbortController()\n cascadeAbort = () => controller.abort(args.signal.reason)\n if (args.signal.aborted) controller.abort(args.signal.reason)\n else args.signal.addEventListener('abort', cascadeAbort, { once: true })\n if (childDeadlineAtMs !== undefined) {\n clearChildDeadline = armDeadlineTimer(Math.max(0, childDeadlineAtMs - now()), () =>\n controller.abort('child deadline exceeded'),\n )\n }\n\n // Seed THIS scope's own keystone deps into the child's `ExecutorContext.seams`, so a\n // child whose executor is a DRIVER can mount a nested `Scope` at `depth+1` over a child\n // pool backed by THIS reservation. A leaf executor ignores it; the parent's sandbox/router\n // seams still pass through for leaves. Each nested driver repeats the same partitioning.\n const deferredOwner: DeferredOwnerSlot = {}\n // Resolved per spawn, not once per scope: the span of the spawning node is opened by the\n // `agent.spawn` hook, so reading it lazily needs no assumption about hook ordering. Absent\n // resolver (the untraced default) ⇒ no seam, and the child's `ExecutorContext` is exactly\n // the object it was before worker trace propagation existed.\n const workerTrace = args.workerTrace?.(args.parentId)\n const ctx: ExecutorContext = {\n signal: controller.signal,\n node: {\n rootId: args.root,\n parentId: args.parentId,\n nodeId: id,\n attemptId,\n ...(identity ? { identity } : {}),\n },\n seams: {\n ...args.seams,\n [nestedScopeSeamKey]: makeNestedScopeSeam(\n args,\n liveWorkerCapacity,\n id,\n opts.budget,\n childDeadlineAtMs,\n deferredOwner,\n ),\n ...(workerTrace ? { [workerTraceSeamKey]: workerTrace } : {}),\n },\n }\n const executor = resolved.value(spec, ctx) as Executor<C>\n const ownedTreeRoot = runtimeOwnedNestedDriverTreeRoot(executor, args.root, id)\n\n const handle: Handle<C> = {\n id,\n label: opts.label,\n ...(opts.assignmentId === undefined ? {} : { assignmentId: opts.assignmentId }),\n ...(identity ? { identity } : {}),\n get status(): NodeStatus {\n return children.get(id)?.status ?? 'cancelled'\n },\n get materialization(): ProfileMaterializationReceipt | undefined {\n return children.get(id)?.materialization\n },\n get executionBindings(): ReadonlyArray<ExecutionBindingReceipt> | undefined {\n const bindings = children.get(id)?.executionBindings\n return bindings && bindings.length > 0 ? Object.freeze([...bindings]) : undefined\n },\n abort(reason?: string): void {\n controller.abort(reason)\n },\n }\n\n const live: LiveChild = {\n id,\n status: 'acquiring',\n runtime: executor.runtime,\n ...(ownedTreeRoot === undefined ? {} : { ownedTreeRoot }),\n ...(identity ? { identity } : {}),\n budget: opts.budget,\n label: opts.label,\n ...(opts.assignmentId === undefined ? {} : { assignmentId: opts.assignmentId }),\n ...(opts.key !== undefined ? { key: opts.key } : {}),\n spent: zeroSpend(),\n settled: undefined as unknown as Promise<PreSeqSettled>,\n delivered: false,\n executorDone: false,\n cleanupConfirmed: false,\n executionBindings: [],\n startedAt,\n lastActivityAt: startedAt,\n ...(executor.deliver\n ? { deliver: (message: unknown): boolean => executor.deliver?.(message) !== false }\n : {}),\n ...(executor.progress ? { readProgress: executor.progress.bind(executor) } : {}),\n ...(executor.traceSource ? { readTraceSource: executor.traceSource.bind(executor) } : {}),\n }\n children.set(id, live)\n if (opts.key !== undefined) {\n keyed.set(opts.key, {\n state: 'live',\n id,\n identity: identity as NodeExecutionIdentity,\n })\n }\n\n const spawnCommitted = args.journal\n .appendEvent(args.root, {\n kind: 'spawned',\n id,\n parent: args.parentId,\n label: opts.label,\n ...(opts.key !== undefined ? { key: opts.key } : {}),\n ...(opts.assignmentId === undefined ? {} : { assignmentId: opts.assignmentId }),\n budget: opts.budget,\n runtime: executor.runtime,\n ...(ownedTreeRoot === undefined ? {} : { ownedTreeRoot }),\n ...(identity ? { identity } : {}),\n seq: ordinal,\n at: new Date(now()).toISOString(),\n })\n .then(async () => {\n // The severed distributed-trace hop, journaled beside the spawn it annotates: this run\n // records spans AND resolved a context for this child, but the backend has no channel to\n // carry it — the child's own trace will surface as a disconnected root, and this record\n // is what makes that a queryable fact instead of a silent stranger tree.\n if (args.workerTraceUnpropagated === undefined || workerTrace === undefined) return\n await args.journal.appendEvent(args.root, {\n kind: 'trace-unpropagated',\n id,\n expectedTraceId: workerTrace.traceId,\n backend: args.workerTraceUnpropagated.backend,\n reason: args.workerTraceUnpropagated.reason,\n seq: ordinal,\n at: new Date(now()).toISOString(),\n })\n })\n let pendingEvidence: { complete: () => Promise<void>; fail: () => Promise<void> } | undefined\n const materializationCommitted = spawnCommitted.then(async () => {\n const profileDigest = identity?.profileDigest ?? authoredProfileDigest(spec.profile)\n let receipt: ProfileMaterializationReceipt\n let binding: ExecutionBindingReceipt\n const declaration = runtimeOwnedExecutorMaterialization(executor)\n const pending = runtimeOwnedPendingExecutorMaterialization(executor)\n const deferredRuntime = runtimeOwnedDeferredExecutorRuntime(executor)\n if (deferredRuntime !== undefined) {\n deferredOwner.ownerMaterialization = {\n runtime: deferredRuntime,\n authoredProfile: spec.profile,\n attemptId,\n journalRoot: args.root,\n nodeId: id,\n requiredKnown: true,\n onReceipt(materialization, executionBinding) {\n live.runtime = materialization.runtime\n live.materialization = materialization\n live.executionBindings.push(executionBinding)\n },\n }\n return\n }\n if (pending !== undefined) {\n if (profileDigest === undefined) {\n throw new ValidationError(\n 'scope.spawn: a pending materialization requires a canonical authored profile',\n )\n }\n if (pending.runtime !== executor.runtime || pending.binding.attemptId !== attemptId) {\n throw new ValidationError(\n 'scope.spawn: pending executor did not bind the kernel-minted attempt id',\n )\n }\n // Validate the planned shape before spend, but do not persist it as proof that the\n // external bridge actually used it. Only the terminal acknowledgement can finalize it.\n const plannedReceipt = knownMaterializationReceipt({\n authoredProfileDigest: profileDigest,\n runtime: executor.runtime,\n declaration: pending.declaration,\n })\n if (\n plannedReceipt.status !== 'known' ||\n plannedReceipt.effectiveProfileDigest !== plannedReceipt.authoredProfileDigest\n ) {\n throw new ValidationError(\n 'scope.spawn: pending executor changed the authored AgentProfile before execution',\n )\n }\n let recorded = false\n pendingEvidence = {\n complete: async () => {\n if (recorded) return\n const acknowledged = runtimeOwnedExecutorMaterialization(executor)\n const acknowledgedBinding = runtimeOwnedExecutorExecutionBinding(executor)\n if (acknowledged === undefined || acknowledgedBinding?.attemptId !== attemptId) {\n throw new ValidationError(\n 'scope.spawn: external executor completed without a terminal materialization acknowledgement',\n )\n }\n const finalReceipt = knownMaterializationReceipt({\n authoredProfileDigest: profileDigest,\n runtime: executor.runtime,\n declaration: acknowledged,\n })\n if (finalReceipt.status !== 'known') {\n throw new ValidationError('scope.spawn: terminal materialization remained unknown')\n }\n if (finalReceipt.effectiveProfileDigest !== finalReceipt.authoredProfileDigest) {\n throw new ValidationError(\n 'scope.spawn: external executor changed the authored AgentProfile',\n )\n }\n const finalBinding = knownExecutionBindingReceipt(finalReceipt, acknowledgedBinding)\n await appendNodeMaterialization(args, id, ordinal, finalReceipt, finalBinding, now)\n live.materialization = finalReceipt\n live.executionBindings.push(finalBinding)\n recorded = true\n },\n fail: async () => {\n if (recorded) return\n // The remote turn can be acknowledged before a later local persistence/check step\n // fails. Preserve that known execution truth even though the child settles down.\n if (runtimeOwnedExecutorMaterialization(executor) !== undefined) {\n await pendingEvidence?.complete()\n return\n }\n const unknown = unknownMaterializationReceipt({\n authoredProfileDigest: profileDigest,\n runtime: executor.runtime,\n reason: 'executor-receipt-pending',\n })\n const unknownBinding = unknownExecutionBindingReceipt(\n unknown,\n attemptId,\n 'executor-receipt-pending',\n )\n await appendNodeMaterialization(args, id, ordinal, unknown, unknownBinding, now)\n live.materialization = unknown\n live.executionBindings.push(unknownBinding)\n recorded = true\n },\n }\n return\n }\n if (declaration === undefined) {\n receipt = unknownMaterializationReceipt({\n ...(profileDigest === undefined ? {} : { authoredProfileDigest: profileDigest }),\n runtime: executor.runtime,\n reason: 'executor-did-not-report',\n })\n binding = unknownExecutionBindingReceipt(receipt, attemptId, 'executor-did-not-report')\n } else {\n try {\n if (profileDigest === undefined) {\n throw new ValidationError(\n 'scope.spawn: a known materialization requires a canonical authored profile',\n )\n }\n receipt = knownMaterializationReceipt({\n authoredProfileDigest: profileDigest,\n runtime: executor.runtime,\n declaration,\n })\n const reportedBinding = runtimeOwnedExecutorExecutionBinding(executor)\n if (reportedBinding === undefined || reportedBinding.attemptId !== attemptId) {\n throw new ValidationError(\n 'scope.spawn: trusted executor did not bind the kernel-minted attempt id',\n )\n }\n binding = knownExecutionBindingReceipt(receipt, reportedBinding)\n } catch (error) {\n receipt = unknownMaterializationReceipt({\n ...(profileDigest === undefined ? {} : { authoredProfileDigest: profileDigest }),\n runtime: executor.runtime,\n reason: 'invalid-executor-report',\n })\n binding = unknownExecutionBindingReceipt(receipt, attemptId, 'invalid-executor-report')\n await appendNodeMaterialization(args, id, ordinal, receipt, binding, now)\n live.materialization = receipt\n live.executionBindings.push(binding)\n throw new ValidationError(\n `scope.spawn: executor ${JSON.stringify(executor.runtime)} returned invalid materialization evidence`,\n { cause: error },\n )\n }\n }\n await appendNodeMaterialization(args, id, ordinal, receipt, binding, now)\n live.materialization = receipt\n live.executionBindings.push(binding)\n })\n\n notifyRuntimeHookEvent(\n args.hooks,\n {\n id: `${id}:spawn`,\n runId: args.root,\n target: 'agent.spawn',\n phase: 'after',\n timestamp: now(),\n stepIndex: ordinal,\n parentId: args.parentId,\n payload: {\n childId: id,\n label: opts.label,\n ...(opts.assignmentId === undefined ? {} : { assignmentId: opts.assignmentId }),\n runtime: executor.runtime,\n ...(identity ? { identity } : {}),\n budget: opts.budget,\n depth: args.depth,\n },\n },\n { signal: args.signal },\n )\n\n // Drive the executor to settlement off to the side; `next()` awaits the resulting\n // promise. A thrown executor (or a real abort) is TYPED into a `down` record by\n // `runChild` (never re-thrown) so a single failing child never rejects the cursor.\n const settled = runChild(\n live,\n executor,\n controller,\n task,\n opts,\n args.pool,\n reservation.ticket,\n args.blobs,\n now,\n materializationCommitted,\n {\n complete: async () => pendingEvidence?.complete(),\n fail: async () => pendingEvidence?.fail(),\n },\n childDeadlineAtMs,\n )\n .then((s) => {\n live.resolved = s\n return s\n })\n .finally(() => {\n if (live.cleanupConfirmed) permit.release()\n clearChildDeadline?.()\n if (cascadeAbort) args.signal.removeEventListener('abort', cascadeAbort)\n })\n ;(live as { settled: Promise<PreSeqSettled> }).settled = settled\n\n return { ok: true, handle, ...(prior ? { prior } : {}) }\n } catch (err) {\n permit.release()\n clearChildDeadline?.()\n if (cascadeAbort) args.signal.removeEventListener('abort', cascadeAbort)\n args.pool.reconcile(reservation.ticket, zeroSpend())\n throw err\n }\n }\n\n async function next(): Promise<Settled<Out> | null> {\n const undelivered = () => [...children.values()].filter((c) => !c.delivered)\n if (undelivered().length === 0) return null\n\n // ray.wait n=1: await the FIRST not-yet-delivered child to settle. Loop because a\n // concurrent `next()` may take the race winner between the await and the pick.\n for (;;) {\n const pending = undelivered()\n if (pending.length === 0) return null\n // Prefer an already-resolved-but-undelivered child (no await needed).\n const ready = pending.find((c) => c.resolved !== undefined)\n const chosen = ready ?? (await raceFirstSettled(pending))\n if (chosen.delivered) continue\n chosen.delivered = true\n\n const seq = cursorSeq++\n const settlement = chosen.resolved\n if (!settlement) {\n throw new ValidationError(\n `scope.next: child '${chosen.id}' won the settle race without a resolved value`,\n )\n }\n const delivered = await finalizeSettlement<Out>(chosen, settlement, seq, args, now)\n if (chosen.key !== undefined) recordKeyedSettlement(chosen.key, delivered)\n return delivered\n }\n }\n\n async function nextResolved(): Promise<Settled<Out> | null> {\n // Same exactly-once delivery as `next()`, but never awaits a RUNNING executor. A child\n // whose executor has finished (`executorDone`) may still be mid-persistence — awaiting its\n // `settled` promise there completes in bounded bookkeeping time, never on live work.\n for (;;) {\n const candidates = [...children.values()].filter((c) => !c.delivered)\n const pick =\n candidates.find((c) => c.resolved !== undefined) ?? candidates.find((c) => c.executorDone)\n if (!pick) return null\n const settlement = await pick.settled\n if (pick.delivered) continue // lost the race with a concurrent cursor — pick again\n pick.delivered = true\n const seq = cursorSeq++\n const delivered = await finalizeSettlement<Out>(pick, settlement, seq, args, now)\n if (pick.key !== undefined) recordKeyedSettlement(pick.key, delivered)\n return delivered\n }\n }\n\n function send(nodeId: NodeId, msg: unknown): boolean {\n if (args.signal.aborted) return false\n const child = children.get(nodeId)\n // Deliver only to a child that is still LIVE (not yet yielded by the cursor) and whose executor\n // accepts an inbox. A settled/unknown child, or a leaf with no `deliver`, cannot be steered.\n if (!child || child.delivered || !child.deliver) return false\n const accepted = child.deliver(msg) !== false\n if (!accepted) return false\n // A delivered steer IS activity: it resets the idle clock so a worker that was about to read\n // as stalled is not immediately re-steered before it can act on the message it just got.\n child.lastActivityAt = now()\n return true\n }\n\n /**\n * Arm a wait-state node. Deliberately NOT a `spawn` with a sleeping executor: it resolves no\n * `AgentSpec`, constructs no `Executor`, and — the point of the whole mechanic — reserves NOTHING\n * from the conserved pool, so a week-long wait costs zero tokens and zero dollars and cannot\n * starve a worker of budget.\n *\n * Fail-closed admission, mirroring `spawn`'s typed outcome. The deadline check is the one that\n * matters: a wait may not silently sleep past the pool's hard wall-clock ceiling, and it may not\n * extend that ceiling either (that would make a wait override a budget guard).\n */\n function wait(\n spec: WaitSpec,\n opts: WaitOpts,\n ): { ok: true; handle: Handle<WaitOutcome> } | { ok: false; reason: WaitRejection } {\n if (args.signal.aborted) return { ok: false, reason: 'deadline-exceeded' }\n if (validateWaitSpec(spec) !== null) return { ok: false, reason: 'invalid-spec' }\n if (spec.kind === 'poll' && args.probes?.resolve(spec.probe) === undefined) {\n return { ok: false, reason: 'unknown-probe' }\n }\n\n // Re-adopt a journaled, still-unfired wait with this label: same node id, same spec, same\n // ORIGINAL arm instant. The caller passes the spec it would have used fresh; the journaled one\n // wins, so a restart cannot slide the deadline forward.\n const adopted = unclaimedWaits.get(opts.label)\n if (adopted) unclaimedWaits.delete(opts.label)\n const effectiveSpec = adopted?.spec ?? spec\n const armedAt = adopted?.armedAt ?? now()\n\n if (!assertWaitWithinDeadline(effectiveSpec, args.pool.readout().deadlineMs)) {\n return { ok: false, reason: 'deadline-exceeded' }\n }\n\n const id: NodeId = adopted ? adopted.id : `${args.parentId}:w${waitOrdinal}`\n const ordinal = adopted ? adopted.ordinal : waitOrdinal\n if (!adopted) waitOrdinal += 1\n\n const waitAbort = new AbortController()\n const cascadeAbort = () => waitAbort.abort()\n if (args.signal.aborted) waitAbort.abort()\n else args.signal.addEventListener('abort', cascadeAbort, { once: true })\n\n const handle: Handle<WaitOutcome> = {\n id,\n label: opts.label,\n get status(): NodeStatus {\n return children.get(id)?.status ?? 'cancelled'\n },\n abort(reason?: string): void {\n waitAbort.abort(reason)\n },\n }\n\n const live: LiveChild = {\n id,\n status: 'waiting',\n runtime: 'wait',\n // A wait's recorded budget is zero on every channel — nothing was reserved, so nothing may\n // be reconciled, and a journal reader sums it as the zero it truly is.\n budget: { maxIterations: 0, maxTokens: 0 },\n label: opts.label,\n spent: zeroSpend(),\n settled: undefined as unknown as Promise<PreSeqSettled>,\n delivered: false,\n executorDone: false,\n cleanupConfirmed: true,\n executionBindings: [],\n startedAt: armedAt,\n lastActivityAt: now(),\n wait: {\n spec: effectiveSpec,\n armedAt,\n label: opts.label,\n armCommitted: adopted !== undefined,\n },\n }\n children.set(id, live)\n\n // Only a FRESH arm journals `waiting`; an adopted one already has its record (re-writing it\n // would duplicate the wait ordinal in the journal's per-tree guard). A fresh wait may not\n // start racing its timer/probe until this identity record is durable: otherwise a zero-delay\n // wait can journal `woken` before `waiting`, or disappear entirely if this append fails.\n const armCommitted = adopted\n ? Promise.resolve()\n : args.journal.appendEvent(args.root, {\n kind: 'waiting',\n id,\n parent: args.parentId,\n label: opts.label,\n spec: effectiveSpec,\n armedAt,\n seq: ordinal,\n at: new Date(now()).toISOString(),\n })\n\n const settled = armCommitted\n .then(() => {\n if (live.wait) live.wait.armCommitted = true\n notifyRuntimeHookEvent(\n args.hooks,\n {\n id: `${id}:waiting`,\n runId: args.root,\n target: 'agent.spawn',\n phase: 'after',\n timestamp: now(),\n stepIndex: ordinal,\n parentId: args.parentId,\n payload: {\n childId: id,\n label: opts.label,\n runtime: 'wait',\n wait: effectiveSpec,\n armedAt,\n resumed: adopted !== undefined,\n },\n },\n { signal: args.signal },\n )\n return runWait({\n spec: effectiveSpec,\n label: opts.label,\n armedAt,\n resumed: adopted !== undefined,\n signal: waitAbort.signal,\n ...(args.probes ? { probes: args.probes } : {}),\n now,\n ...(args.waitSleep ? { sleep: args.waitSleep } : {}),\n })\n })\n .then(async (resolution): Promise<PreSeqSettled> => {\n live.executorDone = true\n live.lastActivityAt = now()\n if (resolution.kind === 'cancelled') {\n return {\n kind: 'down',\n reason: resolution.reason,\n infra: false,\n restartCount: 0,\n trace: { status: 'unavailable', reason: 'not-an-executor' },\n }\n }\n const outRef = contentAddress(resolution.outcome)\n await args.blobs.put(outRef, resolution.outcome)\n return {\n kind: 'done',\n out: resolution.outcome,\n outRef,\n spent: zeroSpend(),\n trace: { status: 'unavailable', reason: 'not-an-executor' },\n }\n })\n .catch((err): PreSeqSettled => {\n live.executorDone = true\n return {\n kind: 'down',\n reason: errMessage(err),\n infra: true,\n restartCount: 0,\n trace: { status: 'unavailable', reason: 'not-an-executor' },\n }\n })\n .then((s) => {\n live.resolved = s\n return s\n })\n .finally(() => {\n args.signal.removeEventListener('abort', cascadeAbort)\n })\n ;(live as { settled: Promise<PreSeqSettled> }).settled = settled\n\n return { ok: true, handle }\n }\n\n function progress(\n nodeId: NodeId,\n opts: { now?: number; stallAfterMs?: number } = {},\n ): WorkerProgress | undefined {\n const child = children.get(nodeId)\n if (!child) return undefined\n // The executor's own read is best-effort enrichment on a live path — a throwing progress\n // implementation must never break the driver's observation of an otherwise healthy worker.\n let fromExecutor: ExecutorProgress | undefined\n try {\n fromExecutor = child.readProgress?.()\n } catch {\n fromExecutor = undefined\n }\n return readWorkerProgress(\n {\n id: child.id,\n status: child.status,\n steerable: child.deliver !== undefined && !child.delivered,\n startedAt: child.startedAt,\n lastActivityAt: child.lastActivityAt,\n turns: child.spent.iterations,\n tokens: child.spent.tokens,\n ...(child.spent.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: child.spent.usd,\n ...(child.spent.usdKnown === false ? { usdKnown: false } : {}),\n },\n fromExecutor,\n opts.now ?? now(),\n opts.stallAfterMs ?? DEFAULT_STALL_AFTER_MS,\n )\n }\n\n function traceSource(nodeId: NodeId): TraceSource | undefined {\n const child = children.get(nodeId)\n if (!child) return undefined\n try {\n return child.readTraceSource?.()\n } catch {\n return undefined\n }\n }\n\n async function meterInternal(\n spend: Spend,\n detail?: Record<string, unknown>,\n providerModel?: ProviderModelExecutionEvidence,\n ): Promise<void> {\n if (args.signal.aborted) {\n throw new ValidationError('scope.meter: cannot record new driver work after scope abort')\n }\n const seq = meterSeq++\n // Debit the driver's own inference against the shared conserved pool (free → committed), so\n // equal-k counts it live and `budget.tokensLeft` reflects it for the in-loop guard.\n // An invalid observation (currently: unknown dollar cost under a dollar ceiling) still\n // describes compute that already happened. Preserve it in the durable record before\n // returning the refusal; otherwise the terminal result would falsely report that cost as $0.\n let observeError: unknown\n try {\n args.pool.observe(spend)\n } catch (error) {\n observeError = error\n }\n // Journal it as a `metered` event — the durable TWIN of the pool debit (as `settled` is the\n // twin of `reconcile`), so every journal-based cost reader sums driver inference automatically.\n // Awaited like the settled append (cost-critical), so it has landed before the supervisor's\n // join-barrier cost roll-up.\n await args.journal.appendEvent(args.root, {\n kind: 'metered',\n id: args.parentId,\n spend,\n ...(providerModel === undefined\n ? {}\n : { providerModel: detachedSnapshot(providerModel, 'runtime provider model evidence') }),\n seq,\n at: new Date(now()).toISOString(),\n })\n // Emit it as an `agent.turn` event so the trace/topology view sees per-turn driver inference\n // (the same stream `spawn`/`next` feed — one observable tree).\n notifyRuntimeHookEvent(\n args.hooks,\n {\n id: `${args.parentId}:meter:${seq}`,\n runId: args.root,\n target: 'agent.turn',\n phase: 'after',\n timestamp: now(),\n parentId: args.parentId,\n payload: { spend, ...(detail ?? {}) },\n },\n { signal: args.signal },\n )\n if (observeError !== undefined) throw observeError\n }\n\n // The replayed committed work, frozen once at construction — a resume-aware `act` reads it\n // to skip re-spawning settled children. Absent on a fresh scope.\n const resume: ResumedWork<Out> | undefined = args.resumeFrom\n ? {\n settled: args.resumeFrom.settled as ReadonlyArray<Settled<Out>>,\n view: args.resumeFrom.view,\n waits: args.resumeFrom.waits,\n keys: args.resumeFrom.keys as ReadonlyMap<string, ResumedKeyState<Out>>,\n priorSpend: args.resumeFrom.priorSpend,\n }\n : undefined\n\n const scope: Scope<Out> = {\n spawn,\n next,\n nextResolved,\n send,\n wait,\n progress,\n traceSource,\n signal: args.signal,\n meter: (spend, detail) => meterInternal(spend, detail),\n ...(resume ? { resume } : {}),\n get view(): TreeView {\n return makeTreeView(args.parentId, children)\n },\n get budget() {\n return args.pool.readout()\n },\n get workerCapacity() {\n return {\n live: liveWorkerCapacity.live,\n freeSlots: freeSlots(liveWorkerCapacity.live, liveWorkerCapacity.max),\n }\n },\n }\n runtimeOwnedProviderMeters.set(scope as Scope<unknown>, async (spend, providerModel, detail) =>\n meterInternal(spend, detail, providerModel),\n )\n if (args.ownerMaterialization !== undefined) {\n const authoredProfile =\n args.ownerMaterialization.authoredProfile === undefined\n ? undefined\n : detachedSnapshot(\n args.ownerMaterialization.authoredProfile,\n 'scope owner authored profile',\n )\n ownerMaterializationStates.set(scope as Scope<unknown>, {\n journal: args.journal,\n root: args.ownerMaterialization.journalRoot ?? args.root,\n nodeId: args.ownerMaterialization.nodeId ?? args.parentId,\n runtime: args.ownerMaterialization.runtime,\n attemptId: args.ownerMaterialization.attemptId,\n ...(authoredProfile === undefined ? {} : { authoredProfile }),\n ...(authoredProfile === undefined\n ? {}\n : { authoredProfileDigest: authoredProfileDigest(authoredProfile) }),\n ...(args.ownerMaterialization.prior === undefined\n ? {}\n : { prior: args.ownerMaterialization.prior }),\n requiredKnown: args.ownerMaterialization.requiredKnown === true,\n ...(args.ownerMaterialization.onReceipt === undefined\n ? {}\n : { onReceipt: args.ownerMaterialization.onReceipt }),\n now,\n receipt: args.ownerMaterialization.prior,\n bindingPublished: false,\n publishedThisProcess: false,\n })\n }\n return scope\n}\n\n/** @internal Meter one Runtime-owned provider attempt into the durable scope journal. */\nexport function meterRuntimeOwnedProviderAttempt(\n scope: Scope<unknown>,\n spend: Spend,\n providerModel: ProviderModelExecutionEvidence,\n detail?: Record<string, unknown>,\n): Promise<void> {\n const meter = runtimeOwnedProviderMeters.get(scope as object)\n if (meter === undefined) {\n throw new ValidationError('scope: Runtime-owned provider meter is not bound to this scope')\n }\n return meter(spend, providerModel, detail)\n}\n\ninterface OwnerMaterializationState {\n readonly journal: SpawnJournal\n readonly root: NodeId\n readonly nodeId: NodeId\n readonly runtime: NodeSnapshot['runtime']\n readonly attemptId: string\n readonly authoredProfile?: unknown\n readonly authoredProfileDigest?: Sha256Digest\n readonly prior?: ProfileMaterializationReceipt\n readonly requiredKnown: boolean\n readonly onReceipt?: (\n materialization: ProfileMaterializationReceipt,\n binding: ExecutionBindingReceipt,\n ) => void\n readonly now: () => number\n receipt?: ProfileMaterializationReceipt\n bindingPublished: boolean\n publishedThisProcess: boolean\n}\n\nconst ownerMaterializationStates = new WeakMap<Scope<unknown>, OwnerMaterializationState>()\n\n/**\n * @internal Publish exact root-manager materialization from a runtime-owned adapter after dynamic\n * attachments exist and before its executor starts. This is deliberately a module function backed\n * by a private WeakMap, not a Scope method an Agent can call.\n */\nexport async function recordScopeOwnerMaterialization(\n scope: Scope<unknown>,\n runtime: NodeSnapshot['runtime'],\n declaration: import('./types').ExecutorMaterialization,\n bindingInput: ExecutorExecutionBinding,\n): Promise<void> {\n const state = ownerMaterializationState(scope)\n if (runtime !== state.runtime) {\n await rejectOwnerMaterialization(state)\n throw new ValidationError(\n `scope owner materialization runtime ${JSON.stringify(runtime)} does not match ${JSON.stringify(state.runtime)}`,\n )\n }\n if (state.authoredProfileDigest === undefined) {\n await rejectOwnerMaterialization(state)\n throw new ValidationError('scope owner materialization requires an exact authored profile')\n }\n let receipt: ProfileMaterializationReceipt\n let binding: ExecutionBindingReceipt\n try {\n if (bindingInput.attemptId !== state.attemptId) {\n throw new ValidationError(\n 'scope owner execution binding does not use the kernel-minted attempt id',\n )\n }\n if (canonicalAgentProfileDigest(declaration.effectiveProfile) !== state.authoredProfileDigest) {\n throw new ValidationError(\n 'scope owner stable effective profile conflicts with its admitted authored profile',\n )\n }\n receipt = knownMaterializationReceipt({\n authoredProfileDigest: state.authoredProfileDigest,\n runtime,\n declaration,\n })\n binding = knownExecutionBindingReceipt(receipt, bindingInput)\n } catch (error) {\n await rejectOwnerMaterialization(state)\n throw new ValidationError('scope owner returned invalid materialization evidence', {\n cause: error,\n })\n }\n if (state.prior !== undefined) {\n if (canonicalCandidateDigest(state.prior) !== canonicalCandidateDigest(receipt)) {\n await rejectOwnerMaterialization(state)\n throw new ValidationError(\n 'scope owner materialization changed across resume; backend, model, execution identity, and plan must match',\n )\n }\n state.receipt = state.prior\n await appendOwnerBinding(state, binding)\n state.onReceipt?.(state.prior, binding)\n state.publishedThisProcess = true\n return\n }\n if (state.receipt !== undefined) {\n // A root driver may be re-entered inside one process after a transient executor failure\n // (`runDriverWithRetry`, #741). That attempt publishes the SAME materialization with a NEW\n // execution binding, which is the resume path's shape minus the process boundary — so it\n // appends a binding rather than a second receipt. A materialization that actually CHANGED is\n // still a fault: backend, model, execution identity, and plan may not move under a live run.\n if (canonicalCandidateDigest(state.receipt) !== canonicalCandidateDigest(receipt)) {\n await rejectOwnerMaterialization(state)\n throw new ValidationError(\n 'scope owner materialization changed mid-run; backend, model, execution identity, and plan must match across driver attempts',\n )\n }\n await appendOwnerBinding(state, binding)\n state.onReceipt?.(state.receipt, binding)\n state.publishedThisProcess = true\n return\n }\n await appendOwnerMaterialization(state, receipt, binding)\n state.onReceipt?.(receipt, binding)\n state.publishedThisProcess = true\n}\n\n/** @internal Kernel identity for constructing the exact deferred owner executor. */\nexport function scopeOwnerExecutorNodeContext(scope: Scope<unknown>): ExecutorNodeContext {\n const state = ownerMaterializationState(scope)\n return Object.freeze({\n rootId: state.root,\n parentId: state.nodeId,\n nodeId: state.nodeId,\n attemptId: state.attemptId,\n })\n}\n\n/** @internal Ensure a deferred root that never published evidence remains visibly unknown. */\nexport async function finalizeScopeOwnerMaterialization(scope: Scope<unknown>): Promise<void> {\n const state = ownerMaterializationStates.get(scope)\n // Rejection paths publish an unknown binding before returning the original validation error.\n // Finalization still runs after that error, so it must not append the same attempt again.\n if (state === undefined || state.publishedThisProcess || state.bindingPublished) return\n if (state.prior !== undefined) {\n await appendUnknownOwnerBinding(state, state.prior, 'root-agent-did-not-report')\n throw new ValidationError(\n 'resumed scope owner did not re-attest its prior materialization before execution',\n )\n }\n if (state.receipt !== undefined) return\n const receipt = unknownMaterializationReceipt({\n ...(state.authoredProfileDigest === undefined\n ? {}\n : { authoredProfileDigest: state.authoredProfileDigest }),\n runtime: state.runtime,\n reason: 'root-agent-did-not-report',\n })\n const binding = unknownExecutionBindingReceipt(\n receipt,\n state.attemptId,\n 'root-agent-did-not-report',\n )\n await appendOwnerMaterialization(state, receipt, binding)\n state.onReceipt?.(receipt, binding)\n if (state.requiredKnown) {\n throw new ValidationError(\n 'runtime-owned scope owner did not publish materialization before completing',\n )\n }\n}\n\nfunction ownerMaterializationState(scope: Scope<unknown>): OwnerMaterializationState {\n const state = ownerMaterializationStates.get(scope)\n if (state === undefined) {\n throw new ValidationError('scope has no deferred runtime-owned root materialization channel')\n }\n return state\n}\n\nasync function rejectOwnerMaterialization(state: OwnerMaterializationState): Promise<void> {\n if (state.bindingPublished) return\n if (state.prior !== undefined) {\n await appendUnknownOwnerBinding(state, state.prior, 'invalid-executor-report')\n return\n }\n if (state.receipt !== undefined) {\n await appendUnknownOwnerBinding(state, state.receipt, 'invalid-executor-report')\n return\n }\n const receipt = unknownMaterializationReceipt({\n ...(state.authoredProfileDigest === undefined\n ? {}\n : { authoredProfileDigest: state.authoredProfileDigest }),\n runtime: state.runtime,\n reason: 'invalid-executor-report',\n })\n const binding = unknownExecutionBindingReceipt(\n receipt,\n state.attemptId,\n 'invalid-executor-report',\n )\n await appendOwnerMaterialization(state, receipt, binding)\n state.onReceipt?.(receipt, binding)\n}\n\nasync function appendOwnerMaterialization(\n state: OwnerMaterializationState,\n receipt: ProfileMaterializationReceipt,\n binding: ExecutionBindingReceipt,\n): Promise<void> {\n await state.journal.appendEvent(state.root, {\n kind: 'materialized',\n id: state.nodeId,\n receipt,\n seq: 0,\n at: new Date(state.now()).toISOString(),\n })\n state.receipt = receipt\n await appendOwnerBinding(state, binding)\n}\n\nasync function appendOwnerBinding(\n state: OwnerMaterializationState,\n binding: ExecutionBindingReceipt,\n): Promise<void> {\n await state.journal.appendEvent(state.root, {\n kind: 'execution-bound',\n id: state.nodeId,\n binding,\n seq: 0,\n at: new Date(state.now()).toISOString(),\n })\n state.bindingPublished = true\n}\n\nasync function appendUnknownOwnerBinding(\n state: OwnerMaterializationState,\n receipt: ProfileMaterializationReceipt,\n reason: import('./types').UnknownMaterializationReason,\n): Promise<void> {\n const binding = unknownExecutionBindingReceipt(receipt, state.attemptId, reason)\n await appendOwnerBinding(state, binding)\n state.onReceipt?.(receipt, binding)\n}\n\nasync function appendNodeMaterialization(\n args: Pick<ScopeArgs, 'journal' | 'root'>,\n id: NodeId,\n seq: number,\n receipt: ProfileMaterializationReceipt,\n binding: ExecutionBindingReceipt,\n now: () => number,\n): Promise<void> {\n const at = new Date(now()).toISOString()\n await args.journal.appendEvent(args.root, {\n kind: 'materialized',\n id,\n receipt,\n seq,\n at,\n })\n await args.journal.appendEvent(args.root, {\n kind: 'execution-bound',\n id,\n binding,\n seq,\n at,\n })\n}\n\n/** Await whichever pending child settles first, returning the child (its `resolved` is set\n * by the time this resolves because `runChild`'s `.then` sets it before the promise\n * resolves downstream). */\nasync function raceFirstSettled(pending: LiveChild[]): Promise<LiveChild> {\n return Promise.race(pending.map((c) => c.settled.then(() => c)))\n}\n\n/** Stamp the cursor `seq`, write the `settled` journal record, and project the\n * `PreSeqSettled` into the frozen `Settled` the driver branches on. */\nasync function finalizeSettlement<Out>(\n child: LiveChild,\n settlement: PreSeqSettled,\n seq: number,\n args: ScopeArgs,\n now: () => number,\n): Promise<Settled<Out>> {\n const handle = frozenHandle<Out>(child)\n // A wait-state settles into the `woken` cursor event, not `settled` — kept distinct so any\n // journal reader can separate zero-cost waiting from paid work without inspecting payloads\n // (`spentFromJournal` therefore sums waits as the zero they are, with no special case).\n if (child.wait) return finalizeWait<Out>(child, settlement, seq, args, now, handle)\n const settledAt = now()\n child.settledAt = settledAt\n const at = new Date(settledAt).toISOString()\n if (settlement.kind === 'down') {\n child.status = 'failed'\n child.trace = settlement.trace\n child.providerModel = settlement.providerModel\n await args.journal.appendEvent(args.root, {\n kind: 'settled',\n id: child.id,\n status: 'down',\n spent: child.spent,\n infra: settlement.infra,\n reason: settlement.reason,\n ...(settlement.providerModel ? { providerModel: settlement.providerModel } : {}),\n trace: settlement.trace,\n seq,\n at,\n })\n // Re-home a crashed driver child's partial inference too (the pool already debited it via\n // `observe`) — so spentTotal/trajectory never undercount a sub-driver that died mid-run.\n if (settlement.metered) {\n await args.journal.appendEvent(args.root, {\n kind: 'metered',\n id: child.id,\n spend: settlement.metered,\n seq,\n at,\n })\n }\n notifyRuntimeHookEvent(\n args.hooks,\n {\n id: `${child.id}:settled`,\n runId: args.root,\n target: 'agent.child',\n phase: 'after',\n timestamp: settledAt,\n stepIndex: seq,\n parentId: args.parentId,\n payload: {\n childId: child.id,\n status: 'down',\n reason: settlement.reason,\n infra: settlement.infra,\n spent: child.spent,\n },\n },\n { signal: args.signal },\n )\n return {\n kind: 'down',\n handle,\n reason: settlement.reason,\n infra: settlement.infra,\n restartCount: settlement.restartCount,\n ...(settlement.providerModel ? { providerModel: settlement.providerModel } : {}),\n trace: settlement.trace,\n settledAt,\n seq,\n }\n }\n\n child.status = 'done'\n child.outRef = settlement.outRef\n child.spent = settlement.spent\n child.trace = settlement.trace\n child.providerModel = settlement.providerModel\n await args.journal.appendEvent(args.root, {\n kind: 'settled',\n id: child.id,\n status: 'done',\n outRef: settlement.outRef,\n ...(settlement.verdict ? { verdict: settlement.verdict } : {}),\n spent: settlement.spent,\n ...(settlement.providerModel ? { providerModel: settlement.providerModel } : {}),\n trace: settlement.trace,\n seq,\n at,\n })\n // Re-home a driver child's OWN-inference subtree total up to THIS (parent) tree as a `metered`\n // event for the child node — mirroring how `settled.spent` rolls child WORK up. So summing any\n // sub-tree root yields its true driver-inference cost, NOT reconciled (already pool-debited).\n if (settlement.metered) {\n await args.journal.appendEvent(args.root, {\n kind: 'metered',\n id: child.id,\n spend: settlement.metered,\n seq,\n at,\n })\n }\n notifyRuntimeHookEvent(\n args.hooks,\n {\n id: `${child.id}:settled`,\n runId: args.root,\n target: 'agent.child',\n phase: 'after',\n timestamp: settledAt,\n stepIndex: seq,\n parentId: args.parentId,\n payload: {\n childId: child.id,\n status: 'done',\n outRef: settlement.outRef,\n score: settlement.verdict?.score,\n valid: settlement.verdict?.valid,\n spent: settlement.spent,\n },\n },\n { signal: args.signal },\n )\n return {\n kind: 'done',\n handle,\n out: settlement.out as Out,\n outRef: settlement.outRef,\n ...(settlement.verdict ? { verdict: settlement.verdict } : {}),\n spent: settlement.spent,\n ...(settlement.providerModel ? { providerModel: settlement.providerModel } : {}),\n trace: settlement.trace,\n settledAt,\n seq,\n }\n}\n\n/** Journal a wait-state's settlement as a `woken` event and project it onto the same `Settled`\n * the driver branches on. `by` names WHY it woke — `fired` / `timeout` / `cancelled` — which is\n * the fact a resumed reader needs and cannot recover from a payload it may never fetch. */\nasync function finalizeWait<Out>(\n child: LiveChild,\n settlement: PreSeqSettled,\n seq: number,\n args: ScopeArgs,\n now: () => number,\n handle: Handle<Out>,\n): Promise<Settled<Out>> {\n const settledAt = now()\n child.settledAt = settledAt\n const at = new Date(settledAt).toISOString()\n if (settlement.kind === 'down') {\n child.status = 'cancelled'\n // A failed fresh `waiting` append means this node never existed durably. Do not leave a\n // terminal `woken` record with no arm record for replay to attach it to.\n if (child.wait?.armCommitted) {\n await args.journal.appendEvent(args.root, {\n kind: 'woken',\n id: child.id,\n by: 'cancelled',\n seq,\n at,\n })\n }\n return {\n kind: 'down',\n handle,\n reason: settlement.reason,\n infra: settlement.infra,\n restartCount: settlement.restartCount,\n trace: settlement.trace,\n settledAt,\n seq,\n }\n }\n child.status = 'done'\n child.outRef = settlement.outRef\n const out = settlement.out as WaitOutcome\n await args.journal.appendEvent(args.root, {\n kind: 'woken',\n id: child.id,\n by: out.settled,\n outRef: settlement.outRef,\n seq,\n at,\n })\n notifyRuntimeHookEvent(\n args.hooks,\n {\n id: `${child.id}:woken`,\n runId: args.root,\n target: 'agent.child',\n phase: 'after',\n timestamp: settledAt,\n stepIndex: seq,\n parentId: args.parentId,\n payload: { childId: child.id, status: 'done', wait: out },\n },\n { signal: args.signal },\n )\n return {\n kind: 'done',\n handle,\n out: settlement.out as Out,\n outRef: settlement.outRef,\n spent: settlement.spent,\n trace: settlement.trace,\n settledAt,\n seq,\n }\n}\n\n/**\n * Drive one child's `Executor` to a terminal `PreSeqSettled`, folding usage into the\n * conserved `Spend`, reconciling the reservation, and persisting the result blob. Both\n * executor shapes are handled here: a one-shot `Promise<ExecutorResult>` and a streaming\n * `AsyncIterable<UsageEvent>` whose terminal artifact is read from `resultArtifact()`.\n *\n * A thrown executor (or a real abort) becomes a TYPED `down` — never re-thrown — so a\n * single failing child cannot reject the `next()` cursor (the M2 typed-result discipline,\n * applied per child). The reservation is reconciled on EVERY path (success, abort, throw)\n * so the conserved pool can never leak a reservation.\n */\nasync function runChild<C>(\n live: LiveChild,\n executor: Executor<C>,\n childAbort: AbortController,\n task: unknown,\n opts: SpawnOpts,\n pool: BudgetPool,\n ticket: ReservationTicket,\n blobs: ResultBlobStore,\n now: () => number,\n executionReady: Promise<void>,\n executionEvidence: {\n complete: () => Promise<void>\n fail: () => Promise<void>\n },\n deadlineAtMs: number | undefined,\n): Promise<PreSeqSettled> {\n let reconciled = false\n let started = false\n let terminalTelemetryCaptured = false\n let teardownStarted = false\n let traceEvidence: WorkerTraceEvidence | undefined\n const captureTraceOnce = async (): Promise<WorkerTraceEvidence> => {\n traceEvidence ??= await captureWorkerTraceEvidence(live.readTraceSource, blobs, started)\n return traceEvidence\n }\n const teardownOnce = async (grace: number | 'brutalKill' | 'infinity'): Promise<void> => {\n if (teardownStarted) return\n teardownStarted = true\n await teardownExecutor(executor, grace, deadlineAtMs, now)\n live.cleanupConfirmed = true\n }\n const reconcileOnce = (spend: Spend): unknown | undefined => {\n if (reconciled) return undefined\n reconciled = true\n // A refused pre-execution path (including an unmetered executor) reconciles zero and refunds\n // its whole reservation. Every path that actually executes reports measured or unknown spend.\n try {\n pool.reconcile(ticket, spend)\n return undefined\n } catch (error) {\n return error\n }\n }\n try {\n // Identity and kernel-owned materialization evidence must be durable before execution can\n // begin. A failed append or invalid executor declaration produces a typed-down child and\n // refunds its reservation; the executor observes zero calls.\n await executionReady\n if (childAbort.signal.aborted) throw abortError(childAbort.signal)\n // A budgetExempt WORKER (e.g. the raw `cli` printer) reports zero spend by contract; its\n // reconcile refunds the whole reservation, keeping it out of the conserved Σk by construction.\n // Only the DRIVER path refuses budget-exempt runtimes (`driveHarnessFromBackend`), because a\n // driver's own inference must be metered.\n live.status = 'running'\n started = true\n const ran = executor.execute(task, childAbort.signal)\n let artifact: ExecutorResult<C>\n if (isAsyncIterable(ran)) {\n // Streaming: fold the incremental usage events as they arrive (the conserved-pool\n // authority), then read the terminal artifact after the stream drains. Each event also\n // republishes the running total + a fresh activity stamp onto the live child, so a\n // concurrent `scope.progress(id)` sees a worker mid-flight rather than a zeroed row.\n const spend = await foldStream(\n ran,\n (running) => {\n live.spent = running\n live.lastActivityAt = now()\n },\n childAbort.signal,\n )\n live.spent = spend\n await executionEvidence.complete()\n artifact = executor.resultArtifact() as ExecutorResult<C>\n const accounting = executor.accounting?.()\n const terminalSpend = preserveUnknownTelemetry(spend, artifact.spent)\n live.spent = accounting?.reported ?? terminalSpend\n terminalTelemetryCaptured = true\n live.executorDone = true\n const reconcileError = reconcileOnce(accounting?.reservation ?? terminalSpend)\n if (reconcileError !== undefined) throw reconcileError\n } else {\n const terminal = await awaitAbortable(Promise.resolve(ran), childAbort.signal)\n await executionEvidence.complete()\n const accounting = executor.accounting?.()\n live.spent = accounting?.reported ?? terminal.spent\n artifact = terminal\n terminalTelemetryCaptured = true\n live.executorDone = true\n const reconcileError = reconcileOnce(accounting?.reservation ?? terminal.spent)\n if (reconcileError !== undefined) throw reconcileError\n }\n // Executor work is complete; everything below is persistence/teardown. From here `settled`\n // resolves without further executor progress — the non-blocking drain keys on this.\n live.executorDone = true\n\n // A driver child's OWN-inference subtree total — re-homed by the parent on EVERY settle exit\n // (done, aborted, crash) so the journal always matches what the pool already debited.\n const ownMetered = executor.metered?.()\n const trace = await captureTraceOnce()\n\n if (childAbort.signal.aborted) {\n await teardownOnce(opts.shutdown ?? 'brutalKill')\n return downRecord(\n 'aborted before settle',\n true,\n trace,\n ownMetered,\n runtimeOwnedExecutorProviderEvidence(executor),\n )\n }\n\n // The durable record is keyed by the canonical content address of the output — the\n // single addressing scheme the blob store enforces and the supervisor's winner path\n // uses. An executor's self-minted `resultArtifact().outRef` is its own internal dedup\n // hint; the journal/blob `outRef` is re-derived here so replay rehydrates by one\n // scheme. Persist the blob BEFORE the journal `settled` record references its `outRef`,\n // so a crash never leaves a journaled ref pointing at a missing blob.\n const outRef = contentAddress(artifact.out)\n await blobs.put(outRef, artifact.out)\n await teardownOnce(opts.shutdown ?? DEFAULT_SUCCESSFUL_SHUTDOWN_MS)\n return {\n kind: 'done',\n out: artifact.out,\n outRef,\n ...(artifact.verdict ? { verdict: artifact.verdict } : {}),\n spent: live.spent,\n trace,\n providerModel: runtimeOwnedExecutorProviderEvidence(executor),\n ...(ownMetered ? { metered: ownMetered } : {}),\n }\n } catch (err) {\n // A thrown executor has also finished its own work — only the down-record persistence\n // remains, so the non-blocking drain may await this child too.\n live.executorDone = true\n let evidenceError: unknown\n try {\n await executionEvidence.fail()\n } catch (error) {\n evidenceError = error\n }\n // A recursive executor can still report the nested work committed before it threw.\n // Reconcile that whole partial subtree while journaling its child-work component separately.\n // A box-backed trace must be collected before teardown destroys the session that owns it.\n const trace = await captureTraceOnce()\n let teardownError: unknown\n try {\n await teardownOnce('brutalKill')\n } catch (error) {\n teardownError = error\n }\n const accounting = executor.accounting?.()\n if (accounting) live.spent = accounting.reported\n const providerModel = runtimeOwnedExecutorProviderEvidence(executor)\n const aborted = childAbort.signal.aborted || isAbortError(err)\n if (started && !terminalTelemetryCaptured && accounting === undefined) {\n // The provider never delivered a terminal usage receipt. This is true for an ordinary\n // network/provider crash just as it is for an abort. Preserve observed partial counts as a\n // lower bound, but never reinterpret the unreported remainder as zero under either root\n // ceiling. A recursive executor's explicit accounting remains authoritative on its throw\n // path; a persistence/teardown failure after a terminal artifact does too.\n live.spent = { ...live.spent, tokensKnown: false, usdKnown: false }\n }\n const reconcileError = reconcileOnce(accounting?.reservation ?? live.spent)\n // A crashed driver child still re-homes the partial inference it durably metered.\n return downRecord(\n // The operation that failed is the causal error. Cleanup and accounting can independently\n // fail while handling it, but must never replace it with a secondary diagnostic (for\n // example, missing terminal usage after a provider crash). Their presence still marks the\n // settlement as infrastructure-related, while the unknown spend flags retain the accounting\n // failure itself in the durable record.\n errMessage(err),\n evidenceError !== undefined ||\n teardownError !== undefined ||\n reconcileError !== undefined ||\n aborted ||\n isInfraError(err),\n trace,\n executor.metered?.(),\n providerModel,\n )\n }\n}\n\n/**\n * The step-8 merge-boundary adapter (M4): rehydrate a `Settled.done` into the kernel's\n * `Iteration` shape so `defaultSelectWinner` stays single-sourced — the supervisor selects\n * across settled children with the SAME argmax the loop kernel uses, not a forked copy.\n *\n * `index` is the cursor `seq` (the recorded, replay-stable order); `output`/`verdict`/\n * `tokenUsage`/`costUsd` are read straight off the settlement (already rehydrated from the\n * `outRef` blob by `next()`). Events are empty — a settled child is an opaque leaf result,\n * not a sandbox event stream — and the timing/cost fields project its conserved `Spend`.\n * Fail loud on a `down` settlement: only a `done` child is an iteration.\n */\nexport function settledToIteration<Out>(settled: Settled<Out>): Iteration<unknown, Out> {\n if (settled.kind === 'down') {\n throw new ValidationError(\n `settledToIteration: cannot adapt a 'down' settlement (node '${settled.handle.id}', seq ${settled.seq}) to an Iteration`,\n )\n }\n return {\n index: settled.seq,\n task: undefined,\n agentRunName: settled.handle.label,\n output: settled.out,\n ...(settled.verdict ? { verdict: settled.verdict } : {}),\n events: [],\n startedAt: 0,\n endedAt: settled.spent.ms,\n costUsd: settled.spent.usd,\n tokenUsage: cloneTokenUsage(settled.spent.tokens),\n }\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────────────────\n\nfunction normalizeLiveWorkerLimit(value: number | undefined): number | undefined {\n if (value === undefined || value <= 0) return undefined\n if (!Number.isSafeInteger(value)) {\n throw new ValidationError(\n `createScope: maxLiveWorkers must be a positive safe integer or <= 0 for uncapped, got ${String(value)}`,\n )\n }\n return value\n}\n\nfunction acquireLiveWorker(\n capacity: LiveWorkerCapacityState,\n): { ok: true; release: () => void } | { ok: false } {\n if (capacity.max !== undefined && capacity.live >= capacity.max) return { ok: false }\n capacity.live += 1\n let released = false\n return {\n ok: true,\n release(): void {\n if (released) return\n released = true\n capacity.live -= 1\n if (capacity.live < 0) {\n throw new ValidationError('scope: live-worker capacity released more than once')\n }\n },\n }\n}\n\nfunction makeTreeView(root: NodeId, children: Map<NodeId, LiveChild>): TreeView {\n const nodes: NodeSnapshot[] = [...children.values()].map((c) => ({\n id: c.id,\n parent: root,\n label: c.label,\n status: c.status,\n runtime: c.runtime,\n budget: c.budget,\n ...(c.ownedTreeRoot === undefined ? {} : { ownedTreeRoot: c.ownedTreeRoot }),\n ...(c.assignmentId === undefined ? {} : { assignmentId: c.assignmentId }),\n ...(c.identity ? { identity: c.identity } : {}),\n ...(c.materialization ? { materialization: c.materialization } : {}),\n ...(c.executionBindings.length > 0\n ? { executionBindings: Object.freeze([...c.executionBindings]) }\n : {}),\n spent: c.spent,\n ...(c.settledAt === undefined ? {} : { settledAt: c.settledAt }),\n ...(c.outRef ? { outRef: c.outRef } : {}),\n ...(c.trace ? { trace: c.trace } : {}),\n ...(c.providerModel ? { providerModel: c.providerModel } : {}),\n }))\n return {\n root,\n nodes,\n inFlight: nodes.filter((n) => n.status === 'running' || n.status === 'acquiring').length,\n waiting: nodes.filter((n) => n.status === 'waiting').length,\n }\n}\n\nfunction frozenHandle<C>(child: LiveChild): Handle<C> {\n return {\n id: child.id,\n label: child.label,\n status: child.status,\n ...(child.assignmentId === undefined ? {} : { assignmentId: child.assignmentId }),\n ...(child.identity ? { identity: child.identity } : {}),\n ...(child.materialization ? { materialization: child.materialization } : {}),\n ...(child.executionBindings.length > 0\n ? { executionBindings: Object.freeze([...child.executionBindings]) }\n : {}),\n abort(): void {\n // A settled child is terminal; abort is a no-op (its executor already tore down).\n },\n }\n}\n\n/** Derive the portable identity of the exact profile and task a node will execute. Caller-owned\n * candidate/correlation fields are checked at this boundary before they enter the durable log. */\nexport function deriveNodeExecutionIdentity(\n spec: Pick<AgentSpec, 'profile' | 'execution'>,\n task: unknown,\n): NodeExecutionIdentity | undefined {\n const digest = (value: unknown) => {\n try {\n return canonicalCandidateDigest(value)\n } catch {\n return undefined\n }\n }\n const profileDigest = authoredProfileDigest(spec.profile)\n const taskDigest = digest(task)\n const candidateDigest = spec.execution?.candidateDigest\n if (candidateDigest !== undefined && !sha256DigestSchema.safeParse(candidateDigest).success) {\n throw new ValidationError('scope.spawn: execution.candidateDigest must be a sha256 digest')\n }\n const correlation = freezeCorrelation(spec.execution?.correlation)\n if (!profileDigest && !taskDigest && !candidateDigest && !correlation) return undefined\n return Object.freeze({\n ...(profileDigest ? { profileDigest } : {}),\n ...(taskDigest ? { taskDigest } : {}),\n ...(candidateDigest ? { candidateDigest } : {}),\n ...(correlation ? { correlation } : {}),\n })\n}\n\nfunction isCompleteIdentity(\n identity: NodeExecutionIdentity | undefined,\n): identity is NodeExecutionIdentity & {\n readonly profileDigest: string\n readonly taskDigest: string\n} {\n return identity?.profileDigest !== undefined && identity.taskDigest !== undefined\n}\n\nfunction sameNodeExecutionIdentity(a: NodeExecutionIdentity, b: NodeExecutionIdentity): boolean {\n return canonicalCandidateDigest(a) === canonicalCandidateDigest(b)\n}\n\nfunction freezeCorrelation(\n value: Readonly<Record<string, string>> | undefined,\n): Readonly<Record<string, string>> | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError('scope.spawn: execution.correlation must be a string record')\n }\n const entries = Object.entries(value)\n for (const [key, item] of entries) {\n if (key.length === 0 || typeof item !== 'string' || item.length === 0) {\n throw new ValidationError(\n 'scope.spawn: execution.correlation keys and values must be non-empty strings',\n )\n }\n }\n return Object.freeze(Object.fromEntries(entries))\n}\n\n/**\n * Fold a streaming executor's normalized usage into the conserved `Spend`, publishing the\n * running total after EVERY event via `onProgress`.\n *\n * The publish is what makes a running worker observable. Before it, `live.spent` was assigned\n * once — after the whole stream drained — so `observe_agent` on a RUNNING worker reported\n * `{tokens:0, iterations:0}` for the entire run and a driver had no way to tell a worker three\n * turns deep from one that had produced nothing. It also means a worker that THROWS mid-stream\n * now reconciles its real partial spend instead of refunding work the provider already billed.\n */\nasync function foldStream(\n stream: AsyncIterable<UsageEvent>,\n onProgress?: (running: Spend) => void,\n signal?: AbortSignal,\n): Promise<Spend> {\n const tokens = zeroTokenUsage()\n let tokensKnown = true\n let usd = 0\n let usdKnown = true\n let iterations = 0\n const iterator = stream[Symbol.asyncIterator]()\n try {\n for (;;) {\n const next = signal\n ? await awaitAbortable(Promise.resolve(iterator.next()), signal)\n : await iterator.next()\n if (next.done) break\n const ev = next.value\n if (ev.kind === 'tokens') {\n addTokenUsage(tokens, ev)\n if (ev.tokensKnown === false) tokensKnown = false\n } else if (ev.kind === 'cost') {\n usd += ev.usd\n if (ev.usdKnown === false) usdKnown = false\n } else {\n iterations += 1\n }\n onProgress?.({\n iterations,\n tokens: cloneTokenUsage(tokens),\n ...(tokensKnown ? {} : { tokensKnown: false }),\n usd,\n ...(usdKnown ? {} : { usdKnown: false }),\n ms: 0,\n })\n }\n } catch (error) {\n // Ask a cooperative async generator to close, but never let a broken `return()` hide the\n // deadline that already won. Its promise is observed so a late rejection is not unhandled.\n void Promise.resolve(iterator.return?.()).catch(() => undefined)\n throw error\n }\n return {\n iterations,\n tokens,\n ...(tokensKnown ? {} : { tokensKnown: false }),\n usd,\n ...(usdKnown ? {} : { usdKnown: false }),\n ms: 0,\n }\n}\n\n/** Usage events carry measured increments; the terminal artifact carries whether a provider omitted\n * a whole accounting channel. Preserve those unknowns on the common streaming path. */\nfunction preserveUnknownTelemetry(streamed: Spend, terminal: Spend): Spend {\n const terminalTokens = cloneTokenUsage(terminal.tokens)\n return {\n ...streamed,\n tokens: {\n ...streamed.tokens,\n ...(streamed.tokens.freshInput === undefined && terminalTokens.freshInput !== undefined\n ? { freshInput: terminalTokens.freshInput }\n : {}),\n ...(streamed.tokens.cacheRead === undefined && terminalTokens.cacheRead !== undefined\n ? { cacheRead: terminalTokens.cacheRead }\n : {}),\n ...(streamed.tokens.cacheWrite === undefined && terminalTokens.cacheWrite !== undefined\n ? { cacheWrite: terminalTokens.cacheWrite }\n : {}),\n ...(streamed.tokens.cacheBreakdownKnown === false ||\n terminalTokens.cacheBreakdownKnown === false\n ? { cacheBreakdownKnown: false as const }\n : {}),\n },\n ...(terminal.tokensKnown === false ? { tokensKnown: false } : {}),\n ...(terminal.usdKnown === false ? { usdKnown: false } : {}),\n ms: terminal.ms,\n }\n}\n\nasync function awaitAbortable<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) {\n // `execute()` may have returned a promise that rejects from the same abort. Observe it before\n // returning the already-winning cancellation so a fast abort cannot become an unhandled\n // provider rejection.\n void work.catch(() => undefined)\n throw abortError(signal)\n }\n return await new Promise<T>((resolve, reject) => {\n let settled = false\n const onAbort = () => {\n // A cooperative executor often resolves its terminal usage receipt from an abort listener.\n // Give that already-triggered resolution one microtask to win; an ignoring executor still\n // loses immediately afterward.\n queueMicrotask(() => {\n if (settled) return\n settled = true\n cleanup()\n reject(abortError(signal))\n })\n }\n const cleanup = () => signal.removeEventListener('abort', onAbort)\n signal.addEventListener('abort', onAbort, { once: true })\n work.then(\n (value) => {\n if (settled) return\n settled = true\n cleanup()\n resolve(value)\n },\n (error) => {\n if (settled) return\n settled = true\n cleanup()\n reject(error)\n },\n )\n })\n}\n\nfunction abortError(signal: AbortSignal): Error {\n const reason = signal.reason\n const error = new Error(\n typeof reason === 'string' && reason.length > 0 ? reason : 'execution aborted',\n )\n error.name = 'AbortError'\n return error\n}\n\nfunction downRecord(\n reason: string,\n infra: boolean,\n trace: WorkerTraceEvidence,\n metered?: Spend,\n providerModel?: import('./types').ProviderModelExecutionEvidence,\n): PreSeqSettled {\n return {\n kind: 'down',\n reason,\n infra,\n restartCount: 0,\n trace,\n ...(providerModel ? { providerModel } : {}),\n ...(metered ? { metered } : {}),\n }\n}\n\nfunction zeroSpend(): Spend {\n return { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 }\n}\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterable<UsageEvent> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as AsyncIterable<UsageEvent>)[Symbol.asyncIterator] === 'function'\n )\n}\n\n/** An `AgentSpec` is identified structurally — it carries a `profile` and a `harness`\n * field (`null` or a `BackendType`) and optionally an `executor`. */\nfunction isAgentSpec(value: unknown): value is AgentSpec {\n if (typeof value !== 'object' || value === null) return false\n const v = value as Record<string, unknown>\n return 'profile' in v && 'harness' in v\n}\n\nfunction isAbortError(err: unknown): boolean {\n return (\n typeof err === 'object' &&\n err !== null &&\n 'name' in err &&\n (err as { name: unknown }).name === 'AbortError'\n )\n}\n\n/** External-boundary failures (network/FS/subprocess) are infra — excluded from the merge\n * `n` and the equal-k assertion. A `ValidationError` from a built-in executor wraps a\n * config/transport failure, so it counts as infra; other throws are a real bad result. */\nfunction isInfraError(err: unknown): boolean {\n return err instanceof ValidationError\n}\n\nfunction errMessage(err: unknown): string {\n if (err instanceof Error) return err.message\n return String(err)\n}\n","/**\n *\n * The recursive driver-executor — the seam that lets a SPAWNED child be a DRIVER, so\n * agents drive agents drive agents over the one keystone atom.\n *\n * A spawned child resolves through the open registry to an `Executor`; the built-in\n * executors (router/inline, sandbox, cli) are LEAVES — `execute(task, signal)` runs the\n * work and settles. This executor is the recursive case: on `execute`, it mounts a NESTED\n * `Scope` (the scope hands it the mount via the `nested-scope` seam) over a child allocation\n * carved from its parent reservation, plus shared journal/blobs and the same open registry, then\n * runs the wrapped driver `Agent.act(task, nestedScope)`. The driver spawns its own\n * children into that nested scope; each resolves to EITHER a leaf executor (a worker child)\n * OR this same driver-executor (a driver child) — recursively. So a driver spawns a driver\n * spawns a worker, all on one budget-conserving tree.\n *\n * Why this preserves every keystone invariant (the scope owns the sharing; this executor\n * only runs the driver over what the scope mounts):\n * - Conserved budget: the parent reserves the driver's whole allocation once. The nested scope\n * partitions only that allocation, and its actual child work + driver inference reconcile the\n * parent ticket once at settle. A deep tree cannot overspend or double-charge the root total.\n * - Journal: the nested scope writes to its OWN tree key (`${journalRoot}/${nodeId}`) so\n * its cursor `seq`s never collide with the parent's in the per-tree uniqueness guard,\n * while every nested tree shares the one `SpawnJournal` — the whole recursion is one\n * journal, queryable tree by tree.\n * - Settlement bubbling: the driver child settles into its PARENT scope with child work and\n * driver inference kept separate in the journal, while their sum reconciles the one parent\n * reservation. The supervisor sees the whole sub-tree exactly once.\n * - Depth ceiling: the nested scope runs at `depth+1`, so the supervisor's `maxDepth`\n * (paired with the conserved pool per R3) fails a spawn closed once the recursion is too\n * deep — exactly as it does for a flat tree.\n *\n * Layering: pure keystone composition. It reuses the scope's `NestedScopeSeam` + the shared\n * `SpawnJournal`; it builds NO new budget, journal, or selection logic. The recursion rides\n * the existing atom.\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport { addTokenUsage, cloneTokenUsage, zeroTokenUsage } from '../util'\nimport { executableAgentSpecSnapshot } from './executable-spec'\nimport {\n attestRuntimeOwnedDeferredExecutor,\n runtimeOwnedScopeOwnerRuntime,\n} from './materialization'\nimport {\n finalizeScopeOwnerMaterialization,\n type NestedScopeSeam,\n nestedScopeSeamKey,\n} from './scope'\nimport { attestNestedDriverTreeOwner, driverRuntime, nestedDriverTreeRoot } from './tree-key'\nimport type {\n Agent,\n AgentExecutionRef,\n AgentSpec,\n DefaultVerdict,\n Executor,\n ExecutorAccounting,\n ExecutorContext,\n ExecutorFactory,\n ExecutorRegistry,\n ExecutorResult,\n Scope,\n SpawnEvent,\n SpawnJournal,\n Spend,\n} from './types'\n\n/** The runtime tag the registry maps a driver child to. */\nexport { driverRuntime } from './tree-key'\n\n/** A driver child's spec carries the `Agent` to run inside the nested scope. */\ninterface DriverSpec extends AgentSpec {\n readonly driverRuntime: typeof driverRuntime\n readonly driver: Agent<unknown, unknown>\n /** The shared journal the nested tree is one tree key inside (so the executor can\n * begin its nested tree + sum its spend off the same record). */\n readonly journal: SpawnJournal\n}\n\n/**\n * Mark + carry a driver `Agent` so the recursive registry resolves it to the\n * driver-executor. The returned agent is SPAWNED (never run directly): its\n * `executorSpec` carries the exact profile, driver agent, and shared\n * journal so the executor can run its `act` inside a nested scope. `act` fails loud if\n * called directly — a driver child runs THROUGH its nested-scope executor, never as a root.\n */\nexport function driverChild<Out>(\n profile: AgentProfile,\n driver: Agent<unknown, Out>,\n journal: SpawnJournal,\n execution?: AgentExecutionRef,\n): Agent<unknown, Out> {\n const name = profile.name ?? driver.name\n const rawSpec: DriverSpec = {\n profile,\n harness: null,\n ...(execution ? { execution } : {}),\n driverRuntime,\n driver: driver as Agent<unknown, unknown>,\n journal,\n }\n const spec = executableAgentSpecSnapshot(rawSpec, 'driverChild') as DriverSpec\n const deliver = driver.deliver?.bind(driver)\n return {\n name,\n executorSpec: spec,\n ...(deliver\n ? {\n deliver(message: unknown): boolean {\n return deliver(message) !== false\n },\n }\n : {}),\n act(): Promise<Out> {\n throw new ValidationError(\n `driverChild: \"${name}\" was run directly; a driver child runs through its nested-scope executor`,\n )\n },\n } as Agent<unknown, Out> & { executorSpec: AgentSpec }\n}\n\n/** True when a spec carries Runtime's explicit nested-driver tag plus a driver Agent. */\nexport function isDriverSpec(spec: AgentSpec): spec is DriverSpec {\n if ((spec as { driverRuntime?: unknown }).driverRuntime !== driverRuntime) return false\n const driver = (spec as { driver?: unknown }).driver\n if (!isAgent(driver)) {\n throw new ValidationError(\n 'driverExecutor: a nested-driver spec must carry a `driver` Agent to run inside its nested scope',\n )\n }\n return true\n}\n\n/**\n * The recursive driver-executor factory. `withDriverExecutor` routes a child carrying\n * Runtime's explicit nested-driver tag here; any other child resolves to a leaf built-in. On `execute`, it\n * reads the `nested-scope` seam the SCOPE seeded, mounts a nested `Scope` one `depth`\n * deeper over the driver's reserved child pool plus shared journal/blobs/registry, runs the driver\n * `Agent.act(task, nestedScope)`, and reports the conserved spend summed off the nested\n * tree's settled events — so the parent scope's reconcile rolls the whole sub-tree's spend\n * into the conserved total.\n *\n * A `down` from the nested driver (a thrown `act` or an aborted scope) propagates as a\n * thrown executor, which the parent scope types into a `down` settlement — the same\n * fail-loud-into-typed-down discipline a leaf gets.\n */\nexport const driverExecutorFactory: ExecutorFactory<unknown> = (rawSpec, ctx) => {\n const spec = executableAgentSpecSnapshot(rawSpec, 'driverExecutorFactory')\n if (!isDriverSpec(spec)) {\n throw new ValidationError(\n 'driverExecutorFactory: spec is not a driver child (missing Runtime nested-driver tag)',\n )\n }\n const driver = spec.driver\n const deliver = driver.deliver?.bind(driver)\n const journal = spec.journal\n const seam = readNestedScopeSeam(ctx)\n\n let artifact: ExecutorResult<unknown> | undefined\n // The nested subtree's driver INFERENCE, cached so the parent re-homes it on settle. Computed\n // on BOTH the success AND crash paths (metered events are durable in the nested tree regardless),\n // so a sub-driver that crashes mid-run still re-homes its partial inference — pool + journal agree.\n let meteredSpend: Spend | undefined\n let accounting: ExecutorAccounting | undefined\n let active:\n | {\n readonly controller: AbortController\n readonly scope: Scope<unknown>\n close?: Promise<void>\n }\n | undefined\n\n const closeActive = (reason: string): Promise<void> => {\n if (active === undefined) return Promise.resolve()\n active.close ??= closeNestedScope(active.scope, active.controller, reason)\n return active.close\n }\n\n const executor: Executor<unknown> = {\n runtime: driverRuntime,\n ...(deliver\n ? {\n deliver(message: unknown): boolean {\n return deliver(message) !== false\n },\n }\n : {}),\n async execute(task, signal): Promise<ExecutorResult<unknown>> {\n // The nested tree key namespaces this driver's children inside the ONE shared\n // journal, so its cursor seqs never collide with the parent's per-tree guard.\n const nestedRoot = nestedDriverTreeRoot(seam.journalRoot, seam.nodeId)\n await journal.beginTree(nestedRoot, new Date(0).toISOString())\n\n const controller = new AbortController()\n const onParentAbort = () => controller.abort(signal.reason)\n if (signal.aborted) controller.abort(signal.reason)\n else signal.addEventListener('abort', onParentAbort, { once: true })\n const nestedScope: Scope<unknown> = seam.mount(nestedRoot, controller.signal)\n active = { controller, scope: nestedScope }\n\n try {\n // Run the driver. Its `act` spawns children into the nested scope and reacts via\n // `scope.next()`; a thrown `act` propagates so the PARENT scope types it into a down.\n const out = await driverActAbortable(() => driver.act(task, nestedScope), controller.signal)\n await finalizeScopeOwnerMaterialization(nestedScope)\n\n // A driver may choose its answer while descendants still run. Its allocation is not\n // refundable until every descendant has stopped and reached a terminal journal record.\n await closeActive('driver completed')\n\n // Read the nested tree's events ONCE. Keep two journal categories while reconciling their\n // sum against this driver's one parent reservation:\n // - `spent` = settled child WORK, written on this driver's settlement.\n // - `metered` = nested driver INFERENCE, re-homed as a separate metered event.\n const events = await loadTreeEvents(journal, nestedRoot)\n const settled = events.filter(isSettled)\n const childWork = sumSpend(settled)\n meteredSpend = nonZeroOrUndef(sumMetered(events))\n accounting = {\n reported: childWork,\n reservation: addSpend(childWork, meteredSpend ?? zeroSpend()),\n }\n // Completion propagation follows both facts: the subtree delivered at least one valid\n // child, and this manager's finalizer actually accepted an output. A custom finalizer may\n // refuse an otherwise valid child because product state is incomplete; that refusal must\n // remain invalid when the nested manager settles into its parent.\n const verdict = deriveDeliveryVerdict(settled, out)\n artifact = {\n outRef: `${driverRuntime}:${nestedRoot}`,\n out,\n spent: childWork,\n ...(verdict ? { verdict } : {}),\n }\n return artifact\n } catch (err) {\n await finalizeScopeOwnerMaterialization(active?.scope ?? nestedScope).catch(() => undefined)\n await closeActive('driver stopped')\n // Crash mid-run: the nested tree still holds the durable `metered` events the sub-driver\n // already wrote (pool already debited them). Cache them so the parent's down-path re-home\n // lands the partial inference and the two ledgers stay in agreement. A missing tree must\n // not mask the original error.\n const partial = await safeRollup(journal, nestedRoot)\n meteredSpend = partial?.metered\n accounting = partial?.accounting\n throw err\n } finally {\n signal.removeEventListener('abort', onParentAbort)\n active = undefined\n }\n },\n accounting(): ExecutorAccounting | undefined {\n return accounting\n },\n metered(): Spend | undefined {\n return meteredSpend\n },\n async teardown(): Promise<{ destroyed: boolean }> {\n await closeActive('driver executor teardown')\n return { destroyed: true }\n },\n resultArtifact(): ExecutorResult<unknown> {\n if (!artifact) {\n throw new ValidationError('driverExecutor: resultArtifact() read before execute()')\n }\n return artifact\n },\n }\n const treeOwner = attestNestedDriverTreeOwner(executor)\n const ownerRuntime = runtimeOwnedScopeOwnerRuntime(driver)\n return ownerRuntime === undefined\n ? treeOwner\n : attestRuntimeOwnedDeferredExecutor(treeOwner, ownerRuntime)\n}\n\n/**\n * Register the driver-executor so a child carrying Runtime's explicit nested-driver tag resolves\n * to it. The base registry resolves by harness alone, so a recursive run needs a registry that\n * routes the driver tag here first. Returns a registry decorator: a tagged driver spec → the\n * driver-executor; everything else → the base registry's resolution\n * (leaf built-ins + BYO).\n */\nexport function withDriverExecutor(base: ExecutorRegistry): ExecutorRegistry {\n return {\n register: base.register.bind(base),\n resolve<Out>(rawSpec: AgentSpec) {\n const spec = executableAgentSpecSnapshot(rawSpec, 'driver executor registry')\n if ((spec as { driverRuntime?: unknown }).driverRuntime === driverRuntime && !spec.executor) {\n return {\n succeeded: true as const,\n value: ((_ignored, context) =>\n driverExecutorFactory(spec, context)) as ExecutorFactory<Out>,\n }\n }\n const resolved = base.resolve<Out>(spec)\n if (!resolved.succeeded) return resolved\n return {\n succeeded: true as const,\n value: (_ignored, context) => resolved.value(spec, context),\n }\n },\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────\n\nasync function closeNestedScope(\n scope: Scope<unknown>,\n controller: AbortController,\n reason: string,\n): Promise<void> {\n if (!controller.signal.aborted) controller.abort(reason)\n for (;;) {\n const settled = await scope.next()\n if (settled === null) break\n }\n const view = scope.view\n if (view.inFlight > 0 || view.waiting > 0) {\n throw new ValidationError(\n `driverExecutor: nested cleanup left ${view.inFlight} running and ${view.waiting} waiting nodes`,\n )\n }\n}\n\nasync function driverActAbortable<T>(act: () => Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) throw driverAbortError(signal)\n return await new Promise<T>((resolve, reject) => {\n let settled = false\n const cleanup = () => signal.removeEventListener('abort', onAbort)\n const onAbort = () => {\n queueMicrotask(() => {\n if (settled) return\n settled = true\n cleanup()\n reject(driverAbortError(signal))\n })\n }\n signal.addEventListener('abort', onAbort, { once: true })\n let work: Promise<T>\n try {\n work = Promise.resolve(act())\n } catch (error) {\n cleanup()\n reject(error)\n return\n }\n work.then(\n (value) => {\n if (settled) return\n settled = true\n cleanup()\n resolve(value)\n },\n (error) => {\n if (settled) return\n settled = true\n cleanup()\n reject(error)\n },\n )\n })\n}\n\nfunction driverAbortError(signal: AbortSignal): Error {\n const reason = signal.reason\n const error = new Error(\n typeof reason === 'string' && reason.length > 0 ? reason : 'driver aborted',\n )\n error.name = 'AbortError'\n return error\n}\n\n/** The nested tree's full event list — the one evidence the spend, verdict, AND driver-inference\n * roll-ups read off the same journal the supervisor sums. */\nasync function loadTreeEvents(journal: SpawnJournal, nestedRoot: string): Promise<SpawnEvent[]> {\n const events = await journal.loadTree(nestedRoot)\n if (events === undefined) {\n throw new ValidationError(\n `driverExecutor: nested tree '${nestedRoot}' missing from the journal after run (corrupted log)`,\n )\n }\n return events\n}\n\nfunction isSettled(ev: SpawnEvent): ev is Extract<SpawnEvent, { kind: 'settled' }> {\n return ev.kind === 'settled'\n}\n\n/** Sum the conserved spend over the nested tree's settled events — the honest per-channel\n * roll-up of the whole sub-tree's child WORK. */\nfunction sumSpend(settled: ReadonlyArray<{ spent: Spend }>): Spend {\n const total: Spend = { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 }\n for (const ev of settled) {\n total.iterations += ev.spent.iterations\n addTokenUsage(total.tokens, ev.spent.tokens)\n if (ev.spent.tokensKnown === false) total.tokensKnown = false\n total.usd += ev.spent.usd\n if (ev.spent.usdKnown === false) total.usdKnown = false\n total.ms += ev.spent.ms\n }\n return total\n}\n\n/** Sum the nested tree's `metered` events — the sub-tree's whole driver INFERENCE (this driver's\n * own turns + any sub-driver inference already re-homed into this tree). Re-homed up to the parent\n * as one `metered` event; never reconciled (already pool-debited live via `observe`). */\nfunction sumMetered(events: ReadonlyArray<SpawnEvent>): Spend {\n const total: Spend = { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 }\n for (const ev of events) {\n if (ev.kind !== 'metered') continue\n total.iterations += ev.spend.iterations\n addTokenUsage(total.tokens, ev.spend.tokens)\n if (ev.spend.tokensKnown === false) total.tokensKnown = false\n total.usd += ev.spend.usd\n if (ev.spend.usdKnown === false) total.usdKnown = false\n total.ms += ev.spend.ms\n }\n return total\n}\n\nfunction zeroSpend(): Spend {\n return { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 }\n}\n\nfunction addSpend(a: Spend, b: Spend): Spend {\n return {\n iterations: a.iterations + b.iterations,\n tokens: (() => {\n const tokens = cloneTokenUsage(a.tokens)\n addTokenUsage(tokens, b.tokens)\n return tokens\n })(),\n ...(a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: a.usd + b.usd,\n ...(a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {}),\n ms: a.ms + b.ms,\n }\n}\n\n/** An all-zero spend that carries an UNKNOWN marker counts as non-zero: a sub-driver whose turns\n * went unmeasured did real work, and dropping its `metered` event here would re-hide upstream the\n * very turn the driver refused to skip. */\nfunction isNonZeroSpend(s: Spend): boolean {\n return (\n s.iterations > 0 ||\n s.tokens.input > 0 ||\n s.tokens.output > 0 ||\n s.usd > 0 ||\n s.ms > 0 ||\n s.tokensKnown === false ||\n s.usdKnown === false\n )\n}\n\n/** A spend, or `undefined` when it is all-zero — so `metered()` returns undefined for a driver\n * whose sub-tree did no inference (and the parent journals no empty `metered` event). */\nfunction nonZeroOrUndef(s: Spend): Spend | undefined {\n return isNonZeroSpend(s) ? s : undefined\n}\n\n/** Sum the nested tree's metered events, tolerating a missing tree (a crash before `beginTree`\n * landed) — never throw here, or it would mask the original `act` error on the crash path. */\nasync function safeRollup(\n journal: SpawnJournal,\n nestedRoot: string,\n): Promise<\n { readonly metered: Spend | undefined; readonly accounting: ExecutorAccounting } | undefined\n> {\n try {\n const events = await loadTreeEvents(journal, nestedRoot)\n const childWork = sumSpend(events.filter(isSettled))\n const metered = nonZeroOrUndef(sumMetered(events))\n return {\n metered,\n accounting: {\n reported: childWork,\n reservation: addSpend(childWork, metered ?? zeroSpend()),\n },\n }\n } catch {\n return undefined\n }\n}\n\n/** Derive the driver child's delivery verdict from its DIRECT children's settlements and the\n * manager's actual finalized output: `valid` iff a direct child delivered AND the finalizer\n * returned a defined output;\n * `score` = the best delivered score. Returns `undefined` when no child settled at all (the\n * driver itself produced nothing to bubble a verdict from). Fail-closed: a child whose verdict\n * carried no `valid` counts as not-delivered. */\nfunction deriveDeliveryVerdict(\n settled: ReadonlyArray<{ status: 'done' | 'down'; verdict?: DefaultVerdict }>,\n finalizedOutput: unknown,\n): DefaultVerdict | undefined {\n let sawChild = false\n let anyValid = false\n let bestValidScore: number | undefined\n let bestDoneScore: number | undefined\n for (const ev of settled) {\n sawChild = true\n if (ev.status !== 'done') continue\n const score = ev.verdict?.score\n if (score !== undefined && (bestDoneScore === undefined || score > bestDoneScore)) {\n bestDoneScore = score\n }\n if (ev.verdict?.valid === true) {\n anyValid = true\n if (score !== undefined && (bestValidScore === undefined || score > bestValidScore)) {\n bestValidScore = score\n }\n }\n }\n if (!sawChild) return undefined\n const accepted = anyValid && finalizedOutput !== undefined\n return {\n valid: accepted,\n score: accepted ? (bestValidScore ?? 1) : (bestDoneScore ?? 0),\n }\n}\n\nfunction readNestedScopeSeam(ctx: ExecutorContext): NestedScopeSeam {\n const seam = ctx.seams[nestedScopeSeamKey] as NestedScopeSeam | undefined\n if (!seam || typeof seam.mount !== 'function') {\n throw new ValidationError(\n `driverExecutor: missing required seam \"${nestedScopeSeamKey}\" — a driver child must be spawned through a Scope that seeds it (the keystone scope does)`,\n )\n }\n return seam\n}\n\nfunction isAgent(value: unknown): value is Agent<unknown, unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { act?: unknown }).act === 'function' &&\n typeof (value as { name?: unknown }).name === 'string'\n )\n}\n","/**\n * `SupervisorFinalizer` — the pluggable last step of a driver run: how the settled-worker ledger\n * becomes the run's output. `bestDelivered` (the default) returns the single highest-scoring\n * DELIVERED child's output; `collectDelivered` returns every verified distinct output with its\n * provenance — the shape a panel of disagreeing evaluators, a Pareto set, or a competing-hypotheses\n * record needs. A custom finalizer plugs in through `DriverAgentOptions.finalizer` /\n * `SuperviseOptions.finalizer`.\n *\n * THE INVARIANT the seam enforces, not merely documents: a finalizer operates on structurally\n * DELIVERED outputs only — children that settled `done` AND passed their completion oracle\n * (`valid === true`). `runFinalizer` materializes exactly those into `ctx.delivered`, and the\n * `ctx.blobs` reader it hands over refuses any `outRef` that is not a delivered child's result\n * (fail loud). An undelivered or invalid child is visible in `ctx.allSettled` as METADATA — a\n * finalizer can record the disagreement — but its prose is unreachable and it can never become\n * (or be folded into) the output. Returning `undefined` means \"nothing deliverable\": the\n * supervisor types it a no-winner, never a best-effort coercion.\n *\n * @experimental\n */\n\nimport { ValidationError } from '../../errors'\nimport type { ResultBlobStore, Scope, TreeView } from './types'\n\n/** One settled worker as the finalizer sees it — the ledger row (structural fields only). */\nexport interface FinalizerSettled {\n readonly id: string\n readonly status: 'done' | 'down'\n readonly score?: number\n readonly valid?: boolean\n readonly outRef?: string\n readonly reason?: string\n}\n\n/** One DELIVERED child, materialized: settled `done`, oracle-passed, output rehydrated. `out` is\n * `undefined` only when the child settled without an `outRef` (no artifact to rehydrate). */\nexport interface DeliveredOutput {\n readonly id: string\n readonly score?: number\n readonly outRef?: string\n readonly out?: unknown\n}\n\n/** What a finalizer gets to decide with. `delivered` is the ONLY output material; `allSettled`\n * and `tree` are metadata (record a disagreement, count the downs); `blobs` re-reads delivered\n * artifacts only; `budget` is the conserved-pool readout at finalize time. */\nexport interface FinalizeContext {\n readonly delivered: ReadonlyArray<DeliveredOutput>\n readonly allSettled: ReadonlyArray<FinalizerSettled>\n readonly tree: TreeView\n readonly blobs: Pick<ResultBlobStore, 'get'>\n readonly budget: Scope<unknown>['budget']\n}\n\n/** The finalization seam: ledger in, output (or `undefined` = nothing deliverable) out. */\nexport type SupervisorFinalizer = (\n ctx: FinalizeContext,\n) => Promise<unknown | undefined> | unknown | undefined\n\n/**\n * The tree that describes the WHOLE run: this process's live nodes plus, on a resumed run, the\n * committed nodes of the prior process(es). Node ids are assigned by the journal and unique across\n * processes, so the union needs no reconciliation. `inFlight`/`waiting` stay the LIVE counts — a\n * prior process's in-flight node died with it and is not in flight now.\n *\n * Without this, a resumed run reports spend for work whose nodes are missing from its own tree.\n * On a run that never resumed there is nothing to merge and the live view is returned unchanged.\n */\nexport function runTree(scope: Pick<Scope<unknown>, 'view' | 'resume'>): TreeView {\n const live = scope.view\n const prior = scope.resume?.view\n if (prior === undefined) return live\n const liveIds = new Set(live.nodes.map((n) => n.id))\n const carried = prior.nodes.filter((n) => !liveIds.has(n.id))\n if (carried.length === 0) return live\n return { ...live, nodes: [...carried, ...live.nodes] }\n}\n\n/** The single argmax both the default finalizer and `finalizeBestDelivered` share: highest\n * score wins, missing scores count 0, ties keep the earliest ledger entry. */\nexport function pickBestDelivered<T extends { readonly score?: number }>(\n delivered: ReadonlyArray<T>,\n): T | undefined {\n let best: T | undefined\n for (const w of delivered) if (best === undefined || (w.score ?? 0) > (best.score ?? 0)) best = w\n return best\n}\n\n/** Keep-best under the completion oracle — the DEFAULT finalizer and the exact behavior every\n * existing caller had: the highest-scoring delivered child's output, `undefined` when nothing\n * delivered (or the best delivered child carries no artifact). */\nexport const bestDelivered: SupervisorFinalizer = (ctx) => pickBestDelivered(ctx.delivered)?.out\n\n/**\n * Every verified distinct output, highest score first — the shape for competing hypotheses, a\n * Pareto front, or a recorded evaluator split (three judges 2:1 → both outputs survive, with\n * provenance, instead of the minority report being erased). Distinct by `outRef` (content\n * address), so identical outputs collapse to one entry. `undefined` when nothing delivered —\n * an empty collection is a no-winner, not a winner wrapping `[]`.\n */\nexport const collectDelivered: SupervisorFinalizer = (ctx) => {\n const seen = new Set<string>()\n const distinct = [...ctx.delivered]\n .sort((a, b) => (b.score ?? 0) - (a.score ?? 0))\n .filter((w) => {\n if (w.outRef === undefined || seen.has(w.outRef)) return false\n seen.add(w.outRef)\n return true\n })\n .map((w) => ({ id: w.id, score: w.score, outRef: w.outRef, out: w.out }))\n return distinct.length > 0 ? distinct : undefined\n}\n\n/**\n * Run a finalizer over a settled-worker ledger under the delivered-only invariant: filter the\n * ledger to structurally delivered children, materialize their outputs, and hand the finalizer a\n * blob reader that throws on any ref outside that set. This is the one call site both driver arms\n * (the in-process tool-loop and the MCP-mounted harness) finalize through.\n */\nexport async function runFinalizer(\n finalizer: SupervisorFinalizer,\n args: {\n readonly settled: ReadonlyArray<FinalizerSettled>\n readonly blobs: ResultBlobStore\n readonly tree: TreeView\n readonly budget: Scope<unknown>['budget']\n },\n): Promise<unknown | undefined> {\n const deliveredRows = args.settled.filter((w) => w.status === 'done' && w.valid === true)\n const deliveredRefs = new Set<string>()\n for (const w of deliveredRows) if (w.outRef !== undefined) deliveredRefs.add(w.outRef)\n const delivered: DeliveredOutput[] = await Promise.all(\n deliveredRows.map(async (w) => ({\n id: w.id,\n ...(w.score !== undefined ? { score: w.score } : {}),\n ...(w.outRef !== undefined ? { outRef: w.outRef, out: await args.blobs.get(w.outRef) } : {}),\n })),\n )\n const guardedBlobs: Pick<ResultBlobStore, 'get'> = {\n get: (outRef: string) => {\n if (!deliveredRefs.has(outRef)) {\n throw new ValidationError(\n `finalizer: outRef '${outRef}' is not a DELIVERED child's result — a finalizer may ` +\n 'only operate on outputs that settled done and passed their completion oracle',\n )\n }\n return args.blobs.get(outRef)\n },\n }\n return finalizer({\n delivered,\n allSettled: args.settled,\n tree: args.tree,\n blobs: guardedBlobs,\n budget: args.budget,\n })\n}\n","/**\n *\n * The `Supervisor` impl (KEYSTONE, build step 5).\n *\n * Owns the four things a free-running recursive `act` cannot own itself: the GLOBAL\n * conserved budget pool, the event-sourced spawn log, the abort cascade over the whole\n * live tree, and the OTP intensity breaker. `run` builds the root `Scope` over those,\n * runs the root `Agent.act`, and returns a TYPED `SupervisedResult` — a no-winner is\n * never coerced into a best-effort `Out`.\n *\n * Three lifecycle invariants this impl enforces by construction:\n * - Join barrier: when `act()` settles (resolve OR reject), every still-live child is\n * torn down before `run` returns — the generalization of the kernel's\n * `finally{ Promise.allSettled(destroy) }` barrier (run-loop.ts) from boxes to the\n * whole sub-tree. A teardown failure is `allSettled`'d and journaled as a\n * `cancelled` event; it NEVER masks act()'s own outcome. act()'s rejection is the\n * PRIMARY error (the kernel's firstError precedence), so a teardown throw during the\n * barrier can never overwrite the real failure.\n * - Abort cascade: a root abort (caller signal, `RootHandle.abort`, a tripped breaker,\n * or pool exhaustion) aborts ONE internal controller whose signal is the root scope's\n * signal. The scope cascades that into every live child's executor abort — which, for\n * an `acquiring` child, chains into the `acquireSandbox` signal and reaps the\n * find-by-name orphan box (M1). The supervisor never reaps children directly.\n * - The supervisor NEVER re-enters a child (m3): the kernel/`acquireSandbox` already\n * retried at the leaf, and a driver re-spawns through `scope.spawn`. The breaker only\n * COUNTS `down` settlements within the intensity window and trips to a typed\n * no-winner; it does not restart anything.\n *\n * Selection lives in the driver, not here (selector≠judge): `act` returns the synthesized\n * winner `Out`. The supervisor content-addresses that `Out` for its replay `outRef`, reads\n * `spentTotal` off the journal (`settled` child work + `metered` driver inference), and wraps\n * it as a typed `winner` — it does not re-rank children behind the driver's back.\n *\n * @stable\n */\n\nimport { sha256DigestSchema } from '@tangle-network/agent-interface'\nimport {\n aggregateProviderModelEvidence,\n contentAddress,\n loadSpawnForest,\n materializeTreeView,\n pendingWaits,\n replaySpawnTree,\n} from '../../durable/spawn-journal'\nimport { RuntimeRunStateError } from '../../errors'\nimport { addTokenUsage, cloneTokenUsage, zeroTokenUsage } from '../util'\nimport { type BudgetPool, createBudgetPool } from './budget'\nimport { armDeadlineTimer } from './deadline'\nimport { runTree } from './finalizer'\nimport {\n knownExecutionBindingReceipt,\n knownMaterializationReceipt,\n newExecutionAttemptId,\n unknownExecutionBindingReceipt,\n unknownMaterializationReceipt,\n} from './materialization'\nimport { createScope, finalizeScopeOwnerMaterialization } from './scope'\nimport { detachedSnapshot } from './snapshot'\nimport type {\n Agent,\n Budget,\n ExecutionBindingReceipt,\n NodeId,\n NoWinnerError,\n ProfileMaterializationReceipt,\n ResumedKeyState,\n RootHandle,\n RootSignal,\n Scope,\n Settled,\n SpawnEvent,\n SpawnJournal,\n Spend,\n SpendChannel,\n SpendGap,\n SteerableRootHandle,\n SupervisedResult,\n Supervisor,\n SupervisorOpts,\n TreeView,\n} from './types'\nimport type { PendingWait } from './wait'\n\n/** The driver-rejection shape a `reason: 'driver-failed'` result carries. Re-exported from the\n * module that produces it so a consumer catching a driver failure names the type instead of\n * retyping `{ name; message; stack? }`. Declared in `./types` beside the result it rides on. */\nexport type { NoWinnerError } from './types'\n\n/** The committed work + cursor maxima the supervisor hands a resumed scope. Shaped to spread\n * into `ScopeArgs.resumeFrom`. */\ninterface ResumeFrom {\n readonly settled: ReadonlyArray<Settled<unknown>>\n readonly view: TreeView\n readonly maxSpawnOrdinal: number\n readonly maxCursorSeq: number\n readonly maxWaitOrdinal: number\n readonly waits: ReadonlyArray<PendingWait>\n readonly keys: ReadonlyMap<string, ResumedKeyState<unknown>>\n readonly priorSpend: { readonly childWork: Spend; readonly driverInference: Spend }\n}\n\n/**\n * The keyed assignments a prior journal proves: every `spawned` event carrying a `key`, resolved\n * against the replayed settlements. A key spawned more than once (a retry chain) resolves to its\n * LATEST attempt — iterate in ordinal order so later spawns overwrite earlier ones. A spawned\n * event with no matching settlement is `in-doubt`: the process died with it in flight.\n */\nfunction keyedAssignments(\n events: SpawnEvent[],\n settled: ReadonlyArray<Settled<unknown>>,\n): ReadonlyMap<string, ResumedKeyState<unknown>> {\n const byId = new Map(settled.map((s) => [s.handle.id, s]))\n const keys = new Map<string, ResumedKeyState<unknown>>()\n const spawns = events\n .filter((ev): ev is Extract<SpawnEvent, { kind: 'spawned' }> => ev.kind === 'spawned')\n .sort((a, b) => a.seq - b.seq)\n for (const ev of spawns) {\n if (ev.key === undefined) continue\n if (ev.identity === undefined) {\n throw new RuntimeRunStateError(\n `supervisor: keyed node '${ev.id}' has no durable execution identity`,\n )\n }\n const s = byId.get(ev.id)\n keys.set(\n ev.key,\n s === undefined\n ? { id: ev.id, label: ev.label, identity: ev.identity, state: 'in-doubt' }\n : {\n id: ev.id,\n label: ev.label,\n identity: ev.identity,\n state: s.kind === 'done' ? 'completed' : 'down',\n settled: s,\n },\n )\n }\n return keys\n}\n\ntype SpawnedEvent = Extract<SpawnEvent, { kind: 'spawned' }>\n\n/** A resumed process may continue only the exact root contract first recorded for this run id. */\nfunction assertResumeContract(events: SpawnEvent[], opts: SupervisorOpts): SpawnedEvent {\n const roots = events.filter(\n (event): event is SpawnedEvent =>\n event.kind === 'spawned' && event.id === opts.runId && event.parent === undefined,\n )\n if (roots.length !== 1) {\n throw new RuntimeRunStateError(\n `supervisor: resumed run '${opts.runId}' must contain exactly one root identity event; found ${roots.length}`,\n )\n }\n const recorded = roots[0]!\n if (contentAddress(recorded.budget) !== contentAddress(opts.budget)) {\n throw new RuntimeRunStateError(\n `supervisor: resume budget mismatch for run '${opts.runId}'; use a new runId to change limits`,\n )\n }\n if (!sameOptionalIdentity(recorded.identity, opts.rootIdentity)) {\n throw new RuntimeRunStateError(\n `supervisor: resume identity mismatch for run '${opts.runId}'; task, profile, candidate, and correlation must match`,\n )\n }\n const receipts = events.filter(\n (event): event is Extract<SpawnEvent, { kind: 'materialized' }> =>\n event.kind === 'materialized' && event.id === opts.runId,\n )\n const expectedReceipt = rootMaterializationReceipt(opts)\n if (expectedReceipt === undefined) {\n if (receipts.length > 1) {\n throw new RuntimeRunStateError(\n `supervisor: resumed run '${opts.runId}' contains duplicate root materialization evidence`,\n )\n }\n } else if (\n receipts.length !== 1 ||\n contentAddress(receipts[0]?.receipt) !== contentAddress(expectedReceipt)\n ) {\n throw new RuntimeRunStateError(\n `supervisor: resume materialization mismatch for run '${opts.runId}'; backend, model, execution identity, and plan must match`,\n )\n }\n return recorded\n}\n\n/** Mint root evidence at the trusted composition boundary. A generic in-process Agent root has no\n * executor declaration and remains explicitly unknown rather than inheriting fabricated details. */\nfunction rootMaterializationReceipt(\n opts: SupervisorOpts,\n): ProfileMaterializationReceipt | undefined {\n const declaration = opts.rootMaterialization\n if (declaration === undefined) {\n return unknownMaterializationReceipt({\n ...(opts.rootIdentity?.profileDigest === undefined\n ? {}\n : { authoredProfileDigest: opts.rootIdentity.profileDigest }),\n runtime: 'inline',\n reason: 'root-agent-did-not-report',\n })\n }\n if (declaration.declaration === 'deferred') return undefined\n if (opts.rootIdentity?.profileDigest === undefined) {\n throw new RuntimeRunStateError(\n `supervisor: run '${opts.runId}' cannot record known root materialization without an exact profileDigest`,\n )\n }\n try {\n return knownMaterializationReceipt({\n authoredProfileDigest: opts.rootIdentity.profileDigest,\n runtime: declaration.runtime,\n declaration: declaration.declaration,\n })\n } catch (error) {\n throw new RuntimeRunStateError(\n `supervisor: run '${opts.runId}' has invalid root materialization evidence`,\n { cause: error },\n )\n }\n}\n\nfunction rootExecutionBindingReceipt(\n opts: SupervisorOpts,\n materialization: ProfileMaterializationReceipt,\n attemptId: string,\n): ExecutionBindingReceipt | undefined {\n const root = opts.rootMaterialization\n if (root?.declaration === 'deferred') return undefined\n if (root === undefined) {\n return unknownExecutionBindingReceipt(materialization, attemptId, 'root-agent-did-not-report')\n }\n try {\n return knownExecutionBindingReceipt(materialization, {\n attemptId,\n ...root.binding,\n })\n } catch (error) {\n throw new RuntimeRunStateError(\n `supervisor: run '${opts.runId}' has invalid root execution binding`,\n { cause: error },\n )\n }\n}\n\nfunction sameOptionalIdentity(\n recorded: SpawnedEvent['identity'],\n requested: SpawnedEvent['identity'],\n): boolean {\n if (recorded === undefined || requested === undefined) return recorded === requested\n return contentAddress(recorded) === contentAddress(requested)\n}\n\n/** Validate caller-supplied root identity before any journal access. Fresh runs may omit identity,\n * but once supplied it is trusted durable evidence and therefore must be complete and canonical;\n * resumed runs always require it so the prior root can be matched exactly. */\nfunction assertRootIdentity(opts: SupervisorOpts): void {\n const identity = opts.rootIdentity\n if (identity === undefined) {\n if (opts.resume !== true) return\n throw new RuntimeRunStateError(\n `supervisor: resumed run '${opts.runId}' requires an exact rootIdentity with profileDigest and taskDigest`,\n )\n }\n const unknownFields = Object.keys(identity).filter(\n (key) =>\n key !== 'profileDigest' &&\n key !== 'taskDigest' &&\n key !== 'candidateDigest' &&\n key !== 'correlation',\n )\n const correlation = identity.correlation\n const validCorrelation =\n correlation === undefined ||\n (typeof correlation === 'object' &&\n correlation !== null &&\n !Array.isArray(correlation) &&\n Object.entries(correlation).every(\n ([key, value]) => key.length > 0 && typeof value === 'string' && value.length > 0,\n ))\n if (\n unknownFields.length > 0 ||\n !sha256DigestSchema.safeParse(identity.profileDigest).success ||\n !sha256DigestSchema.safeParse(identity.taskDigest).success ||\n (identity.candidateDigest !== undefined &&\n !sha256DigestSchema.safeParse(identity.candidateDigest).success) ||\n !validCorrelation\n ) {\n throw new RuntimeRunStateError(\n `supervisor: run '${opts.runId}' requires an exact rootIdentity with valid profileDigest, taskDigest, candidateDigest, and correlation`,\n )\n }\n}\n\n/** The instant the run's root was journaled — the anchor for both the absolute deadline and the\n * terminal wall-clock `ms`, so a resumed run measures from its ORIGINAL start, not this\n * process's. */\nfunction rootStartedAtMs(root: SpawnedEvent): number {\n const startedAt = Date.parse(root.at)\n if (!Number.isFinite(startedAt)) {\n throw new RuntimeRunStateError(\n `supervisor: root event for '${root.id}' has an invalid timestamp '${root.at}'`,\n )\n }\n return startedAt\n}\n\nfunction rootDeadline(root: SpawnedEvent): number {\n return rootStartedAtMs(root) + (root.budget.deadlineMs ?? 0)\n}\n\n/** Child reservations whose spawn was durable but whose terminal record never landed. */\nfunction uncertainSpawnBudgets(events: SpawnEvent[]): Budget[] {\n const terminal = new Set(\n events\n .filter(\n (event) => event.kind === 'settled' || event.kind === 'cancelled' || event.kind === 'woken',\n )\n .map((event) => event.id),\n )\n return events\n .filter(\n (event): event is SpawnedEvent =>\n event.kind === 'spawned' && event.parent !== undefined && !terminal.has(event.id),\n )\n .map((event) => event.budget)\n}\n\n/** Highest `seq` among events matching `pred`, or `-1` when none match (so a resumed scope's\n * first new ordinal/seq is 0 — the same start a fresh scope uses). */\nfunction maxSeqOf(events: SpawnEvent[], pred: (ev: SpawnEvent) => boolean): number {\n let max = -1\n for (const ev of events) if (pred(ev) && ev.seq > max) max = ev.seq\n return max\n}\n\n/** The default runtime recursion-depth ceiling, paired with the conserved pool so a\n * runaway recursion hits budget-exhaustion first and depth-exceeded second (R3). */\nconst defaultMaxDepth = 4\n\n/** Every no-winner reason, pinned to the published `SupervisedResult` union so the contract\n * and the impl cannot drift. */\ntype NoWinnerReason = (SupervisedResult<unknown> & { kind: 'no-winner' })['reason']\n\n/** The reasons the supervisor can prove from its OWN lifecycle state — everything except the\n * driver's rejection, which no lifecycle observation can establish. */\ntype LifecycleNoWinnerReason = Exclude<NoWinnerReason, 'driver-failed'>\n\n/** A captured `act()` rejection. Wrapped rather than passed bare so `throw undefined` — legal, and\n * exactly the kind of authoring bug this field exists to surface — is still distinguishable from\n * \"the driver never threw\". */\ninterface DriverRejection {\n readonly error: unknown\n}\n\n/**\n * Normalize an arbitrary rejection into the serializable triple the result carries. A driver may\n * reject with anything (a string, a plain object, a null-prototype value), and the whole point of\n * this field is that the failure survives, so every branch produces a message instead of throwing:\n * a stringification that itself throws (circular, hostile `toString`) falls back to the tag.\n */\nfunction describeRejection(error: unknown): NoWinnerError {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n ...(error.stack !== undefined ? { stack: error.stack } : {}),\n }\n }\n let message: string\n try {\n message = typeof error === 'string' ? error : (JSON.stringify(error) ?? String(error))\n } catch {\n message = Object.prototype.toString.call(error)\n }\n return { name: 'NonError', message }\n}\n\n/** Create a supervisor that owns one recursive agent execution tree. */\nexport function createSupervisor<Task, Out>(): Supervisor<Task, Out> {\n let attached: RootControl | undefined\n\n async function run(\n root: Agent<Task, Out>,\n task: Task,\n opts: SupervisorOpts,\n ): Promise<SupervisedResult<Out>> {\n // Read every caller-owned field once, then detach and freeze all decision data together before\n // the first await. Stateful runtime collaborators stay live by reference, but replacing a field\n // on the caller's opts object after intake cannot redirect this run.\n const {\n budget,\n rootIdentity,\n rootMaterialization,\n runId,\n journal: journalStore,\n blobs: blobStore,\n executors: executorRegistry,\n probes,\n maxDepth,\n maxLiveWorkers,\n maxRestarts,\n withinMs,\n childSettleGraceMs,\n resume,\n now: suppliedNow,\n signal,\n hooks,\n workerTrace,\n workerTraceUnpropagated,\n } = opts\n const input = detachedSnapshot(\n {\n task,\n options: {\n budget,\n runId,\n ...(rootIdentity === undefined ? {} : { rootIdentity }),\n ...(rootMaterialization === undefined ? {} : { rootMaterialization }),\n ...(maxDepth === undefined ? {} : { maxDepth }),\n ...(maxLiveWorkers === undefined ? {} : { maxLiveWorkers }),\n ...(maxRestarts === undefined ? {} : { maxRestarts }),\n ...(withinMs === undefined ? {} : { withinMs }),\n ...(childSettleGraceMs === undefined ? {} : { childSettleGraceMs }),\n ...(resume === undefined ? {} : { resume }),\n },\n },\n 'supervisor.run',\n )\n opts = Object.freeze({\n ...input.options,\n journal: journalStore,\n blobs: blobStore,\n executors: executorRegistry,\n ...(probes === undefined ? {} : { probes }),\n ...(suppliedNow === undefined ? {} : { now: suppliedNow }),\n ...(signal === undefined ? {} : { signal }),\n ...(hooks === undefined ? {} : { hooks }),\n ...(workerTrace === undefined ? {} : { workerTrace }),\n ...(workerTraceUnpropagated === undefined ? {} : { workerTraceUnpropagated }),\n })\n task = input.task\n const rootAct = root.act.bind(root)\n const rootDeliver = root.deliver?.bind(root)\n const now = opts.now ?? Date.now\n assertRootIdentity(opts)\n // Reserve the attached control synchronously, before the first journal read or write. A handle\n // is one live route, so two concurrent runs may never race to overwrite that route and later\n // detach each other. The lease is released on every early failure as well as normal teardown.\n const rootLease = attached?.acquire()\n try {\n const rootAttemptId = newExecutionAttemptId(opts.runId)\n // One instant owns both the fresh pool's absolute deadline and its durable root records. Capture\n // it before any asynchronous journal work so a slow begin cannot extend the run on restart.\n const runStartedAtMs = now()\n const runStartedAt = new Date(runStartedAtMs).toISOString()\n\n // RESUME-FIRST (opt-in via `opts.resume`): read any prior journal tree for this runId BEFORE\n // beginning a fresh one. A non-empty tree means a prior run for this runId already committed\n // work (it crashed mid-flight, or this is an explicit resume), so rehydrate it instead of\n // starting over. An empty/absent tree — and every run that did NOT opt in — takes the fresh\n // path unchanged. This wires the already-built+tested resume primitives\n // (`replaySpawnTree`/`materializeTreeView`); the journal/blob store decide durability.\n const existing = await opts.journal.loadTree(opts.runId)\n if (opts.resume !== true && existing !== undefined) {\n throw new RuntimeRunStateError(\n `supervisor: runId '${opts.runId}' already exists; pass resume: true to continue it or use a new runId`,\n )\n }\n const prior = opts.resume === true ? existing : undefined\n const resuming = prior !== undefined && prior.length > 0\n let resumeFrom: ResumeFrom | undefined\n let pool: BudgetPool\n // The instant terminal wall-clock `ms` measures from. A resumed run anchors to the ORIGINAL\n // root instant (the same anchor the absolute deadline uses), so its duration spans processes.\n let runEpochMs = runStartedAtMs\n if (resuming) {\n const rootEvent = assertResumeContract(prior, opts)\n runEpochMs = rootStartedAtMs(rootEvent)\n const measured = sumMeasuredSpendFromEvents(prior)\n const uncertainReservations = uncertainSpawnBudgets(prior)\n pool = createBudgetPool(opts.budget, now, {\n committed: addSpend(measured.childWork, measured.driverInference),\n uncertainReservations,\n ...(rootEvent.budget.deadlineMs !== undefined\n ? { absoluteDeadlineMs: rootDeadline(rootEvent) }\n : {}),\n })\n // Rehydrate the committed work: the cursor-ordered `Settled[]` (from the blob store) plus the\n // tree as it stood at the recorded cursor position. The new scope's ordinal/cursor counters\n // continue past the recorded maxima so a fresh spawn never reuses a journaled `seq`.\n const settled = await replaySpawnTree(opts.journal, opts.blobs, opts.runId)\n const view = materializeTreeView(prior)\n resumeFrom = {\n settled,\n view,\n maxSpawnOrdinal: maxSeqOf(prior, (ev) => ev.kind === 'spawned'),\n maxCursorSeq: maxSeqOf(\n prior,\n (ev) => ev.kind === 'settled' || ev.kind === 'cancelled' || ev.kind === 'woken',\n ),\n maxWaitOrdinal: maxSeqOf(prior, (ev) => ev.kind === 'waiting'),\n // Waits armed but never woken: the run died mid-wait. They ride onto `Scope.resume.waits`,\n // and re-arming the same label adopts the ORIGINAL absolute deadline rather than\n // restarting the countdown from this process's clock.\n waits: pendingWaits(prior),\n // Keyed assignments + prior committed spend ride onto `Scope.resume`, so a resume-aware\n // driver resolves keys instead of re-spawning and reports what the run already paid.\n keys: keyedAssignments(prior, settled),\n priorSpend: sumSpendFromEvents(prior),\n }\n } else {\n pool = createBudgetPool(opts.budget, now, {\n ...(opts.budget.deadlineMs !== undefined\n ? { absoluteDeadlineMs: runStartedAtMs + opts.budget.deadlineMs }\n : {}),\n })\n // Fresh run: begin the tree and journal the root as its own `spawned` node (parent-less, the\n // spawn-ordinal-0 marker), so a journal-based reader — `trajectoryReport`, `replaySpawnTree`,\n // `materializeTreeView` — can reconstruct the WHOLE realized tree from a real run, not only\n // hand-built journals. The root is never `scope.spawn`ed (the supervisor runs `act` directly),\n // so without this the root node is absent and `trajectoryReport` fails its `nodes.has(root)`\n // invariant. The uniqueness guard skips `spawned` events (only the cursor namespace must be\n // unique), so sharing ordinal 0 with the first child's spawn is not a collision; replay ignores\n // `spawned` events for settlement reconstruction, so the replayed `Settled[]` is unchanged.\n await opts.journal.beginTree(opts.runId, runStartedAt)\n const rootReceipt = rootMaterializationReceipt(opts)\n const rootRuntime = opts.rootMaterialization?.runtime ?? 'inline'\n await opts.journal.appendEvent(opts.runId, {\n kind: 'spawned',\n id: opts.runId,\n label: 'root',\n budget: opts.budget,\n runtime: rootRuntime,\n ...(opts.rootIdentity ? { identity: opts.rootIdentity } : {}),\n seq: 0,\n at: runStartedAt,\n })\n if (rootReceipt !== undefined) {\n await opts.journal.appendEvent(opts.runId, {\n kind: 'materialized',\n id: opts.runId,\n receipt: rootReceipt,\n seq: 0,\n at: runStartedAt,\n })\n }\n }\n\n const stableRootReceipt = resuming\n ? prior?.find(\n (event): event is Extract<SpawnEvent, { kind: 'materialized' }> =>\n event.kind === 'materialized' && event.id === opts.runId,\n )?.receipt\n : rootMaterializationReceipt(opts)\n if (stableRootReceipt !== undefined) {\n const rootBinding = rootExecutionBindingReceipt(opts, stableRootReceipt, rootAttemptId)\n if (rootBinding !== undefined) {\n await opts.journal.appendEvent(opts.runId, {\n kind: 'execution-bound',\n id: opts.runId,\n binding: rootBinding,\n seq: 0,\n at: runStartedAt,\n })\n }\n }\n\n // ONE internal controller is the root scope's abort source. Every cascade path\n // (caller signal, RootHandle.abort, breaker trip, deadline) aborts it; the scope\n // fans it out to each live child's executor (acquire-aware reap included).\n const controller = new AbortController()\n const cascadeAbort = (reason?: string): boolean => {\n if (controller.signal.aborted) return false\n // Carry the reason on the signal so it chains down to each child's abort signal\n // (`childAbort.signal.reason`) — the diagnostic the scope's executors observe.\n controller.abort(reason)\n return true\n }\n\n const onCallerAbort = () => cascadeAbort('caller signal aborted')\n if (opts.signal) {\n if (opts.signal.aborted) cascadeAbort('caller signal aborted')\n else opts.signal.addEventListener('abort', onCallerAbort, { once: true })\n }\n\n // The breaker watches `down` settlements via a counting journal decorator, so it\n // observes every child failure without intercepting `scope.next()` (the driver's\n // private channel). Tripping aborts the same controller; the trip is recorded so the\n // final result can name it.\n const breaker = createIntensityBreaker(opts, () => cascadeAbort('intensity breaker tripped'))\n const journal = wrapJournalForBreaker(opts.journal, breaker)\n const priorRootMaterialization = prior?.find(\n (event): event is Extract<SpawnEvent, { kind: 'materialized' }> =>\n event.kind === 'materialized' && event.id === opts.runId,\n )?.receipt\n\n const scope = createScope<Out>({\n parentId: opts.runId,\n root: opts.runId,\n pool,\n journal,\n blobs: opts.blobs,\n executors: opts.executors,\n seams: {},\n depth: 0,\n maxDepth: opts.maxDepth ?? defaultMaxDepth,\n ...(opts.maxLiveWorkers !== undefined ? { maxLiveWorkers: opts.maxLiveWorkers } : {}),\n signal: controller.signal,\n now,\n hooks: opts.hooks,\n ...(opts.rootMaterialization?.declaration === 'deferred'\n ? {\n ownerMaterialization: {\n runtime: opts.rootMaterialization.runtime,\n authoredProfile: opts.rootMaterialization.authoredProfile,\n attemptId: rootAttemptId,\n requiredKnown: true,\n ...(priorRootMaterialization === undefined\n ? {}\n : { prior: priorRootMaterialization }),\n },\n }\n : {}),\n ...(opts.probes ? { probes: opts.probes } : {}),\n ...(opts.workerTrace ? { workerTrace: opts.workerTrace } : {}),\n ...(opts.workerTraceUnpropagated\n ? { workerTraceUnpropagated: opts.workerTraceUnpropagated }\n : {}),\n ...(resumeFrom ? { resumeFrom } : {}),\n })\n\n // `view`/drain read the scope opaquely (`Out` erased) — the supervisor never `spawn`s\n // on it, so the live-tree readout and the join barrier are `Out`-agnostic.\n const openScope = scope as unknown as Scope<unknown>\n\n // Bind any attached RootHandle to THIS live run so view()/signal()/abort() reach the\n // live scope + the one cascade controller. Detached again in the finally barrier.\n if (rootLease) {\n rootLease.bind({\n scope: openScope,\n cascadeAbort,\n signal: pushRootSignal(cascadeAbort),\n deliver: rootDeliver ? (message) => rootDeliver(message) !== false : () => false,\n })\n }\n\n let deadlineExceeded = false\n const rootDeadlineAtMs = pool.readout().deadlineMs\n if (rootDeadlineAtMs > 0 && now() >= rootDeadlineAtMs) {\n deadlineExceeded = cascadeAbort('root budget deadline exceeded')\n }\n const clearRootDeadline =\n opts.budget.deadlineMs === undefined\n ? undefined\n : armDeadlineTimer(Math.max(0, rootDeadlineAtMs - now()), () => {\n deadlineExceeded = cascadeAbort('root budget deadline exceeded')\n })\n let actOutcome: { ok: true; out: Out } | { ok: false; error: unknown } = {\n ok: false,\n error: new RuntimeRunStateError('supervisor: root execution did not start'),\n }\n let executionAborted = controller.signal.aborted\n // Whether every spawned child was ALREADY down when root execution settled. Read at settle,\n // never after the join barrier: the barrier's own teardown turns healthy live children into\n // `down` nodes, and reading it afterwards reported a crashed driver's run as\n // `all-children-down` — the tree's state caused by the cleanup, not the cause of the failure.\n let allChildrenDownAtSettle = false\n // Same reasoning for the breaker's tally: children the barrier kills are `down` settlements\n // too, so the count read after cleanup can never distinguish \"children failed\" from \"we\n // stopped them because the driver died\".\n let downCountAtSettle = 0\n try {\n const out = await runAbortable(() => rootAct(task, scope), controller.signal)\n actOutcome = { ok: true, out }\n } catch (error) {\n // act()'s rejection is the PRIMARY error; capture it before the join barrier so a\n // teardown failure in the barrier can never overwrite it (firstError precedence).\n actOutcome = { ok: false, error }\n } finally {\n executionAborted = controller.signal.aborted\n allChildrenDownAtSettle = allSpawnedChildrenDown(runTree(openScope))\n downCountAtSettle = breaker.downCount()\n // A child inherits the root cutoff and can settle the root act on that exact timer turn.\n // If its settlement callback runs before the root timer callback, the finally block clears\n // the still-pending root timer. Preserve the deadline cause from the shared absolute clock;\n // do not overwrite a caller/breaker abort that already won the controller race.\n if (!controller.signal.aborted && rootDeadlineAtMs > 0 && now() >= rootDeadlineAtMs) {\n deadlineExceeded = true\n }\n clearRootDeadline?.()\n // Join barrier: tear down every still-live child. Generalizes the kernel's\n // `finally{ Promise.allSettled(destroy) }` — a teardown throw is allSettled'd and\n // journaled, never re-thrown.\n //\n // #741: a root driver that DIED did not make its children unhealthy. When the run was not\n // cancelled and the driver failed, `childSettleGraceMs` lets live children reach their own\n // terminal state (and write what they hold) before the cascade takes them. Bounded by the\n // run's own deadline, because nothing may outlive that.\n const settleGraceMs =\n actOutcome.ok === false && !controller.signal.aborted\n ? boundedSettleGrace(opts.childSettleGraceMs, rootDeadlineAtMs, now)\n : 0\n try {\n await drainLiveChildren(openScope, controller, settleGraceMs)\n } catch (error) {\n if (actOutcome?.ok !== false) actOutcome = { ok: false, error }\n }\n try {\n await finalizeScopeOwnerMaterialization(openScope)\n } catch (error) {\n if (actOutcome?.ok !== false) actOutcome = { ok: false, error }\n }\n if (opts.signal) opts.signal.removeEventListener('abort', onCallerAbort)\n rootLease?.release()\n }\n\n // The run's tree, not this process's: on a resumed run the prior process's committed nodes are\n // carried in, so `tree` covers the same work `spentTotal` bills for. Identical to `scope.view`\n // on every run that did not resume.\n const tree = runTree(scope)\n // Success and failure both pass the same conservation check. A child promise is never allowed\n // to disappear behind a swallowed cleanup error and leave a reservation open.\n pool.assertNoOpenTickets()\n if (actOutcome.ok) {\n if (executionAborted) return noWinner()\n // Every child has settled (join barrier above); no reservation may remain. A leaked ticket\n // would silently corrupt the conserved spend total, so fail loud here — on the success path\n // only, where the act() error precedence does not apply.\n const out = actOutcome.out\n // Completion-oracle at the root: a `winner` MUST carry a real `Out`. A driver that ran to\n // completion but selected nothing (its keep-best finalize found no DELIVERED child) returns\n // `undefined` — that is a no-winner, never a winner wrapping `undefined`. The supervisor's\n // contract is to refuse coercing a non-result into a best-effort Out (Foreman's 0/18 lesson).\n if (out !== undefined) {\n // The driver synthesized a winner. Content-address it for the replay `outRef`, put it\n // once, and sum the conserved spend off every journaled settlement. No re-ranking — the\n // driver already selected.\n const outRef = contentAddress(out)\n await opts.blobs.put(outRef, out)\n // ONE ledger: the journal. `settled` events carry spawned-child WORK; `metered` events carry\n // the drivers' OWN inference (the twin of `pool.observe`). `spentTotal` is their sum and the\n // breakdown keeps the two separable — the A++ view of where the tokens went. No pool bridge.\n const { spentTotal, childWork, driverInference, gaps, providerModel } =\n await terminalAccounting(journal, opts.runId, now() - runEpochMs)\n return {\n kind: 'winner',\n out,\n outRef,\n tree,\n spentTotal,\n providerModel,\n ...(gaps.length > 0 ? { spendGaps: gaps } : {}),\n ...(isNonEmptySpend(driverInference)\n ? { spentBreakdown: { driverInference, childWork } }\n : {}),\n }\n }\n return noWinner()\n }\n\n // act() rejected. The reason is proven from lifecycle state first, in precedence order:\n // a tripped breaker outranks any abort (it is the most specific cause) outranks\n // budget-exhaustion outranks a real `down` child. Only when NONE of those hold does the\n // rejection itself become the reason — `driver-failed`, the one arm that carries `error`.\n // A no-winner is TYPED — never a best-effort coercion of a partial child (M2).\n return noWinner({ error: actOutcome.error })\n\n // A no-winner still incurred real conserved spend before failing, so it carries `spentTotal`\n // summed off the SAME journal the winner path reads — the caller always learns the cost.\n async function noWinner(rejection?: DriverRejection): Promise<SupervisedResult<Out>> {\n const { spentTotal, gaps, providerModel } = await terminalAccounting(\n journal,\n opts.runId,\n now() - runEpochMs,\n )\n const common = {\n kind: 'no-winner' as const,\n tree,\n downCount: breaker.downCount(),\n spentTotal,\n providerModel,\n ...(gaps.length > 0 ? { spendGaps: gaps } : {}),\n }\n // The lifecycle causes outrank the driver's own rejection, so they are asked first and a\n // proven one ends it. `undefined` means the supervisor's own state explains nothing.\n const lifecycle = classifyNoWinner(\n executionAborted,\n pool,\n opts,\n breaker,\n deadlineExceeded,\n allChildrenDownAtSettle,\n downCountAtSettle,\n )\n if (lifecycle !== undefined) return { ...common, reason: lifecycle }\n // No lifecycle cause AND the driver threw ⇒ the driver itself is the fault. `error` is\n // REQUIRED on this arm, and it is present by construction: this is the only branch that\n // produces `driver-failed`, and it is unreachable unless a rejection was captured.\n if (rejection !== undefined) {\n return { ...common, reason: 'driver-failed', error: describeRejection(rejection.error) }\n }\n // The residual bucket: ran to completion under budget and selected nothing usable.\n return { ...common, reason: 'all-children-down' }\n }\n } finally {\n rootLease?.release()\n }\n }\n\n function attach(h: RootHandle<Out>): void {\n const control = rootControls.get(h as RootHandle<unknown>)\n if (!control) {\n throw new RuntimeRunStateError(\n 'supervisor.attach: handle was not minted by createRootHandle (no control channel)',\n )\n }\n attached = control\n }\n\n return { run, attach }\n}\n\n// ── Root handle ───────────────────────────────────────────────────────────────\n\n/** The live binding the supervisor populates while a run is in flight. `view` reads the\n * live scope; `cascadeAbort`/`signal` reach the one cascade controller. */\ninterface RunBinding {\n readonly scope: Scope<unknown>\n readonly cascadeAbort: (reason?: string) => void\n readonly signal: (msg: RootSignal) => void\n readonly deliver: (msg: unknown) => boolean\n}\n\n/** The supervisor-private control behind a `RootHandle`. `createRootHandle` mints it and\n * registers it in `rootControls`; `attach` looks it up and `bind`s it to the live run. */\ninterface RootLease {\n bind(binding: RunBinding): void\n release(): void\n}\n\ninterface RootControl {\n acquire(): RootLease\n}\n\n/** Module-private channel from a minted `RootHandle` to its `RootControl`, so `attach`\n * can prove a handle is ours and reach its binding without leaking the control onto the\n * frozen `RootHandle` shape. */\nconst rootControls = new WeakMap<RootHandle<unknown>, RootControl>()\n\n/**\n * Mint a `RootHandle` plus its supervisor-private control. The handle is the substrate a\n * chat/pi-viz client attaches to (Q2): `view()` reads the live tree, `signal()` delivers\n * an out-of-band message, `abort()` cascades. Before `run` binds it (and after `run`\n * unbinds it) the handle is fail-loud: a client that talks to a handle that is not\n * driving a live run gets a typed error, never a silent no-op.\n */\nexport function createRootHandle<Out>(): SteerableRootHandle<Out> {\n let binding: RunBinding | undefined\n let activeLease: symbol | undefined\n const handle: SteerableRootHandle<Out> = {\n view(): TreeView {\n if (!binding) {\n throw new RuntimeRunStateError(\n 'RootHandle.view: handle is not bound to a live run (attach it before run, read after run starts)',\n )\n }\n return binding.scope.view\n },\n deliver(msg: unknown): boolean {\n if (!binding) {\n throw new RuntimeRunStateError('RootHandle.deliver: handle is not bound to a live run')\n }\n return binding.deliver(msg)\n },\n signal(msg: RootSignal): void {\n if (!binding) {\n throw new RuntimeRunStateError('RootHandle.signal: handle is not bound to a live run')\n }\n binding.signal(msg)\n },\n abort(reason?: string): void {\n if (!binding) {\n throw new RuntimeRunStateError('RootHandle.abort: handle is not bound to a live run')\n }\n binding.cascadeAbort(reason ?? 'root handle aborted')\n },\n }\n rootControls.set(handle as RootHandle<unknown>, {\n acquire(): RootLease {\n if (activeLease !== undefined) {\n throw new RuntimeRunStateError(\n 'RootHandle: handle already controls a live run; use one handle per concurrent run',\n )\n }\n const token = Symbol('root-handle-lease')\n activeLease = token\n let released = false\n return {\n bind(next: RunBinding): void {\n if (released || activeLease !== token) {\n throw new RuntimeRunStateError('RootHandle: live-run lease is no longer active')\n }\n if (binding !== undefined) {\n throw new RuntimeRunStateError('RootHandle: live-run lease is already bound')\n }\n binding = next\n },\n release(): void {\n if (released) return\n released = true\n if (activeLease !== token) return\n binding = undefined\n activeLease = undefined\n },\n }\n },\n })\n return handle\n}\n\n/** A `RootSignal` sink: `cancel` cascades an abort; pause/resume/ask are observability\n * signals the substrate accepts but does not act on here (the chat/pi-viz client owns\n * pause semantics — building them now would be mechanism ahead of the gate). */\nfunction pushRootSignal(cascadeAbort: (reason?: string) => void): (msg: RootSignal) => void {\n return (msg: RootSignal): void => {\n if (msg.kind === 'cancel') cascadeAbort(msg.reason ?? 'root signal: cancel')\n }\n}\n\n// ── OTP intensity breaker ───────────────────────────────────────────────────────\n\n/**\n * Counts `down` settlements inside a sliding window. More than `maxRestarts` of them\n * within `withinMs` trips the supervisor (aborting the cascade) rather than letting a\n * driver re-spawn a doomed child forever. With either bound unset the breaker is inert\n * (it still counts `down`s for `downCount`). The breaker NEVER restarts a child — it is a\n * circuit breaker over the driver's own re-spawn decisions (m3).\n */\ninterface IntensityBreaker {\n recordDown(at: number): void\n tripped(): boolean\n downCount(): number\n}\n\nfunction createIntensityBreaker(opts: SupervisorOpts, trip: () => void): IntensityBreaker {\n const max = opts.maxRestarts\n const within = opts.withinMs\n const armed = max !== undefined && within !== undefined\n const recent: number[] = []\n let total = 0\n let isTripped = false\n return {\n recordDown(at: number): void {\n total += 1\n if (!armed || isTripped) return\n recent.push(at)\n const cutoff = at - within\n while (recent.length > 0 && recent[0]! < cutoff) recent.shift()\n if (recent.length > max) {\n isTripped = true\n trip()\n }\n },\n tripped(): boolean {\n return isTripped\n },\n downCount(): number {\n return total\n },\n }\n}\n\n/** Decorate the journal so the breaker observes every `settled`-`down` event the scope\n * appends, without the supervisor intercepting `scope.next()`. The decorator is\n * transparent — it forwards every method verbatim and only reads the down events. */\nfunction wrapJournalForBreaker(journal: SpawnJournal, breaker: IntensityBreaker): SpawnJournal {\n return {\n loadTree: (root) => journal.loadTree(root),\n beginTree: (root, at) => journal.beginTree(root, at),\n appendEvent: (root, ev: SpawnEvent) => {\n if (ev.kind === 'settled' && ev.status === 'down') breaker.recordDown(Date.parse(ev.at))\n return journal.appendEvent(root, ev)\n },\n }\n}\n\n// ── Join barrier + result classification ─────────────────────────────────────────\n\n/**\n * Drain the root scope's live set so every still-running/acquiring child is torn down\n * before `run` returns — the join barrier. Abort the cascade controller first (so each\n * child's executor stops cleanly), then pull `next()` to completion so every aborted\n * child's teardown + reconcile runs and its `settled` event is journaled by the scope.\n * A child's own teardown failure is already swallowed inside `runChild`, and the cursor\n * itself never rejects (a failing child is typed into a `down`), so the whole barrier is\n * `allSettled`'d — a stray throw here is NOT the primary error (firstError precedence).\n */\nasync function drainLiveChildren(\n scope: Scope<unknown>,\n controller: AbortController,\n settleGraceMs = 0,\n): Promise<void> {\n // Armed wait-states count here even though they are deliberately excluded from `inFlight`: a\n // wait holds no executor, but it DOES hold a live timer, so a run that returns without\n // cancelling one would leave the process pinned to a deadline nobody is reading anymore.\n const view = scope.view\n const hasLive = view.inFlight > 0 || view.waiting > 0\n if (!hasLive) {\n if (scope.workerCapacity.live > 0) {\n throw new RuntimeRunStateError(\n `supervisor: cleanup ended with ${scope.workerCapacity.live} executor resource(s) not confirmed destroyed`,\n )\n }\n return\n }\n // Cascade the abort into every live child's executor before draining — unless the caller granted\n // a settle grace, in which case the timer owns the cascade and the drain reads whatever the\n // children finish in the meantime. Exactly ONE cursor reader either way: the grace never races\n // `next()`, it only decides when the abort lands.\n let graceTimer: ReturnType<typeof setTimeout> | undefined\n if (settleGraceMs > 0 && !controller.signal.aborted) {\n graceTimer = setTimeout(\n () => controller.abort('root driver failed; child settle grace expired'),\n settleGraceMs,\n )\n graceTimer.unref?.()\n } else if (!controller.signal.aborted) {\n // Same event as the grace-timer branch above, so it carries the same named reason: one\n // path stating why and the other going silent is what put identical deaths in two\n // different diagnostic buckets.\n controller.abort('root driver failed; no child settle grace configured')\n }\n try {\n await drainCursor(scope)\n } finally {\n if (graceTimer !== undefined) clearTimeout(graceTimer)\n }\n const after = scope.view\n if (after.inFlight > 0 || after.waiting > 0 || scope.workerCapacity.live > 0) {\n throw new RuntimeRunStateError(\n `supervisor: cleanup ended with ${after.inFlight} running, ${after.waiting} waiting, and ${scope.workerCapacity.live} executor resource(s) not confirmed destroyed`,\n )\n }\n}\n\n/** The settle window a failed driver's children actually get: the caller's grace, never past the\n * run's own deadline. `0` (the default) keeps the historical immediate cascade. */\nfunction boundedSettleGrace(\n graceMs: number | undefined,\n deadlineAtMs: number,\n now: () => number,\n): number {\n if (graceMs === undefined || graceMs <= 0) return 0\n if (deadlineAtMs <= 0) return graceMs\n return Math.max(0, Math.min(graceMs, deadlineAtMs - now()))\n}\n\nasync function drainCursor(scope: Scope<unknown>): Promise<void> {\n for (;;) {\n const settled = await scope.next()\n if (settled === null) return\n }\n}\n\n/** Race root policy execution against the same signal that stops every child. The losing promise\n * remains observed, so a late rejection cannot surface as an unhandled process error. */\nasync function runAbortable<T>(act: () => Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) throw supervisorAbortError(signal)\n return await new Promise<T>((resolve, reject) => {\n let settled = false\n const cleanup = () => signal.removeEventListener('abort', onAbort)\n const onAbort = () => {\n queueMicrotask(() => {\n if (settled) return\n settled = true\n cleanup()\n reject(supervisorAbortError(signal))\n })\n }\n signal.addEventListener('abort', onAbort, { once: true })\n let work: Promise<T>\n try {\n work = Promise.resolve(act())\n } catch (error) {\n cleanup()\n reject(error)\n return\n }\n work.then(\n (value) => {\n if (settled) return\n settled = true\n cleanup()\n resolve(value)\n },\n (error) => {\n if (settled) return\n settled = true\n cleanup()\n reject(error)\n },\n )\n })\n}\n\nfunction supervisorAbortError(signal: AbortSignal): Error {\n const reason = signal.reason\n const error = new Error(\n typeof reason === 'string' && reason.length > 0 ? reason : 'supervisor aborted',\n )\n error.name = 'AbortError'\n return error\n}\n\n/**\n * The lifecycle cause of a no-winner, or `undefined` when the supervisor's own state proves\n * nothing. Returning `undefined` rather than falling through to `all-children-down` is what lets\n * the caller decide between the `driver-failed` arm (a rejection was captured) and the residual\n * bucket — and it is why `driver-failed` cannot be produced without an `error` to attach.\n */\nfunction classifyNoWinner(\n /** Whether the cascade was aborted at the moment root execution settled — NOT the controller's\n * state now. The join barrier itself aborts the cascade to tear children down, so reading the\n * live controller here reported every driver failure that happened to have a live child as\n * `aborted`, hiding the real cause (#741: the run with one live child reported `aborted`, the\n * identical failure with none reported `driver-failed`). */\n abortedAtSettle: boolean,\n pool: BudgetPool,\n opts: SupervisorOpts,\n breaker: IntensityBreaker,\n deadlineExceeded: boolean,\n /** Every spawned child was already down when root execution settled — measured BEFORE the join\n * barrier, so the barrier's own teardown cannot manufacture this cause. */\n allChildrenDownAtSettle: boolean,\n /** `down` settlements counted at the same instant, for the same reason. */\n downCountAtSettle: number,\n): LifecycleNoWinnerReason | undefined {\n // A tripped breaker is the most specific cause (children kept dying), so it outranks\n // the abort it raised. A deadline that won the abort race remains budget exhaustion;\n // then come caller/handle abort and other exhausted pool channels. Then a real `down`\n // child, which is what `all-children-down` asserts and which only `downCount > 0` can prove.\n if (breaker.tripped()) return 'all-children-down'\n if (deadlineExceeded) return 'budget-exhausted'\n if (abortedAtSettle) return 'aborted'\n // Unknown terminal usage correctly seals the remaining pool, but that accounting consequence is\n // not the cause of a run where every child failed. Preserve the lifecycle outcome before asking\n // whether any budget channel is now unavailable. A real admission failure with no failed child\n // still classifies as budget exhaustion below.\n if (allChildrenDownAtSettle) return 'all-children-down'\n if (poolExhausted(pool, opts)) return 'budget-exhausted'\n if (downCountAtSettle > 0) return 'all-children-down'\n return undefined\n}\n\nfunction allSpawnedChildrenDown(tree: TreeView): boolean {\n const children = tree.nodes.filter((node) => node.id !== tree.root)\n return children.length > 0 && children.every((node) => node.status === 'failed')\n}\n\nfunction poolExhausted(pool: BudgetPool, opts: SupervisorOpts): boolean {\n const r = pool.readout()\n if (r.iterationsLeft <= 0) return true\n if (r.tokensLeft <= 0) return true\n if (opts.budget.maxUsd !== undefined && r.usdLeft <= 0) return true\n if (\n opts.budget.deadlineMs !== undefined &&\n r.deadlineMs > 0 &&\n (opts.now ?? Date.now)() >= r.deadlineMs\n ) {\n return true\n }\n return false\n}\n\n/**\n * The run's terminal accounting, read off the one journal ledger — the honest per-channel\n * sums (input/output/usd/iterations all preserved), the named usage gaps, and the wall-clock\n * duration stamped onto `spentTotal.ms`. Computed AFTER the join barrier so every child's\n * settlement is recorded. Fails loud if the tree was never journaled (the supervisor always\n * `beginTree`s, so a missing tree is a corrupted journal, not a normal path).\n *\n * `spentTotal.ms` is `elapsedMs`, never the per-event sum: executors under-report their own\n * `ms` (most stamp 0) and parallel children overlap, so the sum cannot state the run's real\n * duration. The breakdown keeps the executor-reported sums.\n *\n * `tokensKnown`/`usdKnown` are stamped explicitly on the terminal total: `true` is a checked\n * claim (every spawn reached a terminal record AND every settled/metered record carried a\n * complete receipt on that channel), never the absence of bad news. The conjunction with the\n * summed flags is deliberately redundant — a future divergence between the sum and the gap\n * scan can only make the claim more conservative, never falsely `true`.\n */\nasync function terminalAccounting(\n journal: SpawnJournal,\n root: string,\n elapsedMs: number,\n): Promise<{\n spentTotal: Spend\n childWork: Spend\n driverInference: Spend\n gaps: SpendGap[]\n providerModel: import('./types').ProviderModelExecutionEvidence\n}> {\n const events = await journal.loadTree(root)\n if (events === undefined) {\n throw new RuntimeRunStateError(\n `supervisor: spawn tree '${root}' is missing from the journal after run (corrupted log)`,\n )\n }\n const { childWork, driverInference } = sumSpendFromEvents(events)\n const gaps = spendGapsFromEvents(events)\n const forest = await loadSpawnForest(journal, root)\n const providerModel = aggregateProviderModelEvidence(forest)\n const summed = addSpend(childWork, driverInference)\n const spentTotal: Spend = {\n ...summed,\n ms: Math.max(0, elapsedMs),\n tokensKnown:\n summed.tokensKnown !== false && !gaps.some((gap) => gap.channels.includes('tokens')),\n usdKnown: summed.usdKnown !== false && !gaps.some((gap) => gap.channels.includes('usd')),\n }\n return { spentTotal, childWork, driverInference, gaps, providerModel }\n}\n\n/** The journaled nodes whose usage accounting is incomplete — one `SpendGap` per node+kind,\n * channels merged. A spawn with no terminal record (`settled`/`cancelled`/`woken`) is\n * unaccounted on every channel; a settled or metered record that flags a channel unknown is\n * a floor on that channel. The root's own spawned event is exempt: its terminal state is the\n * result this list rides on. */\nfunction spendGapsFromEvents(events: SpawnEvent[]): SpendGap[] {\n const labels = new Map<NodeId, string>()\n const terminal = new Set<NodeId>()\n for (const ev of events) {\n if (ev.kind === 'spawned') labels.set(ev.id, ev.label)\n else if (ev.kind === 'settled' || ev.kind === 'cancelled' || ev.kind === 'woken') {\n terminal.add(ev.id)\n }\n }\n const gaps = new Map<\n string,\n { id: NodeId; kind: SpendGap['kind']; channels: Set<SpendChannel> }\n >()\n const record = (\n id: NodeId,\n kind: SpendGap['kind'],\n channels: ReadonlyArray<SpendChannel>,\n ): void => {\n if (channels.length === 0) return\n const key = `${kind}:${id}`\n const existing = gaps.get(key)\n if (existing !== undefined) for (const channel of channels) existing.channels.add(channel)\n else gaps.set(key, { id, kind, channels: new Set(channels) })\n }\n for (const ev of events) {\n if (ev.kind === 'spawned' && ev.parent !== undefined && !terminal.has(ev.id)) {\n record(ev.id, 'never-settled', ['tokens', 'usd'])\n } else if (ev.kind === 'settled') {\n record(ev.id, 'unreported', unknownChannels(ev.spent))\n } else if (ev.kind === 'metered') {\n record(ev.id, 'unreported', unknownChannels(ev.spend))\n }\n }\n return [...gaps.values()].map((gap) => {\n const label = labels.get(gap.id)\n return {\n id: gap.id,\n ...(label !== undefined ? { label } : {}),\n kind: gap.kind,\n channels: [...gap.channels],\n }\n })\n}\n\n/** The channels a single spend record explicitly marks incomplete. */\nfunction unknownChannels(spend: Spend): SpendChannel[] {\n const channels: SpendChannel[] = []\n if (spend.tokensKnown === false) channels.push('tokens')\n if (spend.usdKnown === false) channels.push('usd')\n return channels\n}\n\n/** Per-channel sum over a journaled event list: `settled` = spawned-child work (reconciled);\n * `metered` = driver inference (re-homed up the tree, so a single root-tree pass already\n * includes every nested driver's inference). */\nfunction sumSpendFromEvents(events: SpawnEvent[]): { childWork: Spend; driverInference: Spend } {\n const totals = sumMeasuredSpendFromEvents(events)\n const rootBudget = events.find(\n (event): event is SpawnedEvent => event.kind === 'spawned' && event.parent === undefined,\n )?.budget\n let remainingRootUsd = Math.max(\n 0,\n (rootBudget?.maxUsd ?? 0) - totals.childWork.usd - totals.driverInference.usd,\n )\n for (const budget of uncertainSpawnBudgets(events)) {\n totals.childWork.iterations += budget.maxIterations\n // The numeric value is the charged upper bound, not a fabricated measurement. The false flag\n // makes that distinction machine-readable in every report.\n totals.childWork.tokens.input += budget.maxTokens\n totals.childWork.tokensKnown = false\n const usdCharge = budget.maxUsd ?? (rootBudget?.maxUsd !== undefined ? remainingRootUsd : 0)\n totals.childWork.usd += usdCharge\n totals.childWork.usdKnown = false\n remainingRootUsd = Math.max(0, remainingRootUsd - usdCharge)\n }\n return totals\n}\n\nfunction sumMeasuredSpendFromEvents(events: SpawnEvent[]): {\n childWork: Spend\n driverInference: Spend\n} {\n const childWork: Spend = { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 }\n const driverInference: Spend = { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 }\n for (const ev of events) {\n if (ev.kind === 'settled') accumulate(childWork, ev.spent)\n else if (ev.kind === 'metered') accumulate(driverInference, ev.spend)\n }\n return { childWork, driverInference }\n}\n\n/** Add `b` into `a` in place, per channel. */\nfunction accumulate(a: Spend, b: Spend): void {\n a.iterations += b.iterations\n addTokenUsage(a.tokens, b.tokens)\n if (b.tokensKnown === false) a.tokensKnown = false\n a.usd += b.usd\n if (b.usdKnown === false) a.usdKnown = false\n a.ms += b.ms\n}\n\n/** Sum two conserved-spend tallies per channel — the child-work journal sum + the drivers' own\n * metered inference, so `spentTotal` is the true cost of the run. */\nfunction addSpend(a: Spend, b: Spend): Spend {\n return {\n iterations: a.iterations + b.iterations,\n tokens: (() => {\n const tokens = cloneTokenUsage(a.tokens)\n addTokenUsage(tokens, b.tokens)\n return tokens\n })(),\n ...(a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: a.usd + b.usd,\n ...(a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {}),\n ms: a.ms + b.ms,\n }\n}\n\n/** True when any driver metered inference this run (so the winner carries a `spentBreakdown`).\n * Checks every channel `addSpend` sums — including `ms` — so the gate stays consistent with the\n * total even though the coordination driver currently stamps `ms: 0`. */\nfunction isNonEmptySpend(s: Spend): boolean {\n return (\n s.iterations > 0 ||\n s.tokens.input > 0 ||\n s.tokens.output > 0 ||\n s.usd > 0 ||\n s.ms > 0 ||\n s.tokensKnown === false ||\n s.usdKnown === false\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,MAAM,iBAAiB,IAAI,IAAY,kCAAkC;;;;;;;;;;;;;AAczE,MAAM,qBAA0F;CAC9F,UAAU;EAAC;EAAQ;EAAe;EAAW;CAAM;CACnD,QAAQ,CAAC,gBAAgB,cAAc;CACvC,OAAO;EAAC;EAAgB;EAAc;EAAiB;EAAwB;CAAe;CAC9F,WAAW;EACT;EACA;EACA;EACA;EACA;EACA;EACA;CACF;CACA,gBAAgB,CAAC,KAAK;AACxB;;AAGA,MAAa,6BAA6B,qCAAqC;CAC7E,MAAM;CACN,MAAM;AACR,CAAC;;;;;;;AAQD,MAAa,oCAAoC,qCAAqC;CACpF,MAAM;CACN,MAAM;EACJ;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF,CAAC;;;;;;;;;;;AAYD,MAAa,oCAAoC,qCAAqC;CACpF,MAAM;CACN,MAAM;EACJ;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF,CAAC;;AAGD,MAAa,gCAAgC,qCAAqC;CAChF,MAAM;CACN,MAAM;EAAC;EAAQ;EAAW;CAAU;AACtC,CAAC;;;AAID,MAAa,sCAAsC,qCAAqC;CACtF,MAAM;CACN,MAAM;EACJ;EACA;EACA;EACA;EACA;EACA;EACA;EAC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