@tangle-network/agent-runtime 0.107.4 → 0.108.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 (64) hide show
  1. package/README.md +17 -4
  2. package/dist/{activation-Ck5ksFWg.js → activation-DRpnplEm.js} +3 -3
  3. package/dist/{activation-Ck5ksFWg.js.map → activation-DRpnplEm.js.map} +1 -1
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +2 -2
  6. package/dist/candidate-execution/index.js +4 -4
  7. package/dist/{candidate-execution-BUpR0mSD.js → candidate-execution-nYMa-bc-.js} +4 -4
  8. package/dist/{candidate-execution-BUpR0mSD.js.map → candidate-execution-nYMa-bc-.js.map} +1 -1
  9. package/dist/durable.d.ts +134 -0
  10. package/dist/durable.js +124 -0
  11. package/dist/durable.js.map +1 -0
  12. package/dist/{environment-provider-IUGU3epE.d.ts → environment-provider-D0NXc4Qz.d.ts} +73 -4
  13. package/dist/environment-provider.d.ts +1 -1
  14. package/dist/{improvement-cycle-Ulvvbg5p.js → improvement-cycle-CRnDDdX0.js} +49 -155
  15. package/dist/improvement-cycle-CRnDDdX0.js.map +1 -0
  16. package/dist/{index-CeawCSEg.d.ts → index-BZbJWqoZ.d.ts} +175 -27
  17. package/dist/{index-D6MwUzvB.d.ts → index-DQp3BPeC.d.ts} +11 -159
  18. package/dist/{index-jmFVBIHo.d.ts → index-cdkwHruJ.d.ts} +3 -3
  19. package/dist/index.d.ts +6 -6
  20. package/dist/index.js +14 -121
  21. package/dist/index.js.map +1 -1
  22. package/dist/intelligence.d.ts +15 -7
  23. package/dist/intelligence.js +4 -4
  24. package/dist/{knowledge-Dizh_AtL.js → knowledge-rdrpPIXs.js} +5 -5
  25. package/dist/{knowledge-Dizh_AtL.js.map → knowledge-rdrpPIXs.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-BbYG9CeA.d.ts → loop-runner-bin-9-JlGqN7.d.ts} +3 -3
  29. package/dist/{loop-runner-bin-CvdKZkE4.js → loop-runner-bin-B1V-XS5A.js} +3 -3
  30. package/dist/{loop-runner-bin-CvdKZkE4.js.map → loop-runner-bin-B1V-XS5A.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/loops.d.ts +3 -3
  34. package/dist/loops.js +5 -5
  35. package/dist/mcp/bin.js +1 -1
  36. package/dist/mcp/index.d.ts +1 -1
  37. package/dist/mcp/index.js +4 -4
  38. package/dist/{openai-tools-CKLy1C7M.js → openai-tools-BjQq2TTL.js} +2 -2
  39. package/dist/{openai-tools-CKLy1C7M.js.map → openai-tools-BjQq2TTL.js.map} +1 -1
  40. package/dist/{prepare-_WTTffkz.js → prepare-Pr19X93k.js} +141 -6
  41. package/dist/prepare-Pr19X93k.js.map +1 -0
  42. package/dist/primeintellect/index.d.ts +1 -1
  43. package/dist/{protected-model-port-ZUwVuftA.js → protected-model-port-uthtDNqu.js} +2 -2
  44. package/dist/{protected-model-port-ZUwVuftA.js.map → protected-model-port-uthtDNqu.js.map} +1 -1
  45. package/dist/{redact-C5xOm8cu.d.ts → redact-BkasKlyd.d.ts} +17 -27
  46. package/dist/{runtime-5zM5XxLr.js → runtime-CDekUROm.js} +20 -13
  47. package/dist/runtime-CDekUROm.js.map +1 -0
  48. package/dist/{structural-rollout-IXUEplky.js → structural-rollout-BC81Otmc.js} +10 -9
  49. package/dist/structural-rollout-BC81Otmc.js.map +1 -0
  50. package/dist/{supervise-BiRutHS9.js → supervise-JfKPwIlO.js} +270 -69
  51. package/dist/supervise-JfKPwIlO.js.map +1 -0
  52. package/dist/{supervisor-DTKhF-RV.js → supervisor-B2LzaWRb.js} +221 -16
  53. package/dist/supervisor-B2LzaWRb.js.map +1 -0
  54. package/dist/testing.js +3544 -657
  55. package/dist/testing.js.map +1 -1
  56. package/dist/{workspace-archive-CIG1VNCj.js → workspace-archive-C9w_rxt6.js} +2 -2
  57. package/dist/{workspace-archive-CIG1VNCj.js.map → workspace-archive-C9w_rxt6.js.map} +1 -1
  58. package/package.json +11 -6
  59. package/dist/improvement-cycle-Ulvvbg5p.js.map +0 -1
  60. package/dist/prepare-_WTTffkz.js.map +0 -1
  61. package/dist/runtime-5zM5XxLr.js.map +0 -1
  62. package/dist/structural-rollout-IXUEplky.js.map +0 -1
  63. package/dist/supervise-BiRutHS9.js.map +0 -1
  64. package/dist/supervisor-DTKhF-RV.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"supervisor-B2LzaWRb.js","names":[],"sources":["../src/mcp/codex-diagnostics.ts","../src/mcp/local-harness.ts","../src/mcp/worktree.ts","../src/mcp/worktree-harness.ts","../src/runtime/tool-loop.ts","../src/runtime/router-client.ts","../src/runtime-hooks.ts","../src/runtime/supervise/progress.ts","../src/runtime/supervise/wait.ts","../src/runtime/supervise/scope.ts","../src/runtime/supervise/driver-executor.ts","../src/runtime/supervise/budget.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 } 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/** Local coding harness available inside the sandbox. */\nexport type LocalHarness = 'claude' | 'codex' | 'opencode'\n\ntype ReasoningEffort = NonNullable<NonNullable<AgentProfile['model']>['reasoningEffort']>\n\nconst codexReasoningEffort: Record<ReasoningEffort, string> = {\n none: 'none',\n minimal: 'minimal',\n low: 'low',\n medium: 'medium',\n high: 'high',\n xhigh: 'xhigh',\n ultracode: 'xhigh',\n}\n\nfunction codexReasoningArgs(reasoningEffort: ReasoningEffort): string[] {\n const mapped = codexReasoningEffort[reasoningEffort]\n if (mapped === undefined) {\n throw new Error(\n `harnessInvocation: unsupported Codex reasoning effort ${String(reasoningEffort)}`,\n )\n }\n return ['-c', `model_reasoning_effort=\"${mapped}\"`]\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 */\nconst HARNESS_INVOCATIONS: Record<\n LocalHarness,\n {\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 /** Map portable reasoning effort when the harness exposes a native control. */\n reasoningArgs?: (reasoningEffort: ReasoningEffort) => string[]\n }\n> = {\n claude: {\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 },\n codex: {\n command: 'codex',\n buildArgs: (taskPrompt) => ['exec', taskPrompt],\n modelArgs: (model) => ['-m', model],\n reasoningArgs: codexReasoningArgs,\n },\n opencode: {\n command: 'opencode',\n buildArgs: (taskPrompt) => ['run', taskPrompt],\n modelArgs: (model) => ['-m', model],\n },\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 /** Allow an unattended Claude process to edit its isolated candidate worktree.\n * Ignored by harnesses that do not use Claude's permission prompt. */\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 args = HARNESS_INVOCATIONS[harness].buildArgs(taskPrompt)\n if (harness === 'claude' && options.dangerouslySkipPermissions) {\n args.push('--dangerously-skip-permissions')\n }\n if (options.codexReproducible) {\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 && invocation.reasoningArgs) {\n args.push(...invocation.reasoningArgs(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 Claude edits without an interactive permission prompt.\n * 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 if (options.codexReproducible && harness !== 'codex') {\n throw new Error('runLocalHarness: codexReproducible requires the Codex harness')\n }\n if (options.codexReproducible && process.platform !== 'linux') {\n throw new Error('runLocalHarness: codexReproducible currently requires Linux')\n }\n if (options.codexReadDeniedPaths !== undefined && !options.codexReproducible) {\n throw new Error('runLocalHarness: codexReadDeniedPaths requires codexReproducible')\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES\n if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 0) {\n throw new Error('runLocalHarness: maxOutputBytes must be a non-negative safe integer')\n }\n const spawnImpl = options.spawn ?? spawn\n\n const invocation = HARNESS_INVOCATIONS[harness]\n if (!invocation) {\n throw new Error(`runLocalHarness: unknown harness ${String(harness)}`)\n }\n\n const startedAt = Date.now()\n const requestedCommand = options.invocation?.command ?? invocation.command\n const args = options.invocation\n ? [...options.invocation.args]\n : buildHarnessArgs(harness, taskPrompt, options)\n if (options.codexReproducible) assertCodexReproducibleInvocation(requestedCommand, args)\n options.signal?.throwIfAborted()\n\n // We spawn the harness with `cwd`, but a harness that resolves its working\n // directory from `$PWD` rather than `getcwd()` (opencode does; the others may)\n // inherits the parent's stale `PWD` and edits the WRONG directory — its\n // worktree diff then comes back empty and the delegation fails with a phantom\n // \"empty patch\". Pin `PWD` to `cwd` so the harness edits where it was placed.\n // `baseEnv` feeds both the codex-isolated and the plain spawn paths below, so\n // pinning it here covers every runLocalHarness consumer.\n const baseEnv: NodeJS.ProcessEnv = { ...(options.env ?? process.env), PWD: cwd }\n const isolated = options.codexReproducible\n ? await isolateCodexHome({\n baseEnv,\n cwd,\n command: requestedCommand,\n readDeniedPaths: options.codexReadDeniedPaths ?? [],\n resolveExecutable: options.resolveCodexExecutable ?? resolveCodexNativeExecutable,\n })\n : {\n env: baseEnv,\n command: requestedCommand,\n cleanup: async () => undefined,\n controlledConfigSha256: '',\n executableSha256: '',\n readDeniedPathsSha256: '',\n readDeniedPathCount: 0,\n readDeniedPaths: [] as string[],\n diagnosticRedactionValues: [] as string[],\n ambientAuth: '',\n isolatedAuth: '',\n writeProbe: '',\n stagedWriteProbe: '',\n deniedProbePaths: [] as string[],\n }\n const env = isolated.env\n const command = isolated.command\n if (options.codexReproducible) assertCodexReproducibleInvocation(command, args)\n\n try {\n const evidence = options.codexReproducible\n ? await collectCodexExecutionEvidence({\n command,\n args,\n cwd,\n env,\n spawn: spawnImpl,\n controlledConfigSha256: isolated.controlledConfigSha256,\n executableSha256: isolated.executableSha256,\n readDeniedPathsSha256: isolated.readDeniedPathsSha256,\n readDeniedPathCount: isolated.readDeniedPathCount,\n readDeniedPaths: isolated.readDeniedPaths,\n ambientAuth: isolated.ambientAuth,\n isolatedAuth: isolated.isolatedAuth,\n writeProbe: isolated.writeProbe,\n stagedWriteProbe: isolated.stagedWriteProbe,\n deniedProbePaths: isolated.deniedProbePaths,\n ...(options.signal ? { signal: options.signal } : {}),\n })\n : undefined\n return await new Promise<LocalHarnessResult>((resolve, reject) => {\n let child: ChildProcess\n try {\n options.signal?.throwIfAborted()\n child = spawnImpl(command, args, {\n cwd,\n env,\n stdio: 'pipe',\n detached: process.platform !== 'win32',\n })\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)))\n return\n }\n\n // The harness takes its task as an argv arg, not on stdin. Leaving stdin\n // OPEN makes a non-TTY `opencode run` (and likely the other harnesses)\n // BLOCK forever waiting on input — zero output, SIGTERM at the wall cap,\n // empty patch -> \"no candidate passed validation\". Close stdin so the\n // subprocess sees EOF and proceeds (the `cliExecutor` leaf does the same).\n child.stdin?.end()\n\n const stdoutCapture = new RollingByteCapture(maxOutputBytes)\n const stderrCapture = new RollingByteCapture(maxOutputBytes)\n let timedOut = false\n let aborted = false\n let settled = false\n let leaderClosed = false\n let timer: ReturnType<typeof setTimeout> | null = null\n let termination: Promise<void> | null = null\n\n const clearLifecycle = () => {\n if (timer) clearTimeout(timer)\n options.signal?.removeEventListener('abort', onAbort)\n }\n const rejectOnce = (err: unknown) => {\n if (settled) return\n settled = true\n clearLifecycle()\n reject(err instanceof Error ? err : new Error(String(err)))\n }\n const terminate = (): Promise<void> => {\n if (!termination) {\n termination = terminateProcessTreeAndConfirm(child, () => leaderClosed)\n void termination.catch(rejectOnce)\n }\n return termination\n }\n\n timer =\n timeoutMs > 0\n ? setTimeout(() => {\n timedOut = true\n void terminate()\n }, timeoutMs)\n : null\n if (timer && typeof (timer as { unref?: () => void }).unref === 'function') {\n ;(timer as { unref: () => void }).unref()\n }\n\n const onAbort = () => {\n aborted = true\n void terminate()\n }\n if (options.signal) {\n if (options.signal.aborted) onAbort()\n else options.signal.addEventListener('abort', onAbort, { once: true })\n }\n\n child.stdout?.on('data', (chunk) => {\n stdoutCapture.append(chunk)\n })\n child.stderr?.on('data', (chunk) => {\n stderrCapture.append(chunk)\n })\n\n const finalize = (result: LocalHarnessResult) => {\n if (settled) return\n settled = true\n clearLifecycle()\n resolve(result)\n }\n\n child.on('error', (err) => {\n leaderClosed = true\n if (timer) clearTimeout(timer)\n void (async () => {\n try {\n if (termination) await termination\n rejectOnce(err)\n } catch (terminationError) {\n rejectOnce(terminationError)\n }\n })()\n })\n\n child.on('close', (code, signal) => {\n leaderClosed = true\n if (timer) clearTimeout(timer)\n void (async () => {\n const stdout = stdoutCapture.text()\n const stderr = stderrCapture.text()\n try {\n if (\n !termination &&\n process.platform !== 'win32' &&\n typeof child.pid === 'number' &&\n processGroupExists(child.pid)\n ) {\n await terminate()\n }\n if (termination) await termination\n const durationMs = Date.now() - startedAt\n const usage = options.codexReproducible ? parseCodexTokenUsage(stdout) : undefined\n finalize({\n exitCode: code,\n stdout,\n stderr: redactCodexHome(stderr, env.CODEX_HOME),\n killedBySignal: signal,\n durationMs,\n timedOut,\n aborted,\n ...(usage ? { usage } : {}),\n ...(evidence ? { evidence } : {}),\n })\n } catch (err) {\n if (settled) return\n settled = true\n clearLifecycle()\n const durationMs = Date.now() - startedAt\n const reason = err instanceof Error ? err.message : String(err)\n reject(\n options.codexReproducible\n ? createCodexExecutionDiagnosticError({\n reason,\n exitCode: code,\n killedBySignal: signal,\n timedOut,\n aborted,\n durationMs,\n stdout,\n stderr,\n codexHome: env.CODEX_HOME,\n redactionValues: isolated.diagnosticRedactionValues,\n cause: err,\n })\n : err instanceof Error\n ? err\n : new Error(reason),\n )\n }\n })()\n })\n })\n } finally {\n await isolated.cleanup()\n }\n}\n\nconst CODEX_EXECUTION_POLICY: CodexExecutionPolicy = {\n sessionPersistence: 'ephemeral',\n userConfig: false,\n rules: false,\n projectInstructions: false,\n skillInstructions: false,\n appInstructions: false,\n toolSuggestions: false,\n multiAgentInstructions: false,\n sandbox: 'workspace-write',\n permissionProfile: 'agent_runtime_reproducible',\n approvalPolicy: 'never',\n shellNetwork: false,\n webSearch: false,\n serviceTier: 'default',\n shellEnvironment: 'core-filtered',\n loginShell: false,\n credentialsReadable: false,\n hostHomeReadable: false,\n procEnvironment: 'private-sanitized',\n sensitiveEnvironmentNamesVisible: false,\n parentRepoRead: false,\n gitMetadata: false,\n temporaryDirectory: 'workspace-private',\n stagedExecutable: 'static-elf-read-only',\n callerReadDeniedPaths: 'enforced',\n containerSockets: false,\n}\n\nconst FORBIDDEN_CODEX_PROMPT_MARKERS = [\n '<skills_instructions>',\n '# AGENTS.md instructions',\n '<apps_instructions>',\n '<recommended_plugins>',\n '<multi_agent_mode>',\n 'You are `/root`, the primary agent',\n] as const\n\nasync function collectCodexExecutionEvidence(opts: {\n command: string\n args: string[]\n cwd: string\n env: NodeJS.ProcessEnv\n spawn: NonNullable<RunLocalHarnessOptions['spawn']>\n controlledConfigSha256: string\n readDeniedPaths: string[]\n executableSha256: string\n readDeniedPathsSha256: string\n readDeniedPathCount: number\n ambientAuth: string\n isolatedAuth: string\n writeProbe: string\n stagedWriteProbe: string\n deniedProbePaths: string[]\n signal?: AbortSignal\n}): Promise<CodexExecutionEvidence> {\n assertCodexReproducibleInvocation(opts.command, opts.args)\n const prompt = opts.args[1]\n if (opts.args[0] !== 'exec' || typeof prompt !== 'string' || prompt.length === 0) {\n throw new Error('runLocalHarness: reproducible Codex invocation must be codex exec <prompt>')\n }\n const cliVersion = (await runCodexProbe(opts, ['--version'])).stdout.trim()\n if (!/^codex-cli \\d+\\.\\d+\\.\\d+(?:[-+].+)?$/.test(cliVersion)) {\n throw new Error(\n `runLocalHarness: unexpected Codex CLI version output ${JSON.stringify(cliVersion)}`,\n )\n }\n\n const hiddenEnvironmentChecks = [\n 'CODEX_HOME',\n 'CODEX_ACCESS_TOKEN',\n 'CODEX_API_KEY',\n 'OPENAI_API_KEY',\n ]\n .map((name) => `test -z \"\\${${name}:-}\"`)\n .join(' && ')\n const sandboxProof = [\n hiddenEnvironmentChecks,\n 'test -r .',\n '! test -r .git',\n 'touch \"$1\"',\n 'rm \"$1\"',\n 'staged_dir=$(dirname \"$2\")',\n 'test -x \"$staged_dir/codex\"',\n '! chmod 700 \"$staged_dir\" 2>/dev/null',\n '! rm \"$staged_dir/codex\" 2>/dev/null',\n '! touch \"$2\" 2>/dev/null',\n 'shift 2',\n 'for path in \"$@\"; do ! test -r \"$path\" || exit 1; done',\n 'touch \"$TMPDIR/.agent-runtime-tmp-proof\"',\n 'rm \"$TMPDIR/.agent-runtime-tmp-proof\"',\n ].join(' && ')\n await runCodexProbe(opts, [\n 'sandbox',\n '-P',\n CODEX_PERMISSION_PROFILE,\n '-C',\n opts.cwd,\n 'sh',\n '-c',\n sandboxProof,\n 'sh',\n opts.writeProbe,\n opts.stagedWriteProbe,\n ...opts.deniedProbePaths,\n ])\n await runCodexProbe(opts, [\n 'sandbox',\n '-P',\n CODEX_PERMISSION_PROFILE,\n '-C',\n opts.cwd,\n 'python3',\n '-c',\n `import os,re\npattern=re.compile(br'(TOKEN|KEY|SECRET|PASSWORD|CREDENTIAL|AUTH|COOKIE|CODEX_HOME)', re.I)\npaths=('/proc/1/environ', '/proc/self/environ', f'/proc/{os.getppid()}/environ')\nfor path in dict.fromkeys(paths):\n data=open(path,'rb').read().split(b'\\\\0')\n names=(item.split(b'=',1)[0] for item in data if b'=' in item)\n assert not any(pattern.search(name) for name in names), path`,\n ])\n await runCodexProbe(opts, [\n 'sandbox',\n '-P',\n CODEX_PERMISSION_PROFILE,\n '-C',\n opts.cwd,\n 'python3',\n '-c',\n 'import socket,sys\\nfor path in sys.argv[1:]:\\n s=socket.socket(socket.AF_UNIX)\\n try: s.connect(path)\\n except OSError: continue\\n raise SystemExit(1)',\n '/var/run/docker.sock',\n '/run/docker.sock',\n '/var/run/containerd/containerd.sock',\n '/run/containerd/containerd.sock',\n ])\n\n const debugArgs = codexPromptDebugArgs(opts.args, prompt)\n const renderedPrompt = (await runCodexProbe(opts, debugArgs)).stdout\n let parsedPrompt: unknown\n try {\n parsedPrompt = JSON.parse(renderedPrompt)\n } catch {\n throw new Error('runLocalHarness: codex debug prompt-input returned invalid JSON')\n }\n const promptEvidenceText = normalizeCodexDebugPromptNewlines(prompt)\n if (!Array.isArray(parsedPrompt) || !jsonTextContains(parsedPrompt, promptEvidenceText)) {\n throw new Error('runLocalHarness: Codex prompt evidence did not contain the exact task prompt')\n }\n const promptContextWithoutTask = JSON.stringify(redactJsonText(parsedPrompt, promptEvidenceText))\n for (const marker of FORBIDDEN_CODEX_PROMPT_MARKERS) {\n if (promptContextWithoutTask.includes(marker)) {\n throw new Error(`runLocalHarness: Codex prompt evidence contains forbidden marker ${marker}`)\n }\n }\n for (const marker of ['<permissions instructions>', '<environment_context>']) {\n if (!renderedPrompt.includes(marker)) {\n throw new Error(`runLocalHarness: Codex prompt evidence is missing required marker ${marker}`)\n }\n }\n\n const nonPromptArgs = [\n 'codex',\n ...opts.args.map((arg, index) => (index === 1 ? '<PROMPT>' : arg)),\n ]\n return {\n cliVersion,\n executableSha256: opts.executableSha256,\n requestedPromptSha256: sha256(prompt),\n effectivePromptSha256: sha256(renderedPrompt),\n nonPromptArgsSha256: sha256(JSON.stringify(nonPromptArgs)),\n controlledConfigSha256: opts.controlledConfigSha256,\n readDeniedPathsSha256: opts.readDeniedPathsSha256,\n readDeniedPathCount: opts.readDeniedPathCount,\n readDeniedPaths: [...opts.readDeniedPaths],\n policy: { ...CODEX_EXECUTION_POLICY },\n }\n}\n\nfunction assertCodexReproducibleInvocation(command: string, args: string[]): void {\n const executable = basename(command)\n if (executable !== 'codex' && executable !== 'codex.exe') {\n throw new Error('runLocalHarness: reproducible Codex invocation must use the Codex executable')\n }\n const prompt = args[1]\n const expectedPrefix = ['exec', prompt, ...CODEX_REPRODUCIBLE_ARGS]\n const hasExactPrefix = expectedPrefix.every((arg, index) => args[index] === arg)\n const tail = args.slice(expectedPrefix.length)\n const validModel =\n tail[0] === '-m' &&\n typeof tail[1] === 'string' &&\n tail[1].length > 0 &&\n !tail[1].startsWith('-')\n const validReasoning =\n tail[2] === '-c' &&\n typeof tail[3] === 'string' &&\n /^model_reasoning_effort=\"(?:none|minimal|low|medium|high|xhigh)\"$/.test(tail[3])\n if (!hasExactPrefix || tail.length !== 4 || !validModel || !validReasoning) {\n throw new Error(\n 'runLocalHarness: reproducible Codex invocation does not match the required isolated argv',\n )\n }\n}\n\nfunction codexPromptDebugArgs(execArgs: string[], prompt: string): string[] {\n const debugArgs = ['debug', 'prompt-input']\n for (let index = 2; index < execArgs.length; index += 1) {\n const arg = execArgs[index]\n const value = execArgs[index + 1]\n if (arg === '-c' && value !== undefined) {\n debugArgs.push('-c', value)\n index += 1\n } else if (arg === '--disable' && value !== undefined) {\n debugArgs.push('--disable', value)\n index += 1\n } else if (arg === '-m' && value !== undefined) {\n debugArgs.push('-c', `model=${JSON.stringify(value)}`)\n index += 1\n } else if (arg === '-s' && value !== undefined) {\n debugArgs.push('-c', `sandbox_mode=${JSON.stringify(value)}`)\n index += 1\n }\n }\n debugArgs.push(prompt)\n return debugArgs\n}\n\nfunction runCodexProbe(\n opts: {\n command: string\n cwd: string\n env: NodeJS.ProcessEnv\n spawn: NonNullable<RunLocalHarnessOptions['spawn']>\n signal?: AbortSignal\n },\n args: string[],\n): Promise<{ stdout: string; stderr: string }> {\n return new Promise((resolve, reject) => {\n let child: ChildProcess\n try {\n child = opts.spawn(opts.command, args, {\n cwd: opts.cwd,\n env: opts.env,\n stdio: 'pipe',\n detached: process.platform !== 'win32',\n })\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)))\n return\n }\n child.stdin?.end()\n let stdout = ''\n let stderr = ''\n let settled = false\n let leaderClosed = false\n let termination: Promise<void> | null = null\n let terminationReason: 'aborted' | 'timed out' | null = null\n const clearLifecycle = () => {\n clearTimeout(timer)\n opts.signal?.removeEventListener('abort', onAbort)\n }\n const rejectOnce = (err: unknown) => {\n if (settled) return\n settled = true\n clearLifecycle()\n reject(err instanceof Error ? err : new Error(String(err)))\n }\n const terminate = (reason?: 'aborted' | 'timed out'): Promise<void> => {\n if (reason) terminationReason ??= reason\n if (!termination) {\n termination = terminateProcessTreeAndConfirm(child, () => leaderClosed)\n void termination.catch(rejectOnce)\n }\n return termination\n }\n const timer = setTimeout(() => {\n void terminate('timed out')\n }, 10_000)\n timer.unref?.()\n const onAbort = () => {\n void terminate('aborted')\n }\n if (opts.signal) {\n if (opts.signal.aborted) onAbort()\n else opts.signal.addEventListener('abort', onAbort, { once: true })\n }\n child.stdout?.on('data', (chunk) => {\n stdout += String(chunk)\n })\n child.stderr?.on('data', (chunk) => {\n stderr += String(chunk)\n })\n child.on('error', (err) => {\n leaderClosed = true\n clearTimeout(timer)\n void (async () => {\n try {\n if (termination) await termination\n rejectOnce(err)\n } catch (terminationError) {\n rejectOnce(terminationError)\n }\n })()\n })\n child.on('close', (code, signal) => {\n leaderClosed = true\n clearTimeout(timer)\n void (async () => {\n try {\n if (\n !termination &&\n process.platform !== 'win32' &&\n typeof child.pid === 'number' &&\n processGroupExists(child.pid)\n ) {\n await terminate()\n }\n if (termination) await termination\n if (settled) return\n settled = true\n clearLifecycle()\n if (code !== 0 || terminationReason) {\n const safeStderr = redactCodexHome(stderr, opts.env.CODEX_HOME)\n reject(\n new Error(\n `runLocalHarness: Codex evidence probe ${terminationReason ?? 'failed'} (exit ${String(code)}, signal ${String(signal)}): ${safeStderr.trim()}`,\n ),\n )\n return\n }\n resolve({ stdout, stderr })\n } catch (err) {\n rejectOnce(err)\n }\n })()\n })\n })\n}\n\nfunction sha256(value: string): string {\n return createHash('sha256').update(value).digest('hex')\n}\n\n/** Codex's debug renderer converts CRLF pairs to LF. No other whitespace is equivalent. */\nfunction normalizeCodexDebugPromptNewlines(value: string): string {\n return value.replaceAll('\\r\\n', '\\n')\n}\n\nfunction jsonTextContains(value: unknown, needle: string): boolean {\n if (typeof value === 'string') return value.includes(needle)\n if (Array.isArray(value)) return value.some((item) => jsonTextContains(item, needle))\n if (isRecord(value)) return Object.values(value).some((item) => jsonTextContains(item, needle))\n return false\n}\n\nfunction redactJsonText(value: unknown, text: string): unknown {\n if (typeof value === 'string') return value.replaceAll(text, '')\n if (Array.isArray(value)) return value.map((item) => redactJsonText(item, text))\n if (isRecord(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([key, item]) => [key, redactJsonText(item, text)]),\n )\n }\n return value\n}\n\nconst CODEX_AUTH_ENV = ['CODEX_ACCESS_TOKEN', 'CODEX_API_KEY', 'OPENAI_API_KEY'] as const\n\nconst CODEX_PERMISSION_PROFILE = 'agent_runtime_reproducible'\n\nasync function isolateCodexHome(opts: {\n baseEnv: NodeJS.ProcessEnv\n cwd: string\n command: string\n readDeniedPaths: ReadonlyArray<string>\n resolveExecutable: (command: string, env: NodeJS.ProcessEnv) => Promise<string>\n}): Promise<{\n env: NodeJS.ProcessEnv\n command: string\n cleanup: () => Promise<void>\n controlledConfigSha256: string\n executableSha256: string\n readDeniedPaths: string[]\n readDeniedPathsSha256: string\n readDeniedPathCount: number\n diagnosticRedactionValues: string[]\n ambientAuth: string\n isolatedAuth: string\n writeProbe: string\n stagedWriteProbe: string\n deniedProbePaths: string[]\n}> {\n const isolatedHome = await mkdtemp(join(tmpdir(), 'agent-runtime-codex-'))\n await chmod(isolatedHome, 0o700)\n let workspaceTemp = ''\n let stagedExecutableDir = ''\n let ownsStagedExecutableDir = false\n let writeProbe = ''\n const cleanup = async () => {\n if (ownsStagedExecutableDir) {\n await chmod(stagedExecutableDir, 0o700).catch(() => undefined)\n }\n await Promise.all([\n ...(writeProbe ? [rm(writeProbe, { force: true })] : []),\n ...(workspaceTemp ? [rm(workspaceTemp, { recursive: true, force: true })] : []),\n ...(ownsStagedExecutableDir\n ? [rm(stagedExecutableDir, { recursive: true, force: true })]\n : []),\n rm(isolatedHome, { recursive: true, force: true }),\n ])\n }\n try {\n const readDeniedPaths = await normalizeReadDeniedPaths(opts.readDeniedPaths)\n const candidateRoot = await realpath(opts.cwd)\n writeProbe = join(candidateRoot, `.agent-runtime-write-proof-${randomUUID()}`)\n const stagedPath = join(candidateRoot, '.agent-runtime-bin')\n if (\n readDeniedPaths.some(\n (path) =>\n isSameOrDescendant(candidateRoot, path) ||\n isSameOrDescendant(stagedPath, path) ||\n isSameOrDescendant(path, stagedPath),\n )\n ) {\n throw new Error(\n 'runLocalHarness: codexReadDeniedPaths cannot contain the candidate root or staged executable',\n )\n }\n const nativeExecutable = await opts.resolveExecutable(opts.command, opts.baseEnv)\n if (!(await isStaticElfExecutable(nativeExecutable))) {\n throw new Error(\n 'runLocalHarness: reproducible Codex mode requires a statically linked Linux Codex ELF',\n )\n }\n const sourceExecutableSha256 = await sha256File(nativeExecutable)\n\n stagedExecutableDir = stagedPath\n try {\n await mkdir(stagedExecutableDir, { mode: 0o700 })\n ownsStagedExecutableDir = true\n } catch (err) {\n throw new Error(\n `runLocalHarness: candidate-private .agent-runtime-bin must not already exist: ${String((err as NodeJS.ErrnoException).code ?? err)}`,\n )\n }\n const stagedExecutable = join(stagedExecutableDir, 'codex')\n await copyFile(nativeExecutable, stagedExecutable, constants.COPYFILE_FICLONE)\n await chmod(stagedExecutable, 0o500)\n const executableSha256 = await sha256File(stagedExecutable)\n if (\n executableSha256 !== sourceExecutableSha256 ||\n !(await isStaticElfExecutable(stagedExecutable))\n ) {\n throw new Error('runLocalHarness: staged Codex executable digest mismatch')\n }\n await chmod(stagedExecutableDir, 0o500)\n\n workspaceTemp = await mkdtemp(join(candidateRoot, '.agent-runtime-tmp-'))\n await chmod(workspaceTemp, 0o700)\n const ambientHome = resolve(opts.baseEnv.CODEX_HOME?.trim() || join(homedir(), '.codex'))\n const ambientAuth = join(ambientHome, 'auth.json')\n const isolatedAuth = join(isolatedHome, 'auth.json')\n let authText = ''\n try {\n await access(ambientAuth, constants.R_OK)\n authText = await readCodexAuthRedactionText(ambientAuth)\n await symlink(ambientAuth, isolatedAuth)\n } catch (err) {\n throw new Error(\n `runLocalHarness: reproducible Codex mode requires readable auth.json: ${String((err as NodeJS.ErrnoException).code ?? err)}`,\n )\n }\n const deniedHostRoots = [homedir(), opts.baseEnv.HOME?.trim(), ambientHome]\n .filter((path): path is string => Boolean(path))\n .map((path) => resolve(path))\n .filter((path, index, paths) => paths.indexOf(path) === index)\n const controlledConfig = codexControlledConfig({\n ambientTmp: opts.baseEnv.TMPDIR?.trim() || tmpdir(),\n deniedHostRoots,\n workspaceTemp,\n stagedExecutableDir,\n readDeniedPaths,\n })\n await writeFile(join(isolatedHome, 'config.toml'), controlledConfig, { mode: 0o600 })\n const env = { ...opts.baseEnv }\n for (const name of Object.keys(env)) {\n if (\n codexSensitiveEnvironmentName.test(name) ||\n CODEX_AUTH_ENV.some((authName) => authName === name)\n ) {\n delete env[name]\n }\n }\n env.CODEX_HOME = isolatedHome\n const home = homedir()\n const deniedProbePaths = [\n ...deniedHostRoots,\n ambientAuth,\n isolatedAuth,\n join(home, '.claude', '.credentials.json'),\n join(home, '.claude.json'),\n join(home, '.local', 'share', 'opencode', 'auth.json'),\n join(home, '.agents'),\n join(home, 'Documents'),\n join(home, 'Downloads'),\n join(home, '.npm'),\n join(home, 'code'),\n ...readDeniedPaths,\n ].filter((path, index, paths) => paths.indexOf(path) === index)\n return {\n env,\n command: stagedExecutable,\n cleanup,\n controlledConfigSha256: sha256(controlledConfig),\n executableSha256,\n readDeniedPaths,\n readDeniedPathsSha256: sha256(JSON.stringify(readDeniedPaths)),\n readDeniedPathCount: readDeniedPaths.length,\n diagnosticRedactionValues: collectCodexDiagnosticRedactionValues(opts.baseEnv, authText),\n ambientAuth,\n isolatedAuth,\n writeProbe,\n stagedWriteProbe: join(stagedExecutableDir, 'write-proof'),\n deniedProbePaths,\n }\n } catch (err) {\n await cleanup()\n throw err\n }\n}\n\nfunction codexControlledConfig(opts: {\n ambientTmp: string\n deniedHostRoots: string[]\n workspaceTemp: string\n stagedExecutableDir: string\n readDeniedPaths: string[]\n}): string {\n const rules = new Map<string, 'deny' | 'read' | 'write'>()\n const broadDeniedPaths = minimalPathRoots([\n ...opts.deniedHostRoots.map((path) => resolve(path)),\n tmpdir(),\n opts.ambientTmp,\n '/proc',\n '/run/docker',\n '/run/containerd',\n ])\n for (const path of broadDeniedPaths) {\n rules.set(path, 'deny')\n }\n const workspaceRoot = dirname(opts.workspaceTemp)\n for (const path of opts.readDeniedPaths) {\n const alreadyDenied = broadDeniedPaths.some((root) => isSameOrDescendant(path, root))\n if (!alreadyDenied || isSameOrDescendant(path, workspaceRoot)) rules.set(path, 'deny')\n }\n if (!rules.has(opts.workspaceTemp)) rules.set(opts.workspaceTemp, 'write')\n if (!rules.has(opts.stagedExecutableDir)) rules.set(opts.stagedExecutableDir, 'read')\n const filesystemRules = [...rules]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([path, access]) => `${JSON.stringify(path)} = ${JSON.stringify(access)}`)\n .join('\\n')\n return `default_permissions = \"${CODEX_PERMISSION_PROFILE}\"\napproval_policy = \"never\"\nallow_login_shell = false\nservice_tier = \"default\"\n\n[shell_environment_policy]\ninherit = \"core\"\nignore_default_excludes = false\nexclude = [\"^CODEX_HOME$\", \"(?i).*TOKEN.*\", \"(?i).*KEY.*\", \"(?i).*SECRET.*\", \"(?i).*PASSWORD.*\", \"(?i).*CREDENTIAL.*\", \"(?i).*AUTH.*\", \"(?i).*COOKIE.*\"]\nset = { TMPDIR = ${JSON.stringify(opts.workspaceTemp)} }\n\n[permissions.${CODEX_PERMISSION_PROFILE}.filesystem]\n\":minimal\" = \"read\"\n${filesystemRules}\n\":slash_tmp\" = \"deny\"\n\n[permissions.${CODEX_PERMISSION_PROFILE}.filesystem.\":workspace_roots\"]\n\".\" = \"write\"\n\".git\" = \"deny\"\n\n[permissions.${CODEX_PERMISSION_PROFILE}.network]\nenabled = false\n\n[permissions.${CODEX_PERMISSION_PROFILE}.network.unix_sockets]\n\"/var/run/docker.sock\" = \"deny\"\n\"/run/docker.sock\" = \"deny\"\n\"/var/run/containerd/containerd.sock\" = \"deny\"\n\"/run/containerd/containerd.sock\" = \"deny\"\n`\n}\n\nfunction isSameOrDescendant(path: string, root: string): boolean {\n const normalizedPath = resolve(path)\n const normalizedRoot = resolve(root)\n return normalizedPath === normalizedRoot || normalizedPath.startsWith(`${normalizedRoot}${sep}`)\n}\n\nfunction minimalPathRoots(paths: ReadonlyArray<string>): string[] {\n const ordered = [...new Set(paths.map((path) => resolve(path)))].sort(\n (a, b) => a.length - b.length || a.localeCompare(b),\n )\n return ordered.filter(\n (path, index) => !ordered.slice(0, index).some((root) => isSameOrDescendant(path, root)),\n )\n}\n\nasync function normalizeReadDeniedPaths(paths: ReadonlyArray<string>): Promise<string[]> {\n if (!Array.isArray(paths)) {\n throw new Error('runLocalHarness: codexReadDeniedPaths must be an array of absolute paths')\n }\n const normalized = new Set<string>()\n for (const path of paths) {\n if (typeof path !== 'string' || path.length === 0 || path.includes('\\0') || !isAbsolute(path)) {\n throw new Error('runLocalHarness: codexReadDeniedPaths must contain absolute paths')\n }\n const absolute = resolve(path)\n normalized.add(absolute)\n try {\n normalized.add(await realpath(absolute))\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err\n }\n }\n return [...normalized].sort()\n}\n\nasync function resolveCodexNativeExecutable(\n command: string,\n env: NodeJS.ProcessEnv,\n): Promise<string> {\n const candidates =\n command.includes(sep) || isAbsolute(command)\n ? [resolve(command)]\n : (env.PATH ?? '')\n .split(delimiter)\n .filter(Boolean)\n .map((entry) => join(entry, command))\n const seen = new Set<string>()\n for (const candidate of candidates) {\n let resolved: string\n try {\n await access(candidate, constants.X_OK)\n resolved = await realpath(candidate)\n } catch {\n continue\n }\n if (seen.has(resolved)) continue\n seen.add(resolved)\n if (await isStaticElfExecutable(resolved)) return resolved\n const packageRoot = await findCodexPackageRoot(resolved)\n if (!packageRoot) continue\n const bundled = await findBundledCodexExecutable(packageRoot)\n if (bundled) return bundled\n }\n throw new Error(\n 'runLocalHarness: could not resolve the native Codex executable from the requested command',\n )\n}\n\nasync function findCodexPackageRoot(file: string): Promise<string | undefined> {\n let cursor = dirname(file)\n while (true) {\n try {\n const parsed = JSON.parse(await readFile(join(cursor, 'package.json'), 'utf8')) as {\n name?: unknown\n }\n if (parsed.name === '@openai/codex') return cursor\n } catch {\n // Keep walking; PATH wrappers commonly live outside the package directory.\n }\n const parent = dirname(cursor)\n if (parent === cursor) return undefined\n cursor = parent\n }\n}\n\nasync function findBundledCodexExecutable(packageRoot: string): Promise<string | undefined> {\n const target = linuxCodexTarget()\n const candidates = [\n join(\n packageRoot,\n 'node_modules',\n '@openai',\n target.packageName,\n 'vendor',\n target.triple,\n 'bin',\n 'codex',\n ),\n join(packageRoot, 'vendor', target.triple, 'bin', 'codex'),\n ]\n for (const executable of candidates) {\n if (await isStaticElfExecutable(executable)) return executable\n }\n return undefined\n}\n\nfunction linuxCodexTarget(): { packageName: string; triple: string } {\n if (process.platform !== 'linux') {\n throw new Error('runLocalHarness: reproducible Codex mode requires Linux')\n }\n if (process.arch === 'x64') {\n return { packageName: 'codex-linux-x64', triple: 'x86_64-unknown-linux-musl' }\n }\n if (process.arch === 'arm64') {\n return { packageName: 'codex-linux-arm64', triple: 'aarch64-unknown-linux-musl' }\n }\n throw new Error(`runLocalHarness: unsupported Linux architecture ${process.arch}`)\n}\n\nasync function isStaticElfExecutable(path: string): Promise<boolean> {\n let handle: Awaited<ReturnType<typeof open>> | undefined\n try {\n await access(path, constants.X_OK)\n handle = await open(path, 'r')\n const header = Buffer.alloc(64)\n const { bytesRead } = await handle.read(header, 0, header.length, 0)\n if (\n bytesRead !== header.length ||\n !header.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])) ||\n header[4] !== 2 ||\n header[5] !== 1\n ) {\n return false\n }\n const programHeaderOffset = Number(header.readBigUInt64LE(32))\n const programHeaderSize = header.readUInt16LE(54)\n const programHeaderCount = header.readUInt16LE(56)\n const expectedMachine = process.arch === 'x64' ? 62 : process.arch === 'arm64' ? 183 : -1\n if (\n ![2, 3].includes(header.readUInt16LE(16)) ||\n header.readUInt16LE(18) !== expectedMachine ||\n !Number.isSafeInteger(programHeaderOffset) ||\n programHeaderOffset < 64 ||\n programHeaderSize < 56 ||\n programHeaderSize > 1024 ||\n programHeaderCount === 0 ||\n programHeaderCount > 1024\n ) {\n return false\n }\n const tableSize = programHeaderSize * programHeaderCount\n const table = Buffer.alloc(tableSize)\n const tableRead = await handle.read(table, 0, tableSize, programHeaderOffset)\n if (tableRead.bytesRead !== tableSize) return false\n for (let index = 0; index < programHeaderCount; index += 1) {\n const type = table.readUInt32LE(index * programHeaderSize)\n if (type === 3) return false\n }\n return true\n } catch {\n return false\n } finally {\n await handle?.close()\n }\n}\n\nfunction sha256File(path: string): Promise<string> {\n return new Promise((resolveDigest, reject) => {\n const hash = createHash('sha256')\n const stream = createReadStream(path)\n stream.on('error', reject)\n stream.on('data', (chunk) => hash.update(chunk))\n stream.on('end', () => resolveDigest(hash.digest('hex')))\n })\n}\n\nfunction signalProcessTree(child: ChildProcess, signal: NodeJS.Signals): void {\n if (process.platform !== 'win32' && typeof child.pid === 'number') {\n try {\n process.kill(-child.pid, signal)\n return\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ESRCH') return\n }\n }\n try {\n child.kill(signal)\n } catch {\n // The process may have exited between the timer and signal delivery.\n }\n}\n\nexport async function terminateProcessTreeAndConfirm(\n child: ChildProcess,\n leaderClosed: () => boolean,\n context = 'runLocalHarness',\n): Promise<void> {\n signalProcessTree(child, 'SIGTERM')\n if (process.platform === 'win32' || typeof child.pid !== 'number') {\n const graceDeadline = Date.now() + processKillGraceMs\n while (!leaderClosed() && Date.now() < graceDeadline) {\n await delayUntilNextProcessCheck(graceDeadline)\n }\n if (!leaderClosed()) signalProcessTree(child, 'SIGKILL')\n return\n }\n const processGroupId = child.pid\n const graceDeadline = Date.now() + processKillGraceMs\n if (await waitForProcessGroupExit(processGroupId, graceDeadline)) return\n\n signalProcessTree(child, 'SIGKILL')\n const killDeadline = Date.now() + processGroupExitConfirmMs\n if (await waitForProcessGroupExit(processGroupId, killDeadline)) return\n throw new Error(`${context}: process group ${processGroupId} survived SIGKILL`)\n}\n\nasync function waitForProcessGroupExit(processGroupId: number, deadline: number): Promise<boolean> {\n while (processGroupExists(processGroupId)) {\n if (Date.now() >= deadline) return false\n await delayUntilNextProcessCheck(deadline)\n }\n return true\n}\n\nasync function delayUntilNextProcessCheck(deadline: number): Promise<void> {\n const delayMs = Math.min(processGroupExitPollMs, Math.max(0, deadline - Date.now()))\n if (delayMs > 0) await new Promise((resolve) => setTimeout(resolve, delayMs))\n}\n\nfunction processGroupExists(processGroupId: number): boolean {\n try {\n process.kill(-processGroupId, 0)\n return true\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ESRCH') return false\n return true\n }\n}\n\n/** Parse and validate the one terminal usage event emitted by `codex exec --json`. */\nexport function parseCodexTokenUsage(stdout: string): CodexTokenUsage {\n const completed: unknown[] = []\n for (const [index, line] of stdout.split(/\\r?\\n/).entries()) {\n if (line.trim().length === 0) continue\n let event: unknown\n try {\n event = JSON.parse(line)\n } catch {\n throw new Error(`runLocalHarness: Codex JSONL line ${index + 1} is not valid JSON`)\n }\n if (isRecord(event) && event.type === 'turn.completed') completed.push(event)\n }\n if (completed.length !== 1) {\n throw new Error(\n `runLocalHarness: expected exactly one Codex turn.completed usage event, received ${completed.length}`,\n )\n }\n const event = completed[0]\n if (!isRecord(event) || !isRecord(event.usage)) {\n throw new Error('runLocalHarness: Codex turn.completed event is missing usage')\n }\n const usage = event.usage\n const inputTokens = naturalNumber(usage.input_tokens, 'input_tokens')\n const cachedInputTokens = naturalNumber(usage.cached_input_tokens, 'cached_input_tokens')\n const outputTokens = naturalNumber(usage.output_tokens, 'output_tokens')\n const reasoningOutputTokens = naturalNumber(\n usage.reasoning_output_tokens,\n 'reasoning_output_tokens',\n )\n if (cachedInputTokens > inputTokens) {\n throw new Error('runLocalHarness: Codex cached_input_tokens exceeds input_tokens')\n }\n if (reasoningOutputTokens > outputTokens) {\n throw new Error('runLocalHarness: Codex reasoning_output_tokens exceeds output_tokens')\n }\n return { inputTokens, cachedInputTokens, outputTokens, reasoningOutputTokens }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction naturalNumber(value: unknown, field: string): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new Error(`runLocalHarness: Codex usage.${field} must be a non-negative safe integer`)\n }\n return value\n}\n","/**\n *\n * Git worktree helpers for the in-process delegation executor. Each\n * delegation runs in its own worktree so multiple parallel harness\n * subprocesses (claude / codex / opencode in a 3-way fanout) don't clobber\n * each other's edits on the shared workspace.\n *\n * Worktrees live under `<repoRoot>/.agent-worktrees/<runId>/`. After the\n * harness exits + the diff is captured, the worktree is removed.\n *\n * All operations spawn `git` via `child_process.spawn` synchronously\n * (via a `runGit` helper). Stays narrow on purpose: no commits, no rebases.\n * Diff capture stages all changes (`git add -A`) into the ephemeral worktree's\n * index so created (untracked) files appear in the `--cached` diff.\n *\n * @experimental\n */\n\nimport { spawn } from 'node:child_process'\nimport { isAbsolute, win32 } from 'node:path'\n\n/** @experimental */\nexport interface WorktreeHandle {\n /** Absolute path to the worktree directory. */\n path: string\n /** SHA the worktree was created at. */\n baseSha: string\n /** Branch name created for this worktree (typically `delegate/<runId>`). */\n branch: string\n}\n\n/** @experimental */\nexport interface CreateWorktreeOptions {\n /** Absolute path to the main git checkout. */\n repoRoot: string\n /** Unique id for the worktree path + branch. Use the delegation run id. */\n runId: string\n /** Parent directory the worktree lives under. Defaults to `.agent-worktrees`. */\n variantsDir?: string\n /** Override the base ref (default `HEAD`). */\n baseRef?: string\n /** Test seam — inject a custom git runner. */\n runGit?: GitRunner\n}\n\n/** @experimental */\nexport interface DiffOptions {\n /** Worktree to diff. */\n worktree: WorktreeHandle\n /** What to compare against. Default `worktree.baseSha`. */\n baseRef?: string\n /**\n * Repository-relative input paths to omit from the captured worker patch.\n * Paths are passed to Git with literal exclusion magic, so profile-provided\n * `*`, `?`, `[` and `:` characters can never expand into broader pathspecs.\n */\n excludePaths?: ReadonlyArray<string>\n /** Test seam. */\n runGit?: GitRunner\n}\n\n/** @experimental */\nexport interface DiffResult {\n patch: string\n stats: {\n filesChanged: number\n insertions: number\n deletions: number\n }\n}\n\n/** @experimental */\nexport interface RemoveWorktreeOptions {\n worktree: WorktreeHandle\n repoRoot: string\n /** Force removal even if dirty (default true; the loser of a fanout has uncommitted changes). */\n force?: boolean\n /** Test seam. */\n runGit?: GitRunner\n}\n\n/** Pluggable git runner (sync) — replaceable in tests. */\nexport type GitRunner = (\n args: ReadonlyArray<string>,\n opts: { cwd: string },\n) => { stdout: string; stderr: string; exitCode: number }\n\nasync function runGitAsync(\n args: ReadonlyArray<string>,\n cwd: string,\n runner?: GitRunner,\n): Promise<{ stdout: string; stderr: string; exitCode: number }> {\n if (runner) return runner(args, { cwd })\n return new Promise((resolve, reject) => {\n const proc = spawn('git', args, { cwd, stdio: 'pipe' })\n let stdout = ''\n let stderr = ''\n proc.stdout?.on('data', (c) => {\n stdout += String(c)\n })\n proc.stderr?.on('data', (c) => {\n stderr += String(c)\n })\n proc.on('error', reject)\n proc.on('close', (code) => resolve({ stdout, stderr, exitCode: code ?? -1 }))\n })\n}\n\nfunction ensureGitOk(\n step: string,\n result: { stdout: string; stderr: string; exitCode: number },\n): void {\n if (result.exitCode !== 0) {\n throw gitFailure(step, result)\n }\n}\n\nfunction gitFailure(\n step: string,\n result: { stdout: string; stderr: string; exitCode: number },\n): Error {\n return new Error(\n `worktree: git ${step} failed (exit ${result.exitCode}): ${result.stderr.slice(0, 400)}`,\n )\n}\n\n/** Checkout a fresh git worktree for a delegation run on a new branch under `variantsDir`. @experimental */\nexport async function createWorktree(options: CreateWorktreeOptions): Promise<WorktreeHandle> {\n const variants = options.variantsDir ?? '.agent-worktrees'\n const baseRef = options.baseRef ?? 'HEAD'\n const branch = `delegate/${options.runId}`\n const path = `${options.repoRoot.replace(/\\/+$/, '')}/${variants}/${options.runId}`\n\n const headSha = await runGitAsync(['rev-parse', baseRef], options.repoRoot, options.runGit)\n ensureGitOk(`rev-parse ${baseRef}`, headSha)\n\n const add = await runGitAsync(\n ['worktree', 'add', '-b', branch, path, baseRef],\n options.repoRoot,\n options.runGit,\n )\n ensureGitOk(`worktree add ${path}`, add)\n\n return { path, baseSha: headSha.stdout.trim(), branch }\n}\n\n/** Stage worker changes and return the diff + shortstat, excluding declared input paths. @experimental */\nexport async function captureWorktreeDiff(options: DiffOptions): Promise<DiffResult> {\n const baseRef = options.baseRef ?? options.worktree.baseSha\n const pathspecs = worktreeDiffPathspecs(options.excludePaths ?? [])\n // Stage everything (incl. NEW/untracked files) before diffing: a plain `git diff <ref>`\n // omits untracked files, so a worker that delivers by CREATING a file (a fresh dossier,\n // a new module) would produce an empty diff and silently fail to compound. Staging into\n // the index and diffing `--cached` captures created files. The worktree is ephemeral, so\n // mutating its index has no observable side effect.\n const staged = await runGitAsync(\n ['add', '-A', ...(pathspecs.length > 0 ? ['--', '.', ...pathspecs] : [])],\n options.worktree.path,\n options.runGit,\n )\n ensureGitOk('add -A', staged)\n const patch = await runGitAsync(\n ['diff', '--cached', baseRef, ...(pathspecs.length > 0 ? ['--', '.', ...pathspecs] : [])],\n options.worktree.path,\n options.runGit,\n )\n ensureGitOk(`diff --cached ${baseRef}`, patch)\n\n // Stats: `git diff --shortstat` produces e.g. \" 3 files changed, 42 insertions(+), 10 deletions(-)\".\n const shortstat = await runGitAsync(\n [\n 'diff',\n '--cached',\n '--shortstat',\n baseRef,\n ...(pathspecs.length > 0 ? ['--', '.', ...pathspecs] : []),\n ],\n options.worktree.path,\n options.runGit,\n )\n ensureGitOk(`diff --cached --shortstat ${baseRef}`, shortstat)\n const stats = parseShortstat(shortstat.stdout)\n return { patch: patch.stdout, stats }\n}\n\nfunction worktreeDiffPathspecs(paths: ReadonlyArray<string>): string[] {\n const normalized = new Set<string>()\n for (const path of paths) {\n if (\n typeof path !== 'string' ||\n path.length === 0 ||\n path.includes('\\\\') ||\n hasControlCharacter(path) ||\n isAbsolute(path) ||\n win32.isAbsolute(path)\n ) {\n throw new Error(\n `worktree: excluded path must be a canonical repository-relative path: ${path}`,\n )\n }\n const segments = path.split('/')\n if (segments.some((segment) => segment.length === 0 || segment === '.' || segment === '..')) {\n throw new Error(\n `worktree: excluded path must be a canonical repository-relative path: ${path}`,\n )\n }\n normalized.add(path)\n }\n return [...normalized]\n .sort((left, right) => left.localeCompare(right))\n .map((path) => `:(top,exclude,literal)${path}`)\n}\n\nfunction hasControlCharacter(value: string): boolean {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index)\n if (code < 0x20 || code === 0x7f) return true\n }\n return false\n}\n\nfunction parseShortstat(text: string): DiffResult['stats'] {\n // `text` is the raw stdout of `git diff --shortstat`. Empty when no\n // changes. Parse defensively — the format is stable but we don't trust\n // it for type-safety.\n const out = { filesChanged: 0, insertions: 0, deletions: 0 }\n const filesMatch = text.match(/(\\d+)\\s+files?\\s+changed/)\n if (filesMatch?.[1]) out.filesChanged = Number(filesMatch[1])\n const insertMatch = text.match(/(\\d+)\\s+insertions?/)\n if (insertMatch?.[1]) out.insertions = Number(insertMatch[1])\n const deleteMatch = text.match(/(\\d+)\\s+deletions?/)\n if (deleteMatch?.[1]) out.deletions = Number(deleteMatch[1])\n return out\n}\n\n/**\n * Remove a git worktree and delete its branch. Already-removed paths are harmless; every other\n * Git failure rejects so callers cannot report a worktree as destroyed when cleanup failed.\n * @experimental\n */\nexport async function removeWorktree(options: RemoveWorktreeOptions): Promise<void> {\n const force = options.force ?? true\n const args = ['worktree', 'remove']\n if (force) args.push('--force')\n args.push(options.worktree.path)\n const removal = await runGitAsync(args, options.repoRoot, options.runGit)\n const removalError =\n removal.exitCode !== 0 && !/not a working tree/iu.test(removal.stderr)\n ? gitFailure(`worktree remove ${options.worktree.path}`, removal)\n : undefined\n\n // Worktree removal leaves its branch behind by design. Missing branches are repeat cleanup.\n const branchRemoval = await runGitAsync(\n ['branch', '-D', options.worktree.branch],\n options.repoRoot,\n options.runGit,\n )\n const branchError =\n branchRemoval.exitCode !== 0 && !/branch .+ not found/iu.test(branchRemoval.stderr)\n ? gitFailure(`branch -D ${options.worktree.branch}`, branchRemoval)\n : undefined\n\n if (removalError && branchError) {\n throw new AggregateError(\n [removalError, branchError],\n 'worktree: failed to remove worktree and branch',\n )\n }\n if (removalError) throw removalError\n if (branchError) throw branchError\n}\n","/**\n *\n * The ONE worktree-harness execution core. The physical act — run a supervisor-authored\n * `AgentProfile` on a local coding-harness CLI (claude / codex / opencode) against a fresh git\n * worktree off `repoRoot`, capture the diff, derive the test/typecheck PASS signals, then clean\n * up — lives here ONCE. Two executors adapt it to two ports without re-implementing it:\n * - `createWorktreeCliExecutor` — the `Scope`/`Supervisor` leaf `Executor`.\n * - `createInProcessExecutor` — the `runAgentRounds` `SandboxClient` / coder-delegate path.\n *\n * §1.5 by construction: prompt + model reach the direct invocation, while file-backed resources\n * are lowered by the shared profile materializer and applied before spawn. Resource instructions\n * join the direct prompt because reproducible Codex intentionally disables ambient project docs.\n *\n * Lifecycle: `createWorktree` → materialize profile inputs → `harnessInvocation` +\n * `runLocalHarness` → `captureWorktreeDiff` excluding those inputs (BEFORE checks, so the patch is\n * the harness's output, not polluted by files a test run writes) → configured checks → return the\n * result + caller-owned `cleanup`. A throw cleans up before propagating.\n *\n * @experimental\n */\n\nimport { spawn } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport {\n applyWorkspacePlan,\n type HarnessId,\n materializeProfile,\n type WorkspacePlan,\n type WorkspacePlanReceipt,\n} from '@tangle-network/agent-profile-materialize'\nimport {\n type CodexExecutionPolicy,\n type CodexTokenUsage,\n harnessInvocation,\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/** 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; `small`, `provider`, and `metadata` remain hints.\n * Resource failures are always fatal here, regardless of `resources.failOnError`.\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 /** 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\nfunction materializerHarness(harness: LocalHarness): HarnessId {\n return harness === 'claude' ? 'claude-code' : harness\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 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 assertSupportedWorktreeProfile(opts.profile, opts.harness)\n assertSafeProfileResourcePaths(opts.profile)\n const resourceInstructions = resolveResourceInstructions(opts.profile)\n const workspaceProfile = materializationOnlyProfile(opts.profile)\n const plan = materializeProfile(workspaceProfile, materializerHarness(opts.harness))\n if (plan.unsupported.length > 0) {\n throw new Error(\n `runWorktreeHarness: profile cannot be materialized for ${opts.harness}: ${plan.unsupported\n .map(({ dimension, reason }) => `${dimension}: ${reason}`)\n .join('; ')}`,\n )\n }\n assertSafeMaterializedPaths(plan)\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(opts.profile, resourceInstructions)\n const { command, args } = harnessInvocation(opts.harness, invocationProfile, opts.taskPrompt, {\n // This helper created the candidate worktree above; autonomous Claude\n // edits are permitted only inside that isolated checkout.\n dangerouslySkipPermissions: opts.harness === 'claude',\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] },\n env: { ...process.env, ...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\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 // `profile.harness` is only a preference and the explicit run option wins. Model small/provider/\n // metadata fields are routing or descriptive hints; this fixed one-shot path only selects the\n // concrete `model.default`. `resources.failOnError` never weakens this path's fail-closed policy.\n const unsupportedAxes = [\n hasEntries(profile.tools) ? 'tools' : null,\n hasEntries(profile.permissions) ? 'permissions' : null,\n profile.connections && profile.connections.length > 0 ? 'connections' : null,\n hasEntries(profile.confidential) ? 'confidential' : null,\n hasEntries(profile.modes) ? 'modes' : null,\n hasEntries(profile.extensions) ? 'extensions' : null,\n ].filter((axis): axis is string => axis !== null)\n if (profile.model?.reasoningEffort !== undefined && harness !== 'codex') {\n unsupportedAxes.push('model.reasoningEffort')\n }\n for (const [name, server] of Object.entries(profile.mcp ?? {})) {\n const path = `mcp[${JSON.stringify(name)}]`\n if (server.enabled === false && harness !== 'opencode') {\n unsupportedAxes.push(`${path}.enabled`)\n }\n if (hasEntries(server.headers) && harness === 'codex') {\n unsupportedAxes.push(`${path}.headers`)\n }\n if (server.cwd !== undefined && harness === 'opencode') {\n unsupportedAxes.push(`${path}.cwd`)\n }\n }\n if (harness === 'claude') {\n for (const [event, commands] of Object.entries(profile.hooks ?? {})) {\n for (const [index, command] of commands.entries()) {\n const path = `hooks[${JSON.stringify(event)}][${index}]`\n if (hasEntries(command.env)) unsupportedAxes.push(`${path}.env`)\n if (command.blocking !== undefined) unsupportedAxes.push(`${path}.blocking`)\n }\n }\n }\n for (const [name, subagent] of Object.entries(profile.subagents ?? {})) {\n const path = `subagents[${JSON.stringify(name)}]`\n if (hasEntries(subagent.permissions)) unsupportedAxes.push(`${path}.permissions`)\n if (subagent.maxSteps !== undefined) unsupportedAxes.push(`${path}.maxSteps`)\n if (hasEntries(subagent.tools) && harness !== 'claude') {\n unsupportedAxes.push(`${path}.tools`)\n }\n }\n if (unsupportedAxes.length > 0) {\n throw new Error(\n `runWorktreeHarness: profile requests unsupported worktree behavior: ${unsupportedAxes.join(', ')}`,\n )\n }\n}\n\nfunction hasEntries(value: object | undefined): boolean {\n return value !== undefined && Object.keys(value).length > 0\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 const instructionBytes =\n resourceInstructions === undefined ? null : Buffer.from(resourceInstructions, 'utf8')\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],\n resourceInstructions: instructionBytes\n ? {\n delivery: 'invocation-prompt',\n sha256: `sha256:${createHash('sha256').update(instructionBytes).digest('hex')}`,\n byteLength: instructionBytes.byteLength,\n }\n : { delivery: 'none', sha256: null, byteLength: 0 },\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}>\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 { 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\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\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: Record<string, unknown> = {\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 // Injected transport short-circuits the network — the offline benchmark seam (see RouterConfig.complete).\n const raw = cfg.complete\n ? await cfg.complete(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 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(cfg.model)\n ? estimateCost(usage.input, usage.output, cfg.model)\n : undefined\n return {\n content: msg?.content ?? null,\n toolCalls,\n ...(usage ? { usage } : {}),\n ...(costUsd !== undefined ? { costUsd } : {}),\n }\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 routerChatWithTools(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 */\nexport function routerBrain(cfg: RouterConfig, opts: { temperature?: number } = {}): ToolLoopChat {\n const temperature = opts.temperature ?? 0.4\n return (messages, tools) =>\n routerChatWithTools(cfg, messages, tools, { temperature, toolChoice: 'auto' })\n}\n","/**\n *\n * Runtime hook contracts. Hooks are execution-scoped observers, not part of an\n * `AgentProfile`: profiles stay portable agent recipes; hooks attach to the\n * loop or product harness that is running the profile.\n *\n * @experimental\n */\n\nexport type RuntimeHookPhase = 'before' | 'after' | 'error' | 'event'\n\nexport type RuntimeHookTarget =\n | 'agent.run'\n | 'agent.turn'\n | 'agent.tool_call'\n | 'agent.spawn'\n | 'agent.child'\n | 'agent.plan'\n | 'agent.decision'\n | (string & {})\n\nexport type RuntimeDecisionKind =\n | 'continue'\n | 'verify'\n | 'ask'\n | 'retry'\n | 'stop'\n | 'memory-write'\n | 'memory-read'\n | 'tool-select'\n | 'skill-select'\n | 'workflow-select'\n | 'surface-promote'\n | (string & {})\n\nexport interface RuntimeHookEvent<Payload = unknown> {\n id: string\n runId: string\n scenarioId?: string\n target: RuntimeHookTarget\n phase: RuntimeHookPhase\n timestamp: number\n stepIndex?: number\n parentId?: string\n payload?: Payload\n metadata?: Record<string, unknown>\n}\n\nexport interface RuntimeHookContext {\n signal?: AbortSignal\n}\n\nexport interface RuntimeDecisionEvidenceRef {\n source: string\n id: string\n detail?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface RuntimeDecisionPoint {\n id: string\n runId: string\n scenarioId?: string\n stepIndex: number\n kind: RuntimeDecisionKind\n candidateActions: string[]\n context?: string\n evidence: RuntimeDecisionEvidenceRef[]\n metadata?: Record<string, unknown>\n}\n\nexport interface RuntimeHookErrorContext {\n hook: 'onEvent' | 'onDecisionPoint'\n eventId?: string\n target?: RuntimeHookTarget\n phase?: RuntimeHookPhase\n decisionId?: string\n decisionKind?: RuntimeDecisionKind\n}\n\n/**\n * The observation seam attached to a running loop (never to the portable genome).\n * Implement the optional hooks to receive lifecycle events, semantic decision points,\n * and hook errors. Author with {@link defineRuntimeHooks} for inference, and attach N\n * observers at once with {@link composeRuntimeHooks} — there is ONE event stream, not a\n * callback-prop zoo.\n */\nexport interface RuntimeHooks {\n /**\n * General before/after/event hook. Use this for telemetry, memory capture,\n * policy wrapping, child lifecycle observers, or product-specific extension\n * points.\n */\n onEvent?: (event: RuntimeHookEvent, context: RuntimeHookContext) => void | Promise<void>\n /**\n * Semantic decision hook. Belief-state evaluation consumes this, but runtime\n * code should keep emitting ordinary lifecycle events as the base layer.\n */\n onDecisionPoint?: (\n point: RuntimeDecisionPoint,\n context: RuntimeHookContext,\n ) => void | Promise<void>\n onHookError?: (error: Error, context: RuntimeHookErrorContext) => void | Promise<void>\n}\n\n/** Identity helper that types a {@link RuntimeHooks} literal so the fields are inferred. */\nexport function defineRuntimeHooks(hooks: RuntimeHooks): RuntimeHooks {\n return hooks\n}\n\n/**\n * Merge several {@link RuntimeHooks} into one. Falsy entries are dropped (so you can\n * pass `flag && hooks`), and every observer's `onEvent`/`onDecisionPoint` fires for each\n * event. Use this to attach N observers to a loop instead of a second event bus.\n */\nexport function composeRuntimeHooks(\n ...entries: Array<RuntimeHooks | undefined | null | false>\n): RuntimeHooks {\n const hooks = entries.filter((entry): entry is RuntimeHooks => !!entry)\n return {\n onEvent: hooks.some((hook) => hook.onEvent)\n ? (event, context) => {\n const pending: Promise<unknown>[] = []\n for (const hook of hooks) {\n const result = hook.onEvent?.(event, context)\n if (isThenable(result)) pending.push(Promise.resolve(result))\n }\n if (pending.length > 0) return Promise.all(pending).then(() => undefined)\n return undefined\n }\n : undefined,\n onDecisionPoint: hooks.some((hook) => hook.onDecisionPoint)\n ? (point, context) => {\n const pending: Promise<unknown>[] = []\n for (const hook of hooks) {\n const result = hook.onDecisionPoint?.(point, context)\n if (isThenable(result)) pending.push(Promise.resolve(result))\n }\n if (pending.length > 0) return Promise.all(pending).then(() => undefined)\n return undefined\n }\n : undefined,\n onHookError: hooks.some((hook) => hook.onHookError)\n ? (error, context) => {\n const pending: Promise<unknown>[] = []\n for (const hook of hooks) {\n const result = hook.onHookError?.(error, context)\n if (isThenable(result)) pending.push(Promise.resolve(result))\n }\n if (pending.length > 0) return Promise.all(pending).then(() => undefined)\n return undefined\n }\n : undefined,\n }\n}\n\n/** Fire `hooks.onEvent`, swallowing sync throws and surfacing async failures to `onError`. */\nexport function notifyRuntimeHookEvent(\n hooks: RuntimeHooks | undefined,\n event: RuntimeHookEvent,\n context: RuntimeHookContext = {},\n): void {\n const onEvent = hooks?.onEvent\n if (!onEvent) return\n\n try {\n const result = onEvent(event, context)\n if (isThenable(result)) {\n void result.catch((error) => {\n notifyRuntimeHookError(hooks, toError(error), {\n hook: 'onEvent',\n eventId: event.id,\n target: event.target,\n phase: event.phase,\n })\n })\n }\n } catch (error) {\n notifyRuntimeHookError(hooks, toError(error), {\n hook: 'onEvent',\n eventId: event.id,\n target: event.target,\n phase: event.phase,\n })\n }\n}\n\n/** Fire `hooks.onDecisionPoint`, swallowing sync throws and surfacing async failures to `onError`. */\nexport function notifyRuntimeDecisionPoint(\n hooks: RuntimeHooks | undefined,\n point: RuntimeDecisionPoint,\n context: RuntimeHookContext = {},\n): void {\n const onDecisionPoint = hooks?.onDecisionPoint\n if (!onDecisionPoint) return\n\n try {\n const result = onDecisionPoint(point, context)\n if (isThenable(result)) {\n void result.catch((error) => {\n notifyRuntimeHookError(hooks, toError(error), {\n hook: 'onDecisionPoint',\n decisionId: point.id,\n decisionKind: point.kind,\n })\n })\n }\n } catch (error) {\n notifyRuntimeHookError(hooks, toError(error), {\n hook: 'onDecisionPoint',\n decisionId: point.id,\n decisionKind: point.kind,\n })\n }\n}\n\nfunction notifyRuntimeHookError(\n hooks: RuntimeHooks | undefined,\n error: Error,\n context: RuntimeHookErrorContext,\n): void {\n try {\n const result = hooks?.onHookError?.(error, context)\n if (isThenable(result)) void result.catch(() => undefined)\n } catch {\n // Hook errors must never become agent-loop errors.\n }\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'then' in value &&\n typeof (value as { then?: unknown }).then === 'function'\n )\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error))\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 /** 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 readonly usd: number\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 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/** 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 usd: number\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 usd: scope.usd,\n pendingMessages: executor?.pendingMessages ?? 0,\n recentActivity: executor?.recentActivity ?? [],\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 * 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 { contentAddress } from '../../durable/spawn-journal'\nimport { ValidationError } from '../../errors'\nimport { notifyRuntimeHookEvent, type RuntimeHooks } from '../../runtime-hooks'\nimport type { Iteration } from '../types'\nimport type { BudgetPool, ReservationTicket } from './budget'\nimport {\n DEFAULT_STALL_AFTER_MS,\n type ExecutorProgress,\n readWorkerProgress,\n type WorkerProgress,\n} from './progress'\nimport type { TraceSource } from './trace-source'\nimport type {\n Agent,\n AgentSpec,\n Budget,\n DefaultVerdict,\n Executor,\n ExecutorContext,\n ExecutorRegistry,\n ExecutorResult,\n Handle,\n NodeId,\n NodeSnapshot,\n NodeStatus,\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} 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'\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 shared conserved reservation pool (one per supervised run). */\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 /** 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 * 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/**\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 budget: Budget\n readonly label: string\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 /** 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 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) => void\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 /** 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?: { readonly spec: WaitSpec; readonly armedAt: number; readonly label: string }\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 /** 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 /** 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 SAME conserved pool 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 shares the parent's `pool`\n * (conserved budget across depth), `journal`/`blobs` (one record), and `executors` (a\n * nested child resolves to leaf-or-driver through the same open registry).\n */\nexport interface NestedScopeSeam {\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\nfunction makeNestedScopeSeam(args: ScopeArgs, childNodeId: NodeId): NestedScopeSeam {\n return {\n depth: args.depth,\n ...(args.maxDepth !== undefined ? { maxDepth: args.maxDepth } : {}),\n journalRoot: args.root,\n mount(nestedRoot: NodeId, signal: AbortSignal): Scope<unknown> {\n return createScope<unknown>({\n parentId: childNodeId,\n root: nestedRoot,\n pool: args.pool,\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 signal,\n ...(args.now ? { now: args.now } : {}),\n ...(args.hooks ? { hooks: args.hooks } : {}),\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 // 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 }\n | {\n readonly state: 'done'\n readonly id: NodeId\n readonly settled: Settled<Out> & { kind: 'done' }\n }\n | { readonly state: 'down'; readonly id: NodeId; readonly reason: string }\n | { readonly state: 'in-doubt'; readonly id: NodeId }\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 keyed.set(key, {\n state: 'done',\n id: prior.id,\n settled: prior.settled as Settled<Out> & { kind: 'done' },\n })\n } else if (prior.state === 'down' && prior.settled?.kind === 'down') {\n keyed.set(key, { state: 'down', id: prior.id, reason: prior.settled.reason })\n } else {\n keyed.set(key, { state: 'in-doubt', id: prior.id })\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 if (settled.kind === 'done') {\n keyed.set(key, { state: 'done', id: settled.handle.id, settled })\n } else {\n keyed.set(key, { state: 'down', id: settled.handle.id, reason: settled.reason })\n }\n }\n\n function spawn<C extends Out>(\n agent: Agent<unknown, C>,\n task: unknown,\n opts: SpawnOpts,\n ):\n | { ok: true; handle: Handle<C>; prior?: SpawnPrior<C> }\n | { ok: false; reason: SpawnRejection } {\n // Resolve the semantic key FIRST — a committed key spends nothing (no reservation, no\n // executor, no journal record: the prior settlement is already the durable record), and a\n // still-live duplicate is refused before any resource is touched.\n let prior: SpawnPrior<C> | undefined\n if (opts.key !== undefined) {\n const existing = keyed.get(opts.key)\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 // Resolve the leaf executor through the OPEN registry FIRST (no reservation to unwind\n // if the agent is misconfigured). An agent carries its executor mapping as the\n // `executorSpec` (an `AgentSpec`); resolution precedence (BYO → router/inline → harness\n // factory) lives in the registry, not in a call-site switch.\n const spec = (agent as unknown as { executorSpec?: unknown }).executorSpec\n if (!isAgentSpec(spec)) {\n throw new ValidationError(\n `scope.spawn: agent \"${agent.name}\" exposes no \\`executorSpec\\` (AgentSpec) to resolve a Executor`,\n )\n }\n const resolved = args.executors.resolve<C>(spec)\n if (!resolved.succeeded) throw new ValidationError(`scope.spawn: ${resolved.error}`)\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).\n const reservation = args.pool.reserve(opts.budget)\n if (!reservation.ok) return { ok: false, reason: reservation.reason }\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 try {\n const ordinal = spawnOrdinal++\n const id: NodeId = `${args.parentId}:s${ordinal}`\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(). Aborting mid-acquire cascades through the executor's\n // signal into its acquireSandbox find-by-name reap, so an acquiring node never leaks.\n const childAbort = new AbortController()\n const cascadeAbort = () => childAbort.abort()\n if (args.signal.aborted) childAbort.abort()\n else args.signal.addEventListener('abort', cascadeAbort, { once: true })\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 the\n // SAME conserved pool + shared journal/blobs/registry (the recursion seam). A leaf\n // executor ignores it; the parent's sandbox/router seams still pass through for leaves.\n // The mounted nested scope re-seeds the SAME bag for ITS children, so the recursion\n // composes — a driver child of a driver child mounts one level deeper still.\n const ctx: ExecutorContext = {\n signal: childAbort.signal,\n seams: { ...args.seams, [nestedScopeSeamKey]: makeNestedScopeSeam(args, id) },\n }\n const executor = resolved.value(spec, ctx) as Executor<C>\n\n const handle: Handle<C> = {\n id,\n label: opts.label,\n get status(): NodeStatus {\n return children.get(id)?.status ?? 'cancelled'\n },\n abort(reason?: string): void {\n childAbort.abort(reason)\n },\n }\n\n const live: LiveChild = {\n id,\n status: 'acquiring',\n runtime: executor.runtime,\n budget: opts.budget,\n label: opts.label,\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 startedAt: now(),\n lastActivityAt: now(),\n ...(executor.deliver ? { deliver: executor.deliver.bind(executor) } : {}),\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) keyed.set(opts.key, { state: 'live', id })\n\n void args.journal.appendEvent(args.root, {\n kind: 'spawned',\n id,\n parent: args.parentId,\n label: opts.label,\n ...(opts.key !== undefined ? { key: opts.key } : {}),\n budget: opts.budget,\n runtime: executor.runtime,\n seq: ordinal,\n at: new Date(now()).toISOString(),\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 runtime: executor.runtime,\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 childAbort,\n task,\n opts,\n args.pool,\n reservation.ticket,\n args.blobs,\n now,\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, ...(prior ? { prior } : {}) }\n } catch (err) {\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 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 child.deliver(msg)\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 (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 startedAt: armedAt,\n lastActivityAt: now(),\n wait: { spec: effectiveSpec, armedAt, label: opts.label },\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).\n if (!adopted) {\n void 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\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\n const settled = 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 .then(async (resolution): Promise<PreSeqSettled> => {\n live.executorDone = true\n live.lastActivityAt = now()\n if (resolution.kind === 'cancelled') {\n return { kind: 'down', reason: resolution.reason, infra: false, restartCount: 0 }\n }\n const outRef = contentAddress(resolution.outcome)\n await args.blobs.put(outRef, resolution.outcome)\n return { kind: 'done', out: resolution.outcome, outRef, spent: zeroSpend() }\n })\n .catch((err): PreSeqSettled => {\n live.executorDone = true\n return { kind: 'down', reason: errMessage(err), infra: true, restartCount: 0 }\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 usd: child.spent.usd,\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 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 args.pool.observe(spend)\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 }\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 return {\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 }\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 if (settlement.kind === 'down') {\n child.status = 'failed'\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 seq,\n at: new Date(now()).toISOString(),\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: new Date(now()).toISOString(),\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: now(),\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 seq,\n }\n }\n\n child.status = 'done'\n child.outRef = settlement.outRef\n child.spent = settlement.spent\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 seq,\n at: new Date(now()).toISOString(),\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: new Date(now()).toISOString(),\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: now(),\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 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 at = new Date(now()).toISOString()\n if (settlement.kind === 'down') {\n child.status = 'cancelled'\n await args.journal.appendEvent(args.root, {\n kind: 'woken',\n id: child.id,\n by: 'cancelled',\n seq,\n at,\n })\n return {\n kind: 'down',\n handle,\n reason: settlement.reason,\n infra: settlement.infra,\n restartCount: settlement.restartCount,\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: now(),\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 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): Promise<PreSeqSettled> {\n let reconciled = false\n const reconcileOnce = (spend: Spend) => {\n if (reconciled) return\n reconciled = true\n // A budgetExempt executor reports zero spend by contract; the reconcile refunds its\n // whole reservation, keeping it out of the conserved Σk by construction.\n pool.reconcile(ticket, clampSpend(spend, opts.budget))\n }\n try {\n live.status = 'running'\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(ran, (running) => {\n live.spent = running\n live.lastActivityAt = now()\n })\n live.spent = spend\n artifact = executor.resultArtifact() as ExecutorResult<C>\n reconcileOnce(spend)\n } else {\n const terminal = await ran\n live.spent = terminal.spent\n artifact = terminal\n reconcileOnce(terminal.spent)\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\n if (childAbort.signal.aborted) {\n await teardownSafe(executor, opts.shutdown ?? 'brutalKill')\n return downRecord('aborted before settle', true, 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 teardownSafe(executor, opts.shutdown ?? 'infinity')\n return {\n kind: 'done',\n out: artifact.out,\n outRef,\n ...(artifact.verdict ? { verdict: artifact.verdict } : {}),\n spent: live.spent,\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 // Reconcile the (likely partial) spend so the reservation is refunded even on a throw.\n reconcileOnce(live.spent)\n await teardownSafe(executor, 'brutalKill')\n const aborted = childAbort.signal.aborted || isAbortError(err)\n // A crashed driver child still re-homes the partial inference it durably metered.\n return downRecord(errMessage(err), aborted || isInfraError(err), executor.metered?.())\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 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 spent: c.spent,\n ...(c.outRef ? { outRef: c.outRef } : {}),\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 abort(): void {\n // A settled child is terminal; abort is a no-op (its executor already tore down).\n },\n }\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): Promise<Spend> {\n const tokens = { input: 0, output: 0 }\n let usd = 0\n let iterations = 0\n for await (const ev of stream) {\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 } else {\n iterations += 1\n }\n onProgress?.({ iterations, tokens: { ...tokens }, usd, ms: 0 })\n }\n return { iterations, tokens, usd, ms: 0 }\n}\n\n/** Clamp a child's reported spend to its reservation so the pool's fail-loud over-spend\n * guard never trips on a benign overshoot from an external usage report; the difference\n * refunds to the pool as if the child stopped at its ceiling. */\nfunction clampSpend(spend: Spend, budget: Budget): Spend {\n const totalTokens = spend.tokens.input + spend.tokens.output\n const tokensOk = totalTokens <= budget.maxTokens\n const itersOk = spend.iterations <= budget.maxIterations\n const usdOk = budget.maxUsd === undefined || spend.usd <= budget.maxUsd\n if (tokensOk && itersOk && usdOk) return spend\n const ratio = !tokensOk && totalTokens > 0 ? budget.maxTokens / totalTokens : 1\n return {\n iterations: Math.min(spend.iterations, budget.maxIterations),\n tokens:\n ratio < 1\n ? {\n input: Math.floor(spend.tokens.input * ratio),\n output: Math.floor(spend.tokens.output * ratio),\n }\n : spend.tokens,\n usd: budget.maxUsd === undefined ? spend.usd : Math.min(spend.usd, budget.maxUsd),\n ...(spend.usdKnown === false ? { usdKnown: false } : {}),\n ms: spend.ms,\n }\n}\n\nasync function teardownSafe<C>(\n executor: Executor<C>,\n grace: number | 'brutalKill' | 'infinity',\n): Promise<void> {\n try {\n await executor.teardown(grace)\n } catch {\n // Teardown failure is observable through the node staying live; swallow so it never\n // masks the settlement itself. The supervisor's join barrier reaps on its own grace.\n }\n}\n\nfunction downRecord(reason: string, infra: boolean, metered?: Spend): PreSeqSettled {\n return { kind: 'down', reason, infra, restartCount: 0, ...(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\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 the SAME\n * conserved pool + shared journal/blobs + the same open registry, one `depth` deeper, 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 nested scope reserves from the SAME `BudgetPool` the root owns\n * (the scope mounts it over `args.pool`), so `Σk` is conserved ACROSS depth by\n * construction — a deep tree cannot overspend the root ceiling (reserve-on-spawn fails\n * closed at any depth).\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 the conserved\n * spend summed off its nested tree's settled events, so the parent's pool reconcile +\n * the supervisor's `spentTotal` see the whole sub-tree's spend rolled up — settlements\n * bubble to the root.\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 { ValidationError } from '../../errors'\nimport { type NestedScopeSeam, nestedScopeSeamKey } from './scope'\nimport type {\n Agent,\n AgentSpec,\n DefaultVerdict,\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 const driverRuntime = 'driver' as const\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 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 name: string,\n driver: Agent<unknown, Out>,\n journal: SpawnJournal,\n): Agent<unknown, Out> {\n const spec: DriverSpec = {\n profile: { name, metadata: { role: driverRole } } as AgentSpec['profile'],\n harness: null,\n driver: driver as Agent<unknown, unknown>,\n journal,\n }\n return {\n name,\n executorSpec: spec,\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 const role = (spec.profile.metadata as { role?: unknown } | undefined)?.role\n if (role !== driverRole) 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 shared pool/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 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\n return {\n runtime: driverRuntime,\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 = nestedTreeKey(seam, journal)\n await journal.beginTree(nestedRoot, new Date(0).toISOString())\n\n const nestedScope: Scope<unknown> = seam.mount(nestedRoot, signal)\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 driver.act(task, nestedScope)\n\n // Read the nested tree's events ONCE. Two roll-ups, kept separate so the conserved invariant\n // is not double-charged:\n // - `spent` = settled child WORK → reconciled against THIS driver's reservation (as before).\n // - `metered` = the nested subtree's driver INFERENCE → re-homed by the parent scope as a\n // `metered` event, NOT reconciled (already pool-debited live via `observe`).\n const events = await loadTreeEvents(journal, nestedRoot)\n const settled = events.filter(isSettled)\n meteredSpend = nonZeroOrUndef(sumMetered(events))\n // Completion-oracle propagation: a driver \"delivered\" iff at least one of its DIRECT\n // children settled `valid` (the child its keep-best finalize returns). Deriving the\n // driver child's verdict this way composes delivery UP the recursion — a sub-driver is\n // `valid` only when it itself selected a delivered child — so a node never settles\n // \"done = delivered\" on a sub-tree that delivered nothing (Foreman's 0/18 lesson).\n const verdict = deriveDeliveryVerdict(settled)\n artifact = {\n outRef: `${driverRuntime}:${nestedRoot}`,\n out,\n spent: sumSpend(settled),\n ...(verdict ? { verdict } : {}),\n }\n return artifact\n } catch (err) {\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 meteredSpend = await safeSumMetered(journal, nestedRoot)\n throw err\n }\n },\n metered(): Spend | undefined {\n return meteredSpend\n },\n teardown(): Promise<{ destroyed: boolean }> {\n // The nested scope's live children are torn down by the driver's own `act` discipline\n // (it drains to settlement) and by the parent's abort cascade through `signal`; there\n // is no separate box/process to reap here.\n return Promise.resolve({ 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}\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 const role = (spec.profile.metadata as { role?: unknown } | undefined)?.role\n if (role === driverRole && !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\n/** Mint a unique nested-tree key under the parent's journal root. Uses the parent's\n * `journalRoot` + a per-journal monotonic ordinal so two sibling driver trees never\n * collide their keys (each driver child mints exactly one nested tree). */\nfunction nestedTreeKey(seam: NestedScopeSeam, journal: SpawnJournal): string {\n return `${seam.journalRoot}/d${nextNestOrdinal(journal)}`\n}\n\n/** Per-journal monotonic nest counter — keyed on the journal instance so a single run's\n * nested-tree keys are unique without a shared module global. */\nconst nestCounters = new WeakMap<SpawnJournal, { n: number }>()\nfunction nextNestOrdinal(journal: SpawnJournal): number {\n let c = nestCounters.get(journal)\n if (!c) {\n c = { n: 0 }\n nestCounters.set(journal, c)\n }\n return c.n++\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 total.usd += ev.spent.usd\n if (ev.spent.usdKnown === false) total.usdKnown = false\n total.ms += ev.spent.ms\n }\n return total\n}\n\n/** Sum the nested tree's `metered` events — the sub-tree's whole driver INFERENCE (this driver's\n * own turns + any sub-driver inference already re-homed into this tree). Re-homed up to the parent\n * as one `metered` event; never reconciled (already pool-debited live via `observe`). */\nfunction sumMetered(events: ReadonlyArray<SpawnEvent>): Spend {\n const total: Spend = { iterations: 0, tokens: { 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 total.usd += ev.spend.usd\n if (ev.spend.usdKnown === false) total.usdKnown = false\n total.ms += ev.spend.ms\n }\n return total\n}\n\nfunction isNonZeroSpend(s: Spend): boolean {\n return s.iterations > 0 || s.tokens.input > 0 || s.tokens.output > 0 || s.usd > 0 || s.ms > 0\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 safeSumMetered(\n journal: SpawnJournal,\n nestedRoot: string,\n): Promise<Spend | undefined> {\n try {\n return nonZeroOrUndef(sumMetered(await loadTreeEvents(journal, nestedRoot)))\n } catch {\n return undefined\n }\n}\n\n/** Derive the driver child's delivery verdict from its DIRECT children's settlements:\n * `valid` iff any direct child settled `done` AND `valid` (the keep-best finalize's pick);\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): 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 return {\n valid: anyValid,\n score: anyValid ? (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 *\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 (invariant, always)\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.\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}\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 * `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 usdLeft: number\n usdCapped: boolean\n deadlineMs: number\n reservedTokens: number\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: 'budget-exhausted' }\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 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 } else {\n iterations += 1\n }\n }\n return { iterations, tokens, usd, ms: 0 }\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 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 } else {\n iterations += 1\n }\n }\n return { iterations, tokens, usd, ms: 0 }\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 is fixed at construction (`now() + budget.deadlineMs`) so the\n * readout's `deadlineMs` is a stable wall-clock instant, not a shrinking remainder.\n */\nexport function createBudgetPool(root: Budget, now: () => number = Date.now): BudgetPool {\n // free + reserved + committed ≡ root totals, per channel, always.\n let freeTokens = root.maxTokens\n let reservedTokens = 0\n let committedTokens = 0\n\n const usdCapped = root.maxUsd !== undefined\n let freeUsd = root.maxUsd ?? 0\n let reservedUsd = 0\n let committedUsd = 0\n\n let freeIterations = root.maxIterations\n let reservedIterations = 0\n let committedIterations = 0\n\n const 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: 'budget-exhausted' } {\n const wantTokens = b.maxTokens\n const wantUsd = b.maxUsd ?? 0\n const wantIterations = b.maxIterations\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 if (wantUsd > 0 && (!usdCapped || wantUsd > freeUsd)) {\n return { ok: false, reason: 'budget-exhausted' }\n }\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: { id, reserved: { tokens: wantTokens, usd: wantUsd, iterations: wantIterations } },\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 open.delete(ticket.id)\n\n const { tokens: rTokens, usd: rUsd, iterations: rIterations } = ticket.reserved\n if (usdCapped && spent.usdKnown === false) {\n throw new Error(\n `budget pool: ticket ${ticket.id} reported unknown dollar cost under a dollar-capped budget`,\n )\n }\n\n // Clamp actual spend to the reservation: a child must never commit more than it\n // reserved (that would overdraw the conserved pool). Over-spend is a fail-loud bug.\n const spentTokens = totalTokens(spent.tokens)\n if (spentTokens > rTokens) {\n throw new Error(\n `budget pool: ticket ${ticket.id} spent ${spentTokens} tokens > reserved ${rTokens}`,\n )\n }\n if (spent.iterations > rIterations) {\n throw new Error(\n `budget pool: ticket ${ticket.id} spent ${spent.iterations} iterations > reserved ${rIterations}`,\n )\n }\n // USD is conserved ONLY when the root declared a ceiling. `maxUsd` is optional: when no\n // root ceiling exists, usd is an OBSERVED quantity (committed for accounting), never a\n // budgeted constraint — so an unset ceiling must not behave as a hard $0 limit that\n // fail-closes a real priced spend. The over-spend clamp applies only to a capped pool.\n if (usdCapped && spent.usd > rUsd) {\n throw new Error(`budget pool: ticket ${ticket.id} spent $${spent.usd} > reserved $${rUsd}`)\n }\n\n // Release the whole reservation, then commit actual spend; the difference is the\n // refund that flows back to `free`.\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 && rUsd > 0) {\n reservedUsd -= rUsd\n committedUsd += spent.usd\n freeUsd += rUsd - spent.usd\n } else {\n // Uncapped (or a zero-ceiling child under a capped root): record the observed spend\n // without touching the reservation channel — usd is accounted, not conserved here.\n committedUsd += spent.usd\n }\n }\n\n function observe(spend: Spend): void {\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 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 usdLeft: usdCapped ? freeUsd : 0,\n usdCapped,\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 return {\n reserve,\n reconcile,\n spendFrom: foldUsage,\n readout,\n observe,\n assertNoOpenTickets,\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 {\n contentAddress,\n materializeTreeView,\n pendingWaits,\n replaySpawnTree,\n} from '../../durable/spawn-journal'\nimport { RuntimeRunStateError } from '../../errors'\nimport { type BudgetPool, createBudgetPool } from './budget'\nimport { runTree } from './finalizer'\nimport { createScope } from './scope'\nimport type {\n Agent,\n ResumedKeyState,\n RootHandle,\n RootSignal,\n Scope,\n Settled,\n SpawnEvent,\n SpawnJournal,\n Spend,\n SupervisedResult,\n Supervisor,\n SupervisorOpts,\n TreeView,\n} from './types'\nimport type { PendingWait } from './wait'\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 const s = byId.get(ev.id)\n keys.set(\n ev.key,\n s === undefined\n ? { id: ev.id, label: ev.label, state: 'in-doubt' }\n : {\n id: ev.id,\n label: ev.label,\n state: s.kind === 'done' ? 'completed' : 'down',\n settled: s,\n },\n )\n }\n return keys\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/** A no-winner reason the supervisor can prove from its OWN lifecycle state — pinned to\n * the frozen `SupervisedResult` reason union. A driver rejecting for a domain reason\n * (not budget/abort) is classed `all-children-down`, the only typed bucket for \"the tree\n * produced no usable result\". */\ntype NoWinnerReason = (SupervisedResult<unknown> & { kind: 'no-winner' })['reason']\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 const now = opts.now ?? Date.now\n const pool = createBudgetPool(opts.budget, now)\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 prior = opts.resume === true ? await opts.journal.loadTree(opts.runId) : undefined\n const resuming = prior !== undefined && prior.length > 0\n let resumeFrom: ResumeFrom | undefined\n if (resuming) {\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 // 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, new Date(now()).toISOString())\n await opts.journal.appendEvent(opts.runId, {\n kind: 'spawned',\n id: opts.runId,\n label: 'root',\n budget: opts.budget,\n runtime: 'inline',\n seq: 0,\n at: new Date(now()).toISOString(),\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) => {\n if (controller.signal.aborted) return\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 }\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\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 signal: controller.signal,\n now,\n hooks: opts.hooks,\n ...(opts.probes ? { probes: opts.probes } : {}),\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 (attached) {\n attached.bind({ scope: openScope, cascadeAbort, signal: pushRootSignal(cascadeAbort) })\n }\n\n let actOutcome: { ok: true; out: Out } | { ok: false; error: unknown }\n try {\n const out = await root.act(task, scope)\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 // 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 await drainLiveChildren(openScope, controller)\n if (opts.signal) opts.signal.removeEventListener('abort', onCallerAbort)\n if (attached) attached.unbind()\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 if (actOutcome.ok) {\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 pool.assertNoOpenTickets()\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, in precedence order:\n // a tripped breaker outranks any abort (it is the most specific cause) outranks\n // budget-exhaustion outranks the residual \"the tree produced nothing usable\" bucket.\n // A no-winner is TYPED — never a best-effort coercion of a partial child (M2).\n return noWinner()\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(): Promise<SupervisedResult<Out>> {\n const { childWork, driverInference } = await spentFromJournal(journal, opts.runId)\n return {\n kind: 'no-winner',\n reason: classifyNoWinner(controller, pool, opts, breaker),\n tree,\n downCount: breaker.downCount(),\n spentTotal: addSpend(childWork, driverInference),\n }\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}\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 RootControl {\n bind(binding: RunBinding): void\n unbind(): void\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>(): RootHandle<Out> {\n let binding: RunBinding | undefined\n const handle: RootHandle<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 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 bind(b: RunBinding): void {\n binding = b\n },\n unbind(): void {\n binding = undefined\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) return\n // Cascade the abort into every live child's executor before draining.\n if (!controller.signal.aborted) controller.abort()\n await Promise.allSettled([drainCursor(scope)])\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\nfunction classifyNoWinner(\n controller: AbortController,\n pool: BudgetPool,\n opts: SupervisorOpts,\n breaker: IntensityBreaker,\n): NoWinnerReason {\n // A tripped breaker is the most specific cause (children kept dying), so it outranks\n // the generic abort it raised. Then a caller/handle abort. Then the pool. The residual\n // bucket is \"ran to completion under budget but produced nothing usable\".\n if (breaker.tripped()) return 'all-children-down'\n if (controller.signal.aborted) return 'aborted'\n if (poolExhausted(pool, opts)) return 'budget-exhausted'\n return 'all-children-down'\n}\n\nfunction poolExhausted(pool: BudgetPool, opts: SupervisorOpts): boolean {\n const r = pool.readout()\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 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 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 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 s.iterations > 0 || s.tokens.input > 0 || s.tokens.output > 0 || s.usd > 0 || s.ms > 0\n}\n"],"mappings":";;;;;;;;;;;;;;AAmBA,IAAa,gCAAb,cAAmD,MAAM;CAI5C;CACA;CAJX,OAAgB;CAEhB,YACE,QACA,YACA,OACA;EACA,MACE,yDAAyD,OAAO,eAAe,KAAK,UAAU,UAAU,KACxG,EAAE,MAAM,CACV;EAPS,KAAA,SAAA;EACA,KAAA,aAAA;EAOT,KAAK,OAAO;CACd;AACF;AAEA,MAAM,iCAAiC;AACvC,MAAM,uBAAuB,OAAO;AACpC,MAAM,iBAAiB;AACvB,MAAa,gCAAgC;AAE7C,SAAgB,oCAAoC,MAYlB;CAChC,MAAM,UAAU,UACd,sBAAsB,OAAO,KAAK,WAAW,KAAK,eAAe;CACnE,MAAM,gBAAgB,qBAAqB,OAAO,KAAK,MAAM,CAAC;CAC9D,MAAM,gBAAgB,qBAAqB,OAAO,KAAK,MAAM,CAAC;CAC9D,MA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