@tangle-network/agent-runtime 0.120.0 → 0.123.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/{activation-DdIpwQ0k.js → activation-B7sTehZB.js} +3 -3
  2. package/dist/{activation-DdIpwQ0k.js.map → activation-B7sTehZB.js.map} +1 -1
  3. package/dist/agent.d.ts +1 -1
  4. package/dist/agent.js +3 -3
  5. package/dist/candidate-execution/index.js +4 -4
  6. package/dist/{candidate-execution-DDkSRPjY.js → candidate-execution-BFpq-Xi6.js} +4 -4
  7. package/dist/{candidate-execution-DDkSRPjY.js.map → candidate-execution-BFpq-Xi6.js.map} +1 -1
  8. package/dist/{environment-provider-Bh4nX2qt.d.ts → environment-provider-CEjwunXO.d.ts} +105 -11
  9. package/dist/{environment-provider-Cr75N-rU.js → environment-provider-CY22kUQH.js} +4 -85
  10. package/dist/environment-provider-CY22kUQH.js.map +1 -0
  11. package/dist/environment-provider.d.ts +1 -1
  12. package/dist/environment-provider.js +1 -1
  13. package/dist/{improvement-cycle-zjR-MXwK.js → improvement-cycle-BcwsSbT-.js} +4 -4
  14. package/dist/{improvement-cycle-zjR-MXwK.js.map → improvement-cycle-BcwsSbT-.js.map} +1 -1
  15. package/dist/{index-I35151Fr.d.ts → index-BKSzgMvA.d.ts} +5 -5
  16. package/dist/{index-BLsKcxNd.d.ts → index-CKply5aj.d.ts} +3 -3
  17. package/dist/{index-CGADWaa_.d.ts → index-CyXinqJw.d.ts} +1213 -849
  18. package/dist/index.d.ts +6 -6
  19. package/dist/index.js +12 -12
  20. package/dist/intelligence.d.ts +1 -1
  21. package/dist/intelligence.js +6 -6
  22. package/dist/kernel.d.ts +3 -3
  23. package/dist/kernel.js +7 -7
  24. package/dist/{knowledge-I1e9zQGj.js → knowledge-Cuvb21T7.js} +5 -5
  25. package/dist/{knowledge-I1e9zQGj.js.map → knowledge-Cuvb21T7.js.map} +1 -1
  26. package/dist/knowledge.d.ts +1 -1
  27. package/dist/knowledge.js +1 -1
  28. package/dist/{loop-runner-bin-BeG9vTdE.d.ts → loop-runner-bin-BjnNpN5m.d.ts} +3 -3
  29. package/dist/{loop-runner-bin-L996YVPS.js → loop-runner-bin-Clhj8gy5.js} +3 -3
  30. package/dist/{loop-runner-bin-L996YVPS.js.map → loop-runner-bin-Clhj8gy5.js.map} +1 -1
  31. package/dist/loop-runner-bin.d.ts +1 -1
  32. package/dist/loop-runner-bin.js +1 -1
  33. package/dist/mcp/bin.js +2 -2
  34. package/dist/mcp/index.d.ts +3 -3
  35. package/dist/mcp/index.js +5 -5
  36. package/dist/{openai-tools-CvFEzw6f.js → openai-tools-BwTsBfd-.js} +2 -2
  37. package/dist/{openai-tools-CvFEzw6f.js.map → openai-tools-BwTsBfd-.js.map} +1 -1
  38. package/dist/{prepare-DpV6np9e.js → prepare--8EvLqCr.js} +2 -2
  39. package/dist/{prepare-DpV6np9e.js.map → prepare--8EvLqCr.js.map} +1 -1
  40. package/dist/primeintellect/index.d.ts +1 -1
  41. package/dist/{protected-model-port-vQLBRoAQ.js → protected-model-port-CXVfOUu_.js} +2 -2
  42. package/dist/{protected-model-port-vQLBRoAQ.js.map → protected-model-port-CXVfOUu_.js.map} +1 -1
  43. package/dist/{runtime-D4e3GP5K.js → runtime-OI7oLLec.js} +463 -52
  44. package/dist/runtime-OI7oLLec.js.map +1 -0
  45. package/dist/{spawn-journal-IeXpidO2.js → spawn-journal-DsZKDqeh.js} +5 -3
  46. package/dist/spawn-journal-DsZKDqeh.js.map +1 -0
  47. package/dist/{structural-rollout-DQHO3b2Y.js → structural-rollout-C4Jv_7vt.js} +3 -3
  48. package/dist/{structural-rollout-DQHO3b2Y.js.map → structural-rollout-C4Jv_7vt.js.map} +1 -1
  49. package/dist/{supervise-Cq50UT5-.js → supervise-Dwq16u8n.js} +451 -55
  50. package/dist/supervise-Dwq16u8n.js.map +1 -0
  51. package/dist/{supervisor-CpT9yAxL.js → supervisor-DjZ82HIB.js} +166 -23
  52. package/dist/supervisor-DjZ82HIB.js.map +1 -0
  53. package/dist/testing.js +12 -12
  54. package/dist/{workspace-archive-B4SkNJjw.js → workspace-archive-BQxvkypI.js} +2 -2
  55. package/dist/{workspace-archive-B4SkNJjw.js.map → workspace-archive-BQxvkypI.js.map} +1 -1
  56. package/package.json +11 -9
  57. package/dist/environment-provider-Cr75N-rU.js.map +0 -1
  58. package/dist/runtime-D4e3GP5K.js.map +0 -1
  59. package/dist/spawn-journal-IeXpidO2.js.map +0 -1
  60. package/dist/supervise-Cq50UT5-.js.map +0 -1
  61. package/dist/supervisor-CpT9yAxL.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"supervisor-DjZ82HIB.js","names":["zeroSpend","addSpend"],"sources":["../src/mcp/codex-diagnostics.ts","../src/mcp/local-harness.ts","../src/agent/profile-materialization.ts","../src/mcp/worktree.ts","../src/mcp/worktree-harness.ts","../src/runtime/tool-loop.ts","../src/runtime/router-client.ts","../src/runtime/supervise/materialization.ts","../src/runtime/supervise/budget.ts","../src/runtime/supervise/budget-floor.ts","../src/runtime/supervise/deadline.ts","../src/runtime/supervise/dispatch.ts","../src/runtime/supervise/progress.ts","../src/runtime/supervise/wait.ts","../src/sanitize.ts","../src/otel-export.ts","../src/mcp/trace-propagation.ts","../src/runtime/supervise/worker-trace.ts","../src/runtime/supervise/scope.ts","../src/runtime/supervise/driver-executor.ts","../src/runtime/supervise/finalizer.ts","../src/runtime/supervise/supervisor.ts"],"sourcesContent":["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 {\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 = profile.model?.default\n if (typeof model !== 'string' || model.trim().length === 0) {\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 = profile.model?.default\n if (typeof model === 'string' && model.length > 0) {\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/** @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","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: ['name', 'systemPrompt', 'instructions', 'modelDefault', 'harness', 'metadata'],\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 '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: ['name', 'systemPrompt', 'instructions', 'harness', 'metadata'],\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 from an explicit\n * `sandboxOverrides.backend.type`, then `profile.metadata.backendType`, then `profile.harness`,\n * so a candidate that changes only `harness` runs on the harness it declares — and one declaring\n * a harness the sandbox cannot run throws rather than running 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","/**\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 * 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 */\nimport type { RouterToolCall, 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 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) => Promise<{\n content?: string | null\n toolCalls: RouterToolCall[]\n usage?: { input: number; output: number }\n /** The turn's inference cost (usd) when the provider priced it — for callers that meter usd\n * into a conserved pool (the supervisor brain). `runBrainLoop` itself ignores it. */\n costUsd?: number\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}>\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 /** The full conversation after the loop — lets a caller CARRY the messages into the next shot. */\n messages: ToolLoopMessageRecord[]\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 = opts.maxTurns ?? 4\n const messages: ToolLoopMessageRecord[] = [...opts.initialMessages]\n let toolCalls = 0\n let lastText = ''\n const usage = { input: 0, output: 0 }\n const toolTrace: Array<{ name: string; args: string; result: string }> = []\n\n for (let turn = 1; 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 if (r.usage) {\n usage.input += r.usage.input\n usage.output += r.usage.output\n opts.hooks?.onUsage?.(r.usage)\n }\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 { final: lastText, turns: turn, toolCalls, toolTrace, usage, messages }\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 { final: lastText, turns: maxTurns, toolCalls, toolTrace, usage, messages }\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 { estimateCost, isModelPriced } from '@tangle-network/agent-eval'\nimport { ValidationError } from '../errors'\nimport { runBrainLoop, type ToolLoopChat } from './tool-loop'\n\nexport interface RouterConfig {\n routerBaseUrl: string\n routerKey: string\n model: string\n /**\n * Optional completion transport. When set, `routerChatWithUsage` / `routerChatWithTools` call it\n * with the OpenAI-shape request body and use the parsed `/chat/completions` JSON it returns,\n * INSTEAD of `fetch(routerBaseUrl + '/chat/completions')`. When absent the fetch path runs\n * unchanged — the live router stays the default. The injection seam an offline benchmark uses to\n * drive the worker with no network: a deterministic in-process responder satisfies it, no server.\n */\n complete?: (body: Record<string, unknown>) => Promise<unknown>\n /**\n * Ceiling for one completion, forwarded as `max_tokens`. Defaults to 8192.\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 }\n /** Derived from usage via `estimateCost` when the model is priced; else undefined. */\n costUsd?: number\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: Array<{ role: string; content: string }>,\n opts?: {\n temperature?: number\n signal?: AbortSignal\n maxTokens?: number\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?: 'none' | 'low' | 'medium' | 'high'\n },\n): Promise<RouterChatResult> {\n const url = `${cfg.routerBaseUrl.replace(/\\/$/, '')}/chat/completions`\n const headers = { 'content-type': 'application/json', authorization: `Bearer ${cfg.routerKey}` }\n let temperature = opts?.temperature ?? 0.2\n // max_tokens default is generous: THINKING models (kimi-k2.6) spend the budget on\n // reasoning_content first — a small router default yields EMPTY content.\n const body = (): Record<string, unknown> => ({\n model: cfg.model,\n messages,\n temperature,\n max_tokens: opts?.maxTokens ?? 8192,\n ...(opts?.reasoningEffort ? { reasoning_effort: opts.reasoningEffort } : {}),\n })\n // Injected transport short-circuits the network: the offline benchmark seam. It owns its own\n // determinism, so the fetch-specific transient-retry/temperature-handling below does not apply.\n if (cfg.complete) return parseChatResult(await cfg.complete(body()), cfg.model)\n // Retry TRANSIENT upstream failures (429/5xx) with backoff so a single capacity\n // hiccup doesn't kill a whole multi-model benchmark run; and auto-handle the\n // \"only temperature 1 is allowed\" 400 some thinking models (e.g. kimi-k2.6) return.\n let lastErr = ''\n for (let attempt = 0; attempt < 5; attempt += 1) {\n const res = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body()),\n ...(opts?.signal ? { signal: opts.signal } : {}),\n })\n if (res.ok) return parseChatResult(await res.json(), cfg.model)\n const status = res.status\n const text = (await res.text()).slice(0, 200)\n lastErr = `router ${status}: ${text}`\n if (status === 400 && /temperature/i.test(text) && temperature !== 1) {\n temperature = 1 // model requires temperature 1 — retry once with it\n continue\n }\n // Non-retryable (auth/quota/malformed) fails loud immediately; retryable\n // statuses back off and continue until the loop's attempt bound, then the\n // post-loop throw is the honest \"exhausted retries\" terminal. 408/425 + the\n // Cloudflare-origin family (520/522/524) are transient under heavy parallel\n // load — a fleet of concurrent gate runs hits 524 (\"origin timeout\") and must\n // retry, not crash the whole run.\n if (![408, 425, 429, 500, 502, 503, 504, 520, 522, 524].includes(status))\n throw new Error(lastErr)\n if (attempt < 4) await new Promise((r) => setTimeout(r, 800 * 2 ** attempt))\n }\n throw new Error(`${lastErr} (exhausted retries)`)\n}\n\nfunction parseChatResult(json: unknown, model: string): RouterChatResult {\n const data = json as {\n choices?: Array<{\n message?: { content?: string; reasoning?: string; reasoning_content?: string }\n }>\n usage?: { prompt_tokens?: number; completion_tokens?: number }\n }\n const u = data.usage\n const usage =\n u && typeof u.prompt_tokens === 'number' && typeof u.completion_tokens === 'number'\n ? { input: u.prompt_tokens, output: u.completion_tokens }\n : undefined\n const costUsd =\n usage && isModelPriced(model) ? estimateCost(usage.input, usage.output, model) : undefined\n const msg = data.choices?.[0]?.message\n const { content, reasoning } = splitReasoning(\n msg?.content ?? '',\n msg?.reasoning ?? msg?.reasoning_content,\n )\n return {\n content,\n ...(reasoning ? { reasoning } : {}),\n ...(usage ? { usage } : {}),\n ...(costUsd !== undefined ? { costUsd } : {}),\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 }\n costUsd?: number\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}\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 },\n): Promise<RouterChatToolsResult> {\n const body = toolCompletionBody(cfg, messages, tools, opts)\n // Injected transport short-circuits the network — the offline benchmark seam (see RouterConfig.complete).\n const raw = cfg.complete\n ? await cfg.complete(structuredClone(body))\n : await (async () => {\n const res = await fetch(`${cfg.routerBaseUrl.replace(/\\/$/, '')}/chat/completions`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${cfg.routerKey}` },\n body: JSON.stringify(body),\n ...(opts?.signal ? { signal: opts.signal } : {}),\n })\n if (!res.ok) throw new Error(`router ${res.status}: ${(await res.text()).slice(0, 200)}`)\n return res.json()\n })()\n const data = raw as {\n choices?: Array<{\n message?: {\n content?: string | null\n tool_calls?: Array<{ id?: string; function?: { name?: string; arguments?: string } }>\n }\n }>\n usage?: { prompt_tokens?: number; completion_tokens?: number }\n }\n const msg = data.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 } = meterTurn(data.usage, cfg.model)\n return {\n content: msg?.content ?? null,\n toolCalls,\n ...(usage ? { usage } : {}),\n ...(costUsd !== undefined ? { costUsd } : {}),\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?: { temperature?: number; toolChoice?: 'auto' | 'required' | 'none'; maxTokens?: number },\n): Record<string, unknown> {\n return {\n model: cfg.model,\n messages,\n tools,\n tool_choice: opts?.toolChoice ?? 'auto',\n temperature: opts?.temperature ?? 0.3,\n ...(opts?.maxTokens ? { max_tokens: opts.maxTokens } : {}),\n }\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): { usage?: { input: number; output: number }; costUsd?: number; cache?: PromptCacheUsage } {\n const usage =\n raw && typeof raw.prompt_tokens === 'number' && typeof raw.completion_tokens === 'number'\n ? { input: raw.prompt_tokens, output: raw.completion_tokens }\n : undefined\n if (!usage) return {}\n const localEstimate = isModelPriced(model)\n ? estimateCost(usage.input, usage.output, model)\n : undefined\n const cache = readPromptCache(raw?.prompt_cache)\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 } : {}),\n ...(cache ? { cache } : {}),\n }\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 /** 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 prompt_cache?: unknown\n}\n\nfunction 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 readTokens = num(o.read_tokens)\n const writeTokens = num(o.write_tokens)\n if (readTokens === undefined && writeTokens === undefined) return undefined\n const savings = num(o.read_savings_usd)\n return {\n readTokens: readTokens ?? 0,\n writeTokens: writeTokens ?? 0,\n ...(savings !== undefined ? { readSavingsUsd: savings } : {}),\n ...(typeof o.status === 'string' ? { status: o.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 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?: { prompt_tokens?: number; completion_tokens?: number }\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 },\n): Promise<RouterChatToolsResult> {\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 res = await fetch(`${cfg.routerBaseUrl.replace(/\\/$/, '')}/chat/completions`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${cfg.routerKey}`,\n accept: 'text/event-stream',\n },\n body: JSON.stringify(body),\n ...(opts?.signal ? { signal: opts.signal } : {}),\n })\n // Identical failure surface to the buffered path: fail loud on any non-2xx, same message shape.\n if (!res.ok) throw new Error(`router ${res.status}: ${(await res.text()).slice(0, 200)}`)\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: { prompt_tokens?: number; completion_tokens?: number } | undefined\n const calls = new Map<number, StreamingToolCall>()\n let lastCallIndex = -1\n\n for await (const chunk of readChatCompletionChunks(res.body)) {\n if (chunk.error) {\n throw new ValidationError(\n `router stream error: ${chunk.error.message ?? chunk.error.type ?? 'unknown'}`,\n )\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 } = 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 ...(split.reasoning ? { reasoning: split.reasoning } : {}),\n ...(finishReason !== undefined ? { finishReason } : {}),\n ...(usage ? { usage } : {}),\n ...(costUsd !== undefined ? { costUsd } : {}),\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 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\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 },\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 /** 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 /** 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 ? { maxTokens: opts.maxTokens } : {}),\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(cfg: RouterConfig, opts: { temperature?: number } = {}): ToolLoopChat {\n const temperature = opts.temperature ?? 0.4\n return (messages, tools) =>\n chatWithTools(cfg, messages, tools, {\n temperature,\n 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 })\n}\n","import { randomUUID } from 'node:crypto'\nimport {\n agentProfileSchema,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport { detachedSnapshot } from './snapshot'\nimport type {\n ExecutionBindingReceipt,\n Executor,\n ExecutorExecutionBinding,\n ExecutorMaterialization,\n ProfileMaterializationReceipt,\n Runtime,\n UnknownMaterializationReason,\n} from './types'\n\ntype RuntimeOwnedExecutorMaterialization =\n | {\n readonly kind: 'known'\n readonly declaration: ExecutorMaterialization\n readonly binding?: ExecutorExecutionBinding\n }\n | { readonly kind: 'deferred'; readonly runtime: Runtime }\n\nconst runtimeOwnedExecutorMaterializations = new WeakMap<\n object,\n RuntimeOwnedExecutorMaterialization\n>()\nconst runtimeOwnedScopeOwners = new WeakMap<object, Runtime>()\n\ninterface KnownReceiptInput {\n readonly authoredProfileDigest: Sha256Digest\n readonly runtime: Runtime\n readonly declaration: ExecutorMaterialization\n}\n\ninterface UnknownReceiptInput {\n readonly authoredProfileDigest?: Sha256Digest\n readonly runtime: Runtime\n readonly reason: UnknownMaterializationReason\n}\n\nconst declarationKeys = new Set([\n 'effectiveProfile',\n 'backend',\n 'model',\n 'execution',\n 'materializer',\n 'plan',\n 'platformAttachments',\n])\n\n/**\n * Bind a declaration to a runtime-owned executor without putting an attestable method on the\n * public Executor interface. This module is not a package export: arbitrary caller executors stay\n * unknown even if they add a lookalike `materialization()` property.\n */\nexport function attestRuntimeOwnedExecutor<Out>(\n executor: Executor<Out>,\n declaration: ExecutorMaterialization,\n binding?: ExecutorExecutionBinding,\n): Executor<Out> {\n runtimeOwnedExecutorMaterializations.set(\n executor as object,\n Object.freeze({\n kind: 'known',\n declaration: detachedSnapshot(declaration, 'runtime-owned executor materialization'),\n ...(binding === undefined\n ? {}\n : {\n binding: detachedSnapshot(binding, 'runtime-owned executor execution binding'),\n }),\n }),\n )\n return executor\n}\n\n/** Mark a runtime-owned orchestration executor whose exact leaf declaration is published through\n * its private nested Scope before the first backend inference. Arbitrary executors cannot opt in. */\nexport function attestRuntimeOwnedDeferredExecutor<Out>(\n executor: Executor<Out>,\n runtime: Runtime,\n): Executor<Out> {\n runtimeOwnedExecutorMaterializations.set(\n executor as object,\n Object.freeze({ kind: 'deferred', runtime }),\n )\n return executor\n}\n\n/** Preserve the runtime-owned attestation when a trusted wrapper changes result semantics only. */\nexport function inheritRuntimeOwnedExecutorAttestation<Out>(\n source: Executor<Out>,\n wrapper: Executor<Out>,\n): Executor<Out> {\n const attestation = runtimeOwnedExecutorMaterializations.get(source as object)\n if (attestation !== undefined) {\n runtimeOwnedExecutorMaterializations.set(wrapper as object, attestation)\n }\n return wrapper\n}\n\n/** Read a declaration only when Runtime itself branded this exact executor object. */\nexport function runtimeOwnedExecutorMaterialization<Out>(\n executor: Executor<Out>,\n): ExecutorMaterialization | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)\n return attestation?.kind === 'known' ? attestation.declaration : undefined\n}\n\n/** Read one attempt binding only from the private brand on this exact executor object. */\nexport function runtimeOwnedExecutorExecutionBinding<Out>(\n executor: Executor<Out>,\n): ExecutorExecutionBinding | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)\n return attestation?.kind === 'known' ? attestation.binding : undefined\n}\n\n/** Read the expected leaf runtime only for a privately branded deferred orchestration executor. */\nexport function runtimeOwnedDeferredExecutorRuntime<Out>(\n executor: Executor<Out>,\n): Runtime | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)\n return attestation?.kind === 'deferred' ? attestation.runtime : undefined\n}\n\n/** Propagate trust from a built-in driver adapter to the Agent and recursive executor it owns. */\nexport function attestRuntimeOwnedScopeOwner<T extends object>(owner: T, runtime: Runtime): T {\n runtimeOwnedScopeOwners.set(owner, runtime)\n return owner\n}\n\n/** Return a built-in scope owner's expected concrete leaf runtime; caller-owned functions/Agents\n * deliberately have no entry even if they add lookalike fields. */\nexport function runtimeOwnedScopeOwnerRuntime(owner: object): Runtime | undefined {\n return runtimeOwnedScopeOwners.get(owner)\n}\n\n/** Build one kernel-owned known receipt from a data-only executor declaration. */\nexport function knownMaterializationReceipt(\n input: KnownReceiptInput,\n): ProfileMaterializationReceipt {\n const declaration = detachedSnapshot(input.declaration, 'executor materialization')\n assertExactDeclaration(declaration)\n const effectiveProfile = agentProfileSchema.safeParse(declaration.effectiveProfile)\n if (!effectiveProfile.success) {\n throw new ValidationError('executor materialization: effectiveProfile must be an AgentProfile')\n }\n assertNonEmpty(declaration.backend, 'backend')\n assertNonEmpty(declaration.materializer, 'materializer')\n assertNonEmpty(declaration.execution?.kind, 'execution.kind')\n assertNonEmpty(declaration.execution?.id, 'execution.id')\n assertModel(declaration.model)\n\n let effectiveProfileDigest: Sha256Digest\n let materializationPlanDigest: Sha256Digest\n let platformAttachmentsDigest: Sha256Digest | undefined\n try {\n // AgentProfile parsing represents omitted optional fields as `undefined`, while the backend's\n // JSON request omits them. Commit the exact JSON document that crosses that boundary.\n effectiveProfileDigest = canonicalCandidateDigest(jsonWireSnapshot(effectiveProfile.data))\n materializationPlanDigest = canonicalCandidateDigest(jsonWireSnapshot(declaration.plan))\n platformAttachmentsDigest =\n declaration.platformAttachments === undefined\n ? undefined\n : canonicalCandidateDigest(jsonWireSnapshot(declaration.platformAttachments))\n } catch (error) {\n throw new ValidationError(\n 'executor materialization: profile, plan, and attachments must be finite RFC 8785 JSON',\n { cause: error },\n )\n }\n\n return Object.freeze({\n status: 'known' as const,\n authoredProfileDigest: input.authoredProfileDigest,\n effectiveProfileDigest,\n materializationPlanDigest,\n ...(platformAttachmentsDigest === undefined ? {} : { platformAttachmentsDigest }),\n runtime: input.runtime,\n backend: declaration.backend,\n model: declaration.model,\n execution: declaration.execution,\n materializer: declaration.materializer,\n })\n}\n\n/** Build an explicit unknown receipt without fabricating any executor-owned identity. */\nexport function unknownMaterializationReceipt(\n input: UnknownReceiptInput,\n): ProfileMaterializationReceipt {\n return Object.freeze({\n status: 'unknown' as const,\n ...(input.authoredProfileDigest === undefined\n ? {}\n : { authoredProfileDigest: input.authoredProfileDigest }),\n runtime: input.runtime,\n reason: input.reason,\n })\n}\n\n/** Mint a process-unique attempt id before executor construction. */\nexport function newExecutionAttemptId(nodeId: string): string {\n return `${nodeId}:attempt:${randomUUID()}`\n}\n\n/** Build the immutable safe receipt for a full, transient execution binding. */\nexport function knownExecutionBindingReceipt(\n materialization: ProfileMaterializationReceipt,\n bindingInput: ExecutorExecutionBinding,\n): ExecutionBindingReceipt {\n const binding = detachedSnapshot(bindingInput, 'executor execution binding')\n assertNonEmpty(binding.attemptId, 'binding.attemptId')\n assertSafeDescriptor(binding.descriptor)\n let materializationReceiptDigest: Sha256Digest\n let bindingDigest: Sha256Digest\n try {\n materializationReceiptDigest = canonicalCandidateDigest(materialization)\n // Bind the exact JSON document a backend receives. Optional AgentProfile fields are represented\n // as `undefined` in memory but omitted by JSON transport; normalize that one distinction while\n // rejecting every non-finite/non-data value instead of silently coercing it.\n bindingDigest = canonicalCandidateDigest(jsonWireSnapshot(binding.binding))\n } catch (error) {\n throw new ValidationError('executor binding must be finite RFC 8785 JSON', { cause: error })\n }\n return Object.freeze({\n status: 'known' as const,\n attemptId: binding.attemptId,\n materializationReceiptDigest,\n bindingDigest,\n descriptor: binding.descriptor,\n })\n}\n\n/** Preserve an attempt boundary even when its caller-owned transport cannot be attested. */\nexport function unknownExecutionBindingReceipt(\n materialization: ProfileMaterializationReceipt,\n attemptId: string,\n reason: UnknownMaterializationReason,\n): ExecutionBindingReceipt {\n assertNonEmpty(attemptId, 'binding.attemptId')\n return Object.freeze({\n status: 'unknown' as const,\n attemptId,\n materializationReceiptDigest: canonicalCandidateDigest(materialization),\n reason,\n })\n}\n\n/** Derive an authored-profile digest without turning non-canonical input into a fake identity. */\nexport function authoredProfileDigest(profile: unknown): Sha256Digest | undefined {\n try {\n return canonicalCandidateDigest(profile)\n } catch {\n return undefined\n }\n}\n\nfunction assertExactDeclaration(value: ExecutorMaterialization): void {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError('executor materialization: declaration must be an object')\n }\n const unknown = Object.keys(value).filter((key) => !declarationKeys.has(key))\n if (unknown.length > 0) {\n throw new ValidationError(\n `executor materialization: unknown declaration fields: ${unknown.sort().join(', ')}`,\n )\n }\n if (!Object.hasOwn(value, 'plan')) {\n throw new ValidationError('executor materialization: plan is required')\n }\n}\n\nfunction assertModel(model: ExecutorMaterialization['model']): void {\n if (typeof model !== 'object' || model === null || Array.isArray(model)) {\n throw new ValidationError('executor materialization: model must be a known/unknown identity')\n }\n const keys = Object.keys(model).sort()\n if (model.status === 'known') {\n if (keys.join(',') !== 'id,status') {\n throw new ValidationError('executor materialization: known model accepts only status and id')\n }\n assertNonEmpty(model.id, 'model.id')\n return\n }\n if (model.status === 'unknown') {\n if (keys.join(',') !== 'reason,status') {\n throw new ValidationError(\n 'executor materialization: unknown model accepts only status and reason',\n )\n }\n assertNonEmpty(model.reason, 'model.reason')\n return\n }\n throw new ValidationError('executor materialization: model.status must be known or unknown')\n}\n\nfunction assertNonEmpty(value: unknown, field: string): asserts value is string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new ValidationError(`executor materialization: ${field} must be a non-empty string`)\n }\n}\n\nfunction assertSafeDescriptor(descriptor: ExecutorExecutionBinding['descriptor']): void {\n if (typeof descriptor !== 'object' || descriptor === null || Array.isArray(descriptor)) {\n throw new ValidationError('executor binding: descriptor must be an object')\n }\n for (const [key, value] of Object.entries(descriptor)) {\n if (/(url|uri|token|key|secret|bearer|credential|authorization)/i.test(key)) {\n throw new ValidationError(`executor binding: unsafe descriptor key ${JSON.stringify(key)}`)\n }\n if (\n value !== null &&\n typeof value !== 'string' &&\n typeof value !== 'number' &&\n typeof value !== 'boolean'\n ) {\n throw new ValidationError(\n `executor binding: descriptor ${JSON.stringify(key)} must be scalar`,\n )\n }\n if (typeof value === 'string' && (value.includes('://') || value.includes('@'))) {\n throw new ValidationError(\n `executor binding: descriptor ${JSON.stringify(key)} contains transport or credential text`,\n )\n }\n }\n}\n\nfunction jsonWireSnapshot(value: unknown, path = '$'): unknown {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new ValidationError(`executor binding: ${path} must be finite`)\n }\n return value\n }\n if (Array.isArray(value)) {\n return value.map((item, index) => {\n if (item === undefined) {\n throw new ValidationError(`executor binding: ${path}[${index}] cannot be undefined`)\n }\n return jsonWireSnapshot(item, `${path}[${index}]`)\n })\n }\n if (typeof value !== 'object' || value === null) {\n throw new ValidationError(`executor binding: ${path} must be JSON data`)\n }\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n throw new ValidationError(`executor binding: ${path} must be a plain object`)\n }\n const out: Record<string, unknown> = {}\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n if (item === undefined) continue\n out[key] = jsonWireSnapshot(item, `${path}.${key}`)\n }\n return out\n}\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 { 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; `below-runtime-floor` means the request is under the amount that harness needs before\n * it does any work at all, so it is unsatisfiable at that size and the fix is to RAISE it;\n * `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' | 'below-runtime-floor'\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 Object.entries(spend.tokens)) {\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 ['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 usd = 0\n let usdKnown = true\n let iterations = 0\n for (const ev of events) {\n if (ev.kind === 'tokens') {\n addTokenUsage(tokens, { input: ev.input, output: ev.output })\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 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 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, { input: ev.input, output: ev.output })\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 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 throw new Error(\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","/**\n * The token budget below which a harness child cannot do ANY useful work.\n *\n * A coding-agent harness spends a fixed amount before it reads its task: system prompt, tool\n * definitions, workspace context — re-sent every turn. A parent that authors a child budget under\n * that amount has not set a tight ceiling, it has set an impossible one, and the child dies partway\n * through with no signal that the number was never satisfiable.\n *\n * Measured, not guessed. Six live `pi` children on `tangle-router/glm-5.2` settled at 31,211 /\n * 32,296 / 47,365 / 47,965 / 48,253 / 62,616 input tokens for 1–4 iterations, against 515–1,128\n * output. Four separate roots then authored child budgets of 2,000 / 8,000 / 12,000 / 20,000 —\n * every one below the observed minimum. One of those children wrote its deliverable correctly and\n * was killed before it could report, which the run recorded as a failure.\n *\n * A floor is `null` where nobody has measured one. That is deliberate: an unmeasured floor is\n * UNKNOWN, never zero, and enforcing a made-up number would refuse work that would have succeeded.\n * `null` means \"admit anything and let the pool decide\", the behavior before this table existed.\n *\n * The floor is a property of a harness/model pairing, not a universal constant, so this is a\n * conservative lower bound: it uses the smallest spend ever observed, not the median, so a refusal\n * means the budget is below what has EVER worked rather than below what is typical.\n */\nimport type { BackendType } from '@tangle-network/sandbox'\n\n// Already the target shape: one exhaustive row per harness, `satisfies` pinned so a new\n// `BackendType` is a compile error rather than a silent gap. Add a harness by adding a row.\nexport const WORKER_TOKEN_FLOOR = {\n // 31,211 was the lowest of six measured settlements; nothing rounds it up.\n pi: 31_211,\n // Unmeasured. Add a number here only with runs behind it.\n opencode: null,\n 'claude-code': null,\n 'kimi-code': null,\n codex: null,\n amp: null,\n 'factory-droids': null,\n hermes: null,\n forge: null,\n openclaw: null,\n nanoclaw: null,\n acp: null,\n cursor: null,\n 'cli-base': null,\n} as const satisfies Record<BackendType, number | null>\n\n/**\n * The floor for a spawn's harness, or `null` when there is none to enforce.\n *\n * A `null` harness is the router/inline arm: it holds only coordination verbs and re-sends no\n * harness scaffolding, so it has no floor of this kind.\n *\n * Accepts a bare `string` because `AgentProfile.harness` is not exactly `BackendType` — an\n * unrecognised name resolves to `null` (no floor) rather than throwing, which keeps an unknown\n * harness admissible instead of refusing work on a name this table has not heard of.\n */\nexport function workerTokenFloor(harness: BackendType | string | null | undefined): number | null {\n if (harness === null || harness === undefined) return null\n return (WORKER_TOKEN_FLOOR as Record<string, number | null>)[harness] ?? null\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 * 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 * 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 * 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","/**\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 environment channel to the worker can carry\n * this, and the ones that cannot 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 * - `router`,\n * `router-tools` NO — a direct model HTTP call. There is no worker process to inherit anything.\n * - `bridge`,\n * `cli-worktree` NO — the work is dispatched over cli-bridge HTTP or through a local harness\n * transport that exposes no environment channel. Wiring these means adding that\n * channel to the transport first; until then they are 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 environment channel to the worker and stamps the context.\n * `false` = it has none today; it is honestly unpropagated rather than silently dropping.\n */\nexport const WORKER_TRACE_PROPAGATION = {\n cli: true,\n sandbox: true,\n router: false,\n 'router-tools': false,\n bridge: false,\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 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 * @experimental\n */\n\nimport {\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 { type BudgetPool, createBudgetPool, type ReservationTicket } from './budget'\nimport { workerTokenFloor } from './budget-floor'\nimport {\n armDeadlineTimer,\n boundedChildDeadlineAt,\n DEFAULT_SUCCESSFUL_SHUTDOWN_MS,\n teardownExecutor,\n} from './deadline'\nimport { freeSlots } from './dispatch'\nimport {\n authoredProfileDigest,\n knownExecutionBindingReceipt,\n knownMaterializationReceipt,\n newExecutionAttemptId,\n runtimeOwnedDeferredExecutorRuntime,\n runtimeOwnedExecutorExecutionBinding,\n runtimeOwnedExecutorMaterialization,\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 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` — bridge / cli-worktree have 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\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 /** 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 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 /** 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 = snapshotAgentSpec(rawSpec)\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 // 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 // A budget under the harness's measured floor is UNSATISFIABLE at that size, not merely\n // tight — the child burns the whole ceiling on scaffolding it re-sends every turn and dies\n // before reaching the task. Its own reason, for the same purpose `usd-unbudgeted` has one:\n // `budget-exhausted` invites a caller to retry SMALLER, which here is the exact wrong move.\n // Checked after resolution because that is where the harness is known, and refunded the way\n // every sibling failure on this path is.\n // `spec.harness` is null whenever the harness rides in the backend config instead of the\n // spec — which is the path that actually spawns workers through the bridge. Reading only it\n // made this guard miss the case it was written for: a root authored a 6,000-token child\n // against a measured 31,211 floor, the guard never fired, and the child died having produced\n // nothing (discovery-lab run proof-bridge-20260801f). The AgentProfile is where a root\n // declares its child's harness, so it is the more reliable of the two.\n const floor = workerTokenFloor(spec.harness ?? spec.profile.harness ?? null)\n if (floor !== null && opts.budget.maxTokens < floor) {\n args.pool.reconcile(reservation.ticket, zeroSpend())\n permit.release()\n return { ok: false, reason: 'below-runtime-floor' }\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 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 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 (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 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 meter(spend: Spend, detail?: Record<string, unknown>): 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 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,\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 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\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 (canonicalCandidateDigest(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 throw new ValidationError('scope owner materialization was already recorded')\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 if (state === undefined || state.publishedThisProcess) 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 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 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 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 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 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 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 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 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 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('aborted before settle', true, trace, ownMetered)\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 ...(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 // 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 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 teardownError !== undefined || reconcileError !== undefined || aborted || isInfraError(err),\n trace,\n executor.metered?.(),\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: { input: settled.spent.tokens.input, output: settled.spent.tokens.output },\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 }))\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 = digest(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 = { input: 0, output: 0 }\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 tokens.input += ev.input\n tokens.output += ev.output\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: { ...tokens },\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 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 return {\n ...streamed,\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): PreSeqSettled {\n return { kind: 'down', reason, infra, restartCount: 0, trace, ...(metered ? { metered } : {}) }\n}\n\nfunction zeroSpend(): Spend {\n return { iterations: 0, tokens: { input: 0, output: 0 }, 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\n/** Snapshot every data field whose bytes affect identity, admission, or materialization while\n * preserving the executable callbacks by reference. The executor implementation is trusted code;\n * its profile and attribution inputs are not. */\nfunction snapshotAgentSpec(raw: AgentSpec): AgentSpec {\n const {\n profile: rawProfile,\n harness,\n execution: rawExecution,\n ...runtimeExtensions\n } = raw as AgentSpec & Readonly<Record<string, unknown>>\n const profile = detachedSnapshot(rawProfile, 'scope.spawn profile')\n const execution =\n rawExecution === undefined ? undefined : detachedSnapshot(rawExecution, 'scope.spawn execution')\n return Object.freeze({\n ...runtimeExtensions,\n profile,\n harness,\n ...(execution === undefined ? {} : { execution }),\n }) as AgentSpec\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 {\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/** The metadata marker on a driver child's spec the recursive registry routes on. */\nconst driverRole = 'driver'\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` is marked `role: 'driver'` and carries the driver agent + the 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 profileOrName: AgentProfile | string,\n driver: Agent<unknown, Out>,\n journal: SpawnJournal,\n execution?: AgentExecutionRef,\n): Agent<unknown, Out> {\n const profile: AgentProfile =\n typeof profileOrName === 'string'\n ? { name: profileOrName, metadata: { role: driverRole } }\n : profileOrName\n const name = profile.name ?? driver.name\n const spec: DriverSpec = {\n profile,\n harness: null,\n ...(execution ? { execution } : {}),\n driverRuntime,\n driver: driver as Agent<unknown, unknown>,\n journal,\n }\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 is a driver child (carries the role marker + 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 driver-role 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 marked\n * `role: 'driver'` 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> = (spec, ctx) => {\n if (!isDriverSpec(spec)) {\n throw new ValidationError(\n 'driverExecutorFactory: spec is not a driver child (no role:\"driver\" marker)',\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 marked `role: 'driver'` resolves to it. The base\n * registry resolves by harness alone (it does not read `role`), so a recursive run needs a\n * registry that routes the driver tag here FIRST. Returns a registry decorator: a\n * driver-role spec → the 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>(spec: AgentSpec) {\n if ((spec as { driverRuntime?: unknown }).driverRuntime === driverRuntime && !spec.executor) {\n return { succeeded: true as const, value: driverExecutorFactory as ExecutorFactory<Out> }\n }\n return base.resolve<Out>(spec)\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: { input: 0, output: 0 }, usd: 0, ms: 0 }\n for (const ev of settled) {\n total.iterations += ev.spent.iterations\n total.tokens.input += ev.spent.tokens.input\n total.tokens.output += ev.spent.tokens.output\n if (ev.spent.tokensKnown === false) total.tokensKnown = false\n total.usd += ev.spent.usd\n if (ev.spent.tokensKnown === false) total.tokensKnown = false\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: { input: 0, output: 0 }, usd: 0, ms: 0 }\n for (const ev of events) {\n if (ev.kind !== 'metered') continue\n total.iterations += ev.spend.iterations\n total.tokens.input += ev.spend.tokens.input\n total.tokens.output += ev.spend.tokens.output\n if (ev.spend.tokensKnown === false) total.tokensKnown = false\n total.usd += ev.spend.usd\n if (ev.spend.tokensKnown === false) total.tokensKnown = false\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: { input: 0, output: 0 }, usd: 0, ms: 0 }\n}\n\nfunction addSpend(a: Spend, b: Spend): Spend {\n return {\n iterations: a.iterations + b.iterations,\n tokens: {\n input: a.tokens.input + b.tokens.input,\n output: a.tokens.output + b.tokens.output,\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 * @experimental\n */\n\nimport { sha256DigestSchema } from '@tangle-network/agent-interface'\nimport {\n contentAddress,\n materializeTreeView,\n pendingWaits,\n replaySpawnTree,\n} from '../../durable/spawn-journal'\nimport { RuntimeRunStateError } from '../../errors'\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 NoWinnerError,\n ProfileMaterializationReceipt,\n ResumedKeyState,\n RootHandle,\n RootSignal,\n Scope,\n Settled,\n SpawnEvent,\n SpawnJournal,\n Spend,\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\nfunction rootDeadline(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 + (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 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 ...(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 if (resuming) {\n const rootEvent = assertResumeContract(prior, opts)\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 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 // 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 try {\n await drainLiveChildren(openScope, controller)\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 { childWork, driverInference } = await spentFromJournal(journal, opts.runId)\n return {\n kind: 'winner',\n out,\n outRef,\n tree,\n spentTotal: addSpend(childWork, driverInference),\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 { childWork, driverInference } = await spentFromJournal(journal, opts.runId)\n const common = {\n kind: 'no-winner' as const,\n tree,\n downCount: breaker.downCount(),\n spentTotal: addSpend(childWork, driverInference),\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(controller, pool, opts, breaker, deadlineExceeded, tree)\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): 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.\n if (!controller.signal.aborted) controller.abort()\n await drainCursor(scope)\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\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 controller: AbortController,\n pool: BudgetPool,\n opts: SupervisorOpts,\n breaker: IntensityBreaker,\n deadlineExceeded: boolean,\n tree: TreeView,\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 (controller.signal.aborted) 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 (allSpawnedChildrenDown(tree)) return 'all-children-down'\n if (poolExhausted(pool, opts)) return 'budget-exhausted'\n if (breaker.downCount() > 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 * Sum the conserved spend over every journaled `settled` event — the honest per-channel\n * total (input/output/usd/iterations all preserved), read off the same evidence replay\n * reads. Computed AFTER the join barrier so every child's settlement is recorded. Fails\n * loud if the tree was never journaled (the supervisor always `beginTree`s, so a missing\n * tree is a corrupted journal, not a normal path).\n */\nasync function spentFromJournal(\n journal: SpawnJournal,\n root: string,\n): Promise<{ childWork: Spend; driverInference: Spend }> {\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 return sumSpendFromEvents(events)\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: { input: 0, output: 0 }, usd: 0, ms: 0 }\n const driverInference: Spend = { iterations: 0, tokens: { input: 0, output: 0 }, 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 a.tokens.input += b.tokens.input\n a.tokens.output += b.tokens.output\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: { input: a.tokens.input + b.tokens.input, output: a.tokens.output + b.tokens.output },\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 ||\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