@tangle-network/agent-runtime 0.101.1 → 0.102.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +5 -3
- package/dist/agent.js.map +1 -1
- package/dist/analyst-loop.d.ts +1 -1
- package/dist/candidate-execution/index.d.ts +13 -2
- package/dist/candidate-execution/index.js +8 -3
- package/dist/chunk-377GOJHJ.js +578 -0
- package/dist/chunk-377GOJHJ.js.map +1 -0
- package/dist/{chunk-DI677IPX.js → chunk-3DW5DEKQ.js} +3 -3
- package/dist/{chunk-KVJQV342.js → chunk-6MR4IJRW.js} +25 -1777
- package/dist/chunk-6MR4IJRW.js.map +1 -0
- package/dist/{chunk-RJPQLUDA.js → chunk-7FJJUC73.js} +336 -43
- package/dist/chunk-7FJJUC73.js.map +1 -0
- package/dist/{chunk-TA4RBJLE.js → chunk-CI7WS6S2.js} +5 -5
- package/dist/{chunk-U4PRAATQ.js → chunk-CK76OZPM.js} +3 -3
- package/dist/{chunk-KSBUSEUA.js → chunk-KJ2Q4T7F.js} +2 -2
- package/dist/{chunk-MAONWP4R.js → chunk-KPHTCHQ4.js} +611 -1419
- package/dist/chunk-KPHTCHQ4.js.map +1 -0
- package/dist/{chunk-BXZ7GPL4.js → chunk-KSM6GFHP.js} +2 -2
- package/dist/chunk-L5DST3QC.js +351 -0
- package/dist/chunk-L5DST3QC.js.map +1 -0
- package/dist/{chunk-HGSHPVJ6.js → chunk-LJLG734E.js} +200 -441
- package/dist/chunk-LJLG734E.js.map +1 -0
- package/dist/chunk-ROILMKDL.js +1338 -0
- package/dist/chunk-ROILMKDL.js.map +1 -0
- package/dist/{chunk-N2CEE5Q3.js → chunk-RTB3TC73.js} +3 -3
- package/dist/chunk-SQ3ZJH3Y.js +3082 -0
- package/dist/chunk-SQ3ZJH3Y.js.map +1 -0
- package/dist/chunk-UPWGXKXB.js +254 -0
- package/dist/chunk-UPWGXKXB.js.map +1 -0
- package/dist/{completion-gate-C80jiRfN.d.ts → completion-gate-C6dhVN-N.d.ts} +2 -2
- package/dist/{coordination-BFE3Den7.d.ts → coordination-D9l_YmwW.d.ts} +6 -6
- package/dist/environment-provider.d.ts +2 -2
- package/dist/{improve-g75IE2Cx.d.ts → improve-B40dRu0X.d.ts} +47 -19
- package/dist/index.d.ts +331 -23
- package/dist/index.js +544 -136
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +63 -62
- package/dist/intelligence.js +62 -471
- package/dist/intelligence.js.map +1 -1
- package/dist/knowledge.d.ts +8 -8
- package/dist/knowledge.js +9 -7
- package/dist/{local-harness-ZqCx51u7.d.ts → local-harness-CtK9dSny.d.ts} +14 -2
- package/dist/{loop-runner-bin-Cn1N2rRo.d.ts → loop-runner-bin-PnWslIw4.d.ts} +2 -2
- package/dist/loop-runner-bin.d.ts +6 -6
- package/dist/loop-runner-bin.js +6 -4
- package/dist/loops.d.ts +231 -460
- package/dist/loops.js +58 -37
- package/dist/mcp/bin.js +2 -2
- package/dist/mcp/index.d.ts +184 -12
- package/dist/mcp/index.js +31 -9
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/memory-bin.d.ts +1 -0
- package/dist/mcp/memory-bin.js +22 -0
- package/dist/mcp/memory-bin.js.map +1 -0
- package/dist/profiles.d.ts +3 -3
- package/dist/structural-rollout-D7xik9XR.d.ts +446 -0
- package/dist/{substrate-DO2GHNg2.d.ts → substrate-Dyiqmd3o.d.ts} +1 -1
- package/dist/{supervise-BLPI50-w.d.ts → supervise-BQdNAXtK.d.ts} +4 -4
- package/dist/testing.js +255 -211
- package/dist/testing.js.map +1 -1
- package/dist/{types-B3vAW0Oq.d.ts → types-CLat4bT9.d.ts} +1 -1
- package/dist/{types-CmnA2iL3.d.ts → types-D870JlH0.d.ts} +2 -2
- package/dist/{worktree-fanout-DCA3G4bO.d.ts → worktree-fanout-DsIR4d6w.d.ts} +234 -234
- package/package.json +6 -5
- package/dist/chunk-HGSHPVJ6.js.map +0 -1
- package/dist/chunk-IKGCKPDX.js +0 -1115
- package/dist/chunk-IKGCKPDX.js.map +0 -1
- package/dist/chunk-KVJQV342.js.map +0 -1
- package/dist/chunk-MAONWP4R.js.map +0 -1
- package/dist/chunk-RJPQLUDA.js.map +0 -1
- package/dist/{chunk-DI677IPX.js.map → chunk-3DW5DEKQ.js.map} +0 -0
- package/dist/{chunk-TA4RBJLE.js.map → chunk-CI7WS6S2.js.map} +0 -0
- package/dist/{chunk-U4PRAATQ.js.map → chunk-CK76OZPM.js.map} +0 -0
- package/dist/{chunk-KSBUSEUA.js.map → chunk-KJ2Q4T7F.js.map} +0 -0
- package/dist/{chunk-BXZ7GPL4.js.map → chunk-KSM6GFHP.js.map} +0 -0
- package/dist/{chunk-N2CEE5Q3.js.map → chunk-RTB3TC73.js.map} +0 -0
- package/dist/{sanitize-BTSsdBXw.d.ts → sanitize-DEbPNtyI.d.ts} +58 -58
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/mcp/codex-diagnostics.ts","../src/mcp/local-harness.ts","../src/mcp/worktree.ts","../src/runtime/supervise/model-policy.ts","../src/runtime/router-client.ts","../src/runtime/tool-loop.ts","../src/runtime-hooks.ts","../src/runtime/supervise/scope.ts","../src/runtime/supervise/budget.ts","../src/runtime/supervise/supervisor.ts","../src/mcp/worktree-harness.ts","../src/runtime/supervise/driver-executor.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 * `assertModelAllowed` — a fail-loud guard that restricts a run to a chosen subset of\n * models. The two front doors (`supervise()` / `improve()`) call it once per configured\n * model at resolve time, so a run that names a model outside the allowed set throws before\n * any compute is spent — never silently swapped or silently allowed.\n */\nimport { ConfigError } from '../../errors'\n\n/**\n * Throw a `ConfigError` when `allowed` is set, `model` is defined, and `model` is not a\n * member of `allowed`. No-op when `allowed` is unset (the unrestricted default) or when\n * `model` is undefined (nothing was configured to check).\n */\nexport function assertModelAllowed(\n model: string | undefined,\n allowed: readonly string[] | undefined,\n): void {\n if (!allowed || model === undefined) return\n if (!allowed.includes(model)) {\n throw new ConfigError(\n `model ${JSON.stringify(model)} is not in the allowed set ${JSON.stringify([...allowed])}`,\n )\n }\n}\n","/**\n * The one router chat client: direct OpenAI-compatible completions through the\n * Tangle router — the cheapest dial, no sandbox. Three layers: `routerChatWithUsage`\n * (chat-only), `routerChatWithTools` (one completion with function tools), and\n * `routerToolLoop` (the off-box agentic loop over tool-calling). Shared by the\n * built-in executors and the bench/lab harnesses.\n *\n * Reports REAL token usage so the backend-integrity guard sees a real backend.\n * Returns `undefined` usage when the provider omitted it — never a fabricated 0\n * (a phantom 0 reads as a free call downstream, which the gate would act on).\n */\n\nimport { 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 * 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\ntype Msg = 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<Msg>,\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: Msg[]): 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<Msg>) => 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<Msg>) => 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<Msg>): 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: Msg[],\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: Msg[]\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<Msg>\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: Msg[] = [...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 *\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 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 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 Scope,\n Settled,\n SpawnJournal,\n SpawnOpts,\n Spend,\n TreeView,\n UsageEvent,\n} from './types'\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 /** 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 `runLoop`/`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\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 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}\n\n/** A child's terminal settlement before the cursor stamps the monotonic `seq`. */\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 let spawnOrdinal = 0\n let cursorSeq = 0\n let meterSeq = 0\n const now = args.now ?? Date.now\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> }\n | { ok: false; reason: 'budget-exhausted' | 'depth-exceeded' } {\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 spent: zeroSpend(),\n settled: undefined as unknown as Promise<PreSeqSettled>,\n delivered: false,\n executorDone: false,\n ...(executor.deliver ? { deliver: executor.deliver.bind(executor) } : {}),\n }\n children.set(id, live)\n\n void args.journal.appendEvent(args.root, {\n kind: 'spawned',\n id,\n parent: args.parentId,\n label: opts.label,\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 )\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 } 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 return finalizeSettlement<Out>(chosen, settlement, seq, args, now)\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 return finalizeSettlement<Out>(pick, settlement, seq, args, now)\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 return true\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 return {\n spawn,\n next,\n nextResolved,\n send,\n signal: args.signal,\n meter,\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 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/**\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): 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.\n const spend = await foldStream(ran)\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 }\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\nasync function foldStream(stream: AsyncIterable<UsageEvent>): 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 }\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 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 *\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 { contentAddress } from '../../durable/spawn-journal'\nimport { RuntimeRunStateError } from '../../errors'\nimport { type BudgetPool, createBudgetPool } from './budget'\nimport { createScope } from './scope'\nimport type {\n Agent,\n RootHandle,\n RootSignal,\n Scope,\n SpawnEvent,\n SpawnJournal,\n Spend,\n SupervisedResult,\n Supervisor,\n SupervisorOpts,\n TreeView,\n} from './types'\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\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 await opts.journal.beginTree(opts.runId, new Date(now()).toISOString())\n\n // Journal the root as its own `spawned` node (parent-less, the spawn-ordinal-0 marker), so a\n // journal-based reader — `trajectoryReport`, `replaySpawnTree`, `materializeTreeView` — can\n // reconstruct the WHOLE realized tree from a real run, not only hand-built journals. The root\n // is never `scope.spawn`ed (the supervisor runs `act` directly), so without this the root node\n // is absent and `trajectoryReport` fails its `nodes.has(root)` invariant. The uniqueness guard\n // skips `spawned` events (only the cursor namespace must be unique), so sharing ordinal 0 with\n // the first child's spawn is not a collision; replay ignores `spawned` events for settlement\n // reconstruction, so the replayed `Settled[]` is unchanged.\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 // 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 })\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 const tree = scope.view\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 const hasLive = scope.view.inFlight > 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 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 // `settled` = spawned-child work (reconciled); `metered` = driver inference (re-homed up the\n // tree, so this single root-tree pass already includes every nested driver's inference).\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","/**\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 `runLoop` `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 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\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, 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 *\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"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,YAAY;AACrB,SAAS,gCAAgC;AAiBlC,IAAM,gCAAN,cAA4C,MAAM;AAAA,EAGvD,YACW,QACA,YACT,OACA;AACA;AAAA,MACE,yDAAyD,MAAM,gBAAgB,KAAK,UAAU,UAAU,CAAC;AAAA,MACzG,EAAE,MAAM;AAAA,IACV;AAPS;AACA;AAOT,SAAK,OAAO;AAAA,EACd;AAAA,EATW;AAAA,EACA;AAAA,EAJF,OAAO;AAalB;AAEA,IAAM,iCAAiC;AACvC,IAAM,uBAAuB,OAAO;AACpC,IAAM,iBAAiB;AAChB,IAAM,gCAAgC;AAEtC,SAAS,oCAAoC,MAYlB;AAChC,QAAM,SAAS,CAAC,UACd,sBAAsB,OAAO,KAAK,WAAW,KAAK,eAAe;AACnE,QAAM,gBAAgB,qBAAqB,OAAO,KAAK,MAAM,CAAC;AAC9D,QAAM,gBAAgB,qBAAqB,OAAO,KAAK,MAAM,CAAC;AAC9D,QAAM,aAA8C;AAAA,IAClD,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,SAAS,UAAU,CAAC,CAAC;AAAA,EAC7E,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAOA,SAAS,sBACP,SAC4B;AAC5B,MAAI,WAAW;AACf,MAAI,WAAW;AACf,MAAI;AACJ,MAAI;AACJ,aAAW,MAAM,SAAS;AACxB,eAAW;AACX,QAAI,GAAG,WAAW,OAAQ;AAC1B,UAAM,QAAQ,GAAG,SAAS;AAC1B,QAAI,UAAU,WAAc,kBAAkB,UAAa,QAAQ,gBAAgB;AACjF,sBAAgB;AAAA,IAClB;AACA,QAAI,GAAG,SAAS,UAAU,MAAM;AAC9B,iBAAW;AACX,UAAI,UAAU,WAAc,mBAAmB,UAAa,QAAQ,iBAAiB;AACnF,yBAAiB;AAAA,MACnB;AAAA,IACF;AAAA,EACF;AACA,MAAI,CAAC,SAAU,QAAO;AACtB,SAAO;AAAA,IACL,OAAO;AAAA,IACP,OAAO,WAAY,kBAAkB,IAAM,iBAAiB;AAAA,EAC9D;AACF;AAEA,SAAS,oBAAoB,KAAuC;AAClE,QAAM,OAAO,IAAI,MAAM,kBAAkB;AACzC,MAAI,CAAC,QAAQ,OAAO,KAAK,UAAU,YAAY;AAC7C,UAAM,IAAI;AAAA,MACR,0CAA0C,kBAAkB;AAAA,IAC9D;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,QAAQ,OAAkD;AACjE,SACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA4B,QAAQ,cAC5C,OAAQ,MAA6B,SAAS;AAElD;","names":["constants","open","model","resolve","constants","access","open","graceDeadline","event","spawn","isAbsolute","resolve","open","spawn","totalTokens","open","spawn","createHash","createHash","resolve","spawn"]}
|