@tangle-network/agent-runtime 0.91.0 → 0.92.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +4 -2
  2. package/dist/agent.d.ts +3 -3
  3. package/dist/agent.js +88 -9
  4. package/dist/agent.js.map +1 -1
  5. package/dist/{mcp-serve-verifier-XsX8rkB9.d.ts → agentic-generator-B8oeE2Yv.d.ts} +6 -33
  6. package/dist/analyst-loop.d.ts +1 -1
  7. package/dist/candidate-execution/index.d.ts +104 -0
  8. package/dist/candidate-execution/index.js +34 -0
  9. package/dist/candidate-execution/index.js.map +1 -0
  10. package/dist/chunk-3BE7KTMU.js +1229 -0
  11. package/dist/chunk-3BE7KTMU.js.map +1 -0
  12. package/dist/chunk-3D2RHC4K.js +73 -0
  13. package/dist/chunk-3D2RHC4K.js.map +1 -0
  14. package/dist/chunk-3MDZX7YU.js +125 -0
  15. package/dist/chunk-3MDZX7YU.js.map +1 -0
  16. package/dist/{chunk-NC66AM3S.js → chunk-6O5USWVH.js} +32 -1413
  17. package/dist/chunk-6O5USWVH.js.map +1 -0
  18. package/dist/chunk-6O73TRHW.js +142 -0
  19. package/dist/chunk-6O73TRHW.js.map +1 -0
  20. package/dist/{chunk-JRS3YSRZ.js → chunk-7VJJJ2T2.js} +2 -2
  21. package/dist/chunk-A62TP7SK.js +4784 -0
  22. package/dist/chunk-A62TP7SK.js.map +1 -0
  23. package/dist/chunk-APVPRF4Y.js +2166 -0
  24. package/dist/chunk-APVPRF4Y.js.map +1 -0
  25. package/dist/{chunk-DWWII6N2.js → chunk-AUEIDTR3.js} +2 -2
  26. package/dist/{chunk-FF77IBQM.js → chunk-FRBHUNQ7.js} +2 -141
  27. package/dist/chunk-FRBHUNQ7.js.map +1 -0
  28. package/dist/{chunk-7ON74BQO.js → chunk-GDAQUFG6.js} +2 -2
  29. package/dist/{chunk-AD7JW4QG.js → chunk-I7WVPJBZ.js} +23 -1231
  30. package/dist/chunk-I7WVPJBZ.js.map +1 -0
  31. package/dist/{chunk-IOUUITQA.js → chunk-IGGZGKJD.js} +3 -3
  32. package/dist/chunk-PH65PR4F.js +860 -0
  33. package/dist/chunk-PH65PR4F.js.map +1 -0
  34. package/dist/chunk-RSWM2ZKM.js +659 -0
  35. package/dist/chunk-RSWM2ZKM.js.map +1 -0
  36. package/dist/{chunk-BZF3KQ6G.js → chunk-VSWBYWFK.js} +4 -122
  37. package/dist/chunk-VSWBYWFK.js.map +1 -0
  38. package/dist/{completion-gate-DkAnUmpb.d.ts → completion-gate-BLaiN0-X.d.ts} +1 -1
  39. package/dist/{coordination-rRj5hjJK.d.ts → coordination-DxJ83oZA.d.ts} +12 -5
  40. package/dist/environment-provider.d.ts +2 -2
  41. package/dist/environment-provider.js +2 -1
  42. package/dist/improve-CUVCq7xg.d.ts +152 -0
  43. package/dist/{improvement-adapter-CDR8QNVM.d.ts → improvement-adapter-BieWeK5J.d.ts} +16 -0
  44. package/dist/index.d.ts +27 -1092
  45. package/dist/index.js +108 -6491
  46. package/dist/index.js.map +1 -1
  47. package/dist/intelligence.d.ts +160 -13
  48. package/dist/intelligence.js +535 -59
  49. package/dist/intelligence.js.map +1 -1
  50. package/dist/knowledge.d.ts +6 -6
  51. package/dist/knowledge.js +6 -4
  52. package/dist/lifecycle.d.ts +2 -1
  53. package/dist/lifecycle.js +5 -3
  54. package/dist/lifecycle.js.map +1 -1
  55. package/dist/{loop-runner-bin-DTbZVGfM.d.ts → loop-runner-bin-kKUNGLyV.d.ts} +2 -2
  56. package/dist/loop-runner-bin.d.ts +5 -5
  57. package/dist/loop-runner-bin.js +8 -5
  58. package/dist/loops.d.ts +16 -16
  59. package/dist/loops.js +47 -41
  60. package/dist/mcp/bin.js +6 -4
  61. package/dist/mcp/bin.js.map +1 -1
  62. package/dist/mcp/index.d.ts +8 -8
  63. package/dist/mcp/index.js +9 -6
  64. package/dist/mcp/index.js.map +1 -1
  65. package/dist/mcp-serve-verifier-Bg4C3p5S.d.ts +34 -0
  66. package/dist/{openai-tools-C4ZfUD4L.d.ts → openai-tools-E3woykz9.d.ts} +1 -1
  67. package/dist/prepare-Z08a4heC.d.ts +713 -0
  68. package/dist/profiles.d.ts +1 -1
  69. package/dist/{router-client-DJImUDlm.d.ts → sanitize-C9go6tXj.d.ts} +113 -1
  70. package/dist/{structural-rollout-MwlpgQ-6.d.ts → structural-rollout-DHGDbhvR.d.ts} +3 -3
  71. package/dist/{supervise-DPmYPk0j.d.ts → supervise-T2pazU3G.d.ts} +4 -4
  72. package/dist/{types-SyuwunY_.d.ts → types-B00NtbCs.d.ts} +1 -1
  73. package/dist/{types-eMNgWgFi.d.ts → types-DAdIm4AC.d.ts} +1 -1
  74. package/dist/{worktree-fanout-BDFQIO-Y.d.ts → worktree-fanout-BUb2Ag02.d.ts} +3 -3
  75. package/package.json +26 -35
  76. package/skills/build-with-agent-runtime/SKILL.md +1 -1
  77. package/dist/chunk-AD7JW4QG.js.map +0 -1
  78. package/dist/chunk-BZF3KQ6G.js.map +0 -1
  79. package/dist/chunk-FF77IBQM.js.map +0 -1
  80. package/dist/chunk-IVGYLCFH.js +0 -381
  81. package/dist/chunk-IVGYLCFH.js.map +0 -1
  82. package/dist/chunk-NC66AM3S.js.map +0 -1
  83. /package/dist/{chunk-JRS3YSRZ.js.map → chunk-7VJJJ2T2.js.map} +0 -0
  84. /package/dist/{chunk-DWWII6N2.js.map → chunk-AUEIDTR3.js.map} +0 -0
  85. /package/dist/{chunk-7ON74BQO.js.map → chunk-GDAQUFG6.js.map} +0 -0
  86. /package/dist/{chunk-IOUUITQA.js.map → chunk-IGGZGKJD.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../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/sanitize.ts","../src/otel-export.ts","../src/runtime/supervise/driver-executor.ts"],"sourcesContent":["/**\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 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\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 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 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 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 * Sanitization for runtime telemetry. The rule: nothing user-controlled leaks\n * unless the caller opts in with a `RuntimeTelemetryOptions` flag. This is the\n * envelope that ends up in `agent_run.metadata.runtimeEvents` on every\n * consumer, so the default must be safe.\n *\n * @stable\n */\n\nimport type {\n ControlEvalResult,\n ControlRunResult,\n ControlStep,\n DataAcquisitionPlan,\n KnowledgeReadinessReport,\n KnowledgeRequirement,\n UserQuestion,\n} from '@tangle-network/agent-eval'\n\nimport type {\n AgentRuntimeEvent,\n AgentTaskSpec,\n AgentTaskStatus,\n RuntimeSession,\n RuntimeStreamEvent,\n} from './types'\n\n/** @stable */\nexport interface RuntimeTelemetryOptions {\n /**\n * Include raw task inputs. Off by default because task inputs often contain\n * customer facts, credentials, source text, or internal IDs.\n */\n includeInputs?: boolean\n /** Include requirement descriptions. Secret requirements are always redacted. */\n includeRequirementDescriptions?: boolean\n /** Include evidence IDs. Off by default; counts are safer for shared reports. */\n includeEvidenceIds?: boolean\n /** Include user answers from question preflight. Off by default. */\n includeUserAnswers?: boolean\n /** Include action payloads and action results for control steps. Off by default. */\n includeControlPayloads?: boolean\n /** Include task metadata. Off by default because metadata may carry IDs or policy internals. */\n includeMetadata?: boolean\n /** Include eval detail/evidence strings. Off by default because validators may echo private input. */\n includeEvalDetails?: boolean\n}\n\n/** @stable */\nexport interface SanitizedKnowledgeRequirement {\n id: string\n description?: string\n requiredFor: string[]\n category: KnowledgeRequirement['category']\n acquisitionMode: KnowledgeRequirement['acquisitionMode']\n importance: KnowledgeRequirement['importance']\n freshness: KnowledgeRequirement['freshness']\n sensitivity: KnowledgeRequirement['sensitivity']\n confidenceNeeded: number\n currentConfidence: number\n evidenceCount: number\n evidenceIds?: string[]\n fallbackPolicy: KnowledgeRequirement['fallbackPolicy']\n}\n\n/** @stable */\nexport interface SanitizedKnowledgeReadinessReport {\n taskId: string\n readinessScore: number\n recommendedAction: KnowledgeReadinessReport['recommendedAction']\n severity: KnowledgeReadinessReport['severity']\n reason: string\n blockingMissingRequirements: SanitizedKnowledgeRequirement[]\n nonBlockingGaps: SanitizedKnowledgeRequirement[]\n evidenceCount: number\n evidenceIds?: string[]\n missingRequirementIds: string[]\n}\n\n/** Strip PII and large blobs from a `KnowledgeReadinessReport` for safe telemetry emission. @stable */\nexport function sanitizeKnowledgeReadinessReport(\n report: KnowledgeReadinessReport,\n options: RuntimeTelemetryOptions = {},\n): SanitizedKnowledgeReadinessReport {\n return {\n taskId: report.taskId,\n readinessScore: report.readinessScore,\n recommendedAction: report.recommendedAction,\n severity: report.severity,\n reason: report.reason,\n blockingMissingRequirements: report.blockingMissingRequirements.map((requirement) =>\n sanitizeKnowledgeRequirement(requirement, options),\n ),\n nonBlockingGaps: report.nonBlockingGaps.map((requirement) =>\n sanitizeKnowledgeRequirement(requirement, options),\n ),\n evidenceCount: report.bundle.evidenceIds.length,\n evidenceIds: options.includeEvidenceIds ? report.bundle.evidenceIds : undefined,\n missingRequirementIds: report.bundle.missing.map((requirement) => requirement.id),\n }\n}\n\n/** Reduce an `AgentRuntimeEvent` to a PII-safe, serializable plain object for telemetry. @stable */\nexport function sanitizeAgentRuntimeEvent<\n TState,\n TAction,\n TActionResult,\n TEval extends ControlEvalResult,\n>(\n event: AgentRuntimeEvent<TState, TAction, TActionResult, TEval>,\n options: RuntimeTelemetryOptions = {},\n): Record<string, unknown> {\n const base = { type: event.type, task: sanitizeTask(event.task, options) }\n if (\n event.type === 'readiness_start' ||\n event.type === 'task_start' ||\n event.type === 'control_start'\n ) {\n return event.type === 'control_start'\n ? { ...base, knowledge: sanitizeKnowledgeReadinessReport(event.knowledge, options) }\n : base\n }\n if (event.type === 'readiness_end') {\n return { ...base, knowledge: sanitizeKnowledgeReadinessReport(event.knowledge, options) }\n }\n if (event.type === 'questions_start') {\n return {\n ...base,\n questions: event.questions.map((question) => sanitizeQuestion(question, options)),\n }\n }\n if (event.type === 'questions_end') {\n return {\n ...base,\n questions: event.questions.map((question) => sanitizeQuestion(question, options)),\n userAnswers: options.includeUserAnswers ? event.userAnswers : redactRecord(event.userAnswers),\n }\n }\n if (event.type === 'acquisition_start') {\n return { ...base, acquisitionPlans: event.acquisitionPlans.map(sanitizeAcquisitionPlan) }\n }\n if (event.type === 'acquisition_end') {\n return {\n ...base,\n acquisitionPlans: event.acquisitionPlans.map(sanitizeAcquisitionPlan),\n acquiredEvidenceCount: event.acquiredEvidenceIds.length,\n acquiredEvidenceIds: options.includeEvidenceIds ? event.acquiredEvidenceIds : undefined,\n }\n }\n if (event.type === 'control_step') {\n return { ...base, step: sanitizeControlStep(event.step, options) }\n }\n if (event.type === 'control_end') {\n return { ...base, control: sanitizeControlRun(event.control, options) }\n }\n return { ...base, status: event.status, reason: event.reason }\n}\n\n/** Reduce a `RuntimeStreamEvent` to a PII-safe, serializable plain object for telemetry. @stable */\nexport function sanitizeRuntimeStreamEvent(\n event: RuntimeStreamEvent,\n options: RuntimeTelemetryOptions = {},\n): Record<string, unknown> {\n const withTask = 'task' in event && event.task ? { task: sanitizeTask(event.task, options) } : {}\n const withSession =\n 'session' in event && event.session\n ? { session: sanitizeRuntimeSession(event.session, options) }\n : {}\n\n if (event.type === 'readiness_end') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n decision: event.decision,\n knowledge: sanitizeKnowledgeReadinessReport(event.knowledge, options),\n }\n }\n if (event.type === 'questions_start') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n questions: event.questions.map((question) => sanitizeQuestion(question, options)),\n }\n }\n if (event.type === 'questions_end') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n questions: event.questions.map((question) => sanitizeQuestion(question, options)),\n userAnswers: options.includeUserAnswers ? event.userAnswers : redactRecord(event.userAnswers),\n }\n }\n if (event.type === 'acquisition_start') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n acquisitionPlans: event.acquisitionPlans.map(sanitizeAcquisitionPlan),\n }\n }\n if (event.type === 'acquisition_end') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n acquisitionPlans: event.acquisitionPlans.map(sanitizeAcquisitionPlan),\n acquiredEvidenceCount: event.acquiredEvidenceIds.length,\n acquiredEvidenceIds: options.includeEvidenceIds ? event.acquiredEvidenceIds : undefined,\n }\n }\n if (event.type === 'tool_call') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n toolName: event.toolName,\n toolCallId: event.toolCallId,\n args: options.includeControlPayloads ? event.args : undefined,\n }\n }\n if (event.type === 'tool_result') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n toolName: event.toolName,\n toolCallId: event.toolCallId,\n result: options.includeControlPayloads ? event.result : undefined,\n }\n }\n if (event.type === 'llm_call') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n model: event.model,\n tokensIn: event.tokensIn,\n tokensOut: event.tokensOut,\n costUsd: event.costUsd,\n latencyMs: event.latencyMs,\n finishReason: event.finishReason,\n }\n }\n if (event.type === 'artifact') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n artifactId: event.artifactId,\n name: event.name,\n mimeType: event.mimeType,\n uri: options.includeEvidenceIds ? event.uri : undefined,\n content: options.includeControlPayloads ? event.content : undefined,\n metadata: options.includeMetadata ? event.metadata : undefined,\n }\n }\n if (event.type === 'proposal_created') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n proposalId: event.proposalId,\n title: options.includeControlPayloads ? event.title : undefined,\n content: options.includeControlPayloads ? event.content : undefined,\n status: event.status,\n }\n }\n if (event.type === 'final') {\n // Surface error `kind` + `status` always — operators need failure\n // classification regardless of telemetry payload opt-in. `body` follows\n // the same gating as raw payloads (`includeControlPayloads`) because it\n // can echo user-visible text from the upstream provider's error page.\n const sanitizedError =\n event.error !== undefined\n ? {\n kind: event.error.kind,\n message: event.error.message,\n status: event.error.status,\n body: options.includeControlPayloads ? event.error.body : undefined,\n }\n : undefined\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n status: event.status,\n reason: event.reason,\n text: options.includeControlPayloads ? event.text : undefined,\n metadata: options.includeMetadata ? event.metadata : undefined,\n ...(sanitizedError !== undefined ? { error: sanitizedError } : {}),\n }\n }\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: 'timestamp' in event ? event.timestamp : undefined,\n ...pickPublicStreamFields(event),\n }\n}\n\nfunction sanitizeTask(\n task: AgentTaskSpec,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n return {\n id: task.id,\n intent: task.intent,\n domain: task.domain,\n inputs: options.includeInputs ? task.inputs : task.inputs ? '[redacted]' : undefined,\n requiredKnowledge: task.requiredKnowledge?.map((requirement) =>\n sanitizeKnowledgeRequirement(requirement, options),\n ),\n metadata: options.includeMetadata ? task.metadata : task.metadata ? '[redacted]' : undefined,\n }\n}\n\nfunction sanitizeRuntimeSession(\n session: RuntimeSession,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n return {\n id: session.id,\n backend: session.backend,\n status: session.status,\n hasResumeToken: Boolean(session.resumeToken),\n createdAt: session.createdAt,\n updatedAt: session.updatedAt,\n metadata: options.includeMetadata\n ? session.metadata\n : session.metadata\n ? '[redacted]'\n : undefined,\n }\n}\n\nfunction sanitizeKnowledgeRequirement(\n requirement: KnowledgeRequirement,\n options: RuntimeTelemetryOptions,\n): SanitizedKnowledgeRequirement {\n const includeDescription =\n options.includeRequirementDescriptions && requirement.sensitivity !== 'secret'\n return {\n id: requirement.id,\n description: includeDescription ? requirement.description : undefined,\n requiredFor: requirement.requiredFor,\n category: requirement.category,\n acquisitionMode: requirement.acquisitionMode,\n importance: requirement.importance,\n freshness: requirement.freshness,\n sensitivity: requirement.sensitivity,\n confidenceNeeded: requirement.confidenceNeeded,\n currentConfidence: requirement.currentConfidence,\n evidenceCount: requirement.evidenceIds.length,\n evidenceIds: options.includeEvidenceIds ? requirement.evidenceIds : undefined,\n fallbackPolicy: requirement.fallbackPolicy,\n }\n}\n\nfunction sanitizeQuestion(\n question: UserQuestion,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n return {\n id: question.id,\n question:\n options.includeRequirementDescriptions && question.answerType !== 'credential'\n ? question.question\n : undefined,\n reason: options.includeRequirementDescriptions ? question.reason : undefined,\n requirementId: question.requirementId,\n importance: question.importance,\n answerType: question.answerType,\n impactIfUnknown: options.includeRequirementDescriptions ? question.impactIfUnknown : undefined,\n optionCount: question.options?.length ?? 0,\n }\n}\n\nfunction sanitizeAcquisitionPlan(plan: DataAcquisitionPlan): Record<string, unknown> {\n return {\n id: plan.id,\n requirementIds: plan.requirementIds,\n mode: plan.mode,\n priority: plan.priority,\n expectedEvidenceCount: plan.expectedEvidenceIds?.length ?? 0,\n questionCount: plan.questions?.length ?? 0,\n }\n}\n\nfunction sanitizeControlStep<TState, TAction, TActionResult, TEval extends ControlEvalResult>(\n step: ControlStep<TState, TAction, TActionResult, TEval>,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n const actionOutcome = step.actionOutcome\n return {\n index: step.index,\n decisionType: step.decision.type,\n reason: step.decision.reason,\n action:\n options.includeControlPayloads && step.decision.type === 'continue'\n ? step.decision.action\n : undefined,\n result: options.includeControlPayloads && actionOutcome?.ok ? actionOutcome.result : undefined,\n actionOk: actionOutcome?.ok,\n actionError: actionOutcome?.ok === false ? actionOutcome.error : undefined,\n durationMs: actionOutcome?.durationMs,\n evalsBefore: summarizeEvals(step.evalsBefore, options),\n evalsAfter: summarizeEvals(step.evalsAfter, options),\n startedAt: step.startedAt,\n endedAt: step.endedAt,\n }\n}\n\nfunction sanitizeControlRun<TState, TAction, TActionResult, TEval extends ControlEvalResult>(\n control: ControlRunResult<TState, TAction, TActionResult, TEval>,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n return {\n pass: control.pass,\n completed: control.completed,\n reason: control.reason,\n score: control.score,\n stepCount: control.steps.length,\n wallMs: control.wallMs,\n spentCostUsd: control.spentCostUsd,\n failureClass: control.failureClass,\n stoppedBy: control.stoppedBy,\n runId: control.runId,\n runtimeErrorCount: control.runtimeErrors.length,\n finalEvals: summarizeEvals(control.finalEvals, options),\n }\n}\n\nfunction summarizeEvals(\n evals: ControlEvalResult[],\n options: RuntimeTelemetryOptions,\n): Array<Record<string, unknown>> {\n return evals.map((evalResult) => ({\n id: evalResult.id,\n passed: evalResult.passed,\n score: evalResult.score,\n severity: evalResult.severity,\n objective: evalResult.objective,\n detail: options.includeEvalDetails ? evalResult.detail : undefined,\n evidence: options.includeEvalDetails ? evalResult.evidence : undefined,\n }))\n}\n\nfunction redactRecord(record: Record<string, string>): Record<string, string> {\n return Object.fromEntries(Object.keys(record).map((key) => [key, '[redacted]']))\n}\n\nfunction pickPublicStreamFields(event: RuntimeStreamEvent): Record<string, unknown> {\n if (event.type === 'session_created' || event.type === 'session_resumed') return {}\n if (event.type === 'backend_start' || event.type === 'backend_end')\n return { backend: event.backend }\n if (event.type === 'backend_error') {\n // `error.body` is the truncated upstream response — it can carry\n // user-visible text (a `free_tier_limit` envelope is safe, but an HTML\n // error page from a misconfigured proxy may echo the request URL with\n // query string). Redact body by default; surface `kind` + `status` so\n // operators can still classify the failure without raw text.\n const sanitizedError =\n event.error !== undefined\n ? {\n kind: event.error.kind,\n status: event.error.status,\n }\n : undefined\n return {\n backend: event.backend,\n message: event.message,\n recoverable: event.recoverable,\n ...(sanitizedError !== undefined ? { error: sanitizedError } : {}),\n }\n }\n if (event.type === 'task_end') return { status: event.status, reason: event.reason }\n if (event.type === 'text_delta' || event.type === 'reasoning_delta') return { text: event.text }\n return {}\n}\n\n/** @stable */\nexport interface RuntimeEventCollector<\n TState = unknown,\n TAction = unknown,\n TActionResult = unknown,\n TEval extends ControlEvalResult = ControlEvalResult,\n> {\n onEvent: (event: AgentRuntimeEvent<TState, TAction, TActionResult, TEval>) => void\n events: Array<Record<string, unknown>>\n}\n\n/** @stable */\nexport type RuntimeStreamEventSink = (event: RuntimeStreamEvent) => void\n\n/** @stable */\nexport interface RuntimeStreamEventSummary {\n /** Total count of sanitized events collected. */\n eventCount: number\n /** Count of events per `type`. Useful for log-line summaries. */\n eventCountsByType: Record<string, number>\n /** First session id observed in a `session_created` / `session_resumed` event, if any. */\n firstSessionId?: string\n /** Last `final` event's status, if a final event was observed. */\n finalStatus?: AgentTaskStatus\n /** Last `final` event's reason, if a final event was observed. */\n finalReason?: string\n /** Concatenated `text_delta.text` across the stream, even when payloads are redacted. */\n finalText: string\n}\n\n/** @stable */\nexport interface RuntimeStreamEventCollector {\n onEvent: RuntimeStreamEventSink\n events: Array<Record<string, unknown>>\n /** Snapshot of a small streaming-flavored summary derived from collected events. */\n summary(): RuntimeStreamEventSummary\n}\n\n/** Build an in-memory collector that sanitizes and accumulates `AgentRuntimeEvent`s for inspection. @stable */\nexport function createRuntimeEventCollector<\n TState = unknown,\n TAction = unknown,\n TActionResult = unknown,\n TEval extends ControlEvalResult = ControlEvalResult,\n>(\n options: RuntimeTelemetryOptions = {},\n): RuntimeEventCollector<TState, TAction, TActionResult, TEval> {\n const events: Array<Record<string, unknown>> = []\n return {\n events,\n onEvent: (event) => {\n events.push(sanitizeAgentRuntimeEvent(event, options))\n },\n }\n}\n\n/**\n *\n * Streaming-event counterpart of `createRuntimeEventCollector`. Pass each\n * event yielded by `runAgentTaskStream` through `onEvent` and read the\n * sanitized copies off `events`; the same `RuntimeTelemetryOptions` redaction\n * flags apply. Kept distinct from `createRuntimeEventCollector` because the\n * stream and non-stream event shapes overlap on `type` literals — dispatching\n * on `type` alone would misroute events.\n *\n * @stable\n */\nexport function createRuntimeStreamEventCollector(\n options: RuntimeTelemetryOptions = {},\n): RuntimeStreamEventCollector {\n const events: Array<Record<string, unknown>> = []\n const eventCountsByType: Record<string, number> = {}\n let firstSessionId: string | undefined\n let finalStatus: AgentTaskStatus | undefined\n let finalReason: string | undefined\n let finalText = ''\n return {\n events,\n onEvent: (event) => {\n events.push(sanitizeRuntimeStreamEvent(event, options))\n eventCountsByType[event.type] = (eventCountsByType[event.type] ?? 0) + 1\n if (event.type === 'text_delta') finalText += event.text\n if (\n !firstSessionId &&\n (event.type === 'session_created' || event.type === 'session_resumed')\n ) {\n firstSessionId = event.session.id\n }\n if (event.type === 'final') {\n finalStatus = event.status\n finalReason = event.reason\n }\n },\n summary() {\n return {\n eventCount: events.length,\n eventCountsByType: { ...eventCountsByType },\n firstSessionId,\n finalStatus,\n finalReason,\n finalText,\n }\n },\n }\n}\n","/**\n * OTEL span exporter — streams LoopTraceEvents to an OTLP/HTTP collector.\n *\n * Reads OTEL_EXPORTER_OTLP_ENDPOINT + OTEL_EXPORTER_OTLP_HEADERS from env\n * when no explicit config is given. Keeps the runtime dep-free from\n * @opentelemetry/sdk-trace-base — minimal OTLP/JSON serializer.\n *\n * The exporter accepts both raw OtelSpan objects and LoopTraceEvents\n * (which get converted to OTLP spans automatically).\n */\n\nimport { type RuntimeTelemetryOptions, sanitizeRuntimeStreamEvent } from './sanitize'\nimport type { RuntimeStreamEvent } from './types'\n\nexport interface OtelExportConfig {\n /** OTLP endpoint. Reads OTEL_EXPORTER_OTLP_ENDPOINT env by default. */\n endpoint?: string\n /** OTLP headers. Reads OTEL_EXPORTER_OTLP_HEADERS env by default. */\n headers?: Record<string, string>\n /** Batch size before flush. Default 64. */\n batchSize?: number\n /** Flush interval ms. Default 5000. */\n flushIntervalMs?: number\n /** Resource attributes stamped on every export. */\n resourceAttributes?: Record<string, string | number | boolean>\n /** Service name. Default 'agent-runtime'. */\n serviceName?: string\n}\n\nexport interface OtelExporter {\n /** Export a span. */\n exportSpan(span: OtelSpan): void\n /** Force flush pending spans. */\n flush(): Promise<void>\n /** Shutdown cleanly. */\n shutdown(): Promise<void>\n}\n\nexport interface OtelSpan {\n traceId: string\n spanId: string\n parentSpanId?: string\n name: string\n kind?: number\n startTimeUnixNano: string\n endTimeUnixNano: string\n attributes?: OtelAttribute[]\n status?: { code: number; message?: string }\n}\n\nexport interface OtelAttribute {\n key: string\n value: { stringValue?: string; intValue?: string; doubleValue?: number; boolValue?: boolean }\n}\n\ninterface OtlpResourceSpans {\n resource: { attributes: OtelAttribute[] }\n scopeSpans: Array<{ scope: { name: string; version: string }; spans: OtelSpan[] }>\n}\n\ninterface OtlpExport {\n resourceSpans: OtlpResourceSpans[]\n}\n\nconst SCOPE = { name: '@tangle-network/agent-runtime', version: '0.83.0' }\n\n/**\n * Current (non-deprecated) OpenTelemetry GenAI semantic-convention keys.\n * Registry: https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/\n * NB: `gen_ai.system` / `gen_ai.usage.prompt_tokens` / `completion_tokens` are\n * DEPRECATED — do not emit them. We use `provider.name` + `input/output_tokens`.\n */\nconst GEN_AI = {\n operation: 'gen_ai.operation.name',\n agentName: 'gen_ai.agent.name',\n conversationId: 'gen_ai.conversation.id',\n inputTokens: 'gen_ai.usage.input_tokens',\n outputTokens: 'gen_ai.usage.output_tokens',\n} as const\n\n/**\n * Create an OTEL exporter. Returns undefined when no endpoint is configured.\n */\nexport function createOtelExporter(config?: OtelExportConfig): OtelExporter | undefined {\n const resolvedEndpoint =\n config?.endpoint ??\n (typeof process !== 'undefined' ? process.env.OTEL_EXPORTER_OTLP_ENDPOINT : undefined)\n if (!resolvedEndpoint) return undefined\n const endpoint: string = resolvedEndpoint\n\n const headers = config?.headers ?? parseHeadersFromEnv()\n const batchSize = config?.batchSize ?? 64\n const flushIntervalMs = config?.flushIntervalMs ?? 5000\n const serviceName = config?.serviceName ?? 'agent-runtime'\n const resourceAttrs = config?.resourceAttributes ?? {}\n\n const pending: OtelSpan[] = []\n let timer: ReturnType<typeof setInterval> | undefined\n let stopped = false\n\n const exporter: OtelExporter = {\n exportSpan(span: OtelSpan): void {\n if (stopped) return\n pending.push(span)\n if (pending.length >= batchSize) {\n void doFlush()\n }\n },\n\n async flush(): Promise<void> {\n await doFlush()\n },\n\n async shutdown(): Promise<void> {\n stopped = true\n if (timer !== undefined) {\n clearInterval(timer)\n timer = undefined\n }\n await doFlush()\n },\n }\n\n timer = setInterval(() => {\n if (pending.length > 0) void doFlush()\n }, flushIntervalMs)\n if (typeof timer === 'object' && 'unref' in timer) {\n ;(timer as NodeJS.Timeout).unref()\n }\n\n async function doFlush(): Promise<void> {\n if (pending.length === 0) return\n const batch = pending.splice(0)\n const body: OtlpExport = {\n resourceSpans: [\n {\n resource: {\n attributes: toAttributes({\n 'service.name': serviceName,\n ...resourceAttrs,\n }),\n },\n scopeSpans: [{ scope: SCOPE, spans: batch }],\n },\n ],\n }\n const url = `${endpoint.replace(/\\/+$/, '')}/v1/traces`\n try {\n await fetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...headers },\n body: JSON.stringify(body),\n })\n } catch {\n // Best-effort — telemetry export must not crash the runtime.\n }\n }\n\n return exporter\n}\n\n/**\n * Convert a LoopTraceEvent into an OtelSpan for export.\n */\nexport function loopEventToOtelSpan(\n event: {\n kind: string\n runId: string\n timestamp: number\n payload: object\n },\n traceId: string,\n parentSpanId?: string,\n): OtelSpan {\n const spanId = generateSpanId()\n const attrs: Record<string, string | number | boolean> = {\n 'loop.event_kind': event.kind,\n 'loop.run_id': event.runId,\n }\n for (const [k, v] of Object.entries(event.payload)) {\n if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {\n attrs[`loop.${k}`] = v\n }\n }\n const ts = msToNs(event.timestamp)\n return {\n traceId: padTraceId(traceId),\n spanId,\n parentSpanId: parentSpanId ? padSpanId(parentSpanId) : undefined,\n name: event.kind,\n kind: 1,\n startTimeUnixNano: ts,\n endTimeUnixNano: ts,\n attributes: toAttributes(attrs),\n status: { code: 1 },\n }\n}\n\n/**\n * Build a single flat OtelSpan whose attribute keys are emitted VERBATIM — no\n * `loop.` namespace. Use for non-loop spans (e.g. the intelligence per-run\n * span) whose keys ARE the downstream contract (`gen_ai.request.model`,\n * `tangle.sessionId`) and are exact-matched by readers. `loopEventToOtelSpan`\n * namespaces payload keys because loop payload fields are free-form; do not\n * reuse it for spans with contract keys.\n */\nexport function flatOtelSpan(\n name: string,\n attributes: Record<string, string | number | boolean>,\n traceId: string,\n timestampMs: number,\n parentSpanId?: string,\n endTimestampMs = timestampMs,\n): OtelSpan {\n const start = msToNs(timestampMs)\n const end = msToNs(Math.max(timestampMs, endTimestampMs))\n return {\n traceId: padTraceId(traceId),\n spanId: generateSpanId(),\n parentSpanId: parentSpanId ? padSpanId(parentSpanId) : undefined,\n name,\n kind: 1,\n startTimeUnixNano: start,\n endTimeUnixNano: end,\n attributes: toAttributes(attributes),\n status: { code: 1 },\n }\n}\n\nexport interface RuntimeEventOtelOptions extends RuntimeTelemetryOptions {\n /** Final customer redactor applied after the schema-aware runtime sanitizer. */\n redact?: (value: unknown) => unknown\n}\n\nfunction eventTimestampMs(event: RuntimeStreamEvent): number {\n if ('timestamp' in event && typeof event.timestamp === 'string') {\n const parsed = Date.parse(event.timestamp)\n if (Number.isFinite(parsed)) return parsed\n }\n return Date.now()\n}\n\nfunction serialized(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n\nfunction mcpIdentity(toolName: string): { server?: string; tool?: string } {\n if (!toolName.startsWith('mcp__')) return {}\n const [, server, ...toolParts] = toolName.split('__')\n return {\n ...(server ? { server } : {}),\n ...(toolParts.length > 0 ? { tool: toolParts.join('__') } : {}),\n }\n}\n\n/** Convert normalized runtime events into lossless, redacted child spans. */\nexport function buildRuntimeEventOtelSpans(\n events: ReadonlyArray<RuntimeStreamEvent>,\n traceId: string,\n parentSpanId?: string,\n options: RuntimeEventOtelOptions = {},\n): OtelSpan[] {\n return events.map((event) => {\n const sanitized = sanitizeRuntimeStreamEvent(event, options)\n const safe = options.redact ? options.redact(sanitized) : sanitized\n const record =\n safe && typeof safe === 'object' && !Array.isArray(safe)\n ? (safe as Record<string, unknown>)\n : { value: safe }\n const attrs: Record<string, string | number | boolean> = {\n 'tangle.runtime.event_type': event.type,\n 'tangle.runtime.event': serialized(record),\n }\n let name = `tangle.runtime.${event.type}`\n\n if (event.type === 'tool_call' || event.type === 'tool_result') {\n name = `agent.${event.type}`\n attrs['tool.name'] = event.toolName\n if (event.toolCallId) attrs['tool.call_id'] = event.toolCallId\n const mcp = mcpIdentity(event.toolName)\n if (mcp.server) attrs['mcp.server'] = mcp.server\n if (mcp.tool) attrs['mcp.tool.name'] = mcp.tool\n const payload = event.type === 'tool_call' ? record.args : record.result\n if (payload !== undefined) {\n attrs[event.type === 'tool_call' ? 'tool.input' : 'tool.output'] = serialized(payload)\n }\n } else if (event.type === 'llm_call') {\n name = 'gen_ai.client.inference'\n attrs['gen_ai.request.model'] = event.model\n if (event.tokensIn !== undefined) attrs['gen_ai.usage.input_tokens'] = event.tokensIn\n if (event.tokensOut !== undefined) attrs['gen_ai.usage.output_tokens'] = event.tokensOut\n if (event.costUsd !== undefined) attrs['tangle.cost.usd'] = event.costUsd\n if (event.latencyMs !== undefined) attrs['tangle.latency_ms'] = event.latencyMs\n if (event.finishReason !== undefined)\n attrs['gen_ai.response.finish_reasons'] = event.finishReason\n } else if (event.type === 'backend_error') {\n attrs['error.type'] = event.error?.kind ?? 'backend'\n attrs['error.message'] = event.message\n } else if (event.type === 'final') {\n attrs['tangle.outcome.status'] = event.status\n attrs['tangle.outcome.reason'] = event.reason\n if (event.error) {\n attrs['error.type'] = event.error.kind\n attrs['error.message'] = event.error.message\n }\n }\n\n const startMs = eventTimestampMs(event)\n const endMs =\n event.type === 'llm_call' && event.latencyMs !== undefined\n ? startMs + event.latencyMs\n : startMs\n const span = flatOtelSpan(name, attrs, traceId, startMs, parentSpanId, endMs)\n if (\n event.type === 'backend_error' ||\n (event.type === 'final' && event.status !== 'completed')\n ) {\n span.status = { code: 2, message: attrs['error.message']?.toString() ?? event.type }\n }\n return span\n })\n}\n\n/**\n * Sink-neutral node in a reconstructed loop span tree. The root node's\n * `parentSpanId` is `undefined` — sinks decide how to parent it (the OTEL\n * mapper attaches the inherited delegation span; the delegation journal\n * leaves it as the tree root).\n */\nexport interface LoopSpanNode {\n spanId: string\n parentSpanId?: string\n /** `'loop'` | `'loop.round'` | `'loop.iteration'`. */\n name: string\n /** Topology level: loop root, plan round, or iteration branch. */\n kind: 'loop' | 'round' | 'branch'\n startMs: number\n endMs: number\n attrs: Record<string, string | number | boolean>\n /** True when the iteration carried an error — maps to OTEL status code 2. */\n error: boolean\n}\n\n/**\n * Build a nested, real-duration OTLP span tree for ONE loop run from its full\n * ordered `LoopTraceEvent` stream. Unlike `loopEventToOtelSpan` (one flat,\n * zero-duration span per event), this reconstructs the topology hierarchy a\n * GenAI trace viewer renders natively:\n *\n * loop (invoke_workflow)\n * └─ loop.round[k] (invoke_workflow) ← tangle.loop.move.{kind,width,rationale}\n * ├─ loop.iteration[i] (invoke_agent) ← gen_ai.agent.name + usage + verdict + placement\n * └─ …\n *\n * Attributes follow the current GenAI semconv (`gen_ai.*`) where they apply and\n * a namespaced `tangle.loop.*` / `tangle.cost.usd` extension for topology /\n * verdict / placement / cost (not yet standardized). Pure: feed it a buffered\n * per-runId event array (e.g. flushed on `loop.ended`) and export the result.\n */\nexport function buildLoopOtelSpans(\n events: ReadonlyArray<{ kind: string; runId: string; timestamp: number; payload: object }>,\n traceId: string,\n rootParentSpanId?: string,\n): OtelSpan[] {\n const tid = padTraceId(traceId)\n return buildLoopSpanNodes(events).map((node) => ({\n traceId: tid,\n spanId: node.spanId,\n parentSpanId: node.parentSpanId\n ? padSpanId(node.parentSpanId)\n : rootParentSpanId\n ? padSpanId(rootParentSpanId)\n : undefined,\n name: node.name,\n kind: 1,\n startTimeUnixNano: msToNs(node.startMs),\n endTimeUnixNano: msToNs(node.endMs),\n attributes: toAttributes(node.attrs),\n status: { code: node.error ? 2 : 1 },\n }))\n}\n\n/**\n * Sink-neutral core behind {@link buildLoopOtelSpans}: reconstruct the\n * loop → round → branch span tree from one run's ordered `LoopTraceEvent`\n * stream. Consumed by the OTEL mapper above and by the MCP delegation\n * journal's compact trace tee — one topology reconstruction, two sinks.\n * Tolerates partial streams (a run that never reached `loop.ended` closes\n * at the last observed event's timestamp).\n */\nexport function buildLoopSpanNodes(\n events: ReadonlyArray<{ kind: string; runId: string; timestamp: number; payload: object }>,\n): LoopSpanNode[] {\n if (events.length === 0) return []\n const out: LoopSpanNode[] = []\n const num = (v: unknown): number | undefined =>\n typeof v === 'number' && Number.isFinite(v) ? v : undefined\n const str = (v: unknown): string | undefined =>\n typeof v === 'string' && v.length > 0 ? v : undefined\n const rec = (v: unknown): Record<string, unknown> =>\n v && typeof v === 'object' ? (v as Record<string, unknown>) : {}\n\n const started = events.find((e) => e.kind === 'loop.started')\n const ended = events.find((e) => e.kind === 'loop.ended')\n const runId = events[0]?.runId ?? ''\n const rootStart = started?.timestamp ?? events[0]!.timestamp\n const rootEnd = ended?.timestamp ?? events[events.length - 1]!.timestamp\n const rootId = generateSpanId()\n\n const make = (\n spanId: string,\n parentSpanId: string | undefined,\n name: string,\n kind: LoopSpanNode['kind'],\n startMs: number,\n endMs: number,\n attrs: Record<string, string | number | boolean>,\n error = false,\n ): LoopSpanNode => ({\n spanId,\n parentSpanId,\n name,\n kind,\n startMs,\n endMs,\n attrs,\n error,\n })\n\n // root\n const sp = rec(started?.payload)\n const rootAttrs: Record<string, string | number | boolean> = {\n [GEN_AI.operation]: 'invoke_workflow',\n [GEN_AI.conversationId]: runId,\n // Explicit run identity under the tangle namespace so a consuming system of\n // record (Tangle Intelligence's run spine) maps this span tree to one run\n // deterministically, instead of inferring it from the conversation id.\n 'tangle.run.id': runId,\n 'tangle.loop.driver': str(sp.driver) ?? 'driver',\n }\n if (Array.isArray(sp.agentRunNames) && sp.agentRunNames.length > 0) {\n rootAttrs['tangle.loop.agents'] = sp.agentRunNames.map(String).join(',')\n // Subject grain: the primary agent/profile this run drove. Lets the spine\n // group runs under the thing being worked on rather than one service-wide\n // bucket. `agentRunNames[0]` is the lead agent on a fan-out.\n rootAttrs['tangle.subject.key'] = String(sp.agentRunNames[0])\n }\n if (ended) {\n const ep = rec(ended.payload)\n const win = num(ep.winnerIterationIndex)\n if (win !== undefined) rootAttrs['tangle.loop.winner.iteration_index'] = win\n const cost = num(ep.totalCostUsd)\n if (cost !== undefined) rootAttrs['tangle.cost.usd'] = cost\n const dur = num(ep.durationMs)\n if (dur !== undefined) rootAttrs['tangle.loop.duration_ms'] = dur\n const iters = num(ep.iterations)\n if (iters !== undefined) rootAttrs['tangle.loop.iterations'] = iters\n }\n out.push(make(rootId, undefined, 'loop', 'loop', rootStart, rootEnd, rootAttrs))\n\n // rounds + iterations\n const iterStartTs = new Map<number, number>()\n const placementByIdx = new Map<number, Record<string, string>>()\n let currentRoundId: string | undefined\n let pendingRound:\n | { id: string; start: number; attrs: Record<string, string | number | boolean> }\n | undefined\n const flushRound = (endMs: number) => {\n if (!pendingRound) return\n out.push(\n make(\n pendingRound.id,\n rootId,\n 'loop.round',\n 'round',\n pendingRound.start,\n endMs,\n pendingRound.attrs,\n ),\n )\n pendingRound = undefined\n }\n\n for (const e of events) {\n const p = rec(e.payload)\n switch (e.kind) {\n case 'loop.plan': {\n flushRound(e.timestamp)\n const id = generateSpanId()\n const roundIdx = num(p.roundIndex) ?? 0\n const attrs: Record<string, string | number | boolean> = {\n [GEN_AI.operation]: 'invoke_workflow',\n 'tangle.loop.round.index': roundIdx,\n 'tangle.loop.move.kind': str(p.moveKind) ?? 'unknown',\n 'tangle.loop.move.round': roundIdx,\n 'tangle.loop.move.width': num(p.plannedCount) ?? 0,\n }\n const r = str(p.rationale)\n if (r) attrs['tangle.loop.move.rationale'] = r\n const parent = num(p.parentIndex)\n if (parent !== undefined) attrs['tangle.loop.move.parent_index'] = parent\n if (Array.isArray(p.childIndices) && p.childIndices.length > 0) {\n attrs['tangle.loop.move.child_indices'] = p.childIndices.map(String).join(',')\n }\n pendingRound = { id, start: e.timestamp, attrs }\n currentRoundId = id\n break\n }\n case 'loop.iteration.started': {\n const idx = num(p.iterationIndex)\n if (idx !== undefined) iterStartTs.set(idx, e.timestamp)\n break\n }\n case 'loop.iteration.dispatch': {\n const idx = num(p.iterationIndex)\n if (idx === undefined) break\n const place: Record<string, string> = {}\n const kind = str(p.placement)\n if (kind) place['tangle.loop.placement.kind'] = kind\n const sid = str(p.sandboxId)\n if (sid) place['tangle.sandbox.id'] = sid\n const fid = str(p.fleetId)\n if (fid) place['tangle.fleet.id'] = fid\n const mid = str(p.machineId)\n if (mid) place['tangle.machine.id'] = mid\n placementByIdx.set(idx, place)\n break\n }\n case 'loop.iteration.ended': {\n const idx = num(p.iterationIndex) ?? 0\n const start = iterStartTs.get(idx) ?? e.timestamp\n const err = str(p.error)\n const attrs: Record<string, string | number | boolean> = {\n [GEN_AI.operation]: 'invoke_agent',\n 'tangle.loop.iteration.index': idx,\n }\n const agent = str(p.agentRunName)\n if (agent) attrs[GEN_AI.agentName] = agent\n const tu = rec(p.tokenUsage)\n const inTok = num(tu.input)\n if (inTok !== undefined) attrs[GEN_AI.inputTokens] = inTok\n const outTok = num(tu.output)\n if (outTok !== undefined) attrs[GEN_AI.outputTokens] = outTok\n const cost = num(p.costUsd)\n if (cost !== undefined) attrs['tangle.cost.usd'] = cost\n const verdict = rec(p.verdict)\n if (typeof verdict.valid === 'boolean') attrs['tangle.loop.verdict.valid'] = verdict.valid\n const score = num(verdict.score)\n if (score !== undefined) attrs['tangle.loop.verdict.score'] = score\n if (err) attrs['tangle.loop.error'] = err\n const gid = num(p.groupId)\n if (gid !== undefined) attrs['tangle.loop.iteration.group_id'] = gid\n const par = num(p.parentIndex)\n if (par !== undefined) attrs['tangle.loop.iteration.parent_index'] = par\n const dur = num(p.durationMs)\n if (dur !== undefined) attrs['tangle.loop.iteration.duration_ms'] = dur\n const preview = str(p.outputPreview)\n if (preview) attrs['tangle.loop.iteration.output_preview'] = preview\n Object.assign(attrs, placementByIdx.get(idx) ?? {})\n out.push(\n make(\n generateSpanId(),\n currentRoundId ?? rootId,\n 'loop.iteration',\n 'branch',\n start,\n e.timestamp,\n attrs,\n err !== undefined,\n ),\n )\n break\n }\n case 'loop.decision': {\n if (pendingRound) {\n const dec = str(p.decision)\n if (dec) pendingRound.attrs['tangle.loop.decision'] = dec\n flushRound(e.timestamp)\n }\n currentRoundId = undefined\n break\n }\n }\n }\n flushRound(rootEnd)\n return out\n}\n\nfunction parseHeadersFromEnv(): Record<string, string> {\n if (typeof process === 'undefined') return {}\n const raw = process.env.OTEL_EXPORTER_OTLP_HEADERS\n if (!raw) return {}\n const out: Record<string, string> = {}\n for (const pair of raw.split(',')) {\n const eq = pair.indexOf('=')\n if (eq < 0) continue\n const key = pair.slice(0, eq).trim()\n const value = pair.slice(eq + 1).trim()\n if (key) out[key] = value\n }\n return out\n}\n\nfunction toAttributes(record: Record<string, string | number | boolean>): OtelAttribute[] {\n return Object.entries(record).map(([key, value]) => ({\n key,\n value:\n typeof value === 'number'\n ? Number.isInteger(value)\n ? { intValue: value.toString() }\n : { doubleValue: value }\n : typeof value === 'boolean'\n ? { boolValue: value }\n : { stringValue: value },\n }))\n}\n\nfunction msToNs(ms: number): string {\n return (BigInt(Math.floor(ms)) * 1_000_000n).toString()\n}\n\nfunction padSpanId(id: string): string {\n const cleaned = id.replace(/-/g, '')\n return cleaned.slice(0, 16).padEnd(16, '0')\n}\n\nfunction padTraceId(id: string): string {\n const cleaned = id.replace(/-/g, '')\n return cleaned.slice(0, 32).padEnd(32, '0')\n}\n\nfunction generateSpanId(): string {\n const bytes = new Uint8Array(8)\n if (typeof globalThis.crypto?.getRandomValues === 'function') {\n globalThis.crypto.getRandomValues(bytes)\n } else {\n for (let i = 0; i < 8; i++) bytes[i] = Math.floor(Math.random() * 256)\n }\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n// ─── Eval-run ingest (self-improvement provenance) ───────────────────────────\n//\n// Tangle Intelligence has a first-class, non-trace record for self-improvement\n// runs: POST /v1/ingest/eval-runs (\"Mode D\"). Each generation carries a\n// `surfaceHash` (the proposed-change identity) + arbitrary `surface` provenance;\n// a later `gate-decided` event re-emits the same `runId` (idempotent upsert) with\n// a real `gateDecision` + `holdoutLift`, so proposal→verdict is one diffable\n// record. This is how a consumer's RSI loop records WHAT it changed, WHY, from\n// which evidence — the audit trail behind agentic self-improvement.\n\n/** Wire version the eval-runs ingest enforces (X-Tangle-Wire-Version + body). */\nexport const INTELLIGENCE_WIRE_VERSION = '2026-05-26.v1'\n\nexport interface EvalRunGeneration {\n /** 0-based ordinal of this generation within the run (required by ingest). */\n index: number\n /** Identity of the proposed surface change (content-addressed hash). */\n surfaceHash: string\n /** Arbitrary provenance for this generation (rationale, evidence, source). */\n surface?: unknown\n /** Per-scenario results; empty until the generation is measured. */\n cells?: unknown[]\n /** Mean composite score (0 when unmeasured — pair with labels.measured). */\n compositeMean: number\n costUsd: number\n durationMs: number\n}\n\nexport interface EvalRunEvent {\n runId: string\n runDir: string\n /** ISO timestamp. */\n timestamp: string\n status:\n | 'started'\n | 'baseline-complete'\n | 'generation-complete'\n | 'gate-decided'\n | 'finished'\n | 'errored'\n labels?: Record<string, string>\n baseline?: EvalRunGeneration\n generations?: EvalRunGeneration[]\n gateDecision?: 'ship' | 'hold' | 'need_more_work' | 'model_ceiling' | 'arch_ceiling'\n holdoutLift?: number\n totalCostUsd: number\n totalDurationMs: number\n errorMessage?: string\n}\n\nexport interface EvalRunsExportConfig {\n /** Bearer key — tenant is resolved server-side from it. Reads TANGLE_API_KEY. */\n apiKey?: string\n /** Intelligence base. Reads TANGLE_INTELLIGENCE_URL env, else prod. */\n base?: string\n /** Idempotency-Key header (e.g. the runId) — safe retries + upsert. */\n idempotencyKey?: string\n}\n\nexport interface EvalRunsExportResult {\n ok: boolean\n status: number\n accepted: number\n rejected: Array<{ index: number; reason: string }>\n}\n\nconst DEFAULT_INTELLIGENCE_BASE = 'https://intelligence.tangle.tools'\n\n/**\n * Ship self-improvement eval-run events to Tangle Intelligence. Unlike the\n * best-effort span exporter, this RESOLVES with the ingest verdict (accepted /\n * rejected per event) so a consumer's loop can assert its provenance landed.\n * Throws only on a missing key or network failure.\n */\nexport async function exportEvalRuns(\n events: EvalRunEvent[],\n config?: EvalRunsExportConfig,\n): Promise<EvalRunsExportResult> {\n if (events.length === 0) return { ok: true, status: 0, accepted: 0, rejected: [] }\n const apiKey =\n config?.apiKey ?? (typeof process !== 'undefined' ? process.env.TANGLE_API_KEY : undefined)\n if (!apiKey)\n throw new Error('exportEvalRuns: apiKey required (pass config.apiKey or set TANGLE_API_KEY)')\n const base =\n config?.base ??\n (typeof process !== 'undefined' ? process.env.TANGLE_INTELLIGENCE_URL : undefined) ??\n DEFAULT_INTELLIGENCE_BASE\n const url = `${base.replace(/\\/+$/, '')}/v1/ingest/eval-runs`\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${apiKey}`,\n 'X-Tangle-Wire-Version': INTELLIGENCE_WIRE_VERSION,\n ...(config?.idempotencyKey ? { 'Idempotency-Key': config.idempotencyKey } : {}),\n },\n body: JSON.stringify({ wireVersion: INTELLIGENCE_WIRE_VERSION, events }),\n })\n let parsed: { accepted?: number; rejected?: Array<{ index: number; reason: string }> } = {}\n try {\n parsed = (await res.json()) as typeof parsed\n } catch {\n // non-JSON body (e.g. 5xx HTML) — leave parsed empty\n }\n return {\n ok: res.ok,\n status: res.status,\n accepted: parsed.accepted ?? (res.ok ? events.length : 0),\n rejected: parsed.rejected ?? [],\n }\n}\n","/**\n *\n * 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 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 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":";;;;;;;;;;;;;;AAaO,SAAS,mBACd,OACA,SACM;AACN,MAAI,CAAC,WAAW,UAAU,OAAW;AACrC,MAAI,CAAC,QAAQ,SAAS,KAAK,GAAG;AAC5B,UAAM,IAAI;AAAA,MACR,SAAS,KAAK,UAAU,KAAK,CAAC,8BAA8B,KAAK,UAAU,CAAC,GAAG,OAAO,CAAC,CAAC;AAAA,IAC1F;AAAA,EACF;AACF;;;ACXA,SAAS,cAAc,qBAAqB;;;AC4D5C,SAAS,2BAA2B,UAAsC;AACxE,MAAI,QAAQ;AACZ,aAAW,KAAK,UAAU;AACxB,UAAM,UAAW,EAA4B;AAC7C,aAAS,OAAO,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E,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA4B,QAAQ,cAC5C,OAAQ,MAA6B,SAAS;AAElD;","names":["totalTokens"]}
@@ -8,7 +8,7 @@ import {
8
8
  DELEGATION_STATUS_DESCRIPTION,
9
9
  DELEGATION_STATUS_INPUT_SCHEMA,
10
10
  DELEGATION_STATUS_TOOL_NAME
11
- } from "./chunk-NC66AM3S.js";
11
+ } from "./chunk-6O5USWVH.js";
12
12
 
13
13
  // src/mcp/openai-tools.ts
14
14
  function buildTool(name, description, parameters) {
@@ -45,4 +45,4 @@ export {
45
45
  mcpToolsForRuntimeMcp,
46
46
  mcpToolsForRuntimeMcpSubset
47
47
  };
48
- //# sourceMappingURL=chunk-DWWII6N2.js.map
48
+ //# sourceMappingURL=chunk-AUEIDTR3.js.map