@tangle-network/agent-runtime 0.221.0 → 0.222.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/{activation-B80dGdPw.js → activation-C3FIZinc.js} +2 -2
  2. package/dist/{activation-B80dGdPw.js.map → activation-C3FIZinc.js.map} +1 -1
  3. package/dist/{activation-CdwuD1wP.d.ts → activation-CoaTi81Q.d.ts} +2 -2
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +2 -2
  6. package/dist/{coordination-driver-imD3q4L5.js → coordination-driver-BMFwV_aM.js} +2 -2
  7. package/dist/{coordination-driver-imD3q4L5.js.map → coordination-driver-BMFwV_aM.js.map} +1 -1
  8. package/dist/{delegate-BokSjGmE.js → delegate-_MIPlySb.js} +2 -2
  9. package/dist/{delegate-BokSjGmE.js.map → delegate-_MIPlySb.js.map} +1 -1
  10. package/dist/durable.d.ts +5 -5
  11. package/dist/durable.js +27 -5
  12. package/dist/durable.js.map +1 -1
  13. package/dist/{graph-D4MFz-Cy.js → graph-DAzvl-CD.js} +3 -3
  14. package/dist/{graph-D4MFz-Cy.js.map → graph-DAzvl-CD.js.map} +1 -1
  15. package/dist/{improvement-cycle-C_Kdj9DB.js → improvement-cycle-DH28Q79j.js} +3 -3
  16. package/dist/{improvement-cycle-C_Kdj9DB.js.map → improvement-cycle-DH28Q79j.js.map} +1 -1
  17. package/dist/{index-CFzFVR5N.d.ts → index-ZJQ4RpP6.d.ts} +2 -2
  18. package/dist/index.d.ts +4 -4
  19. package/dist/index.js +7 -7
  20. package/dist/intelligence.d.ts +2 -2
  21. package/dist/intelligence.js +3 -3
  22. package/dist/kernel.d.ts +2 -2
  23. package/dist/kernel.js +8 -8
  24. package/dist/{loop-runner-bin-Deg_bFdg.d.ts → loop-runner-bin-CscIVOv-.d.ts} +3 -3
  25. package/dist/{loop-runner-bin-DK0Ov_15.js → loop-runner-bin-D5F5XAqC.js} +3 -3
  26. package/dist/{loop-runner-bin-DK0Ov_15.js.map → loop-runner-bin-D5F5XAqC.js.map} +1 -1
  27. package/dist/loop-runner-bin.d.ts +1 -1
  28. package/dist/loop-runner-bin.js +1 -1
  29. package/dist/mcp/bin.js +3 -3
  30. package/dist/mcp/index.d.ts +2 -2
  31. package/dist/mcp/index.js +4 -4
  32. package/dist/{provision-supervisor-C98UA-kI.js → provision-supervisor-ONy4pJ0l.js} +3 -3
  33. package/dist/{provision-supervisor-C98UA-kI.js.map → provision-supervisor-ONy4pJ0l.js.map} +1 -1
  34. package/dist/{runtime-B3YZlRti.js → runtime-CGZo3BpF.js} +8 -8
  35. package/dist/{runtime-B3YZlRti.js.map → runtime-CGZo3BpF.js.map} +1 -1
  36. package/dist/{server-DW_KDc40.js → server-Z-5x4YsU.js} +3 -3
  37. package/dist/{server-DW_KDc40.js.map → server-Z-5x4YsU.js.map} +1 -1
  38. package/dist/{stream-agent-turn-D_-kbzVn.d.ts → stream-agent-turn-CQf-EMwX.d.ts} +5 -1
  39. package/dist/{structural-rollout-CudZIAJv.js → structural-rollout-ysIAMLwb.js} +10 -4
  40. package/dist/structural-rollout-ysIAMLwb.js.map +1 -0
  41. package/dist/{supervise-CBYdifF2.js → supervise-l9fd1ZaI.js} +35 -14
  42. package/dist/supervise-l9fd1ZaI.js.map +1 -0
  43. package/dist/{supervisor-C0xW7oTl.js → supervisor-af7-tQrQ.js} +2437 -2377
  44. package/dist/supervisor-af7-tQrQ.js.map +1 -0
  45. package/dist/testing.d.ts +2 -2
  46. package/dist/testing.js +12 -12
  47. package/dist/tui/index.d.ts +1 -1
  48. package/dist/tui/index.js +1 -1
  49. package/package.json +1 -1
  50. package/dist/structural-rollout-CudZIAJv.js.map +0 -1
  51. package/dist/supervise-CBYdifF2.js.map +0 -1
  52. package/dist/supervisor-C0xW7oTl.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"supervise-l9fd1ZaI.js","names":["isAsyncIterable","isAsyncIterable","profileMaterializationAxes","addRetainedSpend"],"sources":["../src/runtime/supervise/completion-gate.ts","../src/runtime/supervise/coordination-http.ts","../src/runtime/supervise/single-flight-tools.ts","../src/runtime/supervise/coordination-mcp.ts","../src/runtime/supervise/otel-spans.ts","../src/runtime/supervise/supervisor-agent.ts","../src/runtime/supervise/worker-retry.ts","../src/runtime/supervise/supervise.ts"],"sourcesContent":["/**\n *\n * The completion-oracle: **settled ⟺ DELIVERED.**\n *\n * Foreman's one hard lesson (0/18 self-improvement deliverables) — \"done\" must mean a check\n * PASSED, not the agent's say-so. `gateOnDeliverable` wraps an `Executor` so its settlement\n * is `valid` ONLY when the deliverable check passes. The child still RUNS and settles (its\n * spend is conserved into the pool either way), but a child that ran WITHOUT delivering\n * settles `valid:false` — so a keep-best driver never counts it as done, and a gate never\n * inflates with self-judged wins.\n *\n * Dual-purpose by construction:\n * - product: the agent fleet only advances on real, checked deliverables.\n * - proof: the gate's `valid` is the honest settle — equal-k comparisons can't be gamed by an\n * arm that \"ran\" without producing the artifact.\n *\n * The check is a DEPLOYABLE oracle — a test command, a state verifier, the commit0 judge —\n * read off the child's output, never the model judging itself. A throwing check is\n * fail-closed (not delivered), never a crash.\n *\n * @experimental\n */\n\nimport { inheritRuntimeOwnedExecutorAttestation } from './materialization'\nimport type { DefaultVerdict, Executor, ExecutorResult, UsageEvent } from './types'\n\n/**\n * The deployable completion oracle passed to {@link gateOnDeliverable}: a `check` that\n * decides DELIVERED (settles `valid` ⟺ it resolves true) plus an optional `describe` of\n * what the spawn was supposed to produce. The check reads the child's output — never the\n * model judging itself.\n */\nexport interface DeliverableSpec<Out = unknown> {\n /** The deployable check that decides DELIVERED. `settled.valid ⟺ this resolves true`. */\n check: (out: Out) => boolean | Promise<boolean>\n /** What the spawn was supposed to produce — surfaced in traces/reports. */\n describe?: string\n}\n\n/**\n * Wrap an `Executor` so its settlement `valid` reflects the deliverable check, not the\n * inner verdict. Handles both `execute` shapes (one-shot `Promise<ExecutorResult>` and\n * streaming `AsyncIterable<UsageEvent>` + `resultArtifact()`); the check runs once the inner\n * executor has produced its output. The inner `score` is preserved; only `valid` is gated.\n */\nexport function gateOnDeliverable<Out>(\n inner: Executor<Out>,\n deliverable: DeliverableSpec<Out>,\n): Executor<Out> {\n let gated: DefaultVerdict | undefined\n\n const check = async (out: Out, baseScore?: number): Promise<DefaultVerdict> => {\n let delivered: boolean\n try {\n delivered = (await deliverable.check(out)) === true\n } catch {\n delivered = false // fail-closed: a throwing check is NOT a delivery\n }\n return { valid: delivered, score: baseScore ?? (delivered ? 1 : 0) }\n }\n\n /**\n * Ask the delivery question once, from whatever the inner executor managed to produce.\n *\n * Fail-closed on the artifact being unavailable: an executor that never produced one delivered\n * nothing, and leaving `gated` unset keeps the existing invalid-by-default reading.\n */\n const settleVerdict = async (): Promise<void> => {\n let art: ReturnType<Executor<Out>['resultArtifact']>\n try {\n art = inner.resultArtifact()\n } catch {\n return\n }\n gated = await check(art.out, art.verdict?.score)\n }\n\n const wrapped: Executor<Out> = {\n runtime: inner.runtime,\n ...(inner.budgetExempt !== undefined ? { budgetExempt: inner.budgetExempt } : {}),\n ...(inner.deliver ? { deliver: (m: unknown) => inner.deliver?.(m) } : {}),\n // Forward the OPTIONAL live-observation surfaces so a gated worker stays supervisable\n // mid-flight. The scope captures `progress`/`traceSource` at spawn and only if the executor\n // exposes them; a gate that drops them makes `observe_agent` read `recentActivity:[]` and\n // loses online detection for a running worker (it saw the tokens/turns the fold derives, but\n // none of the harness's own turn count or tool activity). `metered` is a driver-executor's\n // OWN-inference subtree total, re-homed by the parent on settle — dropping it would leak a\n // gated sub-driver's inference out of the journal. Preserve the \"undefined ⟺ not implemented\"\n // contract: only expose a method the inner executor actually implements.\n ...(inner.progress ? { progress: () => inner.progress?.() } : {}),\n ...(inner.traceSource ? { traceSource: () => inner.traceSource?.() } : {}),\n ...(inner.metered ? { metered: () => inner.metered?.() } : {}),\n execute(task, signal) {\n const r = inner.execute(task, signal)\n if (isAsyncIterable(r)) {\n // Streaming: pass the usage events through (the conserved-pool fold consumes them),\n // then gate the verdict from the settled artifact.\n return (async function* () {\n try {\n for await (const ev of r) yield ev\n } finally {\n // `finally`, NOT the straight-line path: delivery is a property of the OUTPUT, not of\n // how the worker terminated. A worker killed by budget, deadline, or abort AFTER it\n // wrote its deliverable has still delivered, and checking only on clean completion\n // reported failure over completed work.\n //\n // Measured: discovery-lab run `proof-native-tools-20260801b` spawned a child that\n // wrote `child-artifact.txt` containing exactly the required line, then overran a\n // parent-authored 12,000-token budget (it spent 76,657 — no pi child in six runs has\n // finished under ~31,000). The stream aborted, this check never ran, and the run\n // recorded `no-winner` over a file that was correct on disk.\n //\n // This does not weaken the gate. The deliverable check IS the ground truth, so a\n // partially-written or absent artifact still fails it; all that changes is that the\n // question now gets asked.\n await settleVerdict()\n }\n })()\n }\n // One-shot: gate the resolved result's verdict in place.\n return (async () => {\n let res: ExecutorResult<Out>\n try {\n res = await r\n } catch (error) {\n // Same reason as the streaming path: a rejected execute can still have left a correct\n // artifact behind. Check it, then re-throw so the failure itself is never swallowed.\n await settleVerdict()\n throw error\n }\n gated = await check(res.out, res.verdict?.score)\n return { ...res, verdict: gated } satisfies ExecutorResult<Out>\n })()\n },\n teardown: (grace) => inner.teardown(grace),\n resultArtifact() {\n const art = inner.resultArtifact()\n return { ...art, verdict: gated ?? art.verdict }\n },\n }\n return inheritRuntimeOwnedExecutorAttestation(inner, wrapped)\n}\n\nexport interface ExecutorResultMapping<Out> {\n outRef: string\n out: Out\n verdict?: DefaultVerdict\n}\n\n/**\n * Transform a Runtime executor's terminal artifact without losing its private\n * profile-materialization attestation or altering its measured spend. This is\n * the composition point for deterministic post-processing and grading; callers\n * must not rebuild an Executor around a model transport merely to change `out`.\n */\nexport function mapExecutorResult<In, Out>(\n inner: Executor<In>,\n map: (\n result: ExecutorResult<In>,\n task: unknown,\n ) => ExecutorResultMapping<Out> | Promise<ExecutorResultMapping<Out>>,\n): Executor<Out> {\n let mapped: ExecutorResult<Out> | undefined\n\n const settle = async (\n result: ExecutorResult<In>,\n task: unknown,\n ): Promise<ExecutorResult<Out>> => {\n const transformed = await map(result, task)\n mapped = {\n outRef: transformed.outRef,\n out: transformed.out,\n ...(transformed.verdict ? { verdict: transformed.verdict } : {}),\n spent: result.spent,\n }\n return mapped\n }\n\n const wrapped: Executor<Out> = {\n runtime: inner.runtime,\n ...(inner.budgetExempt !== undefined ? { budgetExempt: inner.budgetExempt } : {}),\n ...(inner.deliver ? { deliver: (message: unknown) => inner.deliver?.(message) } : {}),\n ...(inner.progress ? { progress: () => inner.progress?.() } : {}),\n ...(inner.traceSource ? { traceSource: () => inner.traceSource?.() } : {}),\n ...(inner.accounting ? { accounting: () => inner.accounting?.() } : {}),\n ...(inner.metered ? { metered: () => inner.metered?.() } : {}),\n execute(task, signal) {\n const execution = inner.execute(task, signal)\n if (isAsyncIterable(execution)) {\n return (async function* () {\n for await (const event of execution) yield event\n await settle(inner.resultArtifact(), task)\n })()\n }\n return (async () => settle(await execution, task))()\n },\n teardown: (grace) => inner.teardown(grace),\n resultArtifact() {\n if (!mapped) throw new Error('mapExecutorResult: resultArtifact() read before execute()')\n return mapped\n },\n }\n return inheritRuntimeOwnedExecutorAttestation(inner, wrapped)\n}\n\nfunction isAsyncIterable(v: unknown): v is AsyncIterable<UsageEvent> {\n return (\n v != null &&\n typeof (v as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function'\n )\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\nimport { ConfigError } from '../../errors'\nimport type { JsonRpcMessage, JsonRpcResponse } from '../../mcp/protocol'\n\nexport interface CoordinationHttpAudit {\n readonly runId: string\n readonly actorId: string\n readonly outcome: 'rejected' | 'accepted' | 'completed' | 'completed-after-deadline'\n readonly status: number\n readonly action?: string\n}\n\n/** Transport limits apply before parsing or executing a coordination action. */\nexport interface CoordinationHttpOptions {\n readonly maxRequestBytes?: number\n readonly requestTimeoutMs?: number\n readonly maxConcurrentRequests?: number\n readonly requestsPerMinute?: number\n /** Browser origins are refused unless explicitly listed. */\n readonly allowedOrigins?: ReadonlyArray<string>\n /** Audit fields exclude credentials, request bodies, and arbitrary error strings. */\n readonly onAudit?: (event: CoordinationHttpAudit) => Promise<void> | void\n}\n\nexport function coordinationHttpLimits(options: CoordinationHttpOptions) {\n const positive = (name: string, value: number | undefined, fallback: number) => {\n const resolved = value ?? fallback\n if (!Number.isSafeInteger(resolved) || resolved <= 0) {\n throw new ConfigError(`coordination ${name} must be a positive safe integer`)\n }\n return resolved\n }\n const origins = new Set(options.allowedOrigins ?? [])\n for (const origin of origins) {\n const parsed = new URL(origin)\n if (parsed.origin !== origin || !['http:', 'https:'].includes(parsed.protocol)) {\n throw new ConfigError('coordination allowedOrigins must contain canonical HTTP origins')\n }\n }\n const requestTimeoutMs = positive('requestTimeoutMs', options.requestTimeoutMs, 30_000)\n if (requestTimeoutMs > 2_147_483_647)\n throw new ConfigError('coordination requestTimeoutMs exceeds the timer limit')\n return {\n maxRequestBytes: positive('maxRequestBytes', options.maxRequestBytes, 1024 * 1024),\n requestTimeoutMs,\n maxConcurrentRequests: positive('maxConcurrentRequests', options.maxConcurrentRequests, 32),\n requestsPerMinute: positive('requestsPerMinute', options.requestsPerMinute, 600),\n origins,\n }\n}\n\n/** One bounded HTTP adapter around the existing JSON-RPC handler; it owns no run commands. */\nexport function coordinationHttpHandler(input: {\n options: CoordinationHttpOptions\n identity: { runId: string; actorId: string }\n authorize(req: IncomingMessage): number | undefined\n handle(message: JsonRpcMessage): Promise<JsonRpcResponse | null>\n toolNames: ReadonlySet<string>\n /** Actions still executing after their request already answered, such as a fenced tool that\n * returned pending. Like a timed-out action, each stays charged against concurrency until it\n * settles, so answering early cannot lift the bound on concurrent work. */\n backgroundActions(): number\n}) {\n const limits = coordinationHttpLimits(input.options)\n let active = 0\n let controlActive = 0\n let controlRequests = 0\n let windowStart = Date.now()\n let requests = 0\n const audit = async (\n outcome: CoordinationHttpAudit['outcome'],\n status: number,\n action?: string,\n ) => {\n await input.options.onAudit?.({\n ...input.identity,\n outcome,\n status,\n ...(action ? { action } : {}),\n })\n }\n return (req: IncomingMessage, res: ServerResponse) => {\n let finished = false\n let executing = false\n let timedOut = false\n let admitted = false\n let controlAdmission = false\n let action: string | undefined\n let timer: ReturnType<typeof setTimeout> | undefined\n const release = () => {\n if (admitted) {\n admitted = false\n if (controlAdmission) controlActive--\n else active--\n }\n if (timer) clearTimeout(timer)\n }\n const respond = (status: number, value?: unknown) => {\n if (finished) return\n finished = true\n if (timer) clearTimeout(timer)\n res.writeHead(status, {\n 'content-type': 'application/json',\n 'cache-control': 'no-store',\n ...(status === 405 ? { allow: 'POST' } : {}),\n })\n res.end(value === undefined ? undefined : JSON.stringify(value))\n if (!executing) release()\n }\n const reject = (status: number) => {\n respond(status)\n void audit('rejected', status, action).catch(() => undefined)\n req.resume()\n }\n req.on('error', () => reject(400))\n req.on('aborted', () => {\n finished = true\n if (!executing) release()\n })\n res.on('close', () => {\n finished = true\n if (!executing) release()\n })\n if (req.method !== 'POST') {\n reject(405)\n return\n }\n const authorization = input.authorize(req)\n if (authorization !== undefined) {\n reject(authorization)\n return\n }\n const origin = req.headers.origin\n if (origin !== undefined && !limits.origins.has(origin)) {\n reject(403)\n return\n }\n if (\n req.headers['content-type']?.split(';', 1)[0]?.trim().toLowerCase() !== 'application/json'\n ) {\n reject(415)\n return\n }\n const length = req.headers['content-length']\n if (\n length !== undefined &&\n (!/^\\d+$/.test(length) || Number(length) > limits.maxRequestBytes)\n ) {\n reject(413)\n return\n }\n const now = Date.now()\n if (now - windowStart >= 60_000) {\n windowStart = now\n requests = 0\n controlRequests = 0\n }\n controlAdmission =\n active + input.backgroundActions() >= limits.maxConcurrentRequests ||\n requests >= limits.requestsPerMinute\n if (controlAdmission) {\n // Keep a small independently bounded path for owner observation and cancellation.\n if (controlActive >= 2 || controlRequests >= 60) {\n reject(429)\n return\n }\n controlActive++\n } else {\n requests++\n active++\n }\n admitted = true\n timer = setTimeout(() => {\n timedOut = true\n reject(executing ? 504 : 408)\n }, limits.requestTimeoutMs)\n timer.unref()\n let size = 0\n const chunks: Buffer[] = []\n req.on('data', (chunk: Buffer) => {\n if (finished) return\n size += chunk.length\n if (size > limits.maxRequestBytes) {\n reject(413)\n return\n }\n chunks.push(chunk)\n })\n req.on('end', () => {\n if (finished) return\n let message: JsonRpcMessage\n try {\n const value: unknown = JSON.parse(\n new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)),\n )\n if (\n !value ||\n typeof value !== 'object' ||\n Array.isArray(value) ||\n !('jsonrpc' in value) ||\n value.jsonrpc !== '2.0' ||\n !('method' in value) ||\n typeof value.method !== 'string' ||\n ('id' in value &&\n value.id !== null &&\n typeof value.id !== 'string' &&\n (typeof value.id !== 'number' || !Number.isFinite(value.id)))\n ) {\n reject(400)\n return\n }\n message = value as JsonRpcMessage\n } catch {\n reject(400)\n return\n }\n const authorization = input.authorize(req)\n if (authorization !== undefined) {\n reject(authorization)\n return\n }\n if (\n message.method === 'tools/call' &&\n message.params &&\n typeof message.params === 'object' &&\n 'name' in message.params &&\n typeof message.params.name === 'string' &&\n input.toolNames.has(message.params.name)\n ) {\n action = message.params.name\n }\n if (controlAdmission) {\n const control =\n message.method === 'initialize' ||\n message.method === 'tools/list' ||\n action === 'stop' ||\n action === 'observe_agent' ||\n action === 'read_journal'\n if (!control) {\n reject(429)\n return\n }\n controlRequests++\n }\n executing = true\n void (async () => {\n try {\n await audit('accepted', 200, action)\n if (finished) return\n const authorization = input.authorize(req)\n if (authorization !== undefined) {\n reject(authorization)\n return\n }\n const response = await input.handle(message)\n if (!finished) respond(response === null ? 202 : 200, response ?? undefined)\n await audit(\n timedOut ? 'completed-after-deadline' : 'completed',\n timedOut ? 504 : response === null ? 202 : 200,\n action,\n )\n } catch {\n respond(500)\n } finally {\n executing = false\n release()\n }\n })()\n })\n }\n}\n","/**\n * Serve method-supplied supervisor tools on the coordination MCP as single-flight, fenced calls.\n *\n * A method tool can run for hours: a literature graph spawns and joins its own children inside one\n * call. The coordination transport answers 504 at `requestTimeoutMs`, so an unwrapped long call\n * reaches the caller as a hard tool error while its handler keeps running. A caller that retries\n * starts a second full run. Run mech-interp-foundations-glm2-20260911d spawned the same enumerate\n * and extract children twice this way.\n *\n * Two rules close that failure:\n * - Identity. A call joins an existing invocation when its tool name and its RFC 8785 canonical\n * arguments match, and that invocation has not yet returned its outcome to a caller. The handler\n * is not invoked again. Key order does not matter: the observed retry reordered every key.\n * - Fence. A call waits at most `fenceMs` for the outcome. If the handler is still running, the call\n * returns a non-error pending result. A later identical call keeps waiting, then returns the value\n * or throws the handler's error once the handler settles.\n *\n * An invocation's identity ends when a call returns its outcome. The next identical call is a fresh\n * run, because equal arguments do not make a call a replay. Code mode's `execute` and Knowledge's\n * `knowledge_search` read live state, so their callers repeat identical arguments to get a current\n * answer. A handler that finishes within the fence therefore behaves exactly as it did unwrapped.\n * No escape hatch is needed: the only calls this absorbs are ones whose caller could not have seen\n * the outcome.\n */\n\nimport { canonicalCandidateJson } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport type { McpToolDescriptor } from '../../mcp/server'\nimport { withTimeout } from '../util'\n\ntype Outcome =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly error: unknown }\n\ninterface Invocation {\n readonly startedAt: number\n /** Resolves once the handler settles; never rejects, so an uncollected failure is not unhandled. */\n readonly settled: Promise<Outcome>\n outcome: Outcome | undefined\n /** Calls currently inside their fence for this invocation. */\n waiting: number\n}\n\n/** The non-error answer for a call whose handler is still running when its fence elapses. */\nexport interface PendingToolCall {\n readonly pending: true\n readonly tool: string\n readonly elapsedMs: number\n readonly instruction: string\n}\n\nexport interface SingleFlightTools {\n readonly tools: ReadonlyArray<McpToolDescriptor>\n /** Invocations still running with no call waiting on them: work that outlived its request. The\n * transport charges these against its concurrency limit until they settle. */\n background(): number\n}\n\nexport function singleFlightTools(\n tools: ReadonlyArray<McpToolDescriptor>,\n options: { readonly fenceMs: number; readonly now?: () => number },\n): SingleFlightTools {\n const { fenceMs } = options\n if (!Number.isSafeInteger(fenceMs) || fenceMs <= 0) {\n throw new ValidationError('singleFlightTools: fenceMs must be a positive safe integer')\n }\n const now = options.now ?? Date.now\n // One registry per coordination server, which serves exactly one manager scope. Driver retries\n // and re-prompts reuse that server, so a re-entered harness joins the run it already started.\n const invocations = new Map<string, Invocation>()\n\n const start = (tool: McpToolDescriptor, raw: unknown): Invocation => {\n const invocation: Invocation = {\n startedAt: now(),\n // An async wrapper turns a synchronous throw into a recorded failure, like a rejection.\n settled: (async () => tool.handler(raw))().then(\n (value): Outcome => {\n invocation.outcome = { ok: true, value }\n return invocation.outcome\n },\n (error: unknown): Outcome => {\n invocation.outcome = { ok: false, error }\n return invocation.outcome\n },\n ),\n outcome: undefined,\n waiting: 0,\n }\n return invocation\n }\n\n const wrap = (tool: McpToolDescriptor): McpToolDescriptor =>\n Object.freeze({\n ...tool,\n handler: async (raw: unknown): Promise<unknown> => {\n const key = invocationKey(tool.name, raw)\n let invocation = invocations.get(key)\n if (invocation === undefined) {\n invocation = start(tool, raw)\n invocations.set(key, invocation)\n }\n if (invocation.outcome === undefined) {\n invocation.waiting++\n try {\n await withTimeout(invocation.settled, fenceMs)\n } finally {\n invocation.waiting--\n }\n }\n const outcome = invocation.outcome\n if (outcome === undefined) return pendingToolCall(tool.name, now() - invocation.startedAt)\n // This call returns the outcome, so the invocation's identity ends here.\n if (invocations.get(key) === invocation) invocations.delete(key)\n if (outcome.ok) return outcome.value\n throw outcome.error\n },\n })\n\n return {\n tools: Object.freeze(tools.map(wrap)),\n background() {\n let count = 0\n for (const invocation of invocations.values()) {\n if (invocation.outcome === undefined && invocation.waiting === 0) count++\n }\n return count\n },\n }\n}\n\nfunction invocationKey(name: string, raw: unknown): string {\n try {\n return canonicalCandidateJson([name, raw])\n } catch (error) {\n throw new ValidationError(\n `${name}: arguments must be finite JSON so a repeated call can join its earlier run`,\n { cause: error },\n )\n }\n}\n\nfunction pendingToolCall(tool: string, elapsedMs: number): PendingToolCall {\n return {\n pending: true,\n tool,\n elapsedMs,\n instruction:\n `${tool} is still running; nothing failed. Call ${tool} again with the same arguments to ` +\n 'keep waiting. That call joins this run and returns its result, or its error, once it ' +\n 'finishes. Different arguments start a separate run.',\n }\n}\n","/**\n *\n * Serve the coordination verbs (spawn_worker / await_event / observe_agent / steer_agent / stop)\n * as a real HTTP MCP server over a LIVE `Scope`. This is the keystone that lets a coding-harness\n * agent (opencode via the cli-bridge, claude-code, codex) BE the supervisor: it mounts this MCP\n * (`mcp.mcpServers.coordination`) and calls `spawn_worker` as a native tool, which lands on\n * `Scope.spawn` — a real box driving real boxes, not emulated function-tools.\n *\n * Coordination vs DELEGATION (`../../mcp/delegates.ts`): coordination SPAWNS workers in a CHOSEN\n * backend (`createExecutor({ backend })` — sandbox OR cli-bridge) and live-drives them — observe /\n * steer / resume, recursive sub-drivers, one conserved budget. To instead delegate a coding task\n * INSIDE the agent's OWN sandbox (a durable fire-and-poll job that survives an MCP restart), use the\n * delegation MCP. Coordination is the live, cross-backend supervisor; delegation is own-sandbox async.\n *\n * Transport: JSON-RPC over HTTP POST (the MCP streamable-HTTP shape — `application/json` for a\n * single response). The server is created INSIDE an agent's `act(task, scope)` so it fronts that\n * agent's live scope; tear it down when the act returns.\n *\n * @experimental\n */\n\nimport { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'\nimport { createServer, type Server } from 'node:http'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ConfigError, ValidationError } from '../../errors'\nimport type { JsonRpcMessage } from '../../mcp/protocol'\nimport type { McpToolDescriptor } from '../../mcp/server'\nimport { createStdioToolServer, type StdioToolServer } from '../../mcp/tool-server'\nimport {\n type AnalystRegistry,\n type AnalyzeOnSettleRoute,\n type AuthorizeDownMessage,\n type ContinuityMode,\n type CoordinationEvent,\n type CoordinationTools,\n createCoordinationTools,\n DEFAULT_AWAIT_EVENT_TIMEOUT_MS,\n type DefinedAnalystRecord,\n type EscalateQuestion,\n type MakeWorkerAgent,\n type QuestionEscalationRecord,\n type QuestionPolicy,\n type QuestionRecord,\n type SettledWorker,\n type SpawnPreflight,\n type WorkerWatchOptions,\n} from '../../mcp/tools/coordination'\nimport { runAbortable } from './abortable'\nimport {\n type CoordinationHttpOptions,\n coordinationHttpHandler,\n coordinationHttpLimits,\n} from './coordination-http'\nimport { singleFlightTools } from './single-flight-tools'\n\nexport type { CoordinationHttpAudit, CoordinationHttpOptions } from './coordination-http'\n\nimport type { DeliverableSpec } from './completion-gate'\nimport type { BusRecord } from './event-bus'\nimport type { PeerMailEvent, PeerMailLimits } from './peer-mail'\nimport type { Budget, ResultBlobStore, Scope } from './types'\n\nexport interface CoordinationMcpHandle {\n /** The URL an in-box harness mounts as `mcp.mcpServers.coordination.url`. */\n readonly url: string\n readonly port: number\n /** Runtime-only credentials. Never put these headers in canonical profiles or journals. */\n readonly headers: Readonly<Record<string, string>>\n readonly credentialExpiresAt: number | undefined\n /** Revoke this listener’s current token and mint another. Remove a signing key to revoke across restarts. */\n rotateCredential(): void\n /** The coordination tools' settled-worker ledger (for the driver's finalize). */\n settled(): ReadonlyArray<SettledWorker>\n /** The first driver-authored result whose injected independent check passed. */\n submittedResult: CoordinationTools['submittedResult']\n /** Post-loop drain of already-settled, unpulled children into the ledger — call before reading\n * `settled()` for a finalize, so a delivered child the harness never awaited is not lost. */\n drainResolved: CoordinationTools['drainResolved']\n isStopped(): boolean\n /** The full ordered bus-event log for current-process observability and audit evidence. */\n history: CoordinationTools['history']\n /** Bus throughput counters for live dashboards. */\n stats: CoordinationTools['stats']\n /** Raise a `finding` on the bus from an online detector watching a worker's live pipe. */\n raiseFinding: CoordinationTools['raiseFinding']\n /** Every peer-mail attempt in order, delivered and refused alike. Empty when peer mail is off. */\n mailHistory(): ReadonlyArray<PeerMailEvent>\n /** End one peer exchange: every further mail on the thread is refused `thread-stopped`. Returns\n * false when peer mail is off or the thread was already stopped. */\n stopMailThread(threadId: string): boolean\n close(): Promise<void>\n}\n\n/** Hosts that reach only this machine, including the IPv4-mapped and bracketed IPv6 spellings a\n * caller may pass through from config. A name that is not recognizably loopback counts as REMOTE:\n * whether it resolves to a loopback interface is not knowable here, and the safe direction of that\n * doubt is \"exposed\". */\nexport function isLoopbackHost(host: string): boolean {\n const h = host.trim().toLowerCase().replace(/^\\[/, '').replace(/\\]$/, '')\n if (h === 'localhost' || h === '::1' || h === '0:0:0:0:0:0:0:1' || h === '::ffff:127.0.0.1') {\n return true\n }\n return /^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(h)\n}\n\nexport interface CoordinationAuthentication {\n /** Credential lifetime; defaults to 15 minutes and cannot exceed 24 hours. */\n readonly ttlMs?: number\n /** Caller-owned secret keys. Keep prior keys to verify unexpired credentials after restart. */\n readonly signingKeys?: {\n readonly activeKeyId: string\n readonly keys: Readonly<Record<string, string>>\n }\n}\n\nexport interface CoordinationPublicAddress {\n readonly host: string\n readonly port: number\n readonly runId: string\n readonly actorId: string\n /** Manager cancellation and deadline; pass this to asynchronous endpoint provisioning. */\n readonly signal: AbortSignal\n}\n\nexport interface CoordinationTransportOptions extends CoordinationHttpOptions {\n readonly host?: string\n readonly port?: number\n /** Required for remote binds. Each server mints a distinct run/actor credential. */\n readonly authentication?: true | CoordinationAuthentication\n /** Caller-owned reachable endpoint or mapping, awaited before dispatch. Runtime creates no tunnel. */\n readonly publicUrl?: string | ((address: CoordinationPublicAddress) => string | Promise<string>)\n}\n\nexport function assertCoordinationTransport(options: CoordinationTransportOptions): void {\n const host = options.host ?? '127.0.0.1'\n if (!isLoopbackHost(host) && !options.authentication) {\n throw new ConfigError(\n 'coordination non-loopback address requires authentication; allowUnauthenticatedRemote is no longer supported',\n )\n }\n if (\n options.authentication !== undefined &&\n options.authentication !== true &&\n (typeof options.authentication !== 'object' ||\n options.authentication === null ||\n Array.isArray(options.authentication))\n ) {\n throw new ConfigError(\n 'coordination authentication must be true or a credential lifetime configuration',\n )\n }\n const ttl = typeof options.authentication === 'object' ? options.authentication.ttlMs : undefined\n if (ttl !== undefined && (!Number.isSafeInteger(ttl) || ttl <= 0 || ttl > 86_400_000)) {\n throw new ConfigError(\n 'coordination credential ttlMs must be a positive integer no greater than 24 hours',\n )\n }\n if (options.publicUrl !== undefined && !options.authentication) {\n throw new ConfigError('coordination publicUrl requires authentication')\n }\n const signingKeys =\n typeof options.authentication === 'object' ? options.authentication.signingKeys : undefined\n if (signingKeys !== undefined) {\n if (!options.publicUrl)\n throw new ConfigError('coordination signingKeys requires a stable publicUrl')\n if (!signingKeys.activeKeyId || !Object.hasOwn(signingKeys.keys, signingKeys.activeKeyId)) {\n throw new ConfigError('coordination signingKeys must contain the active key')\n }\n for (const [id, key] of Object.entries(signingKeys.keys)) {\n if (\n !/^[A-Za-z0-9_-]{1,64}$/.test(id) ||\n typeof key !== 'string' ||\n Buffer.byteLength(key) < 32\n ) {\n throw new ConfigError(\n 'coordination signing keys require bounded key IDs and at least 32 secret bytes',\n )\n }\n }\n }\n coordinationHttpLimits(options)\n}\n\n/**\n * The longest one coordination call holds its HTTP response before it answers with a re-pollable\n * pending result instead: `await_event` by default, and every method-supplied node tool always.\n *\n * It is half of `requestTimeoutMs`, so the answer leaves before the transport's own 504 at\n * `requestTimeoutMs`, with the other half left for body transfer, admission, and serialization.\n * Deriving it here means a configured request timeout moves both fences with it. It is capped at\n * {@link DEFAULT_AWAIT_EVENT_TIMEOUT_MS} so a long request timeout does not lengthen each wait; at\n * the default 30 s request timeout both values are 15 s.\n */\nexport function coordinationResponseFenceMs(requestTimeoutMs: number): number {\n return Math.max(1, Math.min(DEFAULT_AWAIT_EVENT_TIMEOUT_MS, Math.floor(requestTimeoutMs / 2)))\n}\n\n/** Stand up the existing coordination tools with bounded HTTP access over one live scope. */\nexport async function serveCoordinationMcp(\n opts: CoordinationTransportOptions & {\n /** Trusted audit identity; defaults to the live scope node. */\n identity?: { runId: string; actorId: string }\n scope: Scope<unknown>\n blobs: ResultBlobStore\n makeWorkerAgent: MakeWorkerAgent\n authorizeDownMessage?: AuthorizeDownMessage\n perWorker: Budget\n /** Independent completion check exposed to the driver as `submit_result`. */\n deliverable?: DeliverableSpec<unknown>\n /** Called once when the external manager accepts a result or declares completion. */\n onStop?: (reason: string | undefined) => void\n /** Hard cap on simultaneously-LIVE workers — `spawn_worker` fails closed once this many are in\n * flight (a concurrency fence on top of the conserved-pool fence). Omit/`<= 0` = no cap. */\n maxLiveWorkers?: number\n /** Max wall-clock ms a single `await_event` may block before returning a re-pollable\n * `{ pending, live }` snapshot instead of erroring on the client's request timeout. Omit =\n * the `coordinationResponseFenceMs` derived from the request timeout; `<= 0` = prior unbounded\n * block (in-process only). */\n awaitTimeoutMs?: number\n /** Trace-analyst lenses the driver can run (`run_analyst`) or auto-fire on settle. */\n analysts?: AnalystRegistry\n /** Analyst kinds to auto-run when a worker settles `done` — findings flow up the bus. */\n analyzeOnSettle?: ReadonlyArray<string | AnalyzeOnSettleRoute>\n /** Run the ONLINE detector panel over each worker's live tool trace (raises `finding` events). */\n watchWorkers?: WorkerWatchOptions\n /** Idle time after which `observe_agent` reports a worker as stalled. */\n stallAfterMs?: number\n /** Default continuity per worker profile name — `'resume'` re-attaches spawns of that name to\n * the node's latest settled worker; the tool's per-call `continuity` overrides. */\n continuityByProfile?: Readonly<Record<string, ContinuityMode>>\n /** Pass-through subscriber for every bus event, including pre-delivery instruction receipts and\n * steer/answer delivery outcomes. */\n onEvent?: (\n event: CoordinationEvent,\n record: BusRecord<CoordinationEvent>,\n ) => void | Promise<void>\n /** Re-publish resume-time settlements through the awaited observer before this server listens. */\n replaySettlements?: boolean\n questionPolicy?: QuestionPolicy\n /** Where an `ask_parent` question goes when it leaves this manager. Omit = `no-parent`. */\n escalateQuestion?: EscalateQuestion\n /** Escalations replayed from a prior process — seeds what `stop` knows went unheard. */\n priorEscalations?: ReadonlyArray<QuestionEscalationRecord>\n /** Questions replayed from a prior process of this run — seeds the question ledger. */\n priorQuestions?: ReadonlyArray<QuestionRecord>\n /** Every coordination record from prior processes of this run — what `read_journal` reads before\n * this process's own rows, so a resumed manager sees what it already did. */\n priorJournal?: ReadonlyArray<BusRecord<CoordinationEvent>>\n /** Lenses this manager defined in a prior process — seeds the menu and the definition cap. */\n priorAnalystDefinitions?: ReadonlyArray<DefinedAnalystRecord>\n /** Product-selected tools already bound to this exact supervisor node. They share this server\n * with the coordination verbs, so the existing MCP duplicate-name guard applies before listen.\n * Each is served single-flight and fenced (`./single-flight-tools`): an identical call joins\n * the unreturned run, and a call still running at the fence returns a pending result. */\n nodeTools?: ReadonlyArray<McpToolDescriptor>\n /** Exact bare tool names to expose from the coordination and node-tool set. Runtime never\n * grants an implicit complete tool set. An unknown name fails before the listener opens. */\n toolNames: ReadonlyArray<string>\n /**\n * OPT-IN peer mail: let this manager's workers message each other directly, bounded and audited\n * (`runtime/supervise/peer-mail`). Each spawn receives a capability URL on\n * `WorkerSpawnContext.peerMailUrl`.\n *\n * It is a SEPARATE listener on its own port, not another tool on this server, and that is the\n * whole point: this server grants spawn_worker / steer_agent / stop to its manager, so a\n * worker handed its URL could send a REAL `[SUPERVISOR]` instruction to a sibling and the peer\n * channel's authority marking would mean nothing. The mail listener serves `send_mail` and\n * `read_mail` and no other verb, on a per-worker secret path bound to that worker's identity.\n *\n * The residual, stated plainly: the boundary is between AGENTS, not between processes. A worker\n * that can read another worker's environment or process memory still holds that worker's\n * capability. Loopback plus an unguessable path is what this layer can honestly enforce.\n */\n peerMail?: boolean | { limits?: Partial<PeerMailLimits> }\n /** OPT-IN async gate run before every spawn mints an assignment or reserves budget — the one\n * pre-journal point that may ask the backend a question. See\n * `CoordinationToolsOptions.preflightSpawn`. */\n preflightSpawn?: SpawnPreflight\n /** Pre-journal profile resolution for `preflightSpawn`; see\n * `CoordinationToolsOptions.resolveSpawnProfile`. */\n resolveSpawnProfile?: (profile: AgentProfile) => AgentProfile\n /** See `CoordinationToolsOptions.spawnResourceRoot`. */\n spawnResourceRoot?: string\n /** Called with this server's exact MCP tool descriptors once they exist and BEFORE the listener\n * opens — the seam a caller uses to give an already-bound node tool a way to call the same\n * verbs in code (`SupervisorToolInvocationContext.verbs`). */\n onCoordinationTools?: (tools: ReadonlyArray<McpToolDescriptor>) => void\n },\n): Promise<CoordinationMcpHandle> {\n const host = opts.host ?? '127.0.0.1'\n assertCoordinationTransport(opts)\n const requestTimeoutMs = coordinationHttpLimits(opts).requestTimeoutMs\n const responseFenceMs = coordinationResponseFenceMs(requestTimeoutMs)\n if (opts.peerMail && (!isLoopbackHost(host) || opts.publicUrl)) {\n throw new ConfigError(\n 'remote peer mail requires a separate reachable capability transport; coordination authentication does not authorize the peer listener',\n )\n }\n const identity = Object.freeze({\n ...(opts.identity ?? {\n runId: opts.scope.view?.root ?? '',\n actorId: opts.scope.view?.root ?? '',\n }),\n })\n if (\n (opts.authentication || opts.onAudit) &&\n (!identity.runId.trim() || !identity.actorId.trim())\n ) {\n throw new ConfigError('authenticated coordination requires a trusted run and actor identity')\n }\n const auth = typeof opts.authentication === 'object' ? opts.authentication : undefined\n const signingKeys = auth?.signingKeys\n ? { activeKeyId: auth.signingKeys.activeKeyId, keys: { ...auth.signingKeys.keys } }\n : undefined\n let token: Buffer | undefined\n let credentialExpiresAt: number | undefined\n let headers: Readonly<Record<string, string>> = Object.freeze({})\n let credentialAudience = ''\n let closed = false\n const revoked = new Map<string, number>()\n const grantDigest = createHash('sha256')\n .update(JSON.stringify([...opts.toolNames].sort()))\n .digest('hex')\n const rotateCredential = () => {\n if (!opts.authentication) throw new ConfigError('coordination authentication is not configured')\n if (closed) throw new ConfigError('coordination server is closed')\n for (const [credential, expiry] of revoked) {\n if (expiry <= Date.now()) revoked.delete(credential)\n }\n if (token) revoked.set(token.toString(), credentialExpiresAt!)\n credentialExpiresAt = Date.now() + (auth?.ttlMs ?? 900_000)\n const nonce = randomBytes(32).toString('base64url')\n let text = nonce\n if (signingKeys) {\n const payload = Buffer.from(\n JSON.stringify({\n key: signingKeys.activeKeyId,\n run: identity.runId,\n actor: identity.actorId,\n audience: credentialAudience,\n grants: grantDigest,\n expires: credentialExpiresAt,\n nonce,\n }),\n ).toString('base64url')\n const signature = createHmac('sha256', signingKeys.keys[signingKeys.activeKeyId]!)\n .update(payload)\n .digest('base64url')\n text = `${payload}.${signature}`\n }\n token = Buffer.from(text)\n headers = Object.freeze({ Authorization: `Bearer ${text}` })\n }\n const validCredential = (supplied: Buffer): boolean => {\n if (closed || revoked.has(supplied.toString())) return false\n if (!signingKeys)\n return (\n token !== undefined &&\n Date.now() < credentialExpiresAt! &&\n supplied.length === token.length &&\n timingSafeEqual(supplied, token)\n )\n if (supplied.length > 8192) return false\n try {\n const parts = supplied.toString().split('.')\n if (parts.length !== 2) return false\n const payload = parts[0]!\n const claims = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))\n if (!claims || typeof claims.key !== 'string' || !Object.hasOwn(signingKeys.keys, claims.key))\n return false\n const expected = createHmac('sha256', signingKeys.keys[claims.key]!).update(payload).digest()\n const signature = Buffer.from(parts[1]!, 'base64url')\n return (\n signature.length === expected.length &&\n timingSafeEqual(signature, expected) &&\n claims.run === identity.runId &&\n claims.actor === identity.actorId &&\n claims.audience === credentialAudience &&\n claims.grants === grantDigest &&\n Number.isSafeInteger(claims.expires) &&\n claims.expires > Date.now()\n )\n } catch {\n return false\n }\n }\n const audiences = new Set<string>()\n const paths = new Set(['/mcp'])\n const coord = createCoordinationTools({\n scope: opts.scope,\n blobs: opts.blobs,\n makeWorkerAgent: opts.makeWorkerAgent,\n ...(opts.authorizeDownMessage ? { authorizeDownMessage: opts.authorizeDownMessage } : {}),\n perWorker: opts.perWorker,\n ...(opts.deliverable ? { deliverable: opts.deliverable } : {}),\n ...(opts.onStop ? { onStop: opts.onStop } : {}),\n ...(opts.maxLiveWorkers !== undefined ? { maxLiveWorkers: opts.maxLiveWorkers } : {}),\n awaitTimeoutMs: opts.awaitTimeoutMs ?? responseFenceMs,\n ...(opts.analysts ? { analysts: opts.analysts } : {}),\n ...(opts.analyzeOnSettle ? { analyzeOnSettle: opts.analyzeOnSettle } : {}),\n ...(opts.watchWorkers ? { watchWorkers: opts.watchWorkers } : {}),\n ...(opts.stallAfterMs !== undefined ? { stallAfterMs: opts.stallAfterMs } : {}),\n ...(opts.continuityByProfile ? { continuityByProfile: opts.continuityByProfile } : {}),\n ...(opts.onEvent ? { onEvent: opts.onEvent } : {}),\n ...(opts.replaySettlements ? { replaySettlements: true } : {}),\n ...(opts.questionPolicy ? { questionPolicy: opts.questionPolicy } : {}),\n ...(opts.escalateQuestion ? { escalateQuestion: opts.escalateQuestion } : {}),\n ...(opts.priorEscalations?.length ? { priorEscalations: opts.priorEscalations } : {}),\n ...(opts.priorQuestions?.length ? { priorQuestions: opts.priorQuestions } : {}),\n ...(opts.priorJournal?.length ? { priorJournal: opts.priorJournal } : {}),\n ...(opts.priorAnalystDefinitions?.length\n ? { priorAnalystDefinitions: opts.priorAnalystDefinitions }\n : {}),\n ...(opts.preflightSpawn ? { preflightSpawn: opts.preflightSpawn } : {}),\n ...(opts.resolveSpawnProfile ? { resolveSpawnProfile: opts.resolveSpawnProfile } : {}),\n ...(opts.spawnResourceRoot ? { spawnResourceRoot: opts.spawnResourceRoot } : {}),\n ...(opts.peerMail\n ? {\n peerMail:\n typeof opts.peerMail === 'object' && opts.peerMail.limits\n ? { limits: opts.peerMail.limits }\n : {},\n }\n : {}),\n })\n await coord.ready()\n const reservedNames = new Set<string>(coord.tools.map((tool) => tool.name))\n for (const tool of opts.nodeTools ?? []) {\n if (reservedNames.has(tool.name)) {\n throw new ValidationError(\n `serveCoordinationMcp: node tool ${JSON.stringify(tool.name)} shadows a coordination verb or another node tool`,\n )\n }\n reservedNames.add(tool.name)\n }\n const nodeTools = singleFlightTools(opts.nodeTools ?? [], { fenceMs: responseFenceMs })\n const availableTools = [...coord.tools, ...nodeTools.tools]\n const availableByName = new Map(availableTools.map((tool) => [tool.name, tool]))\n if (!Array.isArray(opts.toolNames)) {\n throw new ValidationError(\n 'serveCoordinationMcp: toolNames must name every granted tool explicitly',\n )\n }\n const selectedNames = opts.toolNames\n if (new Set(selectedNames).size !== selectedNames.length) {\n throw new ValidationError('serveCoordinationMcp: toolNames contains a duplicate name')\n }\n const servedTools = selectedNames.map((name) => {\n const tool = availableByName.get(name)\n if (tool === undefined) {\n throw new ValidationError(\n `serveCoordinationMcp: requested tool ${JSON.stringify(name)} is unavailable`,\n )\n }\n return tool\n })\n const mcp = createStdioToolServer({\n serverName: 'coordination',\n serverVersion: '1',\n tools: servedTools,\n })\n // Before the listener opens: a node tool invoked on the first request must already be able to\n // call these verbs. Read back the server's ordered set so every consumer records the exact MCP\n // surface.\n opts.onCoordinationTools?.([...mcp.tools.values()])\n\n const server: Server = createServer(\n coordinationHttpHandler({\n options: opts,\n identity,\n toolNames: new Set(servedTools.map((tool) => tool.name)),\n handle: (message) => mcp.handle(message),\n backgroundActions: nodeTools.background,\n authorize: (req) => {\n if (!paths.has(req.url ?? '')) return 404\n // A proxy may use the destination IP as Host. A wildcard bind must\n // recognize its actual socket address without trusting forwarded names.\n const address = req.socket.localAddress?.replace(/^::ffff:/, '')\n const localAuthority = address?.includes(':')\n ? `[${address}]:${req.socket.localPort}`\n : `${address}:${req.socket.localPort}`\n const boundAuthority =\n audiences.size > 0 &&\n (host === '0.0.0.0' || host === '::') &&\n address !== undefined &&\n req.socket.localPort !== undefined &&\n req.headers.host === localAuthority\n if (!audiences.has(req.headers.host ?? '') && !boundAuthority) return 403\n if (closed) return 401\n if (!opts.authentication) return undefined\n const authorization = req.headers.authorization\n const supplied =\n typeof authorization === 'string' && authorization.startsWith('Bearer ')\n ? Buffer.from(authorization.slice(7))\n : Buffer.alloc(0)\n if (!validCredential(supplied)) return 401\n return undefined\n },\n }),\n )\n\n server.requestTimeout = requestTimeoutMs\n server.headersTimeout = requestTimeoutMs\n\n const port = await new Promise<number>((resolve, reject) => {\n server.once('error', reject)\n server.listen(opts.port ?? 0, host, () => {\n const addr = server.address()\n resolve(typeof addr === 'object' && addr ? addr.port : (opts.port ?? 0))\n })\n })\n\n const urlHost = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host\n const localUrl = `http://${urlHost}:${port}/mcp`\n let url: string\n try {\n const resolver = opts.publicUrl\n const configured =\n typeof resolver === 'function'\n ? await runAbortable(\n async () => resolver({ host, port, ...identity, signal: opts.scope.signal }),\n opts.scope.signal,\n 'coordination public address resolution aborted',\n )\n : resolver\n const publicAddress = new URL(configured ?? localUrl)\n if (\n !['http:', 'https:'].includes(publicAddress.protocol) ||\n publicAddress.username ||\n publicAddress.password ||\n publicAddress.search ||\n publicAddress.hash\n ) {\n throw new ConfigError(\n 'coordination publicUrl must be an HTTP endpoint without credentials, query, or fragment',\n )\n }\n if (\n configured !== undefined &&\n publicAddress.protocol !== 'https:' &&\n !isLoopbackHost(publicAddress.hostname)\n ) {\n throw new ConfigError('remote coordination publicUrl must use HTTPS')\n }\n url = publicAddress.href\n credentialAudience = url\n if (opts.authentication) rotateCredential()\n audiences.add(new URL(localUrl).host)\n audiences.add(publicAddress.host)\n if (host === '0.0.0.0' || host === '::') audiences.add(`127.0.0.1:${port}`)\n paths.add(publicAddress.pathname)\n } catch (error) {\n await new Promise<void>((resolve) => server.close(() => resolve()))\n throw error\n }\n\n const mailbox = coord.peerMail\n const mailListener = mailbox === undefined ? undefined : await servePeerMail(mailbox, host)\n\n return {\n url,\n port,\n get headers() {\n return headers\n },\n get credentialExpiresAt() {\n return credentialExpiresAt\n },\n rotateCredential,\n settled: () => coord.settled(),\n submittedResult: () => coord.submittedResult(),\n drainResolved: () => coord.drainResolved(),\n isStopped: () => coord.isStopped(),\n history: () => coord.history(),\n stats: () => coord.stats(),\n raiseFinding: (finding) => coord.raiseFinding(finding),\n mailHistory: () => mailbox?.history() ?? [],\n stopMailThread: (threadId) => mailbox?.stopThread(threadId) ?? false,\n close: async () => {\n closed = true\n await new Promise<void>((resolve) => {\n server.close(() => resolve())\n })\n await mailListener?.close()\n },\n }\n}\n\n/**\n * Stand up the peer-mail capability listener: one HTTP server, one secret path per worker, and on\n * each path a tool server carrying ONLY `send_mail` / `read_mail` with that worker's identity\n * closed over. An unknown path is a flat 404 — the path is the credential, so a request that does\n * not present a minted one is not a client to reason with.\n *\n * The host is the coordination host, which the caller has already had to justify: the loopback gate\n * above governs both listeners, and there is deliberately no way to bind mail somewhere else.\n */\nasync function servePeerMail(\n mailbox: NonNullable<CoordinationTools['peerMail']>,\n host: string,\n): Promise<{ close(): Promise<void> }> {\n const servers = new Map<string, StdioToolServer>()\n const forCapability = (capabilityId: string): StdioToolServer => {\n const existing = servers.get(capabilityId)\n if (existing) return existing\n const created = createStdioToolServer({\n serverName: 'peer-mail',\n serverVersion: '1',\n tools: mailbox.tools(capabilityId),\n })\n servers.set(capabilityId, created)\n return created\n }\n\n const listener: Server = createServer((req, res) => {\n const capabilityId = /^\\/mail\\/([0-9a-f]{32})$/.exec(req.url ?? '')?.[1]\n if (\n req.method !== 'POST' ||\n capabilityId === undefined ||\n !mailbox.hasCapability(capabilityId)\n ) {\n res.writeHead(404).end()\n return\n }\n let body = ''\n req.on('data', (chunk) => {\n body += chunk\n })\n req.on('end', () => {\n void (async () => {\n try {\n const message = JSON.parse(body) as JsonRpcMessage\n const response = await forCapability(capabilityId).handle(message)\n if (response === null) {\n res.writeHead(202).end() // a notification — no body\n return\n }\n res.writeHead(200, { 'content-type': 'application/json' })\n res.end(JSON.stringify(response))\n } catch (e) {\n res.writeHead(200, { 'content-type': 'application/json' })\n res.end(\n JSON.stringify({\n jsonrpc: '2.0',\n id: null,\n error: { code: -32700, message: e instanceof Error ? e.message : 'parse error' },\n }),\n )\n }\n })()\n })\n })\n\n const port = await new Promise<number>((resolve, reject) => {\n listener.once('error', reject)\n listener.listen(0, host, () => {\n const addr = listener.address()\n resolve(typeof addr === 'object' && addr ? addr.port : 0)\n })\n })\n // Only now is a capability URL a reachable address, so only now may one be minted.\n mailbox.setEndpoint(`http://${host}:${port}/mail`)\n return {\n close: () =>\n new Promise<void>((resolve) => {\n listener.close(() => resolve())\n }),\n }\n}\n","/**\n * Supervisor tree → OTLP spans. OPT-IN, off by default.\n *\n * WHY. A supervised tree is legible today only by parsing this package's own spawn journal, so\n * every other multi-agent shape on the machine (a coding-CLI's subagents, a pi fanout, ad-hoc tool\n * parallelism) needs its own bespoke reader. A span carrying `parent_span_id` IS a tree, and any\n * system can emit one — so emitting spans makes the supervisor readable by the same viewer as\n * everything else, with no per-system reader.\n *\n * WHAT IT IS NOT. This is telemetry, never the record of truth. The spawn journal remains the sole\n * durable ledger for replay/resume and for cost; nothing here is read back, and a run whose export\n * fails is unaffected in every observable way. The two data models are deliberately separate.\n *\n * HOW IT ATTACHES. This is a pure `RuntimeHooks` observer over the lifecycle events `Scope` ALREADY\n * emits — `agent.spawn` (a node opened), `agent.child` (a node settled), `agent.turn` (a driver\n * inference turn was metered). It adds no event, mutates no journal, and changes no result. Because\n * `Scope` re-seeds the same hooks into every nested scope (`makeNestedScopeSeam`), one observer sees\n * the WHOLE recursion at arbitrary depth.\n *\n * SPAN SHAPE. One span per supervised node, opened at spawn and closed at settle, parented to its\n * parent node's span; the run root is the trace. Driver inference rides as an `LLM` child span under\n * the node that metered it. Attributes reuse the vocabulary the rest of the stack already reads\n * (`openinference.span.kind`, `agent.name`, `llm.token_count.*`, `llm.cost_usd`, `tangle.cost.usd`)\n * — see `@tangle-network/agent-eval`'s `src/trace/attribute-vocabulary.ts`, which is the consumer.\n *\n * UNKNOWN IS NEVER ZERO. `Spend.tokensKnown === false` / `usdKnown === false` mark work that\n * HAPPENED with an unreported count. Those spans OMIT the token/cost attribute entirely and set\n * `tangle.supervise.tokens_known` / `tangle.supervise.cost_known` to `false`, so a reader can never\n * mistake an unmeasured turn for a free one.\n */\n\nimport { contentAddress } from '../../durable/spawn-journal'\nimport type { OtelExportConfig, OtelExporter, OtelSpan } from '../../otel-export'\nimport { createOtelExporter, generateSpanId, toOtelAttributes } from '../../otel-export'\nimport type { RuntimeHookEvent, RuntimeHooks } from '../../runtime-hooks'\nimport type { Budget, Spend, SupervisedResult } from './types'\nimport type { TraceContext, WorkerTraceResolver } from './worker-trace'\n\n/** OTEL status codes (`UNSET` / `OK` / `ERROR`) — the numeric wire values `OtelSpan.status` carries. */\nconst STATUS_UNSET = 0\nconst STATUS_OK = 1\nconst STATUS_ERROR = 2\n\n/** Longest string attribute value written from free-form detail, so an oversized turn payload\n * cannot inflate a span. Identity/label attributes we control are never truncated. */\nconst MAX_DETAIL_CHARS = 256\n\n/** OTLP span attribute values. Exported because `SupervisorSpanOptions.attributes` is public and\n * a consumer cannot name the type it is asked to supply otherwise. */\nexport type SupervisorSpanAttributes = Record<string, string | number | boolean>\n\ntype Attrs = SupervisorSpanAttributes\n\nexport interface SupervisorSpanOptions {\n /**\n * The supervised run id (`SupervisorOpts.runId`). Roots the trace, identifies the root span, and\n * is the parent lookup key for every depth-0 spawn (a root scope's `parentId` IS the run id).\n */\n readonly runId: string\n /**\n * Bring your own exporter. It is FLUSHED but never shut down by `finish()` — a caller that owns\n * the exporter owns its lifecycle. Takes precedence over `exportConfig`.\n */\n readonly exporter?: OtelExporter\n /**\n * Otherwise build one with {@link createOtelExporter}. With no `endpoint` here it reads\n * `OTEL_EXPORTER_OTLP_ENDPOINT`, and with neither it resolves to `undefined` — which makes\n * {@link createSupervisorSpanRecorder} return `undefined` and the run emit nothing.\n */\n readonly exportConfig?: OtelExportConfig\n /**\n * Trace id (32 hex chars). Pass the caller's own to JOIN an outer trace. Default: derived\n * deterministically from `runId`, so a resumed run lands in the SAME trace as the process that\n * started it.\n */\n readonly traceId?: string\n /** Parent span id (16 hex chars) to hang the run's root span under — an inherited delegation span. */\n readonly parentSpanId?: string\n /** `agent.name` on the root span. Default `'supervisor'`. */\n readonly agentName?: string\n /** Extra attributes stamped on every span this recorder emits (subject, workspace, campaign, …). */\n readonly attributes?: Attrs\n /** Injectable clock; used only for the root span's start/end. Default `Date.now`. */\n readonly now?: () => number\n}\n\n/** How the supervised run ended, as `finish()` records it on the root span. */\nexport interface SupervisorSpanOutcome {\n readonly result?: SupervisedResult<unknown>\n /** A rejection out of the run itself (the supervisor never resolved). */\n readonly error?: unknown\n}\n\nexport interface SupervisorSpanRecorder {\n /** Attach to `SupervisorOpts.hooks` (compose with a caller's own via `composeRuntimeHooks`). */\n readonly hooks: RuntimeHooks\n /** The trace every span of this run belongs to. */\n readonly traceId: string\n /** The run's root span id — pass it to a child process to join this trace. */\n readonly rootSpanId: string\n /**\n * The trace context a worker spawned BY node `spawningNodeId` should inherit, so its own spans\n * join THIS trace under the span of the node that spawned it. Thread it to a run as\n * `SupervisorOpts.workerTrace` (`supervise()` does this whenever it builds a recorder) and the\n * `Scope` seeds it onto every child's `ExecutorContext`; a backend with an environment channel\n * stamps it with `workerTraceEnv`. An unknown node — one whose span was never opened — resolves\n * to the run's root span rather than to nothing, so a worker is never filed outside its own run.\n */\n readonly workerTrace: WorkerTraceResolver\n /**\n * Close the root span (and any node that never settled, marked as such), export, and flush. Safe\n * to call twice; never throws — a telemetry failure is not a run failure.\n */\n finish(outcome?: SupervisorSpanOutcome): Promise<void>\n}\n\n/** A node span held open between its `agent.spawn` and its `agent.child`. */\ninterface OpenNode {\n readonly spanId: string\n readonly parentSpanId: string\n readonly name: string\n readonly startMs: number\n readonly attrs: Attrs\n}\n\n/**\n * Build the span recorder for one supervised run, or `undefined` when no exporter resolves — the\n * off-by-default path. A run that passes no `exporter` and no `exportConfig` never reaches this\n * function at all; one that passes an `exportConfig` with no endpoint (and no env endpoint) gets\n * `undefined` here, so \"configured but unreachable\" also costs nothing.\n */\nexport function createSupervisorSpanRecorder(\n opts: SupervisorSpanOptions,\n): SupervisorSpanRecorder | undefined {\n const exporter = opts.exporter ?? createOtelExporter(opts.exportConfig)\n if (!exporter) return undefined\n // Only an exporter we built is ours to shut down.\n const ownsExporter = opts.exporter === undefined\n\n const now = opts.now ?? Date.now\n const traceId = normalizeTraceId(opts.traceId, opts.runId)\n const rootSpanId = generateSpanId()\n const rootStartMs = now()\n const base: Attrs = {\n 'tangle.run.id': opts.runId,\n // The sample vocabulary our own OTLP producers already emit; kept so one reader groups a\n // supervised run with a pi/coding-CLI session without a per-producer special case.\n 'tangle.sessionId': opts.runId,\n ...(opts.attributes ?? {}),\n }\n\n /** Node id → its open span. Seeded with the run id ⇒ the root span, because a depth-0 spawn's\n * `parentId` is the run id itself and every deeper spawn's is a real node id. */\n const open = new Map<string, OpenNode>()\n const spanIdOf = new Map<string, string>([[opts.runId, rootSpanId]])\n let finished = false\n\n /** Every export is best-effort: a throwing exporter must never reach the run. */\n const emit = (span: OtelSpan): void => {\n try {\n exporter.exportSpan(span)\n } catch {\n // Telemetry is not the work.\n }\n }\n\n const span = (\n spanId: string,\n parentSpanId: string | undefined,\n name: string,\n startMs: number,\n endMs: number,\n attrs: Attrs,\n status: number,\n message?: string,\n ): OtelSpan => ({\n traceId,\n spanId,\n ...(parentSpanId ? { parentSpanId } : {}),\n name,\n kind: 1,\n startTimeUnixNano: msToNano(startMs),\n endTimeUnixNano: msToNano(Math.max(startMs, endMs)),\n attributes: toOtelAttributes(attrs),\n status: { code: status, ...(message ? { message } : {}) },\n })\n\n function onSpawn(event: RuntimeHookEvent): void {\n const p = record(event.payload)\n const childId = str(p.childId)\n if (!childId) return\n const label = str(p.label) ?? 'node'\n const runtime = str(p.runtime)\n const isWait = runtime === 'wait'\n const attrs: Attrs = {\n ...base,\n // A wait-state node holds no executor and burns nothing; `CHAIN` keeps a token/cost reader\n // from counting it as an agent that reported nothing.\n 'openinference.span.kind': isWait ? 'CHAIN' : 'AGENT',\n 'agent.name': label,\n 'tangle.supervise.node.id': childId,\n 'tangle.supervise.node.label': label,\n 'tangle.supervise.node.kind': isWait ? 'wait' : 'agent',\n // The journal tree this node lives in: a nested driver subtree gets its own tree key, which\n // is what joins a span back to the journal rows that prove its spend.\n 'tangle.supervise.tree.root': event.runId,\n }\n if (event.parentId) attrs['tangle.supervise.node.parent_id'] = event.parentId\n if (runtime) attrs['tangle.supervise.node.runtime'] = runtime\n if (typeof p.depth === 'number') attrs['tangle.supervise.node.depth'] = p.depth\n if (typeof event.stepIndex === 'number')\n attrs['tangle.supervise.node.ordinal'] = event.stepIndex\n if (p.resumed === true) attrs['tangle.supervise.node.resumed'] = true\n assignBudget(attrs, p.budget)\n\n const spanId = generateSpanId()\n spanIdOf.set(childId, spanId)\n open.set(childId, {\n spanId,\n parentSpanId: (event.parentId && spanIdOf.get(event.parentId)) || rootSpanId,\n name: label,\n startMs: event.timestamp,\n attrs,\n })\n }\n\n function onSettled(event: RuntimeHookEvent): void {\n const p = record(event.payload)\n const childId = str(p.childId)\n if (!childId) return\n const node = open.get(childId)\n if (!node) return\n open.delete(childId)\n\n const status = str(p.status)\n const down = status === 'down'\n const attrs: Attrs = { ...node.attrs, 'tangle.supervise.node.status': status ?? 'done' }\n if (typeof event.stepIndex === 'number') attrs['tangle.supervise.node.seq'] = event.stepIndex\n if (typeof p.outRef === 'string') attrs['tangle.supervise.node.out_ref'] = p.outRef\n if (typeof p.valid === 'boolean') attrs['tangle.supervise.verdict.valid'] = p.valid\n if (typeof p.score === 'number') attrs['tangle.supervise.verdict.score'] = p.score\n if (down) {\n attrs['error.type'] = p.infra === true ? 'infra' : 'child-down'\n const reason = str(p.reason)\n if (reason) attrs['error.message'] = truncate(reason)\n if (typeof p.infra === 'boolean') attrs['tangle.supervise.node.infra'] = p.infra\n }\n // A wait node settles with its outcome instead of a spend — free by construction, not by\n // measurement, so it carries no token or cost attribute at all.\n const wait = record(p.wait)\n const wokeBy = str(wait.settled)\n if (wokeBy) attrs['tangle.supervise.wait.settled'] = wokeBy\n assignSpend(attrs, p.spent)\n\n emit(\n span(\n node.spanId,\n node.parentSpanId,\n node.name,\n node.startMs,\n event.timestamp,\n attrs,\n down ? STATUS_ERROR : STATUS_OK,\n down ? (str(p.reason) ?? 'child down') : undefined,\n ),\n )\n }\n\n function onTurn(event: RuntimeHookEvent): void {\n const p = record(event.payload)\n const parentId = event.parentId\n const parentSpanId = (parentId && spanIdOf.get(parentId)) || rootSpanId\n const attrs: Attrs = {\n ...base,\n 'openinference.span.kind': 'LLM',\n 'inference.observation_kind': 'LLM',\n 'tangle.supervise.node.kind': 'inference',\n }\n if (parentId) attrs['tangle.supervise.node.id'] = parentId\n // Free-form `Scope.meter` detail: named keys get the canonical attribute, the rest ride\n // namespaced and bounded so a caller's extra context survives without unbounded span growth.\n for (const [key, value] of Object.entries(p)) {\n if (key === 'spend') continue\n if (key === 'driver' && typeof value === 'string') {\n attrs['agent.name'] = value\n attrs['inference.agent_name'] = value\n continue\n }\n if (key === 'model' && typeof value === 'string') {\n attrs['llm.model_name'] = value\n continue\n }\n if (Array.isArray(value)) {\n const scalars = value.filter((v) => typeof v === 'string' || typeof v === 'number')\n if (scalars.length > 0) {\n attrs[`tangle.supervise.turn.${key}`] = truncate(scalars.join(','))\n }\n continue\n }\n if (typeof value === 'string') attrs[`tangle.supervise.turn.${key}`] = truncate(value)\n else if (typeof value === 'number' || typeof value === 'boolean') {\n attrs[`tangle.supervise.turn.${key}`] = value\n }\n }\n const spend = assignSpend(attrs, p.spend)\n const endMs = event.timestamp + (spend?.ms ?? 0)\n emit(\n span(\n generateSpanId(),\n parentSpanId,\n 'gen_ai.client.inference',\n event.timestamp,\n endMs,\n attrs,\n STATUS_OK,\n ),\n )\n }\n\n const hooks: RuntimeHooks = {\n onEvent(event) {\n if (finished) return\n try {\n if (event.phase !== 'after') return\n if (event.target === 'agent.spawn') onSpawn(event)\n else if (event.target === 'agent.child') onSettled(event)\n else if (event.target === 'agent.turn') onTurn(event)\n } catch {\n // A malformed payload or a broken exporter is a telemetry defect, never a run failure.\n // `notifyRuntimeHookEvent` would already contain a throw; this makes it true regardless of\n // who calls the hook.\n }\n },\n }\n\n return {\n hooks,\n traceId,\n rootSpanId,\n workerTrace(spawningNodeId: string): TraceContext {\n return { traceId, parentSpanId: spanIdOf.get(spawningNodeId) ?? rootSpanId }\n },\n async finish(outcome?: SupervisorSpanOutcome): Promise<void> {\n if (finished) return\n finished = true\n const endMs = now()\n try {\n // A node still open here never settled — the run was aborted, cancelled, or died with it in\n // flight. Its span is closed UNSET and explicitly marked, never silently dropped and never\n // reported as a clean finish.\n for (const [nodeId, node] of open) {\n emit(\n span(\n node.spanId,\n node.parentSpanId,\n node.name,\n node.startMs,\n endMs,\n {\n ...node.attrs,\n 'tangle.supervise.node.status': 'unsettled',\n 'tangle.supervise.node.settled': false,\n 'tangle.supervise.node.id': nodeId,\n },\n STATUS_UNSET,\n ),\n )\n }\n open.clear()\n emit(\n span(\n rootSpanId,\n opts.parentSpanId,\n 'supervisor.run',\n rootStartMs,\n endMs,\n rootAttrs(base, opts.agentName ?? 'supervisor', outcome),\n rootStatus(outcome),\n rootMessage(outcome),\n ),\n )\n await exporter.flush()\n if (ownsExporter) await exporter.shutdown()\n } catch {\n // Telemetry is not the work.\n }\n },\n }\n}\n\n// ── Attribute mapping ─────────────────────────────────────────────────────────\n\nfunction rootAttrs(base: Attrs, agentName: string, outcome?: SupervisorSpanOutcome): Attrs {\n const attrs: Attrs = {\n ...base,\n 'openinference.span.kind': 'AGENT',\n 'inference.observation_kind': 'AGENT',\n 'agent.name': agentName,\n 'inference.agent_name': agentName,\n 'tangle.supervise.node.kind': 'root',\n }\n const result = outcome?.result\n if (result) {\n attrs['tangle.supervise.result'] = result.kind\n if (result.kind === 'no-winner') {\n attrs['tangle.supervise.reason'] = result.reason\n attrs['tangle.supervise.down_count'] = result.downCount\n if (result.reason === 'driver-failed') {\n attrs['error.type'] = result.error.name\n attrs['error.message'] = truncate(result.error.message)\n }\n }\n assignSpend(attrs, result.spentTotal)\n }\n if (outcome?.error !== undefined) {\n attrs['tangle.supervise.result'] = 'error'\n const err = outcome.error\n attrs['error.type'] = err instanceof Error ? err.name : typeof err\n attrs['error.message'] = truncate(err instanceof Error ? err.message : String(err))\n }\n return attrs\n}\n\nfunction rootStatus(outcome?: SupervisorSpanOutcome): number {\n if (outcome?.error !== undefined) return STATUS_ERROR\n if (!outcome?.result) return STATUS_UNSET\n return outcome.result.kind === 'winner' ? STATUS_OK : STATUS_ERROR\n}\n\nfunction rootMessage(outcome?: SupervisorSpanOutcome): string | undefined {\n if (outcome?.error !== undefined) {\n return truncate(outcome.error instanceof Error ? outcome.error.message : String(outcome.error))\n }\n const result = outcome?.result\n return result && result.kind === 'no-winner' ? result.reason : undefined\n}\n\n/**\n * Write a `Spend` onto a span, honouring the \"a missing measurement is never zero\" invariant: a\n * channel marked NOT known contributes no number at all and instead flags itself, so nothing\n * downstream can sum an unmeasured turn as free. Returns the spend it read (for the duration).\n */\nfunction assignSpend(attrs: Attrs, value: unknown): Spend | undefined {\n if (!isRecord(value)) return undefined\n const spend = value as unknown as Spend\n const tokens = isRecord(spend.tokens) ? spend.tokens : undefined\n if (spend.tokensKnown === false) {\n attrs['tangle.supervise.tokens_known'] = false\n } else if (tokens) {\n if (typeof tokens.input === 'number') attrs['llm.token_count.prompt'] = tokens.input\n if (typeof tokens.output === 'number') attrs['llm.token_count.completion'] = tokens.output\n }\n if (spend.usdKnown === false) {\n attrs['tangle.supervise.cost_known'] = false\n } else if (typeof spend.usd === 'number' && Number.isFinite(spend.usd)) {\n attrs['llm.cost_usd'] = spend.usd\n attrs['tangle.cost.usd'] = spend.usd\n }\n if (typeof spend.iterations === 'number') attrs['tangle.supervise.iterations'] = spend.iterations\n if (typeof spend.ms === 'number' && spend.ms > 0) attrs['tangle.supervise.duration_ms'] = spend.ms\n // The platform channel travels with its provenance, so a span never presents a derived box time\n // as a platform receipt. An absent number emits no attribute at all rather than a zero.\n if (typeof spend.boxMinutes === 'number' && Number.isFinite(spend.boxMinutes)) {\n attrs['tangle.platform.box_minutes'] = spend.boxMinutes\n }\n if (spend.boxMinutesProvenance !== undefined) {\n attrs['tangle.platform.box_minutes_provenance'] = spend.boxMinutesProvenance\n attrs['tangle.platform.box_minutes_known'] = spend.boxMinutesKnown === true\n }\n // Absent means the executor's live stream carried the counters, so no attribute is emitted for\n // it: a span states only that the receipt came from somewhere else.\n if (spend.tokensProvenance !== undefined) {\n attrs['tangle.supervise.tokens_provenance'] = spend.tokensProvenance\n }\n return spend\n}\n\nfunction assignBudget(attrs: Attrs, value: unknown): void {\n if (!isRecord(value)) return\n const budget = value as unknown as Budget\n if (typeof budget.maxTokens === 'number') {\n attrs['tangle.supervise.budget.max_tokens'] = budget.maxTokens\n }\n if (typeof budget.maxIterations === 'number') {\n attrs['tangle.supervise.budget.max_iterations'] = budget.maxIterations\n }\n if (typeof budget.maxUsd === 'number') attrs['tangle.supervise.budget.max_usd'] = budget.maxUsd\n}\n\n// ── Small helpers ─────────────────────────────────────────────────────────────\n\n/**\n * A trace id must be 32 hex characters. A caller-supplied one is used verbatim when it already is;\n * anything else (and the default) is DERIVED from the run id by content address — deterministic, so\n * a resumed run rejoins the trace its first process opened rather than forking a new one.\n */\nfunction normalizeTraceId(traceId: string | undefined, runId: string): string {\n if (traceId && /^[0-9a-f]{32}$/i.test(traceId)) return traceId.toLowerCase()\n return contentAddress(traceId ?? runId).slice('sha256:'.length, 'sha256:'.length + 32)\n}\n\nfunction msToNano(ms: number): string {\n const safe = Number.isFinite(ms) ? Math.floor(ms) : 0\n return (BigInt(safe) * 1_000_000n).toString()\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n return isRecord(value) ? value : {}\n}\n\nfunction str(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nfunction truncate(value: string): string {\n return value.length > MAX_DETAIL_CHARS ? `${value.slice(0, MAX_DETAIL_CHARS)}…` : value\n}\n","/**\n * `supervisorAgent` — build a supervisor `Agent` FROM its profile. The brain is resolved from\n * `profile.harness` exactly as `createExecutor({ backend })` resolves a worker: backend-as-data,\n * no hand-built brain. The supervisor stops being special — it's one profile, materialized by the\n * same resolution rule as every other agent.\n *\n * - `harness` omitted or `cli-base` → the in-process router tool-loop: `driverAgent` over the\n * canonical `ToolLoopChat`, built by `routerBrain` from the profile's model + the router seam.\n * - `harness` a coding CLI (`claude-code`/`opencode`/`codex`/…) → an EXTERNAL harness drives the\n * coordination verbs: `serveCoordinationMcp` exposes spawn/await/steer/stop over the live scope,\n * and the caller's `driveHarness` runs the harness with that MCP mounted. `supervise()` builds\n * this automatically only for a local bridge; a remote sandbox needs an explicit reachable\n * relay or tunnel. The harness IS the brain.\n *\n * Both arms spawn children through the SAME `makeWorkerAgent` seam and apply the SAME independent\n * deliverable check to direct submissions. Raw driver prose is never eligible.\n */\nimport {\n type AgentProfile,\n type AgentProfileResources,\n agentProfileSchema,\n} from '@tangle-network/agent-interface'\nimport { ConfigError, ValidationError } from '../../errors'\nimport type { McpToolDescriptor } from '../../mcp/server'\nimport type {\n AnalystRegistry,\n AnalyzeOnSettleRoute,\n AuthorizeDownMessage,\n ContinuityMode,\n CoordinationEvent,\n EscalateQuestion,\n MakeWorkerAgent,\n SpawnPreflight,\n WorkerWatchOptions,\n} from '../../mcp/tools/coordination'\nimport { coordinationVerbNames } from '../../mcp/tools/coordination'\nimport { agentHarness } from '../harness-role'\nimport { type RouterTransportConfig, routerBrain } from '../router-client'\nimport type { ToolLoopChat, ToolLoopCompactionOptions } from '../tool-loop'\nimport type { DeliverableSpec } from './completion-gate'\nimport { driverAgent } from './coordination-driver'\nimport type { PriorCoordination } from './coordination-log'\nimport {\n assertCoordinationTransport,\n type CoordinationTransportOptions,\n serveCoordinationMcp,\n} from './coordination-mcp'\nimport {\n type DriverAttemptRecord,\n type DriverProgressMark,\n type DriverRetryPolicy,\n defaultUnmetContractSteer,\n type OnUnmetContract,\n runDriverWithRetry,\n} from './driver-retry'\nimport type { BusRecord } from './event-bus'\nimport { bestDelivered, runFinalizer, runTree, type SupervisorFinalizer } from './finalizer'\nimport { createInbox } from './inbox'\nimport { attestRuntimeOwnedScopeOwner, runtimeOwnedScopeOwnerRuntime } from './materialization'\nimport {\n assertExecutableAgentProfile,\n concreteProfileModel,\n enforceTokenLimits,\n profileModelExecutionSettings,\n} from './model-policy'\nimport type { PeerMailLimits } from './peer-mail'\nimport type { ExecutorProgress } from './progress'\nimport { applyRunCancellation } from './run-cancellation'\nimport { beginScopeOwnerAttempt } from './scope'\nimport { detachedSnapshot } from './snapshot'\nimport {\n createProgressTracker,\n progressStop,\n type SettledLedger,\n type StopRule,\n} from './stop-rules'\nimport type { TraceSource } from './trace-source'\nimport type { Agent, Budget, NodeExecutionIdentity, ResultBlobStore, Scope } from './types'\n\n/** Runtime-owned coordination is mounted under this MCP alias. */\nexport const coordinationMcpAlias = 'agent-runtime-coordination'\n\n/** A profile declares Runtime-owned tools with this provider-neutral prefix. */\nexport const coordinationProfileToolPrefix = `${coordinationMcpAlias.replaceAll('-', '_')}_`\n\nconst coordinationVerbNameSet = new Set<string>(coordinationVerbNames)\n\n/** Bare Runtime tool names explicitly enabled by one exact profile. */\nexport function declaredRuntimeToolNames(profile: AgentProfile): ReadonlyArray<string> {\n const names = Object.entries(profile.tools ?? {})\n .filter(([name, enabled]) => enabled === true && name.startsWith(coordinationProfileToolPrefix))\n .map(([name]) => name.slice(coordinationProfileToolPrefix.length))\n // Tool maps are sets in AgentProfile. Normalize their order before a provider sees a tool list or\n // Runtime records an attachment, so equivalent authored maps cannot change model behavior.\n return Object.freeze([...new Set(names)].sort())\n}\n\n/** Describe Runtime declarations that cannot resolve without a product tool provider. */\nexport function runtimeToolDeclarationError(\n profile: AgentProfile,\n hasProductToolResolver: boolean,\n mountedStaticToolNames: ReadonlyArray<string> = [],\n): string | undefined {\n const mountedStaticToolNameSet = new Set(mountedStaticToolNames)\n const unresolved = declaredRuntimeToolNames(profile).filter(\n (name) =>\n !coordinationVerbNameSet.has(name) &&\n !hasProductToolResolver &&\n !mountedStaticToolNameSet.has(name),\n )\n if (unresolved.length === 0) return undefined\n return `the profile declares ${unresolved\n .map((name) => JSON.stringify(`${coordinationProfileToolPrefix}${name}`))\n .join(\n ', ',\n )}, but this run has no resolveSupervisorTools provider or router-mounted static tool for those tools`\n}\n\n/** Runtime owns this attachment alias. An authored entry would make the provider mount ambiguous. */\nexport function assertNoReservedCoordinationMcpAlias(profile: AgentProfile, context: string): void {\n if (profile.mcp?.[coordinationMcpAlias] === undefined) return\n throw new ValidationError(\n `${context}: profile MCP alias ${JSON.stringify(coordinationMcpAlias)} is reserved for Runtime coordination`,\n )\n}\n\n/**\n * Project one canonical profile to the profile a provider may receive.\n *\n * The reserved prefix is Runtime-owned in its entirety. A `true` declaration must resolve to a\n * mounted Runtime or product descriptor before execution; a `false` declaration grants nothing.\n * Neither is a provider-native tool. Stripping the whole namespace keeps a false or refused grant\n * from becoming an invented harness capability during strict materialization.\n */\nexport function providerVisibleProfile(profile: AgentProfile): AgentProfile {\n if (profile.tools === undefined) return profile\n const providerTools = Object.fromEntries(\n Object.entries(profile.tools).filter(\n ([name]) => !name.startsWith(coordinationProfileToolPrefix),\n ),\n )\n if (Object.keys(providerTools).length === Object.keys(profile.tools).length) return profile\n if (Object.keys(providerTools).length > 0) return { ...profile, tools: providerTools }\n const { tools: _runtimeTools, ...withoutTools } = profile\n return withoutTools\n}\n\n/** A supervisor is an exact canonical AgentProfile; no looser model/prompt shape exists. */\nexport type SupervisorProfile = AgentProfile\n\n/** The exact profile fields consumed by supervisor materialization. */\nexport interface ResolvedSupervisorProfile {\n readonly name: string\n readonly harness: string | null\n readonly modelId: string\n readonly systemPrompt?: string\n}\n\n/**\n * The instruction lines a canonical `resources.instructions` contributes. A plain string and an\n * `inline` resource are their own text; a `github` reference names bytes that live elsewhere and\n * cannot be fetched while building a supervisor synchronously — that fails loud rather than\n * dropping instructions the profile says the agent runs under (the same rule\n * `improve()`'s memory surface applies to the same field).\n */\nfunction resourceInstructionLines(\n instructions: AgentProfileResources['instructions'],\n): readonly string[] {\n if (instructions === undefined) return []\n if (typeof instructions === 'string') return instructions.length > 0 ? [instructions] : []\n if (instructions.kind === 'inline') {\n return instructions.content.length > 0 ? [instructions.content] : []\n }\n throw new ConfigError(\n 'supervisorAgent: profile.resources.instructions is a github resource reference ' +\n `(${JSON.stringify(instructions.path)}), which cannot be fetched while the supervisor is ` +\n 'built — pass the instruction text as a string or an inline resource',\n )\n}\n\n/**\n * Refuse a best-effort resource policy on the router arm.\n *\n * The router arm inlines `resources.instructions` into the standing prompt and has no channel that\n * could report a resource it skipped. `resources.failOnError: false` asks for the supported subset\n * plus a warning about the rest, so this arm cannot honor it. Running such a profile as strict\n * would apply a policy the profile did not ask for, which is the silent drop the materialization\n * contract exists to prevent.\n */\nfunction assertRouterArmResourcePolicy(profile: SupervisorProfile): void {\n if (profile.resources?.failOnError !== false) return\n throw new ConfigError(\n 'supervisorAgent: resources.failOnError: false requests a best-effort resource subset; the ' +\n 'router-brained supervisor inlines its resources and reports no skipped resource, so the ' +\n 'best-effort policy is refused rather than applied as strict',\n )\n}\n\n/**\n * The standing instruction both arms run under: `prompt.systemPrompt`, then canonical prompt and\n * resource instruction lines.\n * `undefined` only when the profile names none at all.\n */\nfunction resolveSupervisorSystemPrompt(profile: SupervisorProfile): string | undefined {\n const promptSystem = profile.prompt?.systemPrompt\n const lines = [\n ...(profile.prompt?.instructions ?? []),\n ...resourceInstructionLines(profile.resources?.instructions),\n ]\n if (lines.length === 0) return promptSystem\n return (promptSystem !== undefined ? [promptSystem, ...lines] : lines).join('\\n')\n}\n\n/** Resolve the model after refusing any incomplete execution identity. */\nexport function resolveSupervisorModelId(profile: SupervisorProfile): string {\n assertExecutableAgentProfile(profile, 'supervisorAgent')\n return concreteProfileModel(profile)!\n}\n\n/**\n * Reduce one canonical executable profile to the scalars the two brain arms consume.\n */\nexport function resolveSupervisorProfile(profile: SupervisorProfile): ResolvedSupervisorProfile {\n const exact = agentProfileSchema.parse(profile)\n assertExecutableAgentProfile(exact, 'resolveSupervisorProfile')\n const systemPrompt = resolveSupervisorSystemPrompt(exact)\n const modelId = resolveSupervisorModelId(exact)\n return {\n name: exact.name ?? 'supervisor',\n harness: agentHarness(exact.harness) ?? null,\n modelId,\n ...(systemPrompt !== undefined ? { systemPrompt } : {}),\n }\n}\n\n/** Listener, authenticated remote endpoint, and bounded request policy for one manager. */\nexport type CoordinationBinding = CoordinationTransportOptions\n\n/** Validate a manager's coordination authentication and request limits before execution. */\nexport function assertCoordinationBinding(binding: CoordinationBinding | undefined): void {\n assertCoordinationTransport(binding ?? {})\n}\n\n/** Trusted run/node identity Runtime binds to one manager. Model-authored tool arguments cannot\n * provide or replace any of these fields. */\nexport interface SupervisorNodeContext {\n readonly runId: string\n /** Stable across a durable restart; unique per in-memory invocation. */\n readonly runNamespace: string\n /** Concrete Scope node that owns this manager's coordination stream. */\n readonly nodeId: string\n /** Stable identity of this manager's coordination stream. */\n readonly ownerId: string\n readonly depth: number\n readonly identity: NodeExecutionIdentity\n /** Assignment identity within the parent manager; absent only for the root. */\n readonly assignmentId?: string\n readonly profile: SupervisorProfile\n readonly task: unknown\n}\n\n/** Context known before `Agent.act`; Runtime adds the concrete node, profile, and task. */\nexport type SupervisorNodeContextSeed = Omit<SupervisorNodeContext, 'nodeId' | 'profile' | 'task'>\n\n/**\n * The coordination verbs THIS manager serves, callable in code from a product tool handler.\n *\n * Each verb dispatches by name to the live coordination descriptor's own handler, so a spawn made\n * here crosses the identical path the MCP verb crosses: `makeWorkerAgent` → `authorizeSpawn` /\n * security / `allowedModels`, the conserved pool reservation, `maxLiveWorkers`, the journal, and\n * the event bus. There is no second spawn path and no way to bypass a gate by calling in code.\n *\n * The set is deliberately the COORDINATION surface only. `submit_result`, `stop`, and `ask_parent`\n * are the manager's own lifecycle verbs — a product tool that could settle the run or answer as\n * the manager would be a second brain, not a composition surface.\n *\n * Arguments and results are the same JSON shapes the MCP tools take and return.\n */\nexport interface CoordinationVerbs {\n spawnAgent(args: unknown): Promise<unknown>\n awaitEvent(args: unknown): Promise<unknown>\n steerAgent(args: unknown): Promise<unknown>\n observeAgent(args: unknown): Promise<unknown>\n listQuestions(args: unknown): Promise<unknown>\n answerQuestion(args: unknown): Promise<unknown>\n runAnalyst(args: unknown): Promise<unknown>\n /** This manager's OWN coordination journal, paged and redacted. A read, so a program may consult\n * what it already did without spending a model turn on it. */\n readJournal(args: unknown): Promise<unknown>\n /** Define a new trace-analyst lens for this run. Composition, not lifecycle: a program may define\n * a lens and run it over the children it just joined, inside one model turn. */\n defineAnalyst(args: unknown): Promise<unknown>\n}\n\n/** Trusted context for one product-tool invocation. The node identity remains the same detached,\n * immutable snapshot supplied to the resolver; `signal` and `verbs` are the live control\n * references Runtime adds. `signal` aborts when this manager's scope is cancelled by the caller,\n * RootHandle, deadline, breaker, or a recursive parent; `verbs` composes THIS manager's children\n * in code (see {@link CoordinationVerbs}). */\nexport interface SupervisorToolInvocationContext extends SupervisorNodeContext {\n readonly signal: AbortSignal\n readonly verbs: CoordinationVerbs\n /** The static face (name / description / inputSchema) of every coordination tool mounted on\n * THIS manager — the same objects that define the tools, so a product surface rendered from\n * them (code mode's `search`) can never drift from the grant. Late-bound like `verbs`: a call\n * before the coordination tools exist throws instead of answering an empty grant. */\n readonly coordinationTools: () => ReadonlyArray<CoordinationToolFace>\n}\n\n/** One mounted coordination tool's static face; the handler is deliberately absent. */\nexport interface CoordinationToolFace {\n readonly name: string\n readonly description?: string\n readonly inputSchema?: unknown\n}\n\n/**\n * The late binding behind `context.verbs`.\n *\n * Product tools are resolved and bound BEFORE the coordination tools exist on both arms (the\n * external arm serves them from `serveCoordinationMcp`, the router arm builds them inside\n * `driverAgent.act`). So the slot is created first, handed to the tool handlers, and filled the\n * moment the coordination descriptors are built. A verb called before the fill throws instead of\n * silently doing nothing.\n */\ninterface VerbSlot {\n readonly verbs: CoordinationVerbs\n readonly descriptors: () => ReadonlyArray<Omit<McpToolDescriptor, 'handler'>>\n bind(tools: ReadonlyArray<McpToolDescriptor>): void\n}\n\nfunction createVerbSlot(): VerbSlot {\n let bound: ReadonlyArray<McpToolDescriptor> | undefined\n const verb =\n (name: string) =>\n async (args: unknown): Promise<unknown> => {\n if (bound === undefined) {\n throw new ValidationError(\n `supervisorAgent: coordination verb \"${name}\" was called before this manager's coordination tools were bound`,\n )\n }\n const tool = bound.find((descriptor) => descriptor.name === name)\n if (tool === undefined) {\n throw new ValidationError(\n `supervisorAgent: coordination verb \"${name}\" is not mounted on this manager`,\n )\n }\n return tool.handler(args)\n }\n return {\n verbs: Object.freeze({\n spawnAgent: verb('spawn_worker'),\n awaitEvent: verb('await_event'),\n steerAgent: verb('steer_agent'),\n observeAgent: verb('observe_agent'),\n listQuestions: verb('list_questions'),\n answerQuestion: verb('answer_question'),\n runAnalyst: verb('run_analyst'),\n readJournal: verb('read_journal'),\n defineAnalyst: verb('define_analyst'),\n }),\n descriptors(): ReadonlyArray<Omit<McpToolDescriptor, 'handler'>> {\n if (bound === undefined) {\n throw new ValidationError(\n \"supervisorAgent: coordinationTools() was called before this manager's coordination tools were bound\",\n )\n }\n return Object.freeze(\n bound.map(({ name, description, inputSchema }) =>\n Object.freeze({ name, description, inputSchema }),\n ),\n )\n },\n bind(tools): void {\n bound = tools\n },\n }\n}\n\n/** One product-owned tool. It reuses the canonical MCP descriptor fields while Runtime supplies\n * the trusted invocation context as a separate argument and binds the result for either\n * transport. Existing handlers remain compatible: the second argument only gains `signal`. */\nexport interface SupervisorToolDescriptor extends Omit<McpToolDescriptor, 'handler'> {\n readonly handler: (raw: unknown, context: SupervisorToolInvocationContext) => Promise<unknown>\n}\n\n/** Product policy for the tools one exact supervisor node may call. Resolved once per node. */\nexport type ResolveSupervisorTools = (\n context: SupervisorNodeContext,\n) => ReadonlyArray<SupervisorToolDescriptor> | Promise<ReadonlyArray<SupervisorToolDescriptor>>\n\n/** Context-aware observer used internally to bind product transactions to the actual live node. */\nexport type ObserveSupervisorNodeEvent = (\n context: SupervisorNodeContext,\n event: CoordinationEvent,\n record: BusRecord<CoordinationEvent>,\n) => void | Promise<void>\n\n/** How to run an external harness as the DRIVER, with the coordination verbs mounted — the substrate\n * seam the caller supplies (mirrors `makeWorkerAgent` for spawned children). It runs `profile` on\n * `task` in its backend (remote sandbox or local CLI bridge) with `coordinationMcpUrl` mounted as an MCP server,\n * so the harness calls spawn_worker / await_event / stop as native tools over the live scope. */\nexport interface DriveHarness {\n (args: {\n /** The exact provider-visible projection. Runtime-owned coordination tool declarations are\n * removed only when their descriptors are actually mounted; send this profile to the provider. */\n readonly profile: SupervisorProfile\n /** The immutable canonical profile Runtime admitted. Use it only to bind receipts or audit\n * authority; never send it to a provider, because it contains Runtime-owned declarations. */\n readonly authoredProfile: SupervisorProfile\n /** The standing instruction assembled from the profile: its system prompt in either spelling,\n * plus the `prompt.instructions` and `resources.instructions` lines. Absent when the profile\n * names none — the harness's own default then applies. This, not `profile.systemPrompt`, is\n * what the harness should run under. */\n readonly systemPrompt?: string\n readonly task: unknown\n readonly scope: Scope<unknown>\n readonly coordinationMcpUrl: string\n /** Runtime-only transport credentials; never append them to the authored profile or task. */\n readonly coordinationMcpHeaders?: Readonly<Record<string, string>>\n /** Fires when the coordination server accepts a result or declares completion. */\n readonly stopSignal?: AbortSignal\n /** Data-only product tool surface mounted on the coordination MCP. Runtime-owned drivers include\n * this in their materialization evidence without persisting executable handlers. */\n readonly coordinationTools: ReadonlyArray<Omit<McpToolDescriptor, 'handler'>>\n }): Promise<void>\n /** Optional live inbox for the manager session this adapter currently drives. Return `false`\n * when no executor inbox is active instead of claiming a message was delivered. */\n deliver?(message: unknown): boolean\n /** Optional live evidence from the harness execution currently being driven. */\n traceSource?(): TraceSource | undefined\n /** Optional live progress from the harness execution currently being driven. */\n progress?(): ExecutorProgress | undefined\n}\n\n/** Trusted manager identity available before its external harness starts. A product uses this to\n * return one independently steerable harness session per recursive manager. */\nexport type DriveHarnessOwnerContext = Omit<SupervisorNodeContext, 'nodeId'>\n\n/** Resolve an external harness for one exact Runtime-owned manager identity. */\nexport type ResolveDriveHarness = (context: DriveHarnessOwnerContext) => DriveHarness\n\nexport interface SupervisorAgentDeps {\n readonly blobs: ResultBlobStore\n /** Resolve a spawned worker `profile` to a leaf agent — the recursion seam (same for both arms). */\n readonly makeWorkerAgent: MakeWorkerAgent\n /** Product authorization for every down-leg continuation to a child. */\n readonly authorizeDownMessage?: AuthorizeDownMessage\n /** Per-child budget reserved from the conserved pool on each spawn. */\n readonly perWorker: Budget\n /** Runtime-owned sink for provider identity observed by this manager's own turns. */\n readonly onProviderModel?: (model: string | undefined) => void\n /** Independent completion check for direct driver work (`submit_result`). */\n readonly deliverable?: DeliverableSpec<unknown>\n /** Receives a result only after this manager's completion check accepted it. */\n readonly onAcceptedSubmission?: (result: unknown) => void\n /** Hard cap on simultaneously-LIVE workers across both arms — `spawn_worker` fails closed once\n * this many are in flight (a concurrency fence on top of the conserved-pool fence; bounds live\n * boxes/sandboxes, not total work). Omit/`<= 0` = no cap. */\n readonly maxLiveWorkers?: number\n /** Router substrate for a router-brained supervisor (`harness` omitted or `cli-base`). The\n * profile's model wins. */\n readonly router?: RouterTransportConfig\n /** Required to run an external-harness supervisor: runs the harness as the driver. */\n readonly driveHarness?: DriveHarness\n /** How hard a transiently-failed EXTERNAL driver is re-entered before the run ends\n * `driver-failed` (#741). Retries reuse the same scope, coordination server, and live children;\n * the bridge backend reattaches the harness session by its durable execution id. Omit = retry\n * under the defaults; `{ enabled: false }` = the historical first-failure-ends-the-run behavior.\n * The router arm is unaffected: its transport already retries. */\n readonly driverRetry?: DriverRetryPolicy\n /** Per-attempt record for the external driver — how an operator sees \"failed after N attempts\"\n * instead of one backend's last words. */\n readonly onDriverAttempt?: (record: DriverAttemptRecord) => void | Promise<void>\n /** How many times an EXTERNAL driver that RETURNED with `deliverable` still unmet is re-entered\n * on the SAME live session with the unmet items. The harness owns its own turn loop, so it can\n * end while the run has delivered nothing — 376 of 376 winning discovery-lab runs (2026-09-01)\n * ended on the driver's own completion, and the completion gate could only label that result,\n * never change it. A re-prompt reuses the retry path: same scope, same coordination server, same\n * live children, same budget/deadline/abort/attempt bounds. Requires `deliverable`; refused for\n * a router-brained supervisor, which runs its loop in process. Omit/`0` = never re-prompt. */\n readonly repromptOnUnmet?: number\n /** Compose the re-entry instruction for an unmet contract, or return `'stop'` to end the run.\n * Requires `repromptOnUnmet >= 1`. Omit = Runtime's own instruction. */\n readonly onUnmetContract?: OnUnmetContract\n /** Trusted identity for this manager. Required with node-scoped tools or observation. */\n readonly nodeContext?: SupervisorNodeContextSeed\n /** Resolve product-owned tools for this exact manager. Static `extraTools` remain a router-only\n * compatibility seam and deliberately receive no new recursive authority. */\n readonly resolveSupervisorTools?: ResolveSupervisorTools\n /** Awaited product observation, enriched with this manager's actual live node context. */\n readonly observeNodeEvent?: ObserveSupervisorNodeEvent\n /** Replay resume-time settlements through `observeNodeEvent` before the manager starts. */\n readonly replaySettlements?: boolean\n /** WORK tools the supervisor may call DIRECTLY (router arm) — so it can do simple work ITSELF and\n * only delegate when it needs parallelism. Pair with `executeExtraTool`. */\n readonly extraTools?: ReadonlyArray<{\n readonly name: string\n readonly description?: string\n readonly parameters: Record<string, unknown>\n }>\n /** Runs an `extraTools` call; null/undefined falls through to the coordination dispatch. */\n readonly executeExtraTool?: (\n name: string,\n args: Record<string, unknown>,\n ) => Promise<string | null | undefined>\n /** Analyst lenses available to the driver (both arms). Required for `analyzeOnSettle`. */\n readonly analysts?: AnalystRegistry\n /** Where an `ask_parent` question goes when it leaves this manager. Omit and `ask_parent` reports\n * `no-parent` — there is no runtime path that routes a question to a parent by itself. */\n readonly escalateQuestion?: EscalateQuestion\n /** Analyst kinds run on each worker-settle → a `finding` the driver composes its next steer from\n * (the self-improving UP-leg). Unset/empty = status quo (no analyst feed). Requires `analysts`. */\n readonly analyzeOnSettle?: ReadonlyArray<string | AnalyzeOnSettleRoute>\n /** Run the ONLINE detector panel over each worker's LIVE tool trace (both arms) so the driver\n * learns a worker is looping mid-run instead of at settle. Omit = no online watching. */\n readonly watchWorkers?: WorkerWatchOptions\n /** Idle time after which `observe_agent` reports a worker as stalled. Omit = runtime default. */\n readonly stallAfterMs?: number\n /** Default continuity per worker PROFILE NAME (both arms) — `'resume'` re-attaches spawns of\n * that name to the node's latest settled worker; `spawn_worker`'s per-call `continuity`\n * overrides. Omit = every spawn fresh (status quo). */\n readonly continuityByProfile?: Readonly<Record<string, ContinuityMode>>\n /** PROGRESS-derived stop rule (BOTH arms). Ends a run that has stopped learning BEFORE it\n * exhausts a ceiling; it can never keep a run alive past one. Router arm: evaluated before each\n * driver inference turn. External arm: evaluated on each worker settle, and a stop aborts\n * `stopSignal` so the harness ends at its next turn boundary. Build it with `plateau` /\n * `noProgressFor` / `allWorkersStalled` from `supervise/stop-rules` — the thresholds are the\n * caller's judgment. Omit = ceilings only. */\n readonly stopRule?: StopRule\n /** One-shot notification of WHY a `stopRule` ended the run (BOTH arms). */\n readonly onProgressStop?: (\n reason: string,\n request?: import('./run-layout').RunCancelRequest,\n ) => void\n /** Turn cap for the supervisor's own loop. Router arm: driver inference turns (see\n * `DriverAgentOptions.maxTurns`). External arm: the cap belongs to the harness loop, so\n * `supervise()` applies it in the drive seam it builds and this field is not read here. */\n readonly maxTurns?: number\n /** Give the supervisor brain a chapter-lifecycle on its OWN context window (ROUTER ARM ONLY; a\n * harness-brained supervisor is refused at construction rather than silently ignoring it) — it\n * distills its coordination transcript to a compact progress note once it exceeds the threshold,\n * instead of re-billing the whole thing every turn. See `DriverAgentOptions.compaction`. */\n readonly compaction?: ToolLoopCompactionOptions\n /** Pass-through subscriber for every coordination bus event (both arms) — the seam a durable\n * caller hooks its coordination log onto. */\n readonly onEvent?: (\n event: CoordinationEvent,\n record: BusRecord<CoordinationEvent>,\n ) => void | Promise<void>\n /** Questions, findings, and authorized continuation receipts loaded from a prior process.\n * Router arm: questions seed the ledger and all evidence enters the resume brief. External arm:\n * questions seed the ledger; receipts remain durable evidence and are never auto-delivered. */\n readonly priorCoordination?: PriorCoordination\n /** Deferred owner-scoped replay for a recursive supervisor. Its stable owner is known while the\n * parent authorizes the child, but loading remains asynchronous; Runtime calls this before the\n * nested brain can publish or act on coordination state. */\n readonly loadPriorCoordination?: () => Promise<PriorCoordination>\n /** How the settled ledger becomes the run's output (both arms). Default `bestDelivered` — the\n * exact keep-best every existing caller had. Always runs under the delivered-only invariant. */\n readonly finalizer?: SupervisorFinalizer\n /** Where the coordination MCP binds (external arm). Omit = an ephemeral loopback port, which is\n * unreachable from an off-host harness. A non-loopback host fails closed — see\n * {@link assertCoordinationBinding}. */\n readonly coordination?: CoordinationBinding\n /** OPT-IN async gate run before every spawn mints an assignment or reserves budget — the one\n * pre-journal point that may ask the backend a question (does this bridge route the child's\n * wire id; is it already at admission capacity). `supervise` derives one automatically for a\n * bridge backend; see `CoordinationToolsOptions.preflightSpawn`. */\n readonly preflightSpawn?: SpawnPreflight\n /** Pre-journal profile resolution for `preflightSpawn`: the authored profile → the profile that\n * will run, so the gate judges the canonical profile. See\n * `CoordinationToolsOptions.resolveSpawnProfile`. */\n readonly resolveSpawnProfile?: (profile: AgentProfile) => AgentProfile\n /** See `CoordinationToolsOptions.spawnResourceRoot`: the directory a spawn's inline resource\n * `path` resolves under. Set only for a manager whose workspace this process can read. */\n readonly spawnResourceRoot?: string\n /** OPT-IN peer mail (external arm): serve the sibling `send_mail` / `read_mail` post office\n * beside the coordination MCP and mint each spawn a capability URL on\n * `WorkerSpawnContext.peerMailUrl`. A router-brained supervisor is refused: it serves no\n * listener, so there is no post office a worker could reach. */\n readonly peerMail?: boolean | { limits?: Partial<PeerMailLimits> }\n /** Durable cancellation directory. Both arms observe run requests; only the router arm\n * acknowledges worker-scoped requests. See `DriverAgentOptions.controlDir`. */\n readonly controlDir?: string\n /** Which cancel requests this manager's acknowledger owns: `'run'` (default; the tree root —\n * its own direct-child node ids plus label/profile-name references) or `'subtree'` (a nested\n * manager — exact direct-child node ids only). Exactly one manager owns any request, so two\n * acknowledgers can never apply one operation. See `DriverAgentOptions.controlScope`. */\n readonly controlScope?: 'run' | 'subtree'\n /** Abort the whole run — the seam a run-scoped cancel request is applied through (both arms,\n * `'run'` scope only). See `DriverAgentOptions.abortRun`. */\n readonly abortRun?: (reason: string, request?: import('./run-layout').RunCancelRequest) => void\n}\n\nconst ROUTER_TRANSPORT_FIELDS = new Set(['routerBaseUrl', 'routerKey', 'complete'])\n\n/** Capture the transport-only Router seam before any profile lowering. TypeScript excess-property\n * checks are not a runtime boundary: JavaScript and widened objects can otherwise smuggle private\n * generation/retry fields through a spread and override an AgentProfile that omitted them. */\nfunction snapshotRouterTransportConfig(input: RouterTransportConfig): RouterTransportConfig {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw new ValidationError('supervisorAgent: deps.router must be a RouterTransportConfig object')\n }\n const unsupported = Object.keys(input).filter((field) => !ROUTER_TRANSPORT_FIELDS.has(field))\n if (unsupported.length > 0) {\n throw new ValidationError(\n `supervisorAgent: deps.router contains unsupported behavioral fields: ${unsupported.sort().join(', ')}`,\n )\n }\n if (typeof input.routerBaseUrl !== 'string' || input.routerBaseUrl.length === 0) {\n throw new ValidationError(\n 'supervisorAgent: deps.router.routerBaseUrl must be a non-empty string',\n )\n }\n if (typeof input.routerKey !== 'string' || input.routerKey.length === 0) {\n throw new ValidationError('supervisorAgent: deps.router.routerKey must be a non-empty string')\n }\n if (input.complete !== undefined && typeof input.complete !== 'function') {\n throw new ValidationError(\n 'supervisorAgent: deps.router.complete must be a function when provided',\n )\n }\n return Object.freeze({\n routerBaseUrl: input.routerBaseUrl,\n routerKey: input.routerKey,\n ...(input.complete !== undefined ? { complete: input.complete } : {}),\n })\n}\n\n/** Test-only dependency shape. It is exported only through the package's explicit `/testing`\n * entry; production supervisor surfaces cannot replace profile-derived model execution. */\nexport interface SupervisorAgentTestDeps extends SupervisorAgentDeps {\n readonly brain: ToolLoopChat\n}\n\n/** Build a supervisor `Agent` from its profile: the brain resolves from `profile.harness`\n * (backend-as-data), the same resolution rule as every worker. */\nexport function supervisorAgent(\n profile: SupervisorProfile,\n deps: SupervisorAgentDeps,\n): Agent<unknown, unknown> {\n if ('brain' in deps) {\n throw new ValidationError(\n 'supervisorAgent: direct brain injection is test-only; production execution derives the model call from AgentProfile',\n )\n }\n return buildSupervisorAgent(profile, deps)\n}\n\n/** Scripted-brain construction for deterministic tests. Not exported from Runtime's main entry. */\nexport function supervisorAgentWithTestBrain(\n profile: SupervisorProfile,\n deps: SupervisorAgentTestDeps,\n): Agent<unknown, unknown> {\n const { brain, ...runtimeDeps } = deps\n return buildSupervisorAgent(profile, runtimeDeps, brain)\n}\n\nfunction buildSupervisorAgent(\n profile: SupervisorProfile,\n deps: SupervisorAgentDeps,\n testBrain?: ToolLoopChat,\n): Agent<unknown, unknown> {\n const exactProfile = agentProfileSchema.parse(profile)\n assertExecutableAgentProfile(exactProfile, 'supervisorAgent')\n const stableProfile = detachedSnapshot(exactProfile, 'supervisorAgent profile')\n const stableRouter =\n deps.router === undefined ? undefined : snapshotRouterTransportConfig(deps.router)\n const resolveTools = deps.resolveSupervisorTools\n assertNoReservedCoordinationMcpAlias(stableProfile, 'supervisorAgent')\n const harness = agentHarness(stableProfile.harness) ?? null\n // `extraTools` is mounted only by the router tool-loop. An external harness receives product\n // tools only through its coordination MCP, so it must have a node-scoped resolver instead.\n const runtimeToolError = runtimeToolDeclarationError(\n stableProfile,\n resolveTools !== undefined,\n harness === null ? deps.extraTools?.map((tool) => tool.name) : undefined,\n )\n if (runtimeToolError !== undefined) {\n throw new ValidationError(`supervisorAgent: ${runtimeToolError}`)\n }\n const observeNodeEvent = deps.observeNodeEvent\n const nodeContextSeed =\n deps.nodeContext === undefined\n ? undefined\n : detachedSnapshot(deps.nodeContext, 'supervisorAgent node context')\n if ((resolveTools || observeNodeEvent) && !nodeContextSeed) {\n throw new ValidationError(\n 'supervisorAgent: nodeContext is required with resolveSupervisorTools or observeNodeEvent',\n )\n }\n const name = stableProfile.name ?? 'supervisor'\n // The prompt is consumed by BOTH arms, so it resolves here; the model id is router-arm-only and\n // resolves inside that arm, so a harness supervisor never touches a field it does not use.\n // No fallback at this site. Both arms receive only the prompt and instruction bytes declared by\n // the profile.\n const profilePrompt = resolveSupervisorSystemPrompt(stableProfile)\n const runtimeToolNames = declaredRuntimeToolNames(stableProfile)\n\n // Bind safety is a BUILD-time fault, not a run-time one: it must throw before any compute, on the\n // same synchronous path as the other configuration guards. The binding is SNAPSHOT here and the\n // snapshot is both what gets checked and what `act()` binds, so a later mutation of\n // `deps.coordination` cannot slip an unchecked host past the guard.\n const coordination: CoordinationBinding | undefined = deps.coordination\n ? { ...deps.coordination }\n : undefined\n assertCoordinationBinding(coordination)\n\n if (harness === null && coordination !== undefined) {\n throw new ConfigError(\n 'supervisorAgent: coordination binding is only meaningful for a harness-brained supervisor ' +\n '(profile.harness set). A router-brained supervisor calls the coordination verbs in ' +\n 'process and serves no MCP, so this binding would be silently ignored.',\n )\n }\n\n if (harness === null && deps.peerMail) {\n throw new ValidationError(\n 'supervisorAgent: peerMail is only served by a harness-brained supervisor ' +\n '(profile.harness set). A router-brained supervisor serves no coordination MCP listener, ' +\n 'so there is no peer-mail post office to mint worker capabilities from.',\n )\n }\n\n if (harness !== null && deps.compaction) {\n throw new ValidationError(\n 'supervisorAgent: compaction is only supported for router-brained supervisors (profile.harness omitted or cli-base)',\n )\n }\n\n if (\n harness === null &&\n (deps.repromptOnUnmet !== undefined || deps.onUnmetContract !== undefined)\n ) {\n throw new ValidationError(\n 'supervisorAgent: repromptOnUnmet/onUnmetContract apply to an EXTERNAL-harness supervisor ' +\n 'only (profile.harness set). A router-brained supervisor runs its own turn loop in ' +\n 'process, so this option would be silently ignored.',\n )\n }\n\n if (\n deps.repromptOnUnmet !== undefined &&\n (!Number.isInteger(deps.repromptOnUnmet) || deps.repromptOnUnmet < 0)\n ) {\n throw new ValidationError(\n 'supervisorAgent: repromptOnUnmet must be a non-negative integer (0 = never re-prompt)',\n )\n }\n\n if (deps.onUnmetContract !== undefined && (deps.repromptOnUnmet ?? 0) <= 0) {\n throw new ValidationError(\n 'supervisorAgent: onUnmetContract needs repromptOnUnmet >= 1 — without a cap the hook is ' +\n 'never consulted',\n )\n }\n\n if ((deps.repromptOnUnmet ?? 0) > 0 && deps.deliverable === undefined) {\n throw new ValidationError(\n 'supervisorAgent: repromptOnUnmet needs a `deliverable` completion check — with no check ' +\n 'there is no contract that can be unmet, and every run would re-prompt',\n )\n }\n\n if (harness === null) {\n // ROUTER arm: the in-process tool-loop. `routerBrain` is an internal detail — a production\n // caller passes a profile, never a hand-built brain. Deterministic source tests use the\n // separately exported `/testing` constructor.\n assertRouterArmResourcePolicy(stableProfile)\n const brain = testBrain ?? routerBrainFromProfile(stableProfile, stableRouter)\n const inbox = createInbox()\n const build = (\n priorCoordination?: PriorCoordination,\n nodeTools?: ReadonlyArray<McpToolDescriptor>,\n onEvent?: SupervisorAgentDeps['onEvent'],\n slot?: VerbSlot,\n ) =>\n driverAgent({\n name,\n brain,\n ...(testBrain === undefined\n ? { expectedModel: resolveSupervisorModelId(stableProfile) }\n : {}),\n ...(deps.onProviderModel ? { onProviderModel: deps.onProviderModel } : {}),\n blobs: deps.blobs,\n makeWorkerAgent: deps.makeWorkerAgent,\n ...(deps.authorizeDownMessage ? { authorizeDownMessage: deps.authorizeDownMessage } : {}),\n perWorker: deps.perWorker,\n // An omitted prompt means no standing system text. Runtime executes the exact profile and\n // never chooses a research policy for it.\n systemPrompt: resolveSupervisorSystemPrompt(stableProfile) ?? '',\n ...(deps.deliverable ? { deliverable: deps.deliverable } : {}),\n ...(deps.onAcceptedSubmission ? { onAcceptedSubmission: deps.onAcceptedSubmission } : {}),\n toolNames: runtimeToolNames,\n ...(nodeTools?.length ? { nodeTools } : {}),\n ...(deps.maxLiveWorkers !== undefined ? { maxLiveWorkers: deps.maxLiveWorkers } : {}),\n ...(deps.extraTools ? { extraTools: deps.extraTools } : {}),\n ...(deps.executeExtraTool ? { executeExtraTool: deps.executeExtraTool } : {}),\n ...(deps.analysts ? { analysts: deps.analysts } : {}),\n ...(deps.analyzeOnSettle ? { analyzeOnSettle: deps.analyzeOnSettle } : {}),\n ...(deps.escalateQuestion ? { escalateQuestion: deps.escalateQuestion } : {}),\n ...(deps.watchWorkers ? { watchWorkers: deps.watchWorkers } : {}),\n ...(deps.stallAfterMs !== undefined ? { stallAfterMs: deps.stallAfterMs } : {}),\n ...(deps.continuityByProfile ? { continuityByProfile: deps.continuityByProfile } : {}),\n ...(deps.preflightSpawn ? { preflightSpawn: deps.preflightSpawn } : {}),\n ...(deps.resolveSpawnProfile ? { resolveSpawnProfile: deps.resolveSpawnProfile } : {}),\n ...(deps.spawnResourceRoot ? { spawnResourceRoot: deps.spawnResourceRoot } : {}),\n ...(deps.stopRule ? { stopRule: deps.stopRule } : {}),\n ...(deps.onProgressStop ? { onProgressStop: deps.onProgressStop } : {}),\n ...(deps.maxTurns !== undefined ? { maxTurns: deps.maxTurns } : {}),\n ...(deps.compaction ? { compaction: deps.compaction } : {}),\n ...(onEvent ? { onEvent } : {}),\n ...(deps.replaySettlements ? { replaySettlements: true } : {}),\n ...(priorCoordination ? { priorCoordination } : {}),\n ...(deps.finalizer ? { finalizer: deps.finalizer } : {}),\n ...(slot ? { onCoordinationTools: (tools) => slot.bind(tools) } : {}),\n ...(deps.controlDir === undefined ? {} : { controlDir: deps.controlDir }),\n ...(deps.controlScope === undefined ? {} : { controlScope: deps.controlScope }),\n ...(deps.abortRun ? { abortRun: deps.abortRun } : {}),\n inbox,\n })\n if (!deps.loadPriorCoordination && !resolveTools && !observeNodeEvent) {\n return build(deps.priorCoordination, undefined, deps.onEvent)\n }\n return {\n name,\n deliver(message): boolean {\n return inbox.deliver(message)\n },\n async act(task, scope) {\n const context = nodeContextSeed\n ? supervisorNodeContext(nodeContextSeed, stableProfile, task, scope)\n : undefined\n const priorCoordination = await deps.loadPriorCoordination?.()\n // Filled by `driverAgent` the moment it builds this manager's coordination tools, which\n // is after the product tools are bound — hence the slot rather than a value.\n const slot = createVerbSlot()\n const nodeTools =\n resolveTools && context\n ? await bindSupervisorTools(resolveTools, context, scope.signal, slot)\n : undefined\n const onEvent = bindSupervisorNodeObserver(context, observeNodeEvent, deps.onEvent)\n return build(priorCoordination, nodeTools, onEvent, slot).act(task, scope)\n },\n }\n }\n\n // EXTERNAL arm: a caller-driven harness uses the coordination verbs over the live scope.\n const driveHarness = deps.driveHarness\n if (!driveHarness) {\n throw new ValidationError(\n `supervisorAgent: profile.harness=\"${harness}\" needs deps.driveHarness (how to run the harness with the coordination MCP mounted)`,\n )\n }\n const deliver = driveHarness.deliver?.bind(driveHarness)\n const externalAgent: Agent<unknown, unknown> = {\n name,\n ...(deliver\n ? {\n deliver(message: unknown): boolean {\n return deliver(message)\n },\n }\n : {}),\n traceSource: () => driveHarness.traceSource?.(),\n progress: () => driveHarness.progress?.(),\n async act(task, scope) {\n const context = nodeContextSeed\n ? supervisorNodeContext(nodeContextSeed, stableProfile, task, scope)\n : undefined\n const priorCoordination = deps.loadPriorCoordination\n ? await deps.loadPriorCoordination()\n : deps.priorCoordination\n // Filled by `serveCoordinationMcp` right after it builds this manager's coordination tools\n // and before it listens, so a product tool can compose from its first invocation.\n const slot = createVerbSlot()\n const nodeTools =\n resolveTools && context\n ? await bindSupervisorTools(resolveTools, context, scope.signal, slot)\n : undefined\n const nodeObserver = bindSupervisorNodeObserver(context, observeNodeEvent, deps.onEvent)\n const stopController = new AbortController()\n // PROGRESS-derived stop on this arm. The harness owns its own turn loop, so a worker settle\n // is the evaluation boundary the supervisor has — and it is the same ledger + the same\n // `progressStop` evaluator the router arm consults before each of its inference turns.\n // The stop is delivered through the ONE lever this arm already has: `stopController`, which\n // the harness reads as its stop signal and honours at the next turn boundary.\n const tracker = deps.stopRule ? createProgressTracker({ now: Date.now }) : undefined\n let progressStopReason: string | undefined\n let ledger: SettledLedger | undefined\n const rule = deps.stopRule\n const onEvent =\n tracker && rule\n ? async (\n event: CoordinationEvent,\n record: BusRecord<CoordinationEvent>,\n ): Promise<void> => {\n await nodeObserver?.(event, record)\n if (event.type !== 'settled') return\n if (ledger === undefined) {\n throw new ValidationError(\n 'supervisorAgent: a worker settled before the coordination server was bound',\n )\n }\n const decision = progressStop(\n tracker,\n rule,\n ledger,\n scope,\n Date.now,\n deps.stallAfterMs,\n )\n if (!decision.stop || progressStopReason !== undefined) return\n progressStopReason = decision.reason\n deps.onProgressStop?.(decision.reason)\n if (!stopController.signal.aborted) stopController.abort(decision.reason)\n }\n : nodeObserver\n const mcp = await serveCoordinationMcp({\n scope,\n blobs: deps.blobs,\n makeWorkerAgent: deps.makeWorkerAgent,\n ...(deps.authorizeDownMessage ? { authorizeDownMessage: deps.authorizeDownMessage } : {}),\n perWorker: deps.perWorker,\n ...(coordination ?? {}),\n ...(context ? { identity: { runId: context.runNamespace, actorId: context.ownerId } } : {}),\n // Forward the policy so direct server construction and manager preflight enforce the same\n // authentication and request limits.\n ...(deps.deliverable ? { deliverable: deps.deliverable } : {}),\n onStop: (reason) => {\n if (!stopController.signal.aborted) {\n stopController.abort(reason ?? 'coordination stop')\n }\n },\n ...(deps.maxLiveWorkers !== undefined ? { maxLiveWorkers: deps.maxLiveWorkers } : {}),\n ...(deps.analysts ? { analysts: deps.analysts } : {}),\n ...(deps.analyzeOnSettle ? { analyzeOnSettle: deps.analyzeOnSettle } : {}),\n ...(deps.escalateQuestion ? { escalateQuestion: deps.escalateQuestion } : {}),\n ...(deps.watchWorkers ? { watchWorkers: deps.watchWorkers } : {}),\n ...(deps.stallAfterMs !== undefined ? { stallAfterMs: deps.stallAfterMs } : {}),\n ...(deps.continuityByProfile ? { continuityByProfile: deps.continuityByProfile } : {}),\n ...(onEvent ? { onEvent } : {}),\n ...(deps.replaySettlements ? { replaySettlements: true } : {}),\n ...(deps.preflightSpawn ? { preflightSpawn: deps.preflightSpawn } : {}),\n ...(deps.resolveSpawnProfile ? { resolveSpawnProfile: deps.resolveSpawnProfile } : {}),\n ...(deps.spawnResourceRoot ? { spawnResourceRoot: deps.spawnResourceRoot } : {}),\n ...(deps.peerMail ? { peerMail: deps.peerMail } : {}),\n ...(priorCoordination?.questions.length\n ? { priorQuestions: priorCoordination.questions }\n : {}),\n ...(priorCoordination?.escalations?.length\n ? { priorEscalations: priorCoordination.escalations }\n : {}),\n ...(priorCoordination?.records.length ? { priorJournal: priorCoordination.records } : {}),\n ...(priorCoordination?.analystDefinitions?.length\n ? { priorAnalystDefinitions: priorCoordination.analystDefinitions }\n : {}),\n ...(nodeTools?.length ? { nodeTools } : {}),\n toolNames: runtimeToolNames,\n onCoordinationTools: (tools) => slot.bind(tools),\n })\n ledger = mcp\n const coordinationTools = slot.descriptors()\n const providerProfile = detachedSnapshot(\n providerVisibleProfile(stableProfile),\n 'supervisorAgent provider-visible profile',\n )\n try {\n // A restored `submission` record proves this manager's completion check already accepted\n // the value. Return it before starting another harness process.\n const recoveredSubmission = mcp.submittedResult()\n if (recoveredSubmission) {\n deps.onAcceptedSubmission?.(recoveredSubmission.result)\n return recoveredSubmission.result\n }\n // The retry's progress mark. `tokensLeft` only falls, so the difference from the first\n // reading is everything this run has spent from the shared pool — the driver's own turns\n // and any child's. Those two channels are the BURN rate, not the goal, so they are reported\n // beside the contract's verdict and the retry policy reads them together: with a declared\n // check unmet, spend and settlements alone do not buy another attempt.\n const baseTokensLeft = scope.budget.tokensLeft\n const contractDeclared = deps.deliverable !== undefined\n const maxReprompts = deps.repromptOnUnmet ?? 0\n const readProgress = (): DriverProgressMark => {\n const settled = mcp.settled()\n // The same delivered-only rule the finalizer applies: settled `done` AND check-passed.\n const deliveredCount = settled.filter(\n (w) => w.status === 'done' && w.valid === true,\n ).length\n const submitted = Boolean(mcp.submittedResult())\n return {\n poolTokensSpent: baseTokensLeft - scope.budget.tokensLeft,\n settledCount: settled.length,\n submitted,\n deliveredCount,\n contract: !contractDeclared\n ? 'none'\n : submitted || deliveredCount > 0\n ? 'met'\n : 'unmet',\n }\n }\n await runDriverWithRetry({\n drive: async (attempt, reentry) => {\n if (deps.controlDir !== undefined && deps.abortRun !== undefined) {\n applyRunCancellation(deps.controlDir, deps.abortRun, () => new Date().toISOString())\n }\n scope.signal.throwIfAborted()\n // Every drive after the first is a new execution attempt of the root.\n beginScopeOwnerAttempt(scope, attempt)\n try {\n await driveHarness({\n profile: providerProfile,\n authoredProfile: stableProfile,\n ...(profilePrompt !== undefined ? { systemPrompt: profilePrompt } : {}),\n // A re-prompt re-enters the SAME session, so the unmet items ARE the turn. The\n // bridge backend reattaches by durable execution id, exactly as a retry does.\n task: reentry === undefined ? task : reentry.steer,\n scope,\n coordinationMcpUrl: mcp.url,\n coordinationMcpHeaders: mcp.headers,\n stopSignal: stopController.signal,\n coordinationTools,\n })\n } catch (error) {\n // Once the injected check has accepted a result, a later backend shutdown/timeout\n // cannot erase that completed work — and there is nothing left to retry FOR. Without\n // an accepted submission the backend error propagates into the retry decision.\n if (!mcp.submittedResult() && !mcp.isStopped()) throw error\n }\n },\n progress: readProgress,\n budget: () => scope.budget,\n signal: scope.signal,\n ...(deps.driverRetry ? { policy: deps.driverRetry } : {}),\n ...(maxReprompts > 0\n ? {\n reprompt: {\n maxReprompts,\n ...(deps.deliverable?.describe === undefined\n ? {}\n : { describe: deps.deliverable.describe }),\n onUnmetContract: async (context) => {\n // A run the coordination server STOPPED ended on purpose — the driver called\n // `stop`, a stop rule fired, or the turn cap closed it. Re-prompting would\n // re-enter a session whose stop signal is already aborted and argue with a\n // decision the run already made. Runtime refuses that before the product hook\n // is consulted, so no hook can override a declared stop.\n if (mcp.isStopped()) return 'stop'\n return (\n (await deps.onUnmetContract?.(context)) ?? {\n steer: defaultUnmetContractSteer(context),\n }\n )\n },\n },\n }\n : {}),\n ...(deps.onDriverAttempt ? { onAttempt: deps.onDriverAttempt } : {}),\n })\n // Drain settled-but-unpulled children first — a gate-verified delivery the harness never\n // awaited must still reach the finalize ledger.\n await mcp.drainResolved()\n // Direct work is eligible only through `submit_result`, after the injected independent\n // check passes. Raw harness prose remains ineligible.\n const submitted = mcp.submittedResult()\n if (submitted) {\n deps.onAcceptedSubmission?.(submitted.result)\n return submitted.result\n }\n // The deliverable comes from the finalizer seam over DELIVERED children only — never the\n // harness's own output (Foreman 0/18). Default keep-best.\n return await runFinalizer(deps.finalizer ?? bestDelivered, {\n settled: mcp.settled(),\n blobs: deps.blobs,\n tree: runTree(scope),\n budget: scope.budget,\n })\n } finally {\n await mcp.close()\n }\n },\n }\n const runtime = runtimeOwnedScopeOwnerRuntime(driveHarness)\n return runtime === undefined\n ? externalAgent\n : attestRuntimeOwnedScopeOwner(externalAgent, runtime)\n}\n\nfunction supervisorNodeContext(\n seed: SupervisorNodeContextSeed,\n profile: SupervisorProfile,\n task: unknown,\n scope: Scope<unknown>,\n): SupervisorNodeContext {\n return detachedSnapshot(\n { ...seed, nodeId: scope.view.root, profile, task },\n 'supervisorAgent trusted node context',\n )\n}\n\nasync function bindSupervisorTools(\n resolveTools: ResolveSupervisorTools,\n context: SupervisorNodeContext,\n signal: AbortSignal,\n slot: VerbSlot,\n): Promise<ReadonlyArray<McpToolDescriptor>> {\n const resolved = await resolveTools(context)\n if (!Array.isArray(resolved)) {\n throw new ValidationError('supervisorAgent: resolveSupervisorTools must return an array')\n }\n // Keep the durable node snapshot free of live process objects. The invocation wrapper is frozen\n // shallowly so handlers cannot replace identity or signal, while the AbortSignal itself remains\n // live and follows the manager scope's existing root/parent cascade.\n const invocationContext: SupervisorToolInvocationContext = Object.freeze({\n ...context,\n signal,\n verbs: slot.verbs,\n coordinationTools: slot.descriptors,\n })\n const names = new Set<string>(coordinationVerbNames)\n return Object.freeze(\n resolved.map((rawTool, index) => {\n if (typeof rawTool !== 'object' || rawTool === null || Array.isArray(rawTool)) {\n throw new ValidationError(\n `supervisorAgent: resolved tool at index ${index} must be a descriptor`,\n )\n }\n const { name, description, inputSchema, handler } = rawTool\n if (typeof name !== 'string' || name.length === 0) {\n throw new ValidationError(\n `supervisorAgent: resolved tool at index ${index} needs a non-empty name`,\n )\n }\n if (names.has(name)) {\n throw new ValidationError(\n `supervisorAgent: resolved tool \"${name}\" collides with a coordination verb or another resolved tool`,\n )\n }\n names.add(name)\n if (typeof description !== 'string' || description.length === 0) {\n throw new ValidationError(`supervisorAgent: resolved tool \"${name}\" needs a description`)\n }\n if (typeof inputSchema !== 'object' || inputSchema === null || Array.isArray(inputSchema)) {\n throw new ValidationError(`supervisorAgent: resolved tool \"${name}\" needs an inputSchema`)\n }\n if (typeof handler !== 'function') {\n throw new ValidationError(`supervisorAgent: resolved tool \"${name}\" needs a handler`)\n }\n const descriptor = detachedSnapshot(\n { name, description, inputSchema },\n `supervisorAgent resolved tool ${JSON.stringify(name)}`,\n )\n return Object.freeze({\n ...descriptor,\n handler: (raw: unknown) =>\n handler(\n detachedSnapshot(raw, `supervisorAgent tool ${JSON.stringify(name)} input`),\n invocationContext,\n ),\n })\n }),\n )\n}\n\nfunction bindSupervisorNodeObserver(\n context: SupervisorNodeContext | undefined,\n observeNodeEvent: ObserveSupervisorNodeEvent | undefined,\n onEvent: SupervisorAgentDeps['onEvent'],\n): SupervisorAgentDeps['onEvent'] {\n if (!observeNodeEvent && !onEvent) return undefined\n return async (event, record) => {\n if (observeNodeEvent) {\n if (!context) {\n throw new ValidationError('supervisorAgent: observeNodeEvent has no trusted node context')\n }\n await observeNodeEvent(context, event, record)\n }\n await onEvent?.(event, record)\n }\n}\n\nfunction routerBrainFromProfile(\n profile: SupervisorProfile,\n router: RouterTransportConfig | undefined,\n): ToolLoopChat {\n if (!router) {\n throw new ValidationError(\n 'supervisorAgent: a router-brained supervisor (harness omitted or cli-base) needs deps.router',\n )\n }\n const modelId = resolveSupervisorModelId(profile)\n const settings = profileModelExecutionSettings(profile, 'supervisorAgent')\n return routerBrain(\n {\n routerBaseUrl: router.routerBaseUrl,\n routerKey: router.routerKey,\n ...(router.complete !== undefined ? { complete: router.complete } : {}),\n model: modelId,\n ...(settings.retry !== undefined ? { retry: settings.retry } : {}),\n ...enforceTokenLimits(settings.tokenLimits, 'router', 'supervisorAgent').applied,\n ...(settings.stream !== undefined ? { stream: settings.stream } : {}),\n },\n {\n ...(settings.temperature !== undefined ? { temperature: settings.temperature } : {}),\n ...(settings.seed !== undefined ? { seed: settings.seed } : {}),\n ...(settings.toolChoice !== undefined ? { toolChoice: settings.toolChoice } : {}),\n ...(settings.extraBody !== undefined ? { extraBody: settings.extraBody } : {}),\n ...(profile.model?.reasoningEffort ? { reasoningEffort: profile.model.reasoningEffort } : {}),\n },\n )\n}\n","/**\n * WORKER-SPAWN RETRY — the second chance `driverRetry` gives the root, given to a leaf.\n *\n * `driverRetry` guards the root and nothing else. A worker that dies is typed into a `down`\n * settlement, which is the right shape when the worker RAN. It is the wrong shape when the worker\n * never started, and one failure produces exactly that:\n *\n * bridgeExecutor: bridge stream error: host-executor: acquire timeout after 60000ms\n * (in_flight=4/4, queued=1)\n *\n * Measured 2026-08-22 on discovery-lab cells oscnp s2/s3: two live cells held 2 leads and up to 8\n * workers on one bridge whose host executor caps live harness children at 4. A worker spawn that\n * queued past the bridge's single 60 s acquire deadline died there, and the run lost that worker\n * permanently even though a slot freed seconds later. The bridge retries nothing.\n *\n * Retrying execution is dangerous by default, so this seam is FAIL-CLOSED on two independent\n * proofs that the attempt did no work:\n *\n * 1. The error carries a PRE-SPAWN signature — a refusal the backend emits before the harness\n * child or the box exists ({@link isPreSpawnExecutorFailure}). No provider call started.\n * 2. The attempt yielded NO execution event. An attempt that streamed anything may have metered\n * usage, and a blind re-run would double-spend, so it stays fatal whatever its message says.\n *\n * Either proof missing means no retry. This is deliberately NARROWER than \"is this an\n * infrastructure hiccup\": `ECONNRESET` is a transient transport failure and is NOT retried here,\n * because it can arrive mid-stream after a metered call.\n *\n * Re-entry re-invokes `execute` on the SAME executor object. Nothing is rebuilt, so the executor's\n * runtime-owned materialization attestation, its bound session id, and its inbox are all the ones\n * the kernel admitted. For the bridge backend a second `execute` is a fresh session stream over the\n * same durable execution id, and a saturation refusal happens before that session's child spawned.\n *\n * @experimental\n */\n\nimport { ValidationError } from '../../errors'\nimport type { MakeWorkerAgent } from '../../mcp/tools/coordination'\nimport { inheritRuntimeOwnedExecutorAttestation } from './materialization'\nimport type {\n Agent,\n AgentSpec,\n Executor,\n ExecutorResult,\n UsageEvent,\n WorkerInteractiveSession,\n} from './types'\n\n/**\n * The backend refusals that are emitted BEFORE any child process, box, or provider request exists.\n *\n * Each is a queue admission deadline: the executor asked for a slot, waited, and was refused\n * without anything being started. The three names are the pools cli-bridge and the container host\n * admit through — the host executor, one scoped per-run host executor, and the container pool.\n *\n * The pattern is anchored to the whole phrase, including the `after <n>ms` deadline, so a message\n * that merely mentions a queue does not qualify.\n */\nconst PRE_SPAWN_SIGNATURES: ReadonlyArray<RegExp> = Object.freeze([\n /\\b(?:host-executor|scoped-host-executor|container-pool): acquire timeout after \\d+ms\\b/u,\n])\n\n/** One re-entry, reported before it waits. */\nexport interface WorkerSpawnRetryAttempt {\n /** 1-based: the attempt that just failed. */\n readonly attempt: number\n /** How long this seam waits before re-entering `execute`. */\n readonly waitMs: number\n /** The refused profile's name, when it declares one. */\n readonly worker?: string\n readonly error: string\n}\n\n/**\n * How hard a pre-spawn worker refusal is re-entered. Absent from `supervise` means NO retry — the\n * historical behaviour, and the conservative default: a worker failure already has a typed\n * settlement the driver can respond to, so adding silent latency to every run is not the runtime's\n * call to make.\n */\nexport interface WorkerSpawnRetryPolicy {\n /** `false` disables the seam while leaving the option in a recorded run configuration. */\n readonly enabled?: boolean\n /** Total wall-clock ms this seam may spend waiting for a slot, backoff included. Default 900000\n * — the span measured between saturation and the next free slot on a four-way host executor. */\n readonly maxTotalMs?: number\n /** Wait before the first re-entry, doubling per attempt. Default 5000. */\n readonly initialBackoffMs?: number\n /** Ceiling on the doubling. Default 60000. */\n readonly maxBackoffMs?: number\n /**\n * Extra PRE-SPAWN signatures a consumer's own admission layer emits, added to the built-in set.\n *\n * This widens which messages qualify, and it can only be used safely for a refusal the consumer\n * knows is emitted before any provider call. The second proof — that the attempt yielded no\n * execution event — still applies to every added signature, so a mistake here cannot cause a\n * double-spend on a stream that had already started.\n */\n readonly additionalPreSpawnSignatures?: ReadonlyArray<RegExp>\n}\n\nexport interface WorkerSpawnRetryHooks {\n readonly onRetry?: (attempt: WorkerSpawnRetryAttempt) => void\n readonly now?: () => number\n readonly sleep?: (ms: number, signal?: AbortSignal) => Promise<void>\n}\n\n/** A policy with every bound decided — what {@link retryPreSpawnRefusals} acts on. Produced by\n * {@link resolveWorkerSpawnRetry}, never written by hand, so one reading of the defaults serves\n * the `supervise` option and a caller-owned seam alike. */\nexport interface ResolvedWorkerSpawnRetry {\n readonly maxTotalMs: number\n readonly initialBackoffMs: number\n readonly maxBackoffMs: number\n readonly signatures: ReadonlyArray<RegExp>\n}\n\nconst DEFAULT_MAX_TOTAL_MS = 900_000\nconst DEFAULT_INITIAL_BACKOFF_MS = 5_000\nconst DEFAULT_MAX_BACKOFF_MS = 60_000\n\n/**\n * True when `error` is a backend refusal issued before anything ran.\n *\n * This answers \"did this fail BEFORE any provider call\", which is a strictly narrower question\n * than \"is this an infrastructure hiccup\". The broader question admits `ECONNRESET` and a bare\n * `fetch failed`, both of which can arrive after a metered call, and answering the broad question\n * where the narrow one is required is what makes a retry double-spend.\n */\nexport function isPreSpawnExecutorFailure(\n error: unknown,\n additionalSignatures: ReadonlyArray<RegExp> = [],\n): boolean {\n const message = error instanceof Error ? error.message : String(error)\n for (const signature of PRE_SPAWN_SIGNATURES) if (signature.test(message)) return true\n for (const signature of additionalSignatures) if (signature.test(message)) return true\n return false\n}\n\n/** Read the policy, refusing a number a run cannot act on rather than silently clamping it. */\nexport function resolveWorkerSpawnRetry(\n policy: WorkerSpawnRetryPolicy | undefined,\n): ResolvedWorkerSpawnRetry | undefined {\n if (policy === undefined || policy.enabled === false) return undefined\n const maxTotalMs = policy.maxTotalMs ?? DEFAULT_MAX_TOTAL_MS\n const initialBackoffMs = policy.initialBackoffMs ?? DEFAULT_INITIAL_BACKOFF_MS\n const maxBackoffMs = policy.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS\n for (const [name, value] of [\n ['maxTotalMs', maxTotalMs],\n ['initialBackoffMs', initialBackoffMs],\n ['maxBackoffMs', maxBackoffMs],\n ] as const) {\n if (!Number.isFinite(value) || value < 0) {\n throw new ValidationError(\n `workerRetry.${name} must be a nonnegative finite number of milliseconds`,\n )\n }\n }\n const signatures = policy.additionalPreSpawnSignatures ?? []\n for (const signature of signatures) {\n if (!(signature instanceof RegExp)) {\n throw new ValidationError(\n 'workerRetry.additionalPreSpawnSignatures must contain RegExp values',\n )\n }\n }\n return Object.freeze({\n maxTotalMs,\n initialBackoffMs,\n maxBackoffMs: Math.max(initialBackoffMs, maxBackoffMs),\n signatures: Object.freeze([...signatures]),\n })\n}\n\n/**\n * Wrap a worker seam so a leaf whose spawn is refused before it runs is re-entered instead of\n * settling dead.\n *\n * The wrapper composes the agent's `executorFactory`, which is where a leaf executor is built with\n * the real child signal and node context, and it never replaces the executor object the factory\n * returned: the retry lives in one `execute` wrapper that carries the inner executor's attestation\n * forward and delegates every other surface to it.\n */\nexport function withWorkerSpawnRetry(\n make: MakeWorkerAgent,\n policy: WorkerSpawnRetryPolicy | undefined,\n hooks: WorkerSpawnRetryHooks = {},\n): MakeWorkerAgent {\n const resolved = resolveWorkerSpawnRetry(policy)\n if (resolved === undefined) return make\n return (profile, spawnContext) => {\n const agent = make(profile, spawnContext)\n const spec = (agent as Agent<unknown, unknown> & { executorSpec?: AgentSpec }).executorSpec\n if (spec === undefined) return agent\n const seamHooks = {\n ...hooks,\n ...(typeof profile.name === 'string' ? { worker: profile.name } : {}),\n }\n // A factory is the backend-derived shape: the executor is built per spawn with the real child\n // signal. A bring-your-own executor is the other supported shape, and skipping it would make\n // this seam a silent no-op for a caller that uses it.\n if (spec.executorFactory !== undefined) {\n const innerFactory = spec.executorFactory\n const executorFactory: NonNullable<AgentSpec['executorFactory']> = (builtSpec, ctx) =>\n retryPreSpawnRefusals(innerFactory(builtSpec, ctx), resolved, seamHooks)\n return { ...agent, executorSpec: { ...spec, executorFactory } } as typeof agent\n }\n if (spec.executor !== undefined) {\n const executor = retryPreSpawnRefusals(spec.executor, resolved, seamHooks)\n return { ...agent, executorSpec: { ...spec, executor } } as typeof agent\n }\n return agent\n }\n}\n\n/**\n * Re-enter `execute` on one executor while a pre-spawn refusal keeps proving nothing ran.\n *\n * Exported so an owner of `makeLeafAgent` — which builds its own executors — gets the same seam\n * without reimplementing the two proofs.\n */\nexport function retryPreSpawnRefusals<Out>(\n inner: Executor<Out>,\n policy: ResolvedWorkerSpawnRetry,\n hooks: WorkerSpawnRetryHooks & { worker?: string } = {},\n): Executor<Out> {\n const now = hooks.now ?? Date.now\n const sleep = hooks.sleep ?? defaultSleep\n\n /** The wait before the next attempt, or `null` when this failure stays fatal. */\n const nextWait = (\n error: unknown,\n attempt: number,\n yielded: boolean,\n startedAt: number,\n signal: AbortSignal | undefined,\n ): number | null => {\n // Proof two, checked first because it is the cheaper and the more dangerous to get wrong.\n if (yielded) return null\n if (signal?.aborted) return null\n if (!isPreSpawnExecutorFailure(error, policy.signatures)) return null\n const backoff = Math.min(policy.maxBackoffMs, policy.initialBackoffMs * 2 ** (attempt - 1))\n if (now() - startedAt + backoff >= policy.maxTotalMs) return null\n return backoff\n }\n\n const report = (error: unknown, attempt: number, waitMs: number): void => {\n hooks.onRetry?.({\n attempt,\n waitMs,\n ...(hooks.worker === undefined ? {} : { worker: hooks.worker }),\n error: error instanceof Error ? error.message : String(error),\n })\n }\n\n const wrapped: Executor<Out> = {\n runtime: inner.runtime,\n ...(inner.budgetExempt !== undefined ? { budgetExempt: inner.budgetExempt } : {}),\n ...(inner.deliver ? { deliver: (message: unknown) => inner.deliver?.(message) } : {}),\n ...(inner.progress ? { progress: () => inner.progress?.() } : {}),\n ...(inner.traceSource ? { traceSource: () => inner.traceSource?.() } : {}),\n ...(inner.metered ? { metered: () => inner.metered?.() } : {}),\n ...(inner.interactive === undefined\n ? {}\n : { interactive: (): WorkerInteractiveSession => interactiveOf(inner) }),\n execute(task, signal) {\n const first = inner.execute(task, signal)\n const restart = () => inner.execute(task, signal)\n return isAsyncIterable(first)\n ? retryStream(first, restart, signal)\n : retryOneShot(first, restart, signal)\n },\n teardown: (grace) => inner.teardown(grace),\n resultArtifact: () => inner.resultArtifact(),\n }\n\n async function* retryStream(\n first: AsyncIterable<UsageEvent>,\n restart: () => Promise<ExecutorResult<Out>> | AsyncIterable<UsageEvent>,\n signal: AbortSignal | undefined,\n ): AsyncIterable<UsageEvent> {\n const startedAt = now()\n let execution = first\n for (let attempt = 1; ; attempt += 1) {\n let yielded = false\n try {\n for await (const event of execution) {\n yielded = true\n yield event\n }\n return\n } catch (error) {\n const waitMs = nextWait(error, attempt, yielded, startedAt, signal)\n if (waitMs === null) throw error\n report(error, attempt, waitMs)\n await sleep(waitMs, signal)\n const next = restart()\n if (!isAsyncIterable(next)) {\n // An executor keeps one execution shape for the life of one spawn. A re-entry that\n // changed shape would silently drop the event stream the conserved pool folds, so it is\n // named here rather than absorbed.\n throw new ValidationError(\n 'retryPreSpawnRefusals: executor changed execution shape between attempts',\n )\n }\n execution = next\n }\n }\n }\n\n async function retryOneShot(\n first: Promise<ExecutorResult<Out>>,\n restart: () => Promise<ExecutorResult<Out>> | AsyncIterable<UsageEvent>,\n signal: AbortSignal | undefined,\n ): Promise<ExecutorResult<Out>> {\n const startedAt = now()\n let execution = first\n for (let attempt = 1; ; attempt += 1) {\n try {\n return await execution\n } catch (error) {\n // A one-shot executor reports nothing until it resolves, so \"yielded nothing\" is the only\n // state it can be in when it rejects.\n const waitMs = nextWait(error, attempt, false, startedAt, signal)\n if (waitMs === null) throw error\n report(error, attempt, waitMs)\n await sleep(waitMs, signal)\n const next = restart()\n if (isAsyncIterable(next)) {\n throw new ValidationError(\n 'retryPreSpawnRefusals: executor changed execution shape between attempts',\n )\n }\n execution = next\n }\n }\n }\n\n return inheritRuntimeOwnedExecutorAttestation(inner, wrapped)\n}\n\n/** Forward the inner executor's interactive contract exactly. The method is present only when the\n * inner executor implements it, so the reachable call always has one to delegate to. */\nfunction interactiveOf<Out>(inner: Executor<Out>): WorkerInteractiveSession {\n if (inner.interactive === undefined) {\n throw new ValidationError(\n 'retryPreSpawnRefusals: inner executor exposes no interactive session',\n )\n }\n return inner.interactive()\n}\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterable<UsageEvent> {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as AsyncIterable<UsageEvent>)[Symbol.asyncIterator] === 'function'\n )\n}\n\n/** The wait stays REF'd: a worker waiting out a saturated executor is live work, and an unref'd\n * timer lets the process exit mid-backoff when nothing else is pending. */\nfunction defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (ms <= 0 || signal?.aborted) return Promise.resolve()\n return new Promise((resolve) => {\n const done = () => {\n clearTimeout(timer)\n signal?.removeEventListener('abort', done)\n resolve()\n }\n const timer = setTimeout(done, ms)\n signal?.addEventListener('abort', done, { once: true })\n })\n}\n","/**\n * `supervise` — the one-call \"just invoke the supervisor\". Builds + runs a supervisor from its\n * profile with sensible defaults, so the common case is `supervise(profile, task, { backend, budget })`\n * instead of hand-wiring `blobs` / `perWorker` / `journal` / `executors` / `maxDepth`. The raw seams\n * (`supervisorAgent` + `createSupervisor().run`) stay available for power use.\n *\n * `workerFromBackend` derives the worker seam (`makeWorkerAgent`) from a backend config + an optional\n * completion oracle — so \"where the workers run\" is one data choice, not a hand-rolled factory.\n *\n * @stable\n */\nimport { randomUUID } from 'node:crypto'\nimport { resolve } from 'node:path'\nimport {\n type AgentProfile,\n type AgentProfileMcpServer,\n type AgentProfileSecurityPolicy,\n agentProfileSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n type Sha256Digest,\n validateAgentProfileSecurity,\n} from '@tangle-network/agent-interface'\nimport {\n type HarnessId,\n isMaterializerHarness,\n type SkippableDimension,\n} from '@tangle-network/agent-profile-materialize'\nimport type { BackendType } from '@tangle-network/sandbox'\nimport {\n assertProfileMaterialization,\n controlProfileMaterialization,\n defineProfileMaterializationContract,\n fullProfileMaterialization,\n type ProfileMaterializationContract,\n profileMaterializationAxes,\n promptControlProfileMaterialization,\n promptModelProfileMaterialization,\n renderUnsupported,\n unsupportedProfileDimensions,\n worktreeCliProfileMaterialization,\n} from '../../agent/profile-materialization'\nimport { ConfigError, ValidationError } from '../../errors'\nimport type {\n AnalystRegistry,\n AnalyzeOnSettleRoute,\n AuthorizeDownMessage,\n AuthorizedDownMessage,\n ContinuityMode,\n CoordinationEvent,\n DownMessageAuthorizationInput,\n EscalateQuestion,\n MakeWorkerAgent,\n SpawnPreflight,\n WorkerSpawnContext,\n WorkerWatchOptions,\n} from '../../mcp/tools/coordination'\nimport { composeRuntimeHooks, type RuntimeHooks } from '../../runtime-hooks'\nimport { resolveAgentEnvironmentProvider } from '../environment-provider'\nimport { agentHarness, harnessRunsAgent } from '../harness-role'\nimport type { RouterTransportConfig } from '../router-client'\nimport type { ToolLoopChat, ToolLoopCompactionOptions } from '../tool-loop'\nimport { addSpend as addRetainedSpend, unmeteredSpend, zeroSpend } from '../util'\nimport { RunCancellationReason } from './abortable'\nimport { assertValidBudget, meterUsageEvent, newUsageTotals, spendFromUsageTotals } from './budget'\nimport { type DeliverableSpec, gateOnDeliverable } from './completion-gate'\nimport { isLoopbackHost } from './coordination-mcp'\nimport { DEFAULT_SUCCESSFUL_SHUTDOWN_MS, teardownExecutor } from './deadline'\nimport { driverChild, driverExecutorFactory, isDriverSpec } from './driver-executor'\nimport type { DriverAttemptRecord, DriverRetryPolicy, OnUnmetContract } from './driver-retry'\nimport type { BusRecord } from './event-bus'\nimport type { SupervisorFinalizer } from './finalizer'\nimport {\n attestRuntimeOwnedScopeOwner,\n providerAttemptEvidence,\n recordRuntimeOwnedDriveHarnessProviderEvidence,\n runtimeOwnedDriveHarnessProviderEvidence,\n runtimeOwnedExecutorExecutionBinding,\n runtimeOwnedExecutorMaterialization,\n runtimeOwnedExecutorProviderEvidence,\n runtimeOwnedPendingExecutorMaterialization,\n runtimeOwnedScopeOwnerRuntime,\n} from './materialization'\nimport {\n assertExecutableAgentProfile,\n assertModelAllowed,\n assertProfileModelsAllowed,\n profileBridgeWireModel,\n} from './model-policy'\nimport {\n createSupervisorSpanRecorder,\n type SupervisorSpanOptions,\n type SupervisorSpanRecorder,\n} from './otel-spans'\nimport type { PeerMailLimits } from './peer-mail'\nimport { addResourceSpend, resourceTelemetry, withBudgetResources } from './resources'\nimport { registerRetainedExecutorPreparation, retainedExecutorSeamKey } from './retained-executor'\nimport {\n consumeScopeRetainedOwnerResult,\n prepareScopeRetainedOwnerTask,\n scopeRetainedOwnerContext,\n scopeRetainedOwnerPriorSpend,\n scopeRetainedOwnerResult,\n} from './retained-scope-owner'\nimport { watchRunCancellation } from './run-cancellation'\nimport { createFileRunContext, createInMemoryRunContext } from './run-context'\nimport { readRunCancellation, readRunCancelRequest, writeRunCancellation } from './run-layout'\nimport {\n type BridgeSeam,\n bindReusableExecutorExecutionId,\n bridgeAdmissionRefusal,\n bridgeModelRouteRefusal,\n bridgeRuntimeAttachmentsKey,\n bridgeStopSignalKey,\n captureReusableExecutorConfig,\n createExecutor,\n type ExecutorConfig,\n snapshotExecutorConfig,\n} from './runtime'\nimport {\n deriveNodeExecutionIdentity,\n meterRuntimeOwnedAccounting,\n meterRuntimeOwnedProviderAttempt,\n recordScopeOwnerMaterialization,\n restoreScopeOwnerAcceptedExecution,\n scopeOwnerExecutorNodeContext,\n} from './scope'\nimport { detachedSnapshot } from './snapshot'\nimport type { StopRule } from './stop-rules'\nimport { createRootHandle, createSupervisor } from './supervisor'\nimport {\n assertCoordinationBinding,\n assertNoReservedCoordinationMcpAlias,\n type CoordinationBinding,\n coordinationMcpAlias,\n coordinationProfileToolPrefix,\n type DriveHarness,\n type DriveHarnessOwnerContext,\n declaredRuntimeToolNames,\n providerVisibleProfile,\n type ResolveDriveHarness,\n type ResolveSupervisorTools,\n runtimeToolDeclarationError,\n type SupervisorAgentDeps,\n type SupervisorNodeContext,\n type SupervisorProfile,\n supervisorAgent,\n supervisorAgentWithTestBrain,\n} from './supervisor-agent'\nimport type {\n Agent,\n AgentExecutionRef,\n AgentSpec,\n Budget,\n Executor,\n ExecutorContext,\n ExecutorExecutionBinding,\n ExecutorFactory,\n ExecutorMaterialization,\n ExecutorResult,\n NodeExecutionIdentity,\n ProviderModelAttemptEvidence,\n ProviderModelExecutionEvidence,\n ResultBlobStore,\n RootHandle,\n RootProviderModelEvidence,\n SpawnJournal,\n Spend,\n SupervisedResult,\n UsageEvent,\n} from './types'\nimport type { WaitProbeRegistry } from './wait'\nimport {\n type WorkerSpawnRetryAttempt,\n type WorkerSpawnRetryPolicy,\n withWorkerSpawnRetry,\n} from './worker-retry'\nimport { WORKER_TRACE_PROPAGATION } from './worker-trace'\n\n/**\n * Build the worker seam from a backend (WHERE workers run) + an optional completion oracle (the\n * deliverable check that makes \"settled ⟺ delivered\" true — the guard against \"ran but didn't\n * deliver\"). The ONE place a backend becomes a spawnable worker.\n *\n * `seams` exists because this path builds the leaf executor EAGERLY and hands it back as a BYO\n * `executorSpec.executor`. The registry resolves a BYO executor without ever consulting the\n * per-child `ExecutorContext` the `Scope` seeds, so anything the scope would have supplied is\n * invisible here and has to be passed in. It is a FUNCTION because it is resolved once per worker\n * construction, so a caller may hand back something the run only learns later — which is exactly how\n * `supervise()` gives a traced run's workers their trace context without ordering the span recorder\n * ahead of the worker seam.\n *\n * Continuity: the `bridge` backend honors `continuity: 'resume'` by session re-attachment. A\n * bridge session id IS the harness conversation key (cli-bridge maps it to the CLI's own resume —\n * opencode `-s <id>`, claude `--resume`), so this seam records the session id each supervised\n * spawn was bound to, keyed by the worker id the Scope assigned, and a resume spawn binds the\n * prior worker's recorded session id instead of deriving a fresh one. The record is process-local\n * by construction, which matches the kernel's resume boundary (a prior process's workers are not\n * resume targets). Every other backend keeps failing loud: their executors have no re-attachable\n * session, and accepting the spawn would ledger `continuity: 'resume'` over a brand-new session —\n * a stamp asserting something that never happened.\n */\nexport function workerFromBackend(\n backend: ExecutorConfig,\n deliverable?: DeliverableSpec<unknown>,\n seams?: () => Readonly<Record<string, unknown>>,\n): MakeWorkerAgent {\n const capturedBackend = captureReusableExecutorConfig(backend, 'workerFromBackend')\n const unscopedNamespace = randomUUID()\n let unscopedOrdinal = 0\n const bridgeSessionByWorker = new Map<string, string>()\n return (rawProfile, spawnContext) => {\n const parsed = agentProfileSchema.safeParse(rawProfile)\n if (!parsed.success) {\n throw new ValidationError(`workerFromBackend: invalid AgentProfile: ${parsed.error.message}`)\n }\n const profile = parsed.data\n assertBackendProfileMaterialization(profile, capturedBackend, 'workerFromBackend')\n assertBridgeProfileMaterializes(profile, capturedBackend, 'workerFromBackend')\n // Resolved BEFORE any worker exists, so a resume this seam cannot honor fails the spawn\n // itself and the kernel never ledgers a `continuity: 'resume'` stamp for it.\n const resumeSessionId = bridgeResumeSessionId(\n capturedBackend,\n spawnContext,\n bridgeSessionByWorker,\n )\n const name = profile.name ?? 'worker'\n // A Scope assignment is stable across reconstruction. Direct callers that omit that context\n // still get isolation, but only Scope-backed calls claim durable external-session recovery.\n const assignmentId =\n spawnContext?.assignmentId ?? `unscoped:${unscopedNamespace}:${unscopedOrdinal++}`\n // The derived execution id scopes by the spawning manager: assignment ordinals restart at\n // `ordinal:0` under every manager, so an unscoped digest maps worker 1 of EVERY run (and of\n // every sibling manager) to one external session — on a bridge with a persistent session\n // store, a 'fresh' spawn then silently continues a foreign run's harness conversation.\n // Durable recovery is preserved: a replay of the same run re-issues the same manager node id\n // and the same assignments, so it derives the same session ids.\n const executionScope = spawnContext?.parentNodeId\n const boundBackend = bindReusableExecutorExecutionId(\n capturedBackend,\n resumeSessionId ??\n externalExecutionId('supervised-worker', {\n assignmentId,\n ...(executionScope === undefined ? {} : { scope: executionScope }),\n }),\n )\n const boundSessionId = boundBackend.backend === 'bridge' ? boundBackend.sessionId : undefined\n // Resolved BEFORE the executor exists, so a run that asked for peer mail on a backend that\n // cannot deliver it fails the spawn instead of handing the worker a capability nobody serves.\n const peerMailAttachment = peerMailRuntimeAttachment(profile, capturedBackend, spawnContext)\n const baseFactory = createExecutor(boundBackend)\n // Carry the configured factory into Scope. It is built only AFTER reservation with the real\n // child signal/context, so a rejected or already-completed keyed spawn creates no executor.\n const executorFactory = (spec: AgentSpec, ctx: ExecutorContext) => {\n // Record the bridge session this worker is bound to under its Scope-assigned worker id,\n // so a later resume of the node can re-attach it. A resumed worker records the SAME\n // session under its own id, which is what keeps a fresh → resume → resume chain on one\n // harness conversation.\n if (boundSessionId !== undefined && ctx.node?.nodeId !== undefined) {\n bridgeSessionByWorker.set(ctx.node.nodeId, boundSessionId)\n }\n // Caller-supplied seams sit UNDER the per-child seams the Scope seeds, so the scope's\n // recursion and trace context always win on a key collision. The peer-mail attachment sits\n // ABOVE both: it is Runtime-owned, minted by the coordination layer for this exact spawn,\n // and nothing a caller passes may replace the endpoint a sibling's identity is bound to.\n const extraSeams = seams?.()\n const seamsForChild =\n extraSeams === undefined && peerMailAttachment === undefined\n ? ctx.seams\n : {\n ...extraSeams,\n ...ctx.seams,\n ...(peerMailAttachment === undefined\n ? {}\n : {\n [bridgeRuntimeAttachmentsKey]: {\n ...readCallerRuntimeAttachments(ctx.seams),\n ...peerMailAttachment,\n },\n }),\n }\n const built = baseFactory(\n spec,\n seamsForChild === ctx.seams ? ctx : { ...ctx, seams: seamsForChild },\n )\n return deliverable ? gateOnDeliverable(built, deliverable) : built\n }\n const spec: AgentSpec = {\n profile,\n harness: null,\n executorFactory,\n ...(spawnContext?.execution ? { execution: spawnContext.execution } : {}),\n }\n return { name, act: async () => '', executorSpec: spec } as Agent<unknown, unknown> & {\n executorSpec: AgentSpec\n }\n }\n}\n\n/**\n * The reserved MCP alias one worker's PEER MAIL capability endpoint mounts under.\n *\n * Distinct from the driver's coordination alias on purpose: the two servers carry different\n * authority. Coordination mounts spawn_worker / steer_agent / stop; mail mounts send_mail and\n * read_mail and nothing else, on a per-worker secret path bound to that worker's identity.\n */\nconst peerMailMcpAlias = 'agent-runtime-peer-mail'\n\n/**\n * The Runtime-owned MCP attachment that carries this spawn's peer-mail endpoint into the worker,\n * or `undefined` when this backend runs no MCP client at all.\n *\n * The endpoint rides the SAME out-of-band channel the driver's coordination MCP rides\n * (`runtime_attachments` on the bridge wire), for the same reason: the capability path carries\n * fresh random bytes per process, so writing it into `AgentProfile.mcp` would move the canonical\n * profile digest a durable session is bound to, and a keyed re-spawn would then fail its identity\n * check against the journal. Nothing in the authored profile changes, and this runs inside the\n * leaf factory — after `authorizeSpawn` has already decided the profile — so the authorization\n * chain is unchanged.\n *\n * Three backend classes, three honest answers:\n *\n * - `bridge` MOUNTS it. cli-bridge advertises `capabilities.runtimeAttachments.mcp` and mounts\n * the named servers for the run without binding them into the session profile.\n * - `router`, `router-tools` and `provider` mount NOTHING. Those workers are in-process tool\n * loops with no MCP client; their tool surface is the caller's own array, and\n * `WorkerSpawnContext.peerMailUrl` is the deliverable a caller uses directly.\n * - Every other backend REFUSES the spawn. A sandbox box or a local CLI harness receives tools\n * only through its materialized `AgentProfile`, and the runtime has no channel that reaches it\n * out of band, so minting a capability it can never call would ledger a channel that does not\n * exist. This is the same rule `bridgeResumeSessionId` applies to `continuity: 'resume'`.\n */\nfunction peerMailRuntimeAttachment(\n profile: AgentProfile,\n backend: ExecutorConfig,\n spawnContext: WorkerSpawnContext | undefined,\n): Readonly<Record<string, AgentProfileMcpServer>> | undefined {\n const url = spawnContext?.peerMailUrl\n if (url === undefined) return undefined\n switch (backend.backend) {\n case 'router':\n case 'router-tools':\n case 'provider':\n return undefined\n case 'bridge':\n break\n default:\n throw new ValidationError(\n `workerFromBackend: the '${backend.backend}' backend seam cannot mount a peer-mail ` +\n 'endpoint — it materializes tools only through the AgentProfile, and writing a ' +\n 'per-process capability URL there would move the canonical profile digest. Run peer-mail ' +\n \"workers on the 'bridge' backend, mount the endpoint yourself from \" +\n 'WorkerSpawnContext.peerMailUrl through makeLeafAgent or makeWorkerAgent, or drop ' +\n 'peerMail for this run',\n )\n }\n if (profile.mcp?.[peerMailMcpAlias] !== undefined) {\n throw new ValidationError(\n `workerFromBackend: profile MCP alias ${JSON.stringify(peerMailMcpAlias)} is reserved`,\n )\n }\n return Object.freeze({\n [peerMailMcpAlias]: Object.freeze({ transport: 'http', url }) as AgentProfileMcpServer,\n })\n}\n\n/**\n * Runtime attachments a caller already put on the child's `ExecutorContext`, so mounting peer mail\n * ADDS one server rather than replacing the map. An absent or malformed value contributes nothing;\n * the executor that reads the seam owns its validation and refuses a malformed map there.\n */\nfunction readCallerRuntimeAttachments(\n seams: Readonly<Record<string, unknown>>,\n): Readonly<Record<string, unknown>> {\n const existing = seams[bridgeRuntimeAttachmentsKey]\n return existing !== null && typeof existing === 'object' && !Array.isArray(existing)\n ? (existing as Readonly<Record<string, unknown>>)\n : {}\n}\n\nfunction externalExecutionId(kind: string, identity: unknown): string {\n const digest = canonicalCandidateDigest({ kind, identity })\n return `${kind}-${digest.slice('sha256:'.length)}`\n}\n\n/**\n * The bridge session id a `'resume'` spawn re-attaches, or `undefined` for a fresh spawn.\n * Every refusal throws BEFORE a worker exists, which is what keeps the kernel's continuity\n * ledger true: a `'resume'` stamp can only appear over a session that was actually re-attached.\n */\nfunction bridgeResumeSessionId(\n backend: ExecutorConfig,\n spawnContext: WorkerSpawnContext | undefined,\n sessions: ReadonlyMap<string, string>,\n): string | undefined {\n if (spawnContext?.continuity !== 'resume') return undefined\n if (backend.backend !== 'bridge') {\n throw new ValidationError(\n `workerFromBackend: the '${backend.backend}' backend seam does not re-attach sessions and ` +\n \"cannot honor continuity: 'resume' — only the 'bridge' backend resumes here (cli-bridge \" +\n 'keys the harness conversation by session id). Provide a makeWorkerAgent that resumes ' +\n \"(it receives spawnContext.resume.ofWorker), or use continuity: 'fresh'\",\n )\n }\n const ofWorker = spawnContext.resume?.ofWorker\n if (ofWorker === undefined) {\n throw new ValidationError(\n \"workerFromBackend: a 'resume' spawn carries no resume lineage — the kernel stamps \" +\n 'spawnContext.resume for ledgered spawns; a direct caller must pass { ofWorker, sequence }',\n )\n }\n const prior = sessions.get(ofWorker)\n if (prior === undefined) {\n throw new ValidationError(\n `workerFromBackend: no recorded bridge session for worker '${ofWorker}' — this seam ` +\n 're-attaches only sessions it bound in this process (the kernel resume boundary). ' +\n \"Spawn the node fresh first, or use continuity: 'fresh'\",\n )\n }\n return prior\n}\n\n/**\n * The `trace-unpropagated` declaration for a worker backend, or `undefined` when the backend HAS a\n * propagation channel. The census (`WORKER_TRACE_PROPAGATION`) says WHETHER a backend propagates;\n * this maps the non-propagating arms to WHY: `router`/`router-tools`/`provider` have no worker\n * process to inherit an environment, `cli-worktree` has a worker but no environment channel\n * through its transport.\n */\nfunction workerTraceUnpropagatedDeclaration(\n backend: ExecutorConfig['backend'],\n): { backend: string; reason: 'no-env-channel' | 'no-worker-process' } | undefined {\n if (WORKER_TRACE_PROPAGATION[backend]) return undefined\n const reason =\n backend === 'router' || backend === 'router-tools' || backend === 'provider'\n ? ('no-worker-process' as const)\n : ('no-env-channel' as const)\n return { backend, reason }\n}\n\n/**\n * NOT a harness-name test — `ExecutorConfig.backend` is a discriminated-union TAG naming HOW a\n * profile is materialized (bridge / sandbox / cli-worktree / cli-in-place / router / cli /\n * provider), which is a\n * different axis from WHICH CLI runs. An exhaustive switch on a closed union tag is the correct\n * shape and must stay: it is what makes a new executor kind a compile error here rather than a\n * silently weaker materialization contract. Every other `backend.backend === …` in this file and\n * in `runtime.ts` is the same tag; none of them are harness names.\n */\nfunction backendProfileMaterialization(backend: ExecutorConfig): ProfileMaterializationContract {\n switch (backend.backend) {\n case 'bridge':\n case 'sandbox':\n case 'provider':\n return fullProfileMaterialization\n case 'cli-worktree':\n return backend.bridge ? fullProfileMaterialization : worktreeCliProfileMaterialization\n case 'cli-in-place':\n return worktreeCliProfileMaterialization\n case 'router':\n case 'router-tools':\n return promptModelProfileMaterialization\n case 'cli':\n return controlProfileMaterialization\n }\n}\n\nfunction assertProfileContract(\n profile: AgentProfile,\n contract: ProfileMaterializationContract,\n context: string,\n runtimeConsumesCoordinationTools = false,\n): void {\n const materializedProfile = runtimeConsumesCoordinationTools\n ? profileWithoutDeclaredRuntimeCoordinationTools(profile)\n : profile\n assertProfileMaterialization({\n contract,\n changedAxes: profileMaterializationAxes(materializedProfile),\n context,\n })\n}\n\n/**\n * Materialization contracts need the profile axes the provider owns, before an individual manager\n * has asynchronously resolved its exact product-tool descriptors. Runtime-owned declarations are\n * not provider tools; unsupported declarations still fail when the coordination surface resolves.\n */\nfunction profileWithoutDeclaredRuntimeCoordinationTools(profile: AgentProfile): AgentProfile {\n return providerVisibleProfile(profile)\n}\n\nfunction assertBackendProfileMaterialization(\n profile: AgentProfile,\n backend: ExecutorConfig,\n context: string,\n): void {\n assertProfileContract(profile, backendProfileMaterialization(backend), context)\n}\n\n/**\n * The dimensions cli-bridge lowers through its OWN native controls rather than the workspace plan,\n * per harness. The pre-spawn check must skip exactly these, or it refuses a profile the bridge\n * would have executed. Mirrors `provisionProfileWorkspace` / `provisionPiProfile` in cli-bridge\n * `src/backends/profile-support.ts`.\n */\nfunction bridgeMaterializationSkip(harness: HarnessId): readonly SkippableDimension[] {\n return harness === 'pi' ? ['mcp', 'extensions'] : ['mcp']\n}\n\n/**\n * The two prompt intents, gated here because they are the ONLY profile dimensions cli-bridge\n * refuses independently of whether a harness materializes a workspace at all\n * (`assertProfilePromptIntentsSupported`, cli-bridge `src/backends/profile-support.ts`): a\n * backend either owns a control that reaches the harness's system-prompt position or it does not.\n * Every other dimension's verdict belongs to the workspace plan the executing backend builds, and\n * the run's own materialization receipt already refuses those after the fact.\n */\nconst gatedPromptDimensions = ['systemPrompt', 'appendSystemPrompt'] as const\n\n/**\n * Refuse a bridge-bound profile whose prompt intent the harness cannot execute, at the SYNCHRONOUS\n * spawn seam — before the reservation commits, the `spawned` event is journaled, or a token is\n * metered. The verdict is a pure function of the profile and the harness, but the bridge only\n * reaches it while assembling the prompt, by which point the child is spawned, metered, and\n * settled `down` to deliver an answer that was available before it started.\n *\n * Applies to the profiles the runtime SPAWNS — a worker and a nested driver child. A root manager\n * profile is the caller's own input and is not a spawn: the bridge answers it on the manager's\n * first turn without a child ever existing.\n *\n * Silent for every other backend: `cli-worktree` runs the full plan check on its own local plan\n * (`runWorktreeHarness`), and no other backend hands the profile to a harness materializer.\n */\nfunction assertBridgeProfileMaterializes(\n profile: AgentProfile,\n backend: ExecutorConfig,\n context: string,\n): void {\n if (backend.backend !== 'bridge') return\n const harness = agentHarness(profile.harness)\n if (harness === undefined || !isMaterializerHarness(harness)) return\n const unsupported = unsupportedProfileDimensions(\n profile,\n harness,\n gatedPromptDimensions,\n bridgeMaterializationSkip(harness),\n )\n if (unsupported.length === 0) return\n throw new ValidationError(\n `${context}: ${harness} cannot materialize the profile: ${renderUnsupported(unsupported)}`,\n )\n}\n\n/**\n * The ROOT router-brained supervisor's materialization claim. The router arm consumes the\n * identity fields, the resolved system prompt (`prompt.systemPrompt` + `prompt.instructions` +\n * `resources.instructions`), and the resolved model id (`model.default`); the remaining model\n * fields are either applied by the profile-bound Router adapter or refused. Every behavioral axis\n * the Router brain cannot materialize fails before compute.\n *\n * `resourceFailOnError` is carried by the router arm itself. A strict root fails closed on an\n * instruction resource the arm cannot fetch, which is the policy the profile declares. A\n * best-effort root is refused, because the arm reports no skipped resource. Dropping the field\n * would instead force an edit to a champion profile before it can be re-seated as a supervisor\n * root, and that edit changes the profile's canonical identity.\n */\nconst routerSupervisorProfileMaterialization = defineProfileMaterializationContract({\n name: 'router-supervisor-execution',\n axes: [\n 'name',\n 'description',\n 'version',\n 'tags',\n 'systemPrompt',\n 'instructions',\n 'resourceInstructions',\n 'resourceFailOnError',\n 'modelDefault',\n 'modelProvider',\n 'modelReasoningEffort',\n 'modelMaxVisibleOutputTokens',\n 'modelMaxTotalOutputTokens',\n 'modelMetadata',\n 'harness',\n 'metadata',\n ],\n})\n\n/**\n * The pre-flight `supervise` installs for a bridge backend. No new knob: the backend already says\n * where the bridge is, and these are the questions only the bridge can answer.\n *\n * Two bridge causes, after the profile-owned tool preflight:\n *\n * - `model-route` — `GET /v1/capabilities?model=<wire id>`. The bridge answers exactly this\n * question and 404s `no backend matches model \"…\"`. FAIL CLOSED: any answer that is not a route\n * refuses, including a transport error or an unexpected status, because a pre-flight that skips\n * itself on an error is the silent admission it exists to remove.\n * - `bridge-full` — `GET /health` checks the bulk lane that an unreserved Runtime request uses.\n * Older bridges fall back to the overall admission counters. Capacity is advisory, so only a\n * positive reading of fullness refuses the spawn.\n */\nfunction bridgeSpawnPreflight(seam: BridgeSeam): SpawnPreflight {\n return async (profile) => {\n const wireModel = profileBridgeWireModel(profile)\n if (wireModel === undefined) {\n return {\n cause: 'model-route',\n detail: 'the child AgentProfile resolves no bridge wire model (harness + provider + model)',\n }\n }\n const routeRefusal = await bridgeModelRouteRefusal(seam, wireModel)\n if (routeRefusal !== undefined) return { cause: 'model-route', detail: routeRefusal.detail }\n const admissionRefusal = await bridgeAdmissionRefusal(seam)\n if (admissionRefusal !== undefined) return { cause: 'bridge-full', detail: admissionRefusal }\n return undefined\n }\n}\n\n/** Refuse a Runtime-managed child whose declared tools cannot exist on its execution path. */\nfunction profileToolSpawnPreflight(\n runtimeOwnsManager: boolean,\n canResolveProductTools: boolean,\n): SpawnPreflight {\n return async (profile) => {\n // A caller-owned worker factory is the execution port. It receives the exact profile and owns\n // its own native tool mount, just as it owns retry and completion behavior; Runtime cannot\n // truthfully infer that mount from a function value.\n if (!runtimeOwnsManager) return undefined\n const declarationError = runtimeToolDeclarationError(profile, canResolveProductTools)\n if (declarationError !== undefined) {\n return {\n cause: 'unmountable-tool',\n detail: declarationError,\n }\n }\n return undefined\n }\n}\n\n/**\n * Refuse a harness-brained child that declares Runtime coordination tools when nothing can carry\n * the coordination server to it. Such a child runs as a nested manager through `driveHarness`, and\n * the automatic driver reaches Runtime's loopback coordination MCP only through the bridge's\n * runtime-attachments seam (`automaticDriverBackendSupported`). The worker factory throws the same\n * fault, but only after a live-worker permit and a budget reservation were taken and as an unnamed\n * tool error; here it is a pre-flight cause the manager can re-author against, and neither an\n * environment nor a reservation exists yet. A router-brained child holds the same tools in-process\n * and needs no channel.\n */\nfunction coordinationChannelSpawnPreflight(\n runtimeOwnsManager: boolean,\n hasCustomDriveHarness: boolean,\n managerBackend: ExecutorConfig | undefined,\n coordination: CoordinationBinding | undefined,\n): SpawnPreflight | undefined {\n if (!runtimeOwnsManager || hasCustomDriveHarness) return undefined\n if (\n managerBackend !== undefined &&\n automaticDriverBackendSupported(managerBackend, coordination)\n ) {\n if (managerBackend.backend !== 'provider') return undefined\n return async (profile) => {\n if (!isExternalSupervisor(profile) || declaredRuntimeToolNames(profile).length === 0)\n return undefined\n return (await providerAcceptsCoordinationAttachments(managerBackend))\n ? undefined\n : {\n cause: 'unmountable-tool',\n detail:\n \"the 'provider' backend does not advertise create.runtimeAttachments.mcp; Runtime cannot mount this manager's coordination tools before dispatch\",\n }\n }\n }\n const missingChannel =\n managerBackend === undefined\n ? 'this run has no driverBackend'\n : `the '${managerBackend.backend}' backend has no coordination channel`\n return async (profile) => {\n if (!isExternalSupervisor(profile)) return undefined\n const declared = declaredRuntimeToolNames(profile)\n if (declared.length === 0) return undefined\n return {\n cause: 'unmountable-tool',\n detail:\n `the profile declares ${declared\n .map((name) => JSON.stringify(`${coordinationProfileToolPrefix}${name}`))\n .join(', ')} with harness ${JSON.stringify(profile.harness)}, but ${missingChannel}: ` +\n 'Use a local bridge, or a provider with runtime MCP attachments and an authenticated ' +\n 'coordination.publicUrl this child can reach; an explicit driveHarness may supply its own channel',\n }\n }\n}\n\nfunction composeSpawnPreflights(\n ...preflights: ReadonlyArray<SpawnPreflight | undefined>\n): SpawnPreflight | undefined {\n const active = preflights.filter(\n (preflight): preflight is SpawnPreflight => preflight !== undefined,\n )\n if (active.length === 0) return undefined\n return async (profile, context) => {\n for (const preflight of active) {\n const refusal = await preflight(profile, context)\n if (refusal !== undefined) return refusal\n }\n return undefined\n }\n}\n\nconst defaultAllowedMcpHosts: string[] = []\nObject.freeze(defaultAllowedMcpHosts)\n\n/** Manager-authored profiles are untrusted until product policy says otherwise. Remote MCP and\n * ambient connection grants therefore fail closed by default, in addition to local MCP and hooks. */\nexport const DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY: AgentProfileSecurityPolicy = Object.freeze({\n allowLocalMcp: false,\n allowHooks: false,\n allowedMcpHosts: defaultAllowedMcpHosts,\n allowConnections: false,\n})\n\nfunction isExternalSupervisor(profile: AgentProfile): boolean {\n return harnessRunsAgent(profile.harness)\n}\n\nfunction automaticDriverBackendSupported(\n backend: ExecutorConfig,\n coordination?: CoordinationBinding,\n): boolean {\n return (\n backend.backend === 'bridge' ||\n (backend.backend === 'provider' &&\n !backend.steering &&\n coordination?.authentication !== undefined &&\n coordination.publicUrl !== undefined)\n )\n}\n\nasync function providerAcceptsCoordinationAttachments(\n backend: Extract<ExecutorConfig, { backend: 'provider' }>,\n): Promise<boolean> {\n const capabilities = await resolveAgentEnvironmentProvider(\n backend.provider,\n backend.registry,\n ).capabilities()\n const create = capabilities.create\n if (!create || !('runtimeAttachments' in create)) return false\n const attachments = create.runtimeAttachments\n return Boolean(\n attachments &&\n typeof attachments === 'object' &&\n 'mcp' in attachments &&\n attachments.mcp === true,\n )\n}\n\n/** Run a harness-brained manager through the same executor factory as its children. The manager's\n * full profile is preserved, the live coordination server is added under one reserved alias, and\n * every streamed turn is charged to the manager's scope before it may continue. */\nfunction driveHarnessFromBackend(\n backend: ExecutorConfig,\n executionId: string,\n now: () => number = Date.now,\n maxTurns?: number,\n): DriveHarness {\n // Same refusal the router arm makes in `driverAgent`: a negative cap would silently run zero\n // turns and finalize an empty no-winner.\n if (maxTurns !== undefined && maxTurns < 0) {\n throw new ValidationError(\n 'driveHarnessFromBackend: maxTurns must be >= 0 (0 lifts the turn cap; bounds become the conserved pool + deadline + abort)',\n )\n }\n const turnCap = maxTurns ?? 0\n const capturedBackend = captureReusableExecutorConfig(backend, 'driveHarnessFromBackend')\n const boundBackend = bindReusableExecutorExecutionId(capturedBackend, executionId)\n const baseFactory = createExecutor(boundBackend)\n let activeExecutor: Executor<unknown> | undefined\n const drive: DriveHarness = async ({\n profile,\n authoredProfile,\n task,\n scope,\n coordinationMcpUrl,\n coordinationMcpHeaders,\n stopSignal,\n coordinationTools,\n }) => {\n const retainedOwner =\n boundBackend.backend === 'provider' ? scopeRetainedOwnerContext(scope) : undefined\n const originalTask = retainedOwner ? await prepareScopeRetainedOwnerTask(scope, task) : task\n const acceptedOwner = retainedOwner ? await scopeRetainedOwnerResult(scope) : undefined\n if (acceptedOwner) {\n await restoreScopeOwnerAcceptedExecution(scope)\n consumeScopeRetainedOwnerResult(scope)\n // The coordination journal still goes through the normal driver finalizer.\n return\n }\n const initialBudget = scope.budget\n const hasLiveCoordination = scope.view.inFlight > 0 || scope.view.waiting > 0\n if (\n !hasLiveCoordination &&\n (initialBudget.tokensLeft <= 0 ||\n initialBudget.iterationsLeft <= 0 ||\n (initialBudget.usdCapped && initialBudget.usdLeft <= 0) ||\n Object.values(initialBudget.resources ?? {}).some(\n (resource) => !resource.known || resource.remaining <= 0,\n ) ||\n (initialBudget.deadlineMs > 0 && now() >= initialBudget.deadlineMs))\n ) {\n throw new ValidationError('driveHarnessFromBackend: supervisor budget exhausted')\n }\n // `supervise` passes a canonical profile plus its provider projection. Parse both at this\n // boundary and prove the projection still matches the exact descriptors mounted for this turn.\n const canonicalDriverProfile = agentProfileSchema.parse(authoredProfile)\n assertNoReservedCoordinationMcpAlias(canonicalDriverProfile, 'driveHarnessFromBackend')\n const stableCoordinationTools = detachedSnapshot(\n coordinationTools,\n 'driveHarnessFromBackend coordination tools',\n )\n const expectedProviderProfile = providerVisibleProfile(canonicalDriverProfile)\n const providerDriverProfile = agentProfileSchema.parse(profile)\n if (\n canonicalAgentProfileDigest(providerDriverProfile) !==\n canonicalAgentProfileDigest(expectedProviderProfile)\n ) {\n throw new ValidationError(\n 'driveHarnessFromBackend: supervisor passed a provider profile that does not match its canonical profile and mounted coordination tools',\n )\n }\n // The authored profile travels unchanged. The coordination server is a Runtime-owned\n // attachment: it rides the executor's attachment seam, so a resumed run that rebinds the\n // port keeps the profile digest a durable bridge session is bound to.\n const spec: AgentSpec = {\n profile: providerDriverProfile,\n harness:\n boundBackend.backend === 'sandbox' ? (providerDriverProfile.harness as BackendType) : null,\n }\n // The turn cap rides the SAME stop lever the coordination stop uses: the harness runs its own\n // loop, so the only honest bound is \"stop at the next turn boundary\". Composing the two\n // signals keeps one lever rather than a second stop path.\n const turnStop = turnCap > 0 ? new AbortController() : undefined\n const effectiveStopSignal =\n turnStop === undefined\n ? stopSignal\n : stopSignal === undefined\n ? turnStop.signal\n : AbortSignal.any([stopSignal, turnStop.signal])\n const attachment = {\n transport: 'http' as const,\n url: coordinationMcpUrl,\n ...(coordinationMcpHeaders ? { headers: coordinationMcpHeaders } : {}),\n }\n let factory = baseFactory\n if (boundBackend.backend === 'provider') {\n const credentialName = 'AGENT_RUNTIME_COORDINATION_TOKEN'\n const authorization = coordinationMcpHeaders?.Authorization\n if (!authorization?.startsWith('Bearer ')) {\n throw new ValidationError(\n 'driveHarnessFromBackend: provider coordination requires a bearer credential',\n )\n }\n if (Object.hasOwn(boundBackend.defaults?.env ?? {}, credentialName)) {\n throw new ValidationError(\n 'driveHarnessFromBackend: provider defaults contain the reserved coordination credential name',\n )\n }\n if (\n Object.hasOwn(boundBackend.defaults?.runtimeAttachments?.mcp ?? {}, coordinationMcpAlias)\n ) {\n throw new ValidationError(\n 'driveHarnessFromBackend: provider defaults contain the reserved coordination attachment alias',\n )\n }\n if (!(await providerAcceptsCoordinationAttachments(boundBackend))) {\n throw new ValidationError(\n 'driveHarnessFromBackend: provider does not advertise create.runtimeAttachments.mcp; no environment was created',\n )\n }\n factory = createExecutor({\n ...boundBackend,\n defaults: {\n ...(boundBackend.defaults ?? {}),\n env: { ...(boundBackend.defaults?.env ?? {}), [credentialName]: authorization.slice(7) },\n runtimeAttachments: {\n mcp: {\n ...(boundBackend.defaults?.runtimeAttachments?.mcp ?? {}),\n [coordinationMcpAlias]: {\n transport: 'http',\n url: coordinationMcpUrl,\n headers: {\n Authorization: { kind: 'secret-ref', key: credentialName, format: 'bearer' },\n },\n },\n },\n },\n },\n })\n }\n const executor = factory(spec, {\n signal: scope.signal,\n node: scopeOwnerExecutorNodeContext(scope),\n seams: {\n ...(retainedOwner\n ? {\n [retainedExecutorSeamKey]: {\n ...retainedOwner,\n onResult: async (result: ExecutorResult<unknown>) => commitOwnerResult(result),\n },\n }\n : {}),\n ...(effectiveStopSignal === undefined\n ? {}\n : { [bridgeStopSignalKey]: effectiveStopSignal }),\n [bridgeRuntimeAttachmentsKey]: {\n [coordinationMcpAlias]: attachment,\n },\n },\n })\n activeExecutor = executor\n let completed = false\n let started = false\n let terminalAccountingCaptured = false\n let pendingUsage: UsageEvent[] = []\n const ownerUsage = newUsageTotals()\n let observedOwnerSpend = zeroSpend()\n let committedOwnerSpend = retainedOwner\n ? await scopeRetainedOwnerPriorSpend(scope)\n : zeroSpend()\n const ownerDelta = (total: Spend, committed = committedOwnerSpend): Spend => ({\n ...addResourceSpend(\n total.resources === undefined\n ? undefined\n : Object.fromEntries(\n Object.entries(total.resources).map(([name, value]) => {\n const prior = committed.resources?.[name]\n if (prior && prior.unit !== value.unit)\n throw new ValidationError(`resource ${name}: unit mismatch`)\n return [\n name,\n {\n ...value,\n amount: Math.max(0, value.amount - (prior?.amount ?? 0)),\n known: value.known && (prior?.known ?? true),\n },\n ]\n }),\n ),\n ),\n iterations: Math.max(0, total.iterations - committed.iterations),\n tokens: {\n input: Math.max(0, total.tokens.input - committed.tokens.input),\n output: Math.max(0, total.tokens.output - committed.tokens.output),\n ...unmeteredOwnerCache(total.tokens, committed.tokens),\n },\n usd: Math.max(0, total.usd - committed.usd),\n ...(total.usdEstimated === undefined\n ? {}\n : {\n usdEstimated: Math.min(\n Math.max(0, total.usd - committed.usd),\n Math.max(0, total.usdEstimated - (committed.usdEstimated ?? 0)),\n ),\n }),\n ...(total.tokensProvenance === undefined ? {} : { tokensProvenance: total.tokensProvenance }),\n ms: Math.max(0, total.ms - committed.ms),\n ...(total.tokensKnown === false ? { tokensKnown: false } : {}),\n ...(total.usdKnown === false ? { usdKnown: false } : {}),\n })\n let meteredProviderAttempts = 0\n const providerEvidenceForNextMeter = (): ProviderModelExecutionEvidence => {\n const evidence = runtimeOwnedExecutorProviderEvidence(executor)\n const attempt: ProviderModelAttemptEvidence | undefined =\n evidence?.attempts[meteredProviderAttempts++]\n if (attempt === undefined) {\n return providerAttemptEvidence(undefined)\n }\n const observations = Object.freeze([...attempt.observations])\n const models = Object.freeze([...new Set(observations)])\n const providerDispatch = attempt.providerDispatch\n return Object.freeze(\n attempt.identityConflict === true ||\n providerDispatch === 'not_started' ||\n (providerDispatch !== 'not_started' && observations.length === 0)\n ? {\n status: 'unknown' as const,\n attempts: Object.freeze([\n Object.freeze({\n observations,\n ...(attempt.identityConflict === true ? { identityConflict: true } : {}),\n ...(providerDispatch === 'not_started' ? { providerDispatch } : {}),\n }),\n ]),\n models,\n reason:\n attempt.identityConflict === true\n ? ('provider-model-conflict' as const)\n : ('provider-model-missing' as const),\n }\n : {\n status: 'known' as const,\n attempts: Object.freeze([Object.freeze({ observations })]),\n models,\n },\n )\n }\n let teardownStarted = false\n const deadlineAtMs = scope.budget.deadlineMs || undefined\n const teardownOnce = async (grace: number | 'brutalKill' | 'infinity') => {\n if (teardownStarted) return\n teardownStarted = true\n await teardownExecutor(executor, grace, deadlineAtMs, now)\n }\n const meterPending = async (forceUnknown = false) => {\n if (pendingUsage.length === 0) return\n // A forceful steer can finish one preflight attempt before the resumed turn produces usage.\n // Consume those explicit no-dispatch attempts first, so the paid batch keeps its own served\n // identity instead of inheriting the oldest positional evidence.\n for (;;) {\n const evidence = runtimeOwnedExecutorProviderEvidence(executor)\n const next = evidence?.attempts[meteredProviderAttempts]\n if (next?.providerDispatch !== 'not_started') break\n await meterRuntimeOwnedProviderAttempt(scope, zeroSpend(), providerEvidenceForNextMeter(), {\n role: 'driver',\n runtime: executor.runtime,\n telemetry: 'known-zero-before-dispatch',\n })\n }\n const batch = pendingUsage\n pendingUsage = []\n for (const event of batch) meterUsageEvent(ownerUsage, event)\n const measured = spendFromUsageTotals(ownerUsage)\n const charge = ownerDelta(measured, retainedOwner ? committedOwnerSpend : observedOwnerSpend)\n // The next additive receipt mutates ownerUsage.tokens, not this already-metered baseline.\n observedOwnerSpend = detachedSnapshot(measured, 'metered owner spend')\n await meterRuntimeOwnedProviderAttempt(\n scope,\n forceUnknown\n ? {\n ...charge,\n tokensKnown: false,\n usdKnown: false,\n }\n : charge,\n providerEvidenceForNextMeter(),\n {\n role: 'driver',\n runtime: executor.runtime,\n },\n )\n if (retainedOwner) committedOwnerSpend = addRetainedSpend(committedOwnerSpend, charge)\n const budget = scope.budget\n if (\n budget.tokensLeft <= 0 ||\n (budget.usdCapped && budget.usdLeft <= 0) ||\n Object.values(budget.resources ?? {}).some(\n (resource) => !resource.known || resource.remaining <= 0,\n ) ||\n (budget.deadlineMs > 0 && now() >= budget.deadlineMs)\n ) {\n throw new ValidationError('driveHarnessFromBackend: supervisor budget exhausted')\n }\n }\n\n const pending = runtimeOwnedPendingExecutorMaterialization(executor)\n let failed = false\n let failure: unknown\n let ownerMaterializationPublished = false\n const ownerDeclaration = (\n exactDeclaration: ExecutorMaterialization,\n ): ExecutorMaterialization => ({\n ...exactDeclaration,\n // The provider sees the projected profile while the receipt remains bound to the canonical\n // profile that authorized Runtime coordination.\n authoredProfile: canonicalDriverProfile,\n effectiveProfile: providerDriverProfile,\n platformAttachments: {\n [coordinationMcpAlias]: {\n kind: 'coordination-mcp',\n transport: 'http',\n tools: stableCoordinationTools,\n },\n },\n })\n const publishMaterialization = async (\n exactDeclaration: ExecutorMaterialization,\n exactBinding: ExecutorExecutionBinding,\n ): Promise<void> => {\n await recordScopeOwnerMaterialization(\n scope,\n executor.runtime,\n ownerDeclaration(exactDeclaration),\n {\n ...exactBinding,\n binding: {\n stableBinding: exactBinding.binding,\n platformAttachments: {\n [coordinationMcpAlias]: {\n transport: 'http',\n url: coordinationMcpUrl,\n },\n },\n },\n descriptor: {\n ...exactBinding.descriptor,\n coordination: true,\n },\n },\n )\n }\n const commitOwnerResult = async (result: ExecutorResult<unknown>) => {\n const declaration = runtimeOwnedExecutorMaterialization(executor)\n const binding = runtimeOwnedExecutorExecutionBinding(executor)\n if (!declaration || !binding) {\n throw new ValidationError(\n 'retained owner result requires terminal materialization before release',\n )\n }\n if (!ownerMaterializationPublished) {\n await publishMaterialization(declaration, binding)\n ownerMaterializationPublished = true\n }\n await meterPending()\n const total = withBudgetResources(\n { ...result.spent, ...resourceTelemetry(observedOwnerSpend, result.spent), iterations: 0 },\n scope.budget,\n )\n const delta = ownerDelta(total)\n await meterRuntimeOwnedAccounting(scope, delta, { role: 'driver', runtime: executor.runtime })\n committedOwnerSpend = addRetainedSpend(committedOwnerSpend, delta)\n await retainedOwner!.onResult(result)\n terminalAccountingCaptured = true\n }\n try {\n // Construction transfers cleanup ownership immediately. Even a rejected receipt or an\n // unmetered runtime reaches the single bounded teardown path below.\n const declaration = runtimeOwnedExecutorMaterialization(executor)\n const executionBinding = runtimeOwnedExecutorExecutionBinding(executor)\n if (pending === undefined && (declaration === undefined || executionBinding === undefined)) {\n throw new ValidationError(\n `driveHarnessFromBackend: built-in runtime ${JSON.stringify(executor.runtime)} has no trusted materialization declaration or execution binding`,\n )\n }\n if (pending !== undefined) {\n if (\n pending.runtime !== executor.runtime ||\n pending.binding.attemptId !== scopeOwnerExecutorNodeContext(scope).attemptId\n ) {\n throw new ValidationError(\n 'driveHarnessFromBackend: pending executor did not bind the kernel-minted attempt',\n )\n }\n if (\n canonicalAgentProfileDigest(pending.declaration.effectiveProfile) !==\n canonicalAgentProfileDigest(providerDriverProfile)\n ) {\n throw new ValidationError(\n 'driveHarnessFromBackend: pending executor changed the provider-visible AgentProfile before execution',\n )\n }\n } else {\n await publishMaterialization(declaration!, executionBinding!)\n ownerMaterializationPublished = true\n }\n if (executor.budgetExempt) {\n throw new ValidationError(\n `driveHarnessFromBackend: runtime ${JSON.stringify(executor.runtime)} does not report usage and cannot drive a budgeted supervisor`,\n )\n }\n\n started = true\n // A coordination completion stops the NEXT external turn. The active bridge request must\n // drain so its served model and terminal materialization remain valid evidence.\n if (retainedOwner?.admissions.length && !executor.recover) {\n throw new ValidationError('retained owner executor does not support recovery')\n }\n const run = retainedOwner?.admissions.length\n ? executor.recover!(originalTask, scope.signal)\n : executor.execute(originalTask, scope.signal)\n if (isAsyncIterable<UsageEvent>(run)) {\n let turns = 0\n for await (const event of run) {\n if (event.kind === 'iteration') {\n await meterPending()\n turns += 1\n if (turnStop !== undefined && turns >= turnCap && !turnStop.signal.aborted) {\n turnStop.abort(`supervise: maxTurns ${turnCap} reached`)\n }\n } else if (event.kind !== 'progress') {\n // A progress event carries the driver's observed output, never accounting.\n pendingUsage.push(event)\n }\n }\n await meterPending()\n const artifact = executor.resultArtifact()\n const terminalResources = withBudgetResources(\n { ...artifact.spent, ...resourceTelemetry(observedOwnerSpend, artifact.spent) },\n scope.budget,\n ).resources\n const resourceCorrection = addResourceSpend(\n terminalResources === undefined\n ? undefined\n : Object.fromEntries(\n Object.entries(terminalResources).map(([name, value]) => [\n name,\n {\n ...value,\n amount: Math.max(\n 0,\n value.amount - (observedOwnerSpend.resources?.[name]?.amount ?? 0),\n ),\n },\n ]),\n ),\n )\n // A stream carries increments, while its terminal artifact says whether either accounting\n // channel was omitted. Preserve unknowns in the shared pool instead of treating them as 0.\n if (\n !retainedOwner &&\n (artifact.spent.tokensKnown === false ||\n artifact.spent.usdKnown === false ||\n resourceCorrection.resources !== undefined)\n ) {\n await meterRuntimeOwnedAccounting(\n scope,\n {\n ...resourceCorrection,\n iterations: 0,\n tokens: { input: 0, output: 0 },\n ...(artifact.spent.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: 0,\n ...(artifact.spent.usdKnown === false ? { usdKnown: false } : {}),\n ms: 0,\n },\n { role: 'driver', runtime: executor.runtime, telemetry: 'unknown' },\n )\n }\n terminalAccountingCaptured = true\n } else {\n const artifact = await run\n await meterRuntimeOwnedProviderAttempt(\n scope,\n withBudgetResources({ ...artifact.spent, iterations: 0 }, scope.budget),\n providerEvidenceForNextMeter(),\n { role: 'driver', runtime: executor.runtime },\n )\n terminalAccountingCaptured = true\n }\n if (pending !== undefined && !ownerMaterializationPublished) {\n const acknowledged = runtimeOwnedExecutorMaterialization(executor)\n const acknowledgedBinding = runtimeOwnedExecutorExecutionBinding(executor)\n if (acknowledged === undefined || acknowledgedBinding === undefined) {\n throw new ValidationError(\n 'driveHarnessFromBackend: external executor completed without a terminal materialization acknowledgement',\n )\n }\n await publishMaterialization(acknowledged, acknowledgedBinding)\n ownerMaterializationPublished = true\n }\n completed = true\n } catch (error) {\n failed = true\n failure = error\n } finally {\n // The bridge can return its terminal receipt, then Runtime metering can fail before normal\n // publication (for example, after an accepted submit_result exceeds the token budget).\n // The executor attestation is the trusted receipt; publish it before teardown destroys the\n // bridge-owned state. If no receipt exists, leave the owner unknown and preserve the\n // original failure instead of inventing evidence or replacing its diagnostic.\n if (pending !== undefined && !ownerMaterializationPublished) {\n const acknowledged = runtimeOwnedExecutorMaterialization(executor)\n const acknowledgedBinding = runtimeOwnedExecutorExecutionBinding(executor)\n if (acknowledged !== undefined && acknowledgedBinding !== undefined) {\n try {\n await publishMaterialization(acknowledged, acknowledgedBinding)\n ownerMaterializationPublished = true\n } catch (error) {\n if (!failed) {\n failed = true\n failure = error\n }\n }\n }\n }\n // Capture provider evidence before teardown destroys the executor-owned observation state.\n // This is independent from terminal materialization: an aborted paid turn still needs its\n // served identity, while a plan-only receipt must never be used as a substitute.\n recordRuntimeOwnedDriveHarnessProviderEvidence(\n drive,\n runtimeOwnedExecutorProviderEvidence(executor),\n )\n try {\n await meterPending(failed && started && !terminalAccountingCaptured)\n } catch (error) {\n if (!failed) {\n failed = true\n failure = error\n }\n }\n if (failed && started && !terminalAccountingCaptured) {\n try {\n // A reconnect may have started several provider attempts before the bridge failed.\n // Persist one unknown-cost marker for every unmetered attempt; dropping a later model\n // observation would let an earlier model appear homogeneous by accident.\n for (;;) {\n const evidence = runtimeOwnedExecutorProviderEvidence(executor)\n const attempts = evidence?.attempts.length ?? 0\n if (attempts <= meteredProviderAttempts) break\n const providerDispatchDidNotStart =\n evidence?.attempts[meteredProviderAttempts]?.providerDispatch === 'not_started'\n await meterRuntimeOwnedProviderAttempt(\n scope,\n withBudgetResources(\n providerDispatchDidNotStart ? zeroSpend() : unmeteredSpend(0),\n scope.budget,\n providerDispatchDidNotStart,\n ),\n providerEvidenceForNextMeter(),\n {\n role: 'driver',\n runtime: executor.runtime,\n telemetry: providerDispatchDidNotStart\n ? 'known-zero-before-dispatch'\n : 'unknown-after-failure',\n },\n )\n }\n if (meteredProviderAttempts === 0) {\n await meterRuntimeOwnedProviderAttempt(\n scope,\n withBudgetResources(unmeteredSpend(0), scope.budget),\n providerEvidenceForNextMeter(),\n { role: 'driver', runtime: executor.runtime, telemetry: 'unknown-after-failure' },\n )\n }\n // Increments cannot prove the final resource total after an interrupted invocation.\n const attempts = runtimeOwnedExecutorProviderEvidence(executor)?.attempts\n const provenNotStarted =\n attempts !== undefined &&\n attempts.length > 0 &&\n attempts.every((attempt) => attempt.providerDispatch === 'not_started')\n if (scope.budget.resources !== undefined && !provenNotStarted) {\n await meterRuntimeOwnedAccounting(\n scope,\n withBudgetResources(zeroSpend(), scope.budget),\n { role: 'driver', runtime: executor.runtime, telemetry: 'unknown-after-failure' },\n )\n }\n } catch (error) {\n // The budget pool intentionally throws after durably recording unknown capped usage and\n // closing that capacity. Only replace the original failure if the marker did not land.\n const budget = scope.budget\n if (budget.tokensKnown !== false || (budget.usdCapped && budget.usdKnown !== false)) {\n failure = error\n }\n }\n }\n try {\n await teardownOnce(completed ? DEFAULT_SUCCESSFUL_SHUTDOWN_MS : 'brutalKill')\n } catch (error) {\n if (!failed) {\n failed = true\n failure = error\n }\n }\n if (activeExecutor === executor) activeExecutor = undefined\n }\n if (failed) throw failure\n }\n drive.deliver = (message): boolean => {\n const deliver = activeExecutor?.deliver\n if (!deliver) return false\n return deliver.call(activeExecutor, message) !== false\n }\n drive.traceSource = () => activeExecutor?.traceSource?.()\n drive.progress = () => activeExecutor?.progress?.()\n return attestRuntimeOwnedScopeOwner(\n drive,\n boundBackend.backend === 'provider'\n ? (boundBackend.runtime ??\n resolveAgentEnvironmentProvider(boundBackend.provider, boundBackend.registry).name)\n : 'cli',\n )\n}\n\nfunction isAsyncIterable<T>(value: unknown): value is AsyncIterable<T> {\n return (\n value !== null &&\n typeof value === 'object' &&\n Symbol.asyncIterator in value &&\n typeof (value as AsyncIterable<T>)[Symbol.asyncIterator] === 'function'\n )\n}\n\n/** A name→value table, in this package's resolver-port shape (the same one `WaitProbeRegistry`\n * uses): construction stays the caller's, lookup stays lazy, and a table backed by a file, a\n * plugin loader, or a plain object all satisfy one interface. */\nexport interface SuperviseRegistryTable<T> {\n resolve(name: string): T | undefined\n}\n\n/**\n * The name→value tables that make the four CODE-valued options expressible as run DATA.\n *\n * `deliverable` / `finalizer` / `analysts` / `probes` are functions and registries, so a recorded\n * run configuration (a JSON row, a campaign spec, a resumed run's options) cannot carry them — and\n * a run with no `deliverable` cannot return a `winner` at all outside the sandbox backend, because\n * the finalizer keeps only children whose oracle passed and nothing else writes that verdict. A\n * caller that owns the code registers it here once and names it from data thereafter.\n */\nexport interface SuperviseRegistry {\n readonly deliverables?: SuperviseRegistryTable<DeliverableSpec<unknown>>\n readonly finalizers?: SuperviseRegistryTable<SupervisorFinalizer>\n readonly analysts?: SuperviseRegistryTable<AnalystRegistry>\n readonly probes?: SuperviseRegistryTable<WaitProbeRegistry>\n}\n\n/** Which registry table each nameable option resolves against. Indexing this map inside\n * {@link resolveNamed} makes the pairing a type error to get wrong: `resolveNamed('probes',\n * 'deliverables', …)` does not compile. */\ninterface SuperviseRegistryTableFor {\n readonly deliverable: 'deliverables'\n readonly finalizer: 'finalizers'\n readonly analysts: 'analysts'\n readonly probes: 'probes'\n}\n\n/** Resolve one option that may be given as a value OR as a name into `opts.registry`. Both failure\n * modes name the option, the requested name, and the table it was looked up in — a typo must not\n * degrade into a silently unconfigured run (which for `deliverable` means \"no run can ever\n * deliver\"). A resolver port cannot enumerate its names, so the message names the table instead of\n * listing what was in it. */\nfunction resolveNamed<K extends keyof SuperviseRegistryTableFor, T extends object>(\n option: K,\n table: SuperviseRegistryTableFor[K],\n value: T | string | undefined,\n registry: SuperviseRegistryTable<T> | undefined,\n): T | undefined {\n if (typeof value !== 'string') return value\n if (!registry) {\n throw new ConfigError(\n `supervise: opts.${option} = ${JSON.stringify(value)} names a registry entry, but no ` +\n `opts.registry.${table} was provided to resolve it against`,\n )\n }\n const entry = registry.resolve(value)\n if (entry === undefined) {\n throw new ConfigError(\n `supervise: opts.${option} = ${JSON.stringify(value)} is not in opts.registry.${table} — ` +\n 'the table resolved no entry under that name',\n )\n }\n return entry\n}\n\nexport interface SuperviseOptions {\n /** The conserved compute pool for the whole run. */\n readonly budget: Budget\n /** Caller-created live handle for observing, steering, or cancelling this root manager. Runtime\n * attaches it before execution and detaches it after the join barrier. */\n readonly rootHandle?: RootHandle<unknown>\n /** Caller-owned cancellation for the complete recursive run. Aborting it cascades through the\n * root scope and every live child, including acquisition and backend execution. */\n readonly signal?: AbortSignal\n /** Trusted candidate and pursuit attribution for the root. The runtime derives profile/task\n * digests itself from the exact detached values it executes. */\n readonly execution?: AgentExecutionRef\n /** WHERE workers run — derives the worker seam. Provide this OR an explicit `makeWorkerAgent`. */\n readonly backend?: ExecutorConfig\n /** The independent completion check for backend-derived workers and direct supervisor\n * submissions. Strongly recommended: without it the supervisor cannot submit its own work and\n * backend-derived workers fall back to their own validity signal. A `string` names an entry in\n * `registry.deliverables`. */\n readonly deliverable?: DeliverableSpec<unknown> | string\n /** Resolve the completion check for one exact authorized backend-derived child. The callback runs\n * after spawn authorization and receives a detached immutable context. It may return `undefined`\n * to use the run-wide `deliverable`; a managed child receives its selected check for direct work. */\n readonly resolveDeliverable?: (\n input: DeliverableResolutionInput,\n ) => DeliverableSpec<unknown> | undefined\n /** Name→value tables for the four code-valued options, so a recorded run configuration can name\n * them instead of carrying closures. See {@link SuperviseRegistry}. */\n readonly registry?: SuperviseRegistry\n /** Where the coordination MCP binds when the supervisor is harness-driven. Omit = an ephemeral\n * port on `127.0.0.1`, which an off-host root cannot reach. A non-loopback host is refused\n * unless authentication is configured; provider managers also need a reachable public URL. */\n readonly coordination?: CoordinationBinding\n /** OPT-IN peer mail for the run's workers: sibling-to-sibling `send_mail` / `read_mail`, bounded\n * and audited (`CoordinationToolsOptions.peerMail`). The runtime mints one capability URL per\n * spawn, serves the mail listener beside the coordination MCP, and hands each worker its\n * endpoint on {@link WorkerSpawnContext.peerMailUrl}.\n *\n * On the backend-derived worker path the runtime also MOUNTS that endpoint, the way a driver\n * receives its coordination MCP: out of band on the bridge's `runtime_attachments`, so the\n * authored profile digest never moves, and inside the leaf factory, so `authorizeSpawn` has\n * already decided the profile. A `bridge` worker therefore calls `send_mail` / `read_mail` as\n * native tools. `router`, `router-tools` and `provider` workers run no MCP client, so the URL\n * stays the caller's to use; every other backend refuses the spawn rather than mint a\n * capability it can never reach. A caller-owned `makeWorkerAgent` owns its own mount.\n *\n * Requires a harness-brained supervisor; a router-brained supervisor is refused rather than\n * silently unmailed. */\n readonly peerMail?: boolean | { limits?: Partial<PeerMailLimits> }\n /** Override the worker seam directly (tests / advanced) instead of deriving it from `backend`.\n * This is caller-owned execution: profile security, spawn authorization, and recursive-driver\n * selection below apply only to the backend-derived worker path. `authorizeMessage` still\n * governs continuations sent through Runtime's coordination tools. */\n readonly makeWorkerAgent?: MakeWorkerAgent\n /** Override ONLY how an authorized LEAF executes, keeping the whole backend-derived path —\n * profile security, spawn authorization, recursive-driver selection, nested supervisors — in\n * force. Unlike `makeWorkerAgent`, which replaces that path, this slots inside it: the kernel\n * authorizes and classifies every spawn, and a child that is NOT a driver runs through this\n * factory instead of `backend`. A child that IS a driver still becomes a nested supervisor, whose\n * own leaves use this same factory. Composes with `authorizeSpawn`; `backend` is then optional.\n * This is the seam an offline test or a pinning layer (an agent graph) should use. */\n readonly makeLeafAgent?: MakeWorkerAgent\n /** Run harness-brained supervisors here. Automatic execution supports a local `bridge`, or a\n * provider advertising runtime MCP attachments with authenticated `coordination.publicUrl`.\n * Defaults to `backend`; separate it when managers and workers use different services. */\n readonly driverBackend?: ExecutorConfig\n /** Security policy applied to every manager-authored child profile before budget reservation.\n * The default blocks local and remote MCP, hooks, and connection grants. Pass an explicit\n * allowlist to grant remote MCP hosts or other author-controlled capabilities. */\n readonly profileSecurity?: AgentProfileSecurityPolicy\n /** Product authority over one complete manager-authored spawn. The callback sees the detached,\n * immutable profile, task, budget, label, and key together, so approving a profile cannot\n * authorize a different task. Return the exact allowed profile (which may be narrowed) plus\n * trusted candidate/pursuit attribution, or throw to refuse the whole spawn before reservation. */\n readonly authorizeSpawn?: (input: {\n readonly profile: AgentProfile\n readonly parent: AgentProfile\n /** Trusted identity of the manager authorizing this exact child. */\n readonly parentIdentity: NodeExecutionIdentity\n /** Concrete manager node; never accepted from model-authored tool arguments. */\n readonly parentNodeId: string\n /** Stable manager-scoped assignment, including deterministic unkeyed siblings. */\n readonly assignmentId: string\n readonly task: unknown\n readonly budget: Budget\n readonly label: string\n readonly key?: string\n readonly depth: number\n /** Present (as the analyst id) only when the runtime's analyst-on-settle hook initiated this\n * spawn — authored by the runtime, never accepted from a driver's tool arguments. A node-pinning\n * authority reads it to admit the analyst node it would refuse as a driver-authored spawn. */\n readonly analyst?: string\n /** The EFFECTIVE continuity of this spawn, resolved by the coordination layer. */\n readonly continuity?: ContinuityMode\n }) => AuthorizedSpawn\n /** Product authority over every continuation sent to a live child. When spawn authorization is\n * enabled, omitting this refuses steer/answer instructions instead of silently extending the\n * authorized task. The exact worker identity and detached bytes are recorded before delivery. */\n readonly authorizeMessage?: (\n input: DownMessageAuthorizationInput & {\n readonly parent: AgentProfile\n readonly depth: number\n },\n ) => AuthorizedDownMessage\n /** The supervisor's router substrate (`profile.harness` omitted or `cli-base`). The profile's\n * model wins. */\n readonly router?: RouterTransportConfig\n /** When `driverBackend` is absent, whether an external-harness ROOT may default to running on\n * `backend` (where workers run). `true` (default) keeps the convenience every direct caller has.\n * A layer that gives `backend` a narrower meaning — `runGraph`, where it places WORKER nodes only\n * — sets `false`, so an external root without an explicit `driverBackend` is refused before any\n * compute rather than silently driven from the worker placement. */\n readonly rootDriverFromBackend?: boolean\n /** Pre-journal profile resolution for the spawn pre-flight: the profile a driver authored →\n * the profile that will run (`CoordinationToolsOptions.resolveSpawnProfile`). A pinning layer\n * sets this alongside `authorizeSpawn` so the backend gate and the authorization see the same\n * canonical profile. Identity-free and synchronous; throw to refuse. */\n readonly resolveSpawnProfile?: (profile: AgentProfile) => AgentProfile\n /** Run an external-harness supervisor explicitly. Required for a remote sandbox; optional as a\n * caller-owned override for a local bridge. */\n readonly driveHarness?: DriveHarness\n /**\n * How hard a transiently-failed EXTERNAL driver is re-entered before the run ends\n * `driver-failed`. A harness process SIGKILLed at a bridge timeout, a stream cut mid-turn, or an\n * upstream 5xx used to end a run of arbitrary length while its budget and deadline sat almost\n * untouched (#741). A retry re-enters the driver over the SAME scope, coordination server, and\n * live children; the bridge backend reattaches the harness session by its durable execution id.\n *\n * Runtime's own refusals (a validation guard, an exhausted budget, an abort, a client-side\n * transport status) are never retried — they were decisions. Retries stop at the budget, the\n * deadline, an abort, or a run of attempts that changed nothing at all.\n *\n * Omit = retry under the defaults. `{ enabled: false }` = the historical behavior where the first\n * driver failure ends the run. Applies to the root manager and every recursive manager under it.\n */\n readonly driverRetry?: DriverRetryPolicy\n /** Per-attempt record for every external driver in the tree — what makes \"failed after N\n * attempts, last cause X\" visible instead of one backend's last words. */\n readonly onDriverAttempt?: (record: DriverAttemptRecord) => void | Promise<void>\n /**\n * How a BACKEND-DERIVED WORKER whose spawn was refused before it ran is re-entered, instead of\n * settling dead with a slot free seconds later.\n *\n * `driverRetry` guards the root only. A worker that dies is typed into a `down` settlement,\n * which is the right shape when the worker RAN — and the wrong shape for\n * `host-executor: acquire timeout after 60000ms (in_flight=4/4, queued=1)`, a queue refusal the\n * bridge emits before any harness child exists. Measured 2026-08-22 on discovery-lab cells\n * oscnp s2/s3: ten live agents on one bridge that admits four, and every worker refused at the\n * 60 s acquire deadline was lost for the whole run.\n *\n * Fail-closed on two proofs that the attempt did no work: the error carries a pre-spawn\n * signature, AND the attempt yielded no execution event. An attempt that streamed anything may\n * have metered usage, so a blind re-run would double-spend and stays fatal.\n *\n * Omit = no retry, the historical behaviour. Applies to backend-derived leaves, including those\n * a `makeLeafAgent` builds; a caller-owned `makeWorkerAgent` composes\n * {@link withWorkerSpawnRetry} itself.\n */\n readonly workerRetry?: WorkerSpawnRetryPolicy\n /** Per-re-entry record for every retried worker spawn — what makes a saturated executor visible\n * as waiting rather than as a worker that silently took longer. */\n readonly onWorkerRetry?: (attempt: WorkerSpawnRetryAttempt) => void\n /**\n * How many times an EXTERNAL-harness driver that RETURNED with `deliverable` still unmet is\n * re-entered on the SAME live session with the unmet items.\n *\n * A harness owns its own turn loop, so it decides when it is finished — and it can decide that\n * while the run has produced nothing. Measured on discovery-lab (2026-09-01, n = 1,422 settled\n * runs): 376 of 376 winning runs ended on the driver's own completion, and the completion gate\n * could only LABEL an undelivered result `valid:false`, never send the driver back for it.\n *\n * A re-prompt is the retry path, not a second loop: same scope, same coordination server, same\n * live children, and the same budget, deadline, abort, and `driverRetry.maxAttempts` bounds. A\n * run the coordination server already stopped is never re-prompted — that stop was a decision.\n *\n * Requires `deliverable`, and applies to every external manager with a completion check. A\n * recursive manager receives the check selected for its exact assignment. Refused for a\n * router-brained manager, which runs its turn loop in process. Omit/`0` = never.\n */\n readonly repromptOnUnmet?: number\n /** Compose the re-entry instruction for an unmet contract, or return `'stop'` to end the run.\n * Requires `repromptOnUnmet >= 1`. Omit = Runtime's own instruction, which names what the run\n * owes and reports how many workers passed the check. */\n readonly onUnmetContract?: OnUnmetContract\n /**\n * How long live children may keep running after the root driver returns or fails, before the join\n * barrier cascades the abort into them. `null` waits until children settle or the caller cancels.\n * An explicit run deadline always wins. Omit/`0` = immediate teardown.\n */\n readonly childSettleGraceMs?: number | null\n /**\n * What root settlement does with provider environments that settled children still hold for a\n * retained execution: `'release'` them with one `environment-teardown` receipt each, or `'keep'`\n * them for a later call that resumes this run. Default: `'keep'` with `runDir` (re-running the\n * same `runDir` and `runId` resumes), `'release'` without it (nothing can resume an in-memory\n * run). See `SupervisorOpts.retainedAtSettlement`.\n */\n readonly retainedAtSettlement?: 'release' | 'keep'\n /** Resolve one custom external-harness session per trusted manager identity. Use this instead of\n * `driveHarness` when recursive managers must be independently steerable. */\n readonly resolveDriveHarness?: ResolveDriveHarness\n /** Required with a custom `driveHarness` or `resolveDriveHarness`: declares which complete\n * AgentProfile axes that path really applies. Built-in bridge driving supplies its own\n * full-profile contract. */\n readonly driveHarnessMaterialization?: ProfileMaterializationContract\n /** Resolve product-owned tools from the exact trusted manager context. The same descriptors and\n * handlers are bound to router and external-harness managers; resolution happens once per node.\n * Each handler receives that manager scope's live cancellation signal in its trusted invocation\n * context, including recursive parent and root cascades, plus `context.verbs` — that manager's\n * own coordination verbs, callable in code so a product tool can COMPOSE its children (fan out,\n * chain, join, retry) in one tool call instead of one model turn per verb. Every verb crosses\n * the same authorizeSpawn / security / allowedModels gate, pool reservation, `maxLiveWorkers`\n * cap, journal, and bus the MCP verb crosses, at every depth and on both arms. */\n readonly resolveSupervisorTools?: ResolveSupervisorTools\n /**\n * Where an `ask_parent` question goes when it leaves a manager (see {@link EscalateQuestion}).\n *\n * Installed on EVERY manager of the run, at every depth, so a driver's escalation reaches the\n * product's own inbox — a UI, an operator queue, a human. Omit and every manager reports\n * `outcome: 'no-parent'` on `ask_parent`, which is the honest reading when nothing above it is\n * listening: the runtime routes no question to a parent by itself.\n */\n readonly escalateQuestion?: EscalateQuestion\n /** Awaited product transaction hook for every coordination record. `eventId` is stable across a\n * lost acknowledgement and durable restart; the record is not pull-visible until this commits. */\n readonly onCoordinationEvent?: (\n context: SupervisorNodeContext,\n eventId: Sha256Digest,\n record: BusRecord<CoordinationEvent>,\n ) => void | Promise<void>\n /** WORK tools the supervisor may call DIRECTLY — so a recursive atom can ACT (do simple work\n * itself) OR SPAWN (delegate when it needs parallelism), not be a pure manager. Pair with\n * `executeExtraTool`. Router arm only (`profile.harness` omitted or `cli-base`). */\n readonly extraTools?: ReadonlyArray<{\n readonly name: string\n readonly description?: string\n readonly parameters: Record<string, unknown>\n }>\n /** Runs an `extraTools` call; null/undefined falls through to the coordination dispatch. */\n readonly executeExtraTool?: (\n name: string,\n args: Record<string, unknown>,\n ) => Promise<string | null | undefined>\n /** Per-child budget reserved on each spawn. Defaults to a quarter of the pool's tokens. */\n readonly perWorker?: Budget\n /** Hard cap on simultaneously executing spawned workers across the WHOLE recursive tree. The\n * root is excluded; nested drivers and leaves share one allocation, so recursion cannot multiply\n * the cap. Omit/`<= 0` = no cap (the conserved pool stays the only bound). */\n readonly maxLiveWorkers?: number\n /** Analyst lenses available to the driver. Required for `analyzeOnSettle`. Unset → status quo\n * (the driver receives settled worker outputs, no analyst findings). A `string` names an entry in\n * `registry.analysts`. */\n readonly analysts?: AnalystRegistry | string\n /** Analyst kind ids run AUTOMATICALLY when a worker settles `done` — each re-enters as a `finding`\n * the driver pulls (`await_event`) and composes its next steer from. The self-improving UP-leg,\n * threaded to the driver at this level (propagate to sub-drivers via a recursive `makeWorkerAgent`).\n * Omit/empty = status quo (no analyst feed). Requires `analysts`. */\n readonly analyzeOnSettle?: ReadonlyArray<string | AnalyzeOnSettleRoute>\n /**\n * Watch every worker's LIVE tool trace with the online detector panel and raise a `finding` the\n * moment one loops or error-storms — so the supervisor learns it mid-run (via `await_event`)\n * instead of at settle. Pairs with a steerable worker: the finding is the evidence, `steer_agent`\n * is the correction. Requires a backend whose executor exposes a trace source (the steerable\n * sandbox worker and the pi wrapper do); other runtimes are simply not watched.\n *\n * Omit = off (status quo — no online watching, no extra events).\n */\n readonly watchWorkers?: WorkerWatchOptions\n /** Idle time after which `observe_agent` reports a running worker as `stalled`. A derived read\n * at observation time — nothing is killed or retried. Omit = the runtime default. */\n readonly stallAfterMs?: number\n /** Default continuity per worker PROFILE NAME: `'resume'` makes each spawn of that name after\n * the first re-attach to the node's most recent SETTLED worker — a NEW live worker whose spawn\n * context carries the prior worker's identity (`WorkerSpawnContext.resume`), which the executor\n * seam re-attaches with. `spawn_worker`'s per-call `continuity` argument overrides in either\n * direction; `runGraph` derives this from delegates-edge `continuity`. Omit = every spawn is\n * `'fresh'` (status quo). See `CoordinationToolsOptions.continuityByProfile` for the\n * refusal semantics (no-prior / while-live / with-key) and the process-local resume boundary. */\n readonly continuityByProfile?: Readonly<Record<string, ContinuityMode>>\n /** Worker output store. Defaults to in-memory. */\n readonly blobs?: ResultBlobStore\n /**\n * Make the run DURABLE: journal + result blobs + the coordination side-log are file-backed under\n * this directory (`createFileRunContext`), fsynced per write, and the supervisor reads the prior\n * tree first. Re-running with the same `runDir` AND the same `runId` resumes only when the exact\n * root profile/task identity and declared budget match. The original absolute deadline and prior\n * measured spend are restored before new admission. The built-in driver is resume-aware: children\n * that already settled, including their exact execution identities, are replayed onto\n * `Scope.resume` (and into the driver's settled ledger + its first context), keyed assignments\n * (`spawn_worker`'s `key`) resolve to their committed results instead of re-running, pending\n * waits re-arm on their original deadlines, and the coordination log loads prior questions,\n * findings, and instruction receipts. The router arm receives all three in its resume brief; the\n * external arm seeds prior questions while findings and receipts remain in the durable log.\n * Instruction receipts are evidence and are never delivered automatically to a replacement\n * worker. The final result spans both processes' work. Unset = in-memory, fresh every call.\n *\n * The boundary that remains: work that was IN FLIGHT when the process died is not recovered —\n * the built-in executors cannot re-attach to a dead process's executions. Each such keyed\n * assignment resumes as `in-doubt`, its full declared reservation stays charged, and its\n * token/dollar telemetry remains unknown. Runtime refuses a replacement under that key until the\n * exact prior execution is recovered, so restart cannot duplicate work or slide the deadline.\n *\n * `runId` matters here: it defaults to the constant `'supervise'`, which is fine for a single\n * resumable run per directory but collides across concurrent runs sharing one `runDir`.\n */\n readonly runDir?: string\n /** Override the spawn journal directly (advanced; `runDir` is the ordinary durable path). Pair\n * with `blobs` — a journal whose result payloads live in a different store cannot replay. */\n readonly journal?: SpawnJournal\n /** Predicate registry for `poll` wait-states (`Scope.wait`). A `poll` names its predicate so the\n * wait survives a restart; this is what the name resolves against. Unset ⇒ `poll` waits are\n * refused `unknown-probe` and `timer` waits still work. A `string` names an entry in\n * `registry.probes`. */\n readonly probes?: WaitProbeRegistry | string\n /**\n * PROGRESS-derived stop rule (BOTH arms). Ends a run that has stopped LEARNING before it\n * exhausts a ceiling — the answer to \"a run should end because it is done or stuck, not because\n * it ran out\". It composes with the budget guards and can never override one.\n *\n * The evaluation boundary differs by arm because the loop does: a router-brained supervisor is\n * evaluated before each of its own inference turns; a harness-brained supervisor is evaluated on\n * each worker settle, and a stop aborts its stop signal so the harness ends at its next turn\n * boundary. Both arms fold the same settled ledger through the same evaluator.\n *\n * Build it from `supervise/stop-rules`: `plateau({window, minDelta})`,\n * `noProgressFor({ms, settles})`, `allWorkersStalled({...})`, combined with `anyOf`/`allOf`. The\n * thresholds are policy and stay with you; the enforcement lives in the runtime. Omit = ceilings\n * only (unchanged behavior).\n */\n readonly stopRule?: StopRule\n /** One-shot notification of WHY a `stopRule` ended the run (BOTH arms) — so a caller records the\n * reason instead of inferring an early stop from an unexhausted budget. */\n readonly onProgressStop?: (reason: string) => void\n readonly maxDepth?: number\n /** Turn cap for the supervisor's OWN loop (BOTH arms). Router arm: inference turns of the\n * driver's tool loop. Harness arm: turns the harness reports, counted off its `iteration`\n * stream — reaching the cap aborts the stop signal, so the harness ends at its next turn\n * boundary rather than mid-request. `0` lifts the cap on both arms and leaves the conserved\n * pool, the deadline, and abort as the bounds; a negative value is refused. Omit = the router\n * arm's default cap, and no turn cap on the harness arm. */\n readonly maxTurns?: number\n /** Give the supervisor brain a chapter-lifecycle on its OWN context window (ROUTER ARM ONLY —\n * a harness owns its own context window and its own compaction, so this is refused for a\n * harness-brained supervisor rather than silently ignored): once its coordination transcript\n * exceeds `thresholdTokens` it distills to a compact progress note and continues, instead of\n * re-billing the whole transcript every turn (the cost that makes the LLM-brain front door lose\n * to a dumb-Ralph respawn). The live `Scope` roster is the durable state across chapters.\n * Default off. `distill` defaults to a brain self-summary + the settled-worker roster. */\n readonly compaction?: ToolLoopCompactionOptions\n readonly runId?: string\n readonly now?: () => number\n /** Restrict the run to this subset of models. When set, every configured model — the\n * supervisor router model, the profile's model, and the backend's model — must be a member,\n * or `supervise()` throws a `ConfigError` before any compute is spent. Unset = unrestricted.\n *\n * This is a MODEL-ID filter, not a route filter. The compared values are the bare ids a profile\n * declares — `model.default`, `model.small`, `subagents[].model`, `modes[].model`. The composed\n * wire id (`harness/provider/model`) is never built here and never compared, so an entry written\n * in qualified form matches nothing, and a child that names an allowed id is admitted whatever\n * harness and provider its own profile declares. Pin the route with `authorizeSpawn`: it reads\n * the authored child profile and may refuse the spawn before any reservation. */\n readonly allowedModels?: readonly string[]\n /** How the settled-worker ledger becomes the run's output. Default `bestDelivered` — the single\n * highest-scoring DELIVERED child (the exact behavior every existing caller had). Alternatives:\n * `collectDelivered` (every verified distinct output with provenance — a Pareto set / recorded\n * disagreement) or a custom `SupervisorFinalizer`. Whatever the finalizer, it operates on\n * structurally DELIVERED outputs only — an undelivered or invalid child stays ineligible. A\n * `string` names an entry in `registry.finalizers`. */\n readonly finalizer?: SupervisorFinalizer | string\n /** Lifecycle observers for the whole recursive tree (`Scope` re-seeds them into every nested\n * scope). Composed with the `otel` recorder below when both are set. Omit = no observers, which\n * is the behavior every existing caller has. */\n readonly hooks?: RuntimeHooks\n /**\n * OPT-IN OTLP tracing: emit one span per supervised node (opened at spawn, closed at settle,\n * parented to its parent node's span) plus an `LLM` child span per metered driver turn, so the\n * tree is readable by any trace viewer instead of only by a journal parser. See `otel-spans.ts`.\n *\n * Omit and the run emits nothing, allocates no recorder, and installs no hook — telemetry is\n * never a default. Present with no reachable endpoint (no `exportConfig.endpoint` and no\n * `OTEL_EXPORTER_OTLP_ENDPOINT`) is also a no-op. The spawn journal is untouched either way:\n * spans are telemetry, never the replay/resume record.\n */\n readonly otel?: Omit<SupervisorSpanOptions, 'runId' | 'now'>\n}\n\n/**\n * Every `SuperviseOptions` key, as data.\n *\n * `supervise()` reads the options it knows and leaves the rest untouched, so a key no reader\n * consults — a typo, or a seam whose name moved in a later version — is discarded in silence: the\n * call type-checks against a widened value, the run succeeds, and the capability the caller asked\n * for is simply not there. Nothing downstream can detect that, because nothing downstream knows it\n * was supposed to happen. {@link assertSuperviseOptionKeys} turns it into a refusal before any\n * compute, naming the key.\n *\n * The two assignments below fail to COMPILE, naming the offender, when this list and\n * `keyof SuperviseOptions` disagree in either direction — a new option cannot go missing from it,\n * and a removed one cannot linger.\n */\nconst superviseOptionKeys = [\n 'allowedModels',\n 'analysts',\n 'analyzeOnSettle',\n 'authorizeMessage',\n 'authorizeSpawn',\n 'backend',\n 'blobs',\n 'budget',\n 'childSettleGraceMs',\n 'retainedAtSettlement',\n 'compaction',\n 'continuityByProfile',\n 'coordination',\n 'deliverable',\n 'driveHarness',\n 'driveHarnessMaterialization',\n 'driverBackend',\n 'driverRetry',\n 'executeExtraTool',\n 'execution',\n 'extraTools',\n 'finalizer',\n 'hooks',\n 'journal',\n 'makeLeafAgent',\n 'makeWorkerAgent',\n 'escalateQuestion',\n 'maxDepth',\n 'maxLiveWorkers',\n 'maxTurns',\n 'now',\n 'onCoordinationEvent',\n 'onDriverAttempt',\n 'onProgressStop',\n 'otel',\n 'peerMail',\n 'perWorker',\n 'probes',\n 'profileSecurity',\n 'registry',\n 'resolveDeliverable',\n 'resolveDriveHarness',\n 'resolveSpawnProfile',\n 'resolveSupervisorTools',\n 'rootDriverFromBackend',\n 'rootHandle',\n 'router',\n 'runDir',\n 'runId',\n 'signal',\n 'stallAfterMs',\n 'stopRule',\n 'watchWorkers',\n 'repromptOnUnmet',\n 'onUnmetContract',\n 'workerRetry',\n 'onWorkerRetry',\n] as const\n\ntype UnlistedSuperviseOption = Exclude<keyof SuperviseOptions, (typeof superviseOptionKeys)[number]>\n/** A `SuperviseOptions` key missing from `superviseOptionKeys` makes this assignment fail, and the\n * compiler error names the key. Add it to the list. */\nconst everySuperviseOptionIsListed: UnlistedSuperviseOption extends never\n ? true\n : UnlistedSuperviseOption = true\nvoid everySuperviseOptionIsListed\n\ntype StaleSuperviseOptionKey = Exclude<(typeof superviseOptionKeys)[number], keyof SuperviseOptions>\n/** A listed key that `SuperviseOptions` no longer declares makes this assignment fail. Remove it,\n * or the check would accept an option no reader consults. */\nconst everyListedSuperviseOptionExists: StaleSuperviseOptionKey extends never\n ? true\n : StaleSuperviseOptionKey = true\nvoid everyListedSuperviseOptionExists\n\nconst superviseOptionKeySet: ReadonlySet<string> = new Set<string>(superviseOptionKeys)\n\n/**\n * Refuse a top-level option key `supervise()` reads nowhere, naming it.\n *\n * The shape is `assertExactConfigKeys`, which does the same for one executor configuration: an\n * unknown field is a caller asking for behavior that will not happen, and intake is the only\n * moment it is observable. The error class is not the same, on purpose. A bad `SuperviseOptions`\n * key is a configuration fault, and `ConfigError` is already what `supervise()` throws for one —\n * see `resolveNamed`, for an option that names a registry entry the registry does not hold.\n */\nfunction assertSuperviseOptionKeys(opts: SuperviseOptions, context: string): void {\n const unknown = Object.keys(opts).filter((key) => !superviseOptionKeySet.has(key))\n if (unknown.length > 0) {\n throw new ConfigError(\n `${context}: unknown option ${unknown.sort().join(', ')} — no reader consults that name, ` +\n 'so the value would be discarded and the capability it asks for would silently be absent',\n )\n }\n}\n\n/** The product-authorized result for one complete spawn request. Attribution is never accepted\n * from the manager itself; it enters only through this trusted callback. */\nexport interface AuthorizedSpawn {\n readonly profile: AgentProfile\n readonly execution?: AgentExecutionRef\n}\n\n/** Exact trusted context after a manager-authored spawn has passed product authorization. */\nexport interface AuthorizedSpawnContext {\n readonly profile: AgentProfile\n readonly parent: AgentProfile\n readonly parentIdentity: NodeExecutionIdentity\n readonly execution: NodeExecutionIdentity\n readonly parentNodeId: string\n readonly assignmentId: string\n readonly task: unknown\n readonly budget: Budget\n readonly label: string\n readonly key?: string\n readonly depth: number\n}\n\n/** Exact trusted context for selecting one backend-derived leaf's completion check. */\nexport type DeliverableResolutionInput = AuthorizedSpawnContext\n\nfunction captureDeliverable(\n deliverable: DeliverableSpec<unknown>,\n context: string,\n): DeliverableSpec<unknown> {\n if (typeof deliverable !== 'object' || deliverable === null || Array.isArray(deliverable)) {\n throw new ValidationError(`${context}: deliverable must be an object`)\n }\n if (typeof deliverable.check !== 'function') {\n throw new ValidationError(`${context}: deliverable.check must be a function`)\n }\n return Object.freeze({\n ...detachedSnapshot({ describe: deliverable.describe }, `${context} configuration`),\n check: deliverable.check,\n })\n}\n\n/**\n * Every `SuperviseOptions` key whose value IS a callback, as data.\n *\n * `captureSuperviseOptions` detaches its decision data with `detachedSnapshot`, which\n * structured-clones. A function cannot be structured-cloned, so a callback key that the capture\n * does not lift out of the remainder makes `supervise()` throw\n * `supervise options: input must be structured-cloneable` before any compute — a refusal that names\n * the snapshot rather than the option, so a caller reads it as a bad value and not as a capability\n * the entry point cannot carry.\n *\n * That is what happened to `onUnmetContract`: added with the re-prompt path in 0.186.0, accepted by\n * the option-key check, forwarded by `supervisorAgent`, read by the retry loop, and never\n * destructured here. Every `supervisePursuit` run that passed the callback failed at construction\n * on 0.186.0, 0.187.1 and 0.188.0, and the only working configuration was the number alone.\n *\n * The assignment below fails to COMPILE, naming the offender, when a callback-valued option is not\n * in this list, so the next one cannot be added silently. The list is not merely documentation:\n * {@link assertNoUncapturedExecutableOption} refuses at runtime any callback that still reaches the\n * snapshot, including one nested in an option this type test cannot see.\n */\nconst superviseExecutableOptionKeys = [\n 'authorizeMessage',\n 'authorizeSpawn',\n 'driveHarness',\n 'escalateQuestion',\n 'executeExtraTool',\n 'finalizer',\n 'makeLeafAgent',\n 'makeWorkerAgent',\n 'now',\n 'onCoordinationEvent',\n 'onDriverAttempt',\n 'onProgressStop',\n 'onUnmetContract',\n 'onWorkerRetry',\n 'resolveDeliverable',\n 'resolveDriveHarness',\n 'resolveSpawnProfile',\n 'resolveSupervisorTools',\n 'stopRule',\n] as const\n\n/** A `SuperviseOptions` key whose value is callable. An object-valued option that CONTAINS a\n * callback (`router.complete`, `compaction.distill`, `analysts.run`) is captured field by field and\n * is deliberately outside this test; the runtime guard covers what a type cannot see. */\ntype CallableSuperviseOption = {\n [K in keyof SuperviseOptions]-?: NonNullable<SuperviseOptions[K]> extends (\n ...args: never[]\n ) => unknown\n ? K\n : never\n}[keyof SuperviseOptions]\n\ntype UncapturedCallableOption = Exclude<\n CallableSuperviseOption,\n (typeof superviseExecutableOptionKeys)[number]\n>\n/** A callback-valued option missing from `superviseExecutableOptionKeys` makes this assignment\n * fail, and the compiler error names the key. Add it to the list AND to the destructuring below —\n * the list alone carries no value through. */\nconst everyCallableOptionIsListed: UncapturedCallableOption extends never\n ? true\n : UncapturedCallableOption = true\nvoid everyCallableOptionIsListed\n\ntype StaleExecutableOptionKey = Exclude<\n (typeof superviseExecutableOptionKeys)[number],\n keyof SuperviseOptions\n>\n/** A listed key that `SuperviseOptions` no longer declares makes this assignment fail. */\nconst everyListedExecutableOptionExists: StaleExecutableOptionKey extends never\n ? true\n : StaleExecutableOptionKey = true\nvoid everyListedExecutableOptionExists\n\n/** The callback-valued options, for a test that proves the capture forwards each one. */\nexport const SUPERVISE_EXECUTABLE_OPTION_KEYS: ReadonlyArray<keyof SuperviseOptions> =\n Object.freeze([...superviseExecutableOptionKeys])\n\n/**\n * Refuse a callback that reached the decision-data remainder, naming the option.\n *\n * The type test above cannot see a callback nested inside an object-valued option, and\n * `detachedSnapshot` would report only that its input is not structured-cloneable. This says which\n * key carries the callback and what to do about it, so the next occurrence is a five-second fix\n * instead of a bisect over every option a caller passed.\n */\nfunction assertNoUncapturedExecutableOption(decisionData: Readonly<Record<string, unknown>>): void {\n const carried = Object.entries(decisionData)\n .filter(([, value]) => typeof value === 'function')\n .map(([key]) => key)\n if (carried.length > 0) {\n throw new ValidationError(\n `supervise: option ${carried.sort().join(', ')} carries a callback that the option capture ` +\n 'does not forward, so the run would fail on a structured-clone refusal that names the ' +\n 'snapshot instead of the option; lift the key out of the decision data in ' +\n 'captureSuperviseOptions and add it to superviseExecutableOptionKeys',\n )\n }\n}\n\n/** Capture the public one-call configuration before any asynchronous work starts. Decision data is\n * detached and frozen; executable ports are copied as the exact references selected at intake.\n * Service internals intentionally remain live, while replacing a callback/service on the caller's\n * mutable options object can no longer change an in-flight run. */\n/** The directory a root manager's spawn may resolve an inline resource `path` under. Only a\n * loopback bridge driver has one this process can read: its `cwd` is a directory on this host.\n * A remote bridge, a provider sandbox, or an in-process driver with no cwd yields `undefined`. */\nexport function rootSpawnResourceRoot(backend: ExecutorConfig | undefined): string | undefined {\n if (backend === undefined || backend.backend !== 'bridge' || backend.cwd === undefined)\n return undefined\n let host: string\n try {\n host = new URL(backend.bridgeUrl).hostname\n } catch {\n return undefined\n }\n return isLoopbackHost(host) ? resolve(backend.cwd) : undefined\n}\n\nexport function captureSuperviseOptions(opts: SuperviseOptions): SuperviseOptions {\n assertSuperviseOptionKeys(opts, 'supervise')\n const {\n backend,\n coordination,\n driverBackend,\n deliverable,\n resolveDeliverable,\n router,\n compaction,\n watchWorkers,\n analysts,\n makeWorkerAgent,\n makeLeafAgent,\n resolveSpawnProfile,\n blobs,\n journal,\n probes,\n registry,\n hooks,\n otel,\n authorizeSpawn,\n authorizeMessage,\n driveHarness,\n resolveDriveHarness,\n resolveSupervisorTools,\n escalateQuestion,\n onCoordinationEvent,\n executeExtraTool,\n stopRule,\n onProgressStop,\n onDriverAttempt,\n onUnmetContract,\n workerRetry,\n onWorkerRetry,\n finalizer,\n now,\n signal,\n rootHandle,\n ...decisionData\n } = opts\n assertNoUncapturedExecutableOption(decisionData)\n const capturedData = detachedSnapshot(decisionData, 'supervise options')\n const capturedCoordination =\n coordination === undefined\n ? undefined\n : (() => {\n const { publicUrl, onAudit, ...configuration } = coordination\n return Object.freeze({\n ...detachedSnapshot(configuration, 'supervise coordination configuration'),\n ...(publicUrl === undefined ? {} : { publicUrl }),\n ...(onAudit === undefined ? {} : { onAudit }),\n })\n })()\n const capturedBackend = backend === undefined ? undefined : snapshotExecutorConfig(backend)\n const capturedDriverBackend =\n driverBackend === undefined ? undefined : snapshotExecutorConfig(driverBackend)\n // A string names a registry entry; it is resolved (and the resolved spec validated) by\n // `resolveNamed` before anything is built or spent.\n const capturedDeliverable =\n deliverable === undefined || typeof deliverable === 'string'\n ? deliverable\n : captureDeliverable(deliverable, 'supervise deliverable')\n const capturedRouter =\n router === undefined\n ? undefined\n : (() => {\n const { complete, ...routerData } = router\n return Object.freeze({\n ...detachedSnapshot(routerData, 'supervise router configuration'),\n ...(complete === undefined ? {} : { complete }),\n })\n })()\n const capturedCompaction =\n compaction === undefined\n ? undefined\n : (() => {\n const { distill, estimateTokens, onCompact, ...compactionData } = compaction\n return Object.freeze({\n ...detachedSnapshot(compactionData, 'supervise compaction configuration'),\n ...(distill === undefined ? {} : { distill }),\n ...(estimateTokens === undefined ? {} : { estimateTokens }),\n ...(onCompact === undefined ? {} : { onCompact }),\n })\n })()\n const capturedWatchWorkers =\n watchWorkers === undefined\n ? undefined\n : Object.freeze({\n ...detachedSnapshot(\n { maxFindingsPerWorker: watchWorkers.maxFindingsPerWorker },\n 'supervise worker-watch configuration',\n ),\n ...(watchWorkers.detectors === undefined\n ? {}\n : { detectors: Object.freeze([...watchWorkers.detectors]) }),\n })\n // A RegExp does not survive a JSON snapshot, so the policy's numbers are snapshot and its\n // signatures are copied as the exact values the caller selected.\n const capturedWorkerRetry =\n workerRetry === undefined\n ? undefined\n : Object.freeze({\n ...detachedSnapshot(\n {\n ...(workerRetry.enabled === undefined ? {} : { enabled: workerRetry.enabled }),\n ...(workerRetry.maxTotalMs === undefined\n ? {}\n : { maxTotalMs: workerRetry.maxTotalMs }),\n ...(workerRetry.initialBackoffMs === undefined\n ? {}\n : { initialBackoffMs: workerRetry.initialBackoffMs }),\n ...(workerRetry.maxBackoffMs === undefined\n ? {}\n : { maxBackoffMs: workerRetry.maxBackoffMs }),\n },\n 'supervise worker-retry configuration',\n ),\n ...(workerRetry.additionalPreSpawnSignatures === undefined\n ? {}\n : {\n additionalPreSpawnSignatures: Object.freeze([\n ...workerRetry.additionalPreSpawnSignatures,\n ]),\n }),\n })\n\n // Rebuilt field by field so a caller's mutable registry object cannot be held live. EVERY\n // callable field must be listed: an omitted one is silently dropped at intake and the capability\n // it carries disappears from every manager in the tree with no type error, because the field is\n // optional. `register` is what mounts `define_analyst`.\n const capturedAnalysts =\n analysts === undefined || typeof analysts === 'string'\n ? analysts\n : Object.freeze({\n kinds: detachedSnapshot(analysts.kinds, 'supervise analyst kinds'),\n run: analysts.run,\n ...(typeof analysts.register === 'function' ? { register: analysts.register } : {}),\n })\n\n return Object.freeze({\n ...capturedData,\n ...(capturedCoordination === undefined ? {} : { coordination: capturedCoordination }),\n ...(capturedBackend === undefined ? {} : { backend: capturedBackend }),\n ...(capturedDriverBackend === undefined ? {} : { driverBackend: capturedDriverBackend }),\n ...(capturedDeliverable === undefined ? {} : { deliverable: capturedDeliverable }),\n ...(resolveDeliverable === undefined ? {} : { resolveDeliverable }),\n ...(capturedRouter === undefined ? {} : { router: capturedRouter }),\n ...(capturedCompaction === undefined ? {} : { compaction: capturedCompaction }),\n ...(capturedWatchWorkers === undefined ? {} : { watchWorkers: capturedWatchWorkers }),\n ...(capturedAnalysts === undefined ? {} : { analysts: capturedAnalysts }),\n ...(makeWorkerAgent === undefined ? {} : { makeWorkerAgent }),\n ...(makeLeafAgent === undefined ? {} : { makeLeafAgent }),\n ...(resolveSpawnProfile === undefined ? {} : { resolveSpawnProfile }),\n ...(blobs === undefined ? {} : { blobs }),\n ...(journal === undefined ? {} : { journal }),\n ...(probes === undefined ? {} : { probes }),\n ...(authorizeSpawn === undefined ? {} : { authorizeSpawn }),\n ...(authorizeMessage === undefined ? {} : { authorizeMessage }),\n ...(driveHarness === undefined ? {} : { driveHarness }),\n ...(resolveDriveHarness === undefined ? {} : { resolveDriveHarness }),\n ...(resolveSupervisorTools === undefined ? {} : { resolveSupervisorTools }),\n ...(escalateQuestion === undefined ? {} : { escalateQuestion }),\n ...(onCoordinationEvent === undefined ? {} : { onCoordinationEvent }),\n ...(executeExtraTool === undefined ? {} : { executeExtraTool }),\n ...(stopRule === undefined ? {} : { stopRule }),\n ...(onProgressStop === undefined ? {} : { onProgressStop }),\n ...(onDriverAttempt === undefined ? {} : { onDriverAttempt }),\n ...(onUnmetContract === undefined ? {} : { onUnmetContract }),\n ...(capturedWorkerRetry === undefined ? {} : { workerRetry: capturedWorkerRetry }),\n ...(onWorkerRetry === undefined ? {} : { onWorkerRetry }),\n ...(finalizer === undefined ? {} : { finalizer }),\n ...(now === undefined ? {} : { now }),\n ...(signal === undefined ? {} : { signal }),\n ...(rootHandle === undefined ? {} : { rootHandle }),\n // Live collaborators: registries resolve lazily, hooks and otel exporters are process objects.\n // They are captured as the exact references selected at intake, never deep-snapshot.\n ...(registry === undefined ? {} : { registry }),\n ...(hooks === undefined ? {} : { hooks }),\n ...(otel === undefined ? {} : { otel }),\n })\n}\n\n/**\n * Record what a run-scoped cancel actually did, at the ONE place that observes the run's terminal\n * state: the `supervise()` settle path.\n *\n * The observer writes `cancel_requested` when it issues the abort; only here is the run's own\n * outcome known. An aborted run reads `cancelled` only with confirmed teardown, otherwise `unknown`.\n * A run that reached any other terminal state despite the request terminated nothing and reads `not_live`,\n * never a success. A request the run ended before applying is expired here too, so a reader can\n * tell run-over from in-progress and a stale request cannot outlive its run.\n */\nfunction recordRunCancellationOutcome(\n runDir: string | undefined,\n result: SupervisedResult<unknown>,\n now: () => number,\n): void {\n if (runDir === undefined) return\n const dir = resolve(runDir)\n const request = readRunCancelRequest(dir)\n if (request === undefined) return\n const record = readRunCancellation(dir, request.operationId)\n if (record !== undefined && record.effect !== 'cancel_requested') return\n const aborted =\n result.kind === 'no-winner' &&\n result.reason === 'cancelled' &&\n result.operationId === request.operationId\n const observedAt = new Date(now()).toISOString()\n const base = {\n operationId: request.operationId,\n requestedAt: request.at,\n observedAt,\n ...(record?.path === undefined ? {} : { path: record.path }),\n ...(record?.appliedAfterMs === undefined ? {} : { appliedAfterMs: record.appliedAfterMs }),\n ...(record?.deadlineExceeded === undefined\n ? {}\n : { deadlineExceeded: record.deadlineExceeded }),\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n }\n if (record === undefined) {\n writeRunCancellation(dir, {\n ...base,\n effect: 'not_live',\n detail: 'run ended before the request was applied',\n })\n return\n }\n if (aborted && result.teardownUnconfirmed?.length) {\n writeRunCancellation(dir, {\n ...base,\n effect: 'unknown',\n detail: `run aborted but teardown remains unconfirmed for: ${result.teardownUnconfirmed.map((node) => node.id).join(', ')}`,\n })\n return\n }\n writeRunCancellation(\n dir,\n aborted\n ? { ...base, effect: 'cancelled', detail: 'the run reached its terminal cancelled state' }\n : {\n ...base,\n effect: 'not_live',\n detail: `run settled ${result.kind === 'winner' ? 'winner' : result.reason} despite the abort request; nothing was terminated`,\n },\n )\n}\n\n/** A quarter of token and optional dollar capacity per worker; nested managers partition again. */\n/** A per-child budget may not exceed the conserved pool it is reserved from. */\nfunction assertPerWorkerWithinPool(perWorker: Budget, pool: Budget): void {\n const over = (child: number, total: number, field: string): string | null =>\n child > total\n ? `supervise perWorker.${field} (${child}) exceeds budget.${field} (${total})`\n : null\n for (const [name, resource] of Object.entries(pool.resources ?? {})) {\n const child = perWorker.resources?.[name]\n if (!child)\n throw new ValidationError(\n `supervise perWorker resource ${name}: child must declare its limit`,\n )\n if (child.unit !== resource.unit)\n throw new ValidationError(`supervise perWorker resource ${name}: unit mismatch`)\n const problem = over(child.limit, resource.limit, `resources.${name}.limit`)\n if (problem) throw new ValidationError(problem)\n }\n for (const name of Object.keys(perWorker.resources ?? {})) {\n if (!Object.hasOwn(pool.resources ?? {}, name)) {\n throw new ValidationError(`supervise perWorker resource ${name}: root must declare its limit`)\n }\n }\n const problems = [\n over(perWorker.maxTokens, pool.maxTokens, 'maxTokens'),\n over(perWorker.maxIterations, pool.maxIterations, 'maxIterations'),\n perWorker.maxUsd !== undefined && pool.maxUsd !== undefined\n ? over(perWorker.maxUsd, pool.maxUsd, 'maxUsd')\n : null,\n ].filter((x): x is string => x !== null)\n if (problems.length > 0) {\n throw new ValidationError(\n `${problems.join('; ')} — a per-child ceiling cannot exceed the pool it draws from, and ` +\n 'accepting it silently leaves the caller believing a knob is in effect when the ' +\n 'reservation still clamps the child.',\n )\n }\n}\n\nfunction defaultPerWorker(budget: Budget): Budget {\n return {\n ...(budget.resources === undefined\n ? {}\n : {\n resources: Object.fromEntries(\n Object.entries(budget.resources).map(([name, value]) => [\n name,\n { unit: value.unit, limit: Math.floor(value.limit / 4) },\n ]),\n ),\n }),\n maxIterations: Math.max(1, Math.floor(budget.maxIterations / 4)),\n maxTokens: Math.max(1, Math.floor(budget.maxTokens / 4)),\n ...(budget.maxUsd !== undefined ? { maxUsd: budget.maxUsd / 4 } : {}),\n }\n}\n\nfunction freezeDetached<T>(value: T): T {\n return detachedSnapshot(value, 'supervise')\n}\n\nfunction freezeDetachedProfile(value: unknown): AgentProfile {\n return freezeDetached(agentProfileSchema.parse(value))\n}\n\nfunction canonicalExecution(\n profile: AgentProfile,\n task: unknown,\n rawExecution: AgentExecutionRef | undefined,\n context: string,\n): { readonly identity: NodeExecutionIdentity; readonly ref?: AgentExecutionRef } {\n const execution = rawExecution === undefined ? undefined : freezeDetached(rawExecution)\n if (execution !== undefined) {\n if (typeof execution !== 'object' || execution === null || Array.isArray(execution)) {\n throw new ValidationError(`${context}: execution must be an object`)\n }\n const unknown = Object.keys(execution).filter(\n (key) => key !== 'candidateDigest' && key !== 'correlation',\n )\n if (unknown.length > 0) {\n throw new ValidationError(`${context}: unknown execution fields: ${unknown.join(', ')}`)\n }\n }\n const identity = deriveNodeExecutionIdentity({ profile, execution }, task)\n if (!identity?.profileDigest || !identity.taskDigest) {\n throw new ValidationError(\n `${context}: profile and task must be finite, acyclic canonical JSON for durable identity`,\n )\n }\n const ref: AgentExecutionRef | undefined =\n identity.candidateDigest || identity.correlation\n ? Object.freeze({\n ...(identity.candidateDigest ? { candidateDigest: identity.candidateDigest } : {}),\n ...(identity.correlation ? { correlation: identity.correlation } : {}),\n })\n : undefined\n return { identity, ...(ref ? { ref } : {}) }\n}\n\nfunction rootCoordinationOwner(identity: NodeExecutionIdentity): string {\n return canonicalCandidateDigest({ kind: 'supervisor-root', identity })\n}\n\nfunction childCoordinationOwner(\n parentOwnerId: string,\n identity: NodeExecutionIdentity,\n context: WorkerSpawnContext,\n depth: number,\n): string {\n return canonicalCandidateDigest({\n kind: 'supervisor-child',\n parentOwnerId,\n identity,\n assignment: {\n id: context.assignmentId,\n label: context.label,\n key: context.key ?? null,\n depth,\n },\n })\n}\n\nfunction supervisionRunNamespace(runDir: string | undefined, runId: string): string {\n return canonicalCandidateDigest(\n runDir === undefined\n ? { kind: 'supervise-ephemeral-run', runId, nonce: randomUUID() }\n : { kind: 'supervise-durable-run', runId, runDir: resolve(runDir) },\n )\n}\n\nfunction workerAssignmentNamespace(\n runNamespace: string,\n parentOwnerId: string,\n assignmentId: string,\n): string {\n return canonicalCandidateDigest({\n kind: 'supervise-worker-assignment',\n runNamespace,\n parentOwnerId,\n assignmentId,\n })\n}\n\n/** Hash only durable coordination meaning. Bus sequence/timestamp are delivery metadata and a\n * resumed projection's marker describes the reader, not the original settlement. */\nfunction coordinationEventId(\n context: SupervisorNodeContext,\n event: CoordinationEvent,\n): Sha256Digest {\n const durableEvent =\n event.type === 'settled' && event.worker.resumed === true\n ? (() => {\n const { resumed: _resumed, ...worker } = event.worker\n return { type: 'settled' as const, worker }\n })()\n : event\n return canonicalCandidateDigest({\n kind: 'supervise-coordination-event',\n runNamespace: context.runNamespace,\n ownerId: context.ownerId,\n event: detachedSnapshot(durableEvent, 'supervise coordination event identity'),\n })\n}\n\n/** Test-only one-call shape, exported only through the package's explicit `/testing` entry. */\nexport interface SuperviseTestOptions extends SuperviseOptions {\n readonly brain: ToolLoopChat\n}\n\n/** One-call supervisor: build + run a supervisor from its exact profile. @stable */\nexport function supervise(profile: SupervisorProfile, task: unknown, opts: SuperviseOptions) {\n if ('brain' in opts) {\n throw new ValidationError(\n 'supervise: direct brain injection is test-only; production execution derives the model call from AgentProfile',\n )\n }\n return superviseInternal(profile, task, opts)\n}\n\n/** Deterministic scripted-brain path for tests. Not exported from Runtime's main entry. */\nexport function superviseWithTestBrain(\n profile: SupervisorProfile,\n task: unknown,\n opts: SuperviseTestOptions,\n) {\n const { brain, ...runtimeOptions } = opts\n return superviseInternal(profile, task, runtimeOptions, brain)\n}\n\nfunction superviseInternal(\n profile: SupervisorProfile,\n task: unknown,\n opts: SuperviseOptions,\n testBrain?: ToolLoopChat,\n) {\n const options = captureSuperviseOptions(opts)\n assertValidBudget(options.budget, 'supervise budget')\n // Fail loud before any compute: every configured model must be in the allowed subset (no-op\n // when allowedModels is unset). The backend seam carries its own model on most backends.\n const parsedProfile = agentProfileSchema.safeParse(profile)\n if (!parsedProfile.success) {\n throw new ValidationError(`supervise: invalid AgentProfile: ${parsedProfile.error.message}`)\n }\n const canonicalProfile = freezeDetachedProfile(parsedProfile.data)\n assertExecutableAgentProfile(canonicalProfile, 'supervise root')\n const canonicalTask = freezeDetached(task)\n if (options.makeWorkerAgent && options.authorizeSpawn) {\n throw new ValidationError(\n 'supervise: authorizeSpawn cannot be combined with caller-owned makeWorkerAgent; use makeLeafAgent to override leaf execution inside the authorized path, or use backend-derived workers',\n )\n }\n if (options.makeWorkerAgent && options.makeLeafAgent) {\n throw new ValidationError(\n 'supervise: makeWorkerAgent replaces the worker path and makeLeafAgent overrides a leaf inside it; pass one',\n )\n }\n if (options.makeWorkerAgent && (options.workerRetry || options.onWorkerRetry)) {\n throw new ValidationError(\n 'supervise: workerRetry applies only to backend-derived workers; compose withWorkerSpawnRetry onto a caller-owned makeWorkerAgent explicitly',\n )\n }\n if (options.makeWorkerAgent && options.resolveDeliverable) {\n throw new ValidationError(\n 'supervise: resolveDeliverable applies only to backend-derived workers; wrap a caller-owned makeWorkerAgent with its completion checks explicitly',\n )\n }\n const authorizeDownFor = (\n parent: AgentProfile,\n depth: number,\n ): AuthorizeDownMessage | undefined => {\n if (!options.authorizeSpawn && !options.authorizeMessage) return undefined\n return (input) => {\n if (!options.authorizeMessage) {\n throw new ValidationError(\n 'supervise: authorizeMessage is required before steer_agent or answer_question when authorizeSpawn is enabled',\n )\n }\n return freezeDetached(\n options.authorizeMessage(\n freezeDetached({\n ...input,\n parent,\n depth,\n }),\n ),\n )\n }\n }\n const rootExecution = canonicalExecution(\n canonicalProfile,\n canonicalTask,\n options.execution,\n 'supervise root',\n )\n const backendModel = (options.backend as { model?: unknown } | undefined)?.model\n const driverBackendModel = (options.driverBackend as { model?: unknown } | undefined)?.model\n assertProfileModelsAllowed(canonicalProfile, options.allowedModels)\n assertModelAllowed(\n typeof backendModel === 'string' ? backendModel : undefined,\n options.allowedModels,\n )\n assertModelAllowed(\n typeof driverBackendModel === 'string' ? driverBackendModel : undefined,\n options.allowedModels,\n )\n\n // Named options become values before anything is built or spent — an unknown name is a\n // configuration fault, and a fault that surfaces after a run started has already cost budget.\n const deliverable = resolveNamed(\n 'deliverable',\n 'deliverables',\n options.deliverable,\n options.registry?.deliverables,\n )\n const finalizer = resolveNamed(\n 'finalizer',\n 'finalizers',\n options.finalizer,\n options.registry?.finalizers,\n )\n const analysts = resolveNamed(\n 'analysts',\n 'analysts',\n options.analysts,\n options.registry?.analysts,\n )\n const probes = resolveNamed('probes', 'probes', options.probes, options.registry?.probes)\n assertCoordinationBinding(options.coordination)\n\n // `withDriver: true` is the wiring invariant: a child constructed by `driverChild` must resolve\n // to the nested-scope executor; `runDir` only changes where the journal and blobs live.\n const ctx =\n options.runDir !== undefined\n ? createFileRunContext(options.runDir, { withDriver: true })\n : createInMemoryRunContext({ withDriver: true })\n const blobs = options.blobs ?? ctx.blobs\n const perWorker = options.perWorker ?? defaultPerWorker(options.budget)\n assertValidBudget(perWorker, 'supervise perWorker')\n // A per-child ceiling larger than the pool it draws from cannot be honored, so accepting it\n // silently misleads the caller: the child is capped by the reservation instead and dies with\n // \"ticket N spent X tokens > reserved Y\", which reads as a budget outcome rather than a\n // misconfiguration. Observed in the field with perWorker.maxTokens = 3_200_000_000 against a\n // 200_000_000 pool, where children were still clamped at 700_000 and the caller had no way to\n // tell the knob was inert. Refuse at construction, where the caller can still fix it.\n assertPerWorkerWithinPool(perWorker, options.budget)\n const journal = options.journal ?? ctx.journal\n const runId = options.runId ?? 'supervise'\n const runNamespace = supervisionRunNamespace(options.runDir, runId)\n const log = ctx.coordinationLog\n const rootOwnerId = rootCoordinationOwner(rootExecution.identity)\n const rootProviderModels: Array<string | undefined> = []\n const observeNodeEvent = options.onCoordinationEvent\n ? async (\n context: SupervisorNodeContext,\n event: CoordinationEvent,\n record: BusRecord<CoordinationEvent>,\n ) => {\n await options.onCoordinationEvent?.(context, coordinationEventId(context, event), record)\n }\n : undefined\n const managerBackend =\n options.driverBackend ?? (options.rootDriverFromBackend === false ? undefined : options.backend)\n if (options.driveHarness && options.resolveDriveHarness) {\n throw new ValidationError('supervise: provide driveHarness or resolveDriveHarness, not both')\n }\n const hasCustomDriveHarness = Boolean(options.driveHarness || options.resolveDriveHarness)\n // The root manager's workspace, when this process can read it: a loopback bridge runs the\n // driver on this host with `cwd` as its workspace, so a spawn that names an inline resource by\n // path resolves there. A caller-supplied harness is the actual driver and its workspace is its\n // own; the bridge's cwd says nothing about it, so no root is inferred and a spawn by path is\n // refused with the reason rather than read from a directory the driver never saw.\n const spawnResourceRoot = hasCustomDriveHarness\n ? undefined\n : rootSpawnResourceRoot(managerBackend)\n // Runtime-managed tool declarations and the driver's coordination channel are checked before\n // reservation or journaling. A bridge adds its own route/admission check after that purely local\n // validation. A caller-owned worker port owns its own mount and receives the exact profile\n // unchanged.\n const spawnPreflight = composeSpawnPreflights(\n profileToolSpawnPreflight(\n options.makeWorkerAgent === undefined,\n options.resolveSupervisorTools !== undefined,\n ),\n coordinationChannelSpawnPreflight(\n options.makeWorkerAgent === undefined,\n hasCustomDriveHarness,\n managerBackend,\n options.coordination,\n ),\n options.backend?.backend === 'bridge' ? bridgeSpawnPreflight(options.backend) : undefined,\n )\n // A custom harness receives the provider-visible profile plus the immutable canonical profile\n // for receipt binding. An undeclared materialization therefore defaults to the full canonical\n // leaf set, apart from Runtime-owned coordination declarations consumed before dispatch.\n // Declaring `driveHarnessMaterialization` narrows that claim and turns dropped axes into\n // pre-spawn faults.\n const driverMaterialization = hasCustomDriveHarness\n ? (options.driveHarnessMaterialization ?? fullProfileMaterialization)\n : managerBackend && automaticDriverBackendSupported(managerBackend, options.coordination)\n ? backendProfileMaterialization(managerBackend)\n : undefined\n if (\n isExternalSupervisor(canonicalProfile) &&\n !options.driveHarness &&\n !options.resolveDriveHarness &&\n (!managerBackend || !automaticDriverBackendSupported(managerBackend, options.coordination))\n ) {\n throw new ValidationError(\n `supervise: external supervisor profile.harness=${JSON.stringify(canonicalProfile.harness)} requires a local bridge, a provider with authenticated coordination.publicUrl and runtime MCP attachments, or an explicit driveHarness with reachable coordination transport`,\n )\n }\n const harnessClaims = new WeakMap<\n DriveHarness,\n { readonly owners: Set<string>; steerable: boolean }\n >()\n const claimDriveHarness = (rawHarness: unknown, ownerId: string): DriveHarness => {\n if (typeof rawHarness !== 'function') {\n throw new ValidationError(\n 'supervise: resolveDriveHarness must return a DriveHarness function',\n )\n }\n const harness = rawHarness as DriveHarness\n const deliver: unknown = harness.deliver\n if (deliver !== undefined && typeof deliver !== 'function') {\n throw new ValidationError('supervise: driveHarness.deliver must be a function when provided')\n }\n const claim = harnessClaims.get(harness)\n const conflictingOwner = claim\n ? [...claim.owners].find((claimedOwner) => claimedOwner !== ownerId)\n : undefined\n const steerable = typeof deliver === 'function'\n if (conflictingOwner !== undefined && (steerable || claim?.steerable === true)) {\n throw new ValidationError(\n `supervise: steerable driveHarness is already bound to manager owner ${JSON.stringify(conflictingOwner)}; resolveDriveHarness must return a distinct steerable instance for owner ${JSON.stringify(ownerId)}`,\n )\n }\n if (claim) {\n claim.owners.add(ownerId)\n claim.steerable ||= steerable\n } else {\n harnessClaims.set(harness, { owners: new Set([ownerId]), steerable })\n }\n return harness\n }\n const driveHarnessForOwner = (context: DriveHarnessOwnerContext): DriveHarness | undefined => {\n if (options.resolveDriveHarness) {\n return claimDriveHarness(options.resolveDriveHarness(context), context.ownerId)\n }\n if (options.driveHarness) {\n return claimDriveHarness(options.driveHarness, context.ownerId)\n }\n return managerBackend && automaticDriverBackendSupported(managerBackend, options.coordination)\n ? driveHarnessFromBackend(\n managerBackend,\n externalExecutionId('supervised-manager', {\n runNamespace,\n ownerId: context.ownerId,\n }),\n options.now ?? Date.now,\n options.maxTurns,\n )\n : undefined\n }\n const rootDriveHarness = isExternalSupervisor(canonicalProfile)\n ? driveHarnessForOwner(\n freezeDetached({\n runId,\n runNamespace,\n ownerId: rootOwnerId,\n depth: 0,\n identity: rootExecution.identity,\n profile: canonicalProfile,\n task: canonicalTask,\n }),\n )\n : undefined\n const rootOwnerRuntime =\n !isExternalSupervisor(canonicalProfile) || rootDriveHarness === undefined\n ? undefined\n : runtimeOwnedScopeOwnerRuntime(rootDriveHarness)\n assertProfileContract(\n canonicalProfile,\n isExternalSupervisor(canonicalProfile)\n ? (driverMaterialization as ProfileMaterializationContract)\n : testBrain\n ? promptControlProfileMaterialization\n : routerSupervisorProfileMaterialization,\n 'supervise root',\n true,\n )\n\n const now = options.now ?? Date.now\n\n // The span recorder for this run, built inside `start()` so a configuration fault below still\n // throws without leaving an exporter's flush timer behind. The worker seam reads it LAZILY (it is\n // resolved once per spawned worker, long after `start()` assigned this), which is what lets the\n // seam be built here while the recorder is built there.\n let spans: SupervisorSpanRecorder | undefined\n\n // Classify the worker backend against the propagation census ONCE: a backend with no channel to\n // carry the trace context makes every traced spawn a severed hop, journaled per spawn as\n // `trace-unpropagated` (see `worker-trace.ts` for the census). A caller-owned `makeWorkerAgent`\n // is unclassifiable — no claim is journaled rather than a guessed one.\n const traceUnpropagated = options.backend\n ? workerTraceUnpropagatedDeclaration(options.backend.backend)\n : undefined\n\n const recoveryFactories = new WeakMap<MakeWorkerAgent, ExecutorFactory<unknown>>()\n let makeWorkerAgent = options.makeWorkerAgent\n if (!makeWorkerAgent) {\n if (!options.backend && !options.makeLeafAgent) {\n throw new ValidationError(\n 'supervise: provide opts.backend (where workers run), opts.makeLeafAgent, or opts.makeWorkerAgent',\n )\n }\n // A caller-owned leaf factory slots in here, under the same authorization and classification\n // every backend-derived leaf gets; `backend` is then only needed for a per-spawn deliverable.\n //\n // The retry seam wraps the leaf factory, so a spawn refused BEFORE the worker ran is\n // re-entered rather than settled dead. It sits inside the authorized path: the profile is\n // already decided, and a re-entry runs the same executor object the kernel admitted.\n const withRetry = (make: MakeWorkerAgent): MakeWorkerAgent =>\n withWorkerSpawnRetry(make, options.workerRetry, {\n ...(options.onWorkerRetry ? { onRetry: options.onWorkerRetry } : {}),\n })\n const makeLeaf = withRetry(\n options.makeLeafAgent ?? workerFromBackend(options.backend as ExecutorConfig, deliverable),\n )\n const securityPolicy = options.profileSecurity ?? DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY\n\n const makeRecursiveWorkerFor = (\n parent: AgentProfile,\n parentIdentity: NodeExecutionIdentity,\n depth: number,\n parentOwnerId: string,\n ): MakeWorkerAgent => {\n const makeRecursiveWorker = (\n authoredProfile: AgentProfile,\n spawnContext: WorkerSpawnContext | undefined,\n recovering = false,\n ): ReturnType<MakeWorkerAgent> => {\n if (!spawnContext) {\n throw new ValidationError('supervise: backend-derived workers require spawn context')\n }\n const input = freezeDetachedProfile(authoredProfile)\n const authorizationInput = Object.freeze({\n profile: input,\n parent,\n parentIdentity,\n parentNodeId: spawnContext.parentNodeId,\n assignmentId: spawnContext.assignmentId,\n task: spawnContext.task,\n budget: spawnContext.budget,\n label: spawnContext.label,\n ...(spawnContext.key !== undefined ? { key: spawnContext.key } : {}),\n depth,\n ...(spawnContext.analyst !== undefined ? { analyst: spawnContext.analyst } : {}),\n ...(spawnContext.continuity !== undefined ? { continuity: spawnContext.continuity } : {}),\n })\n // Recovery reconstructs the admitted authority; authorization cannot replace it.\n const decision =\n !recovering && options.authorizeSpawn\n ? freezeDetached(options.authorizeSpawn(authorizationInput))\n : Object.freeze({\n profile: input,\n ...(spawnContext.execution ? { execution: spawnContext.execution } : {}),\n })\n if (typeof decision !== 'object' || decision === null || Array.isArray(decision)) {\n throw new ValidationError('supervise: authorizeSpawn must return an AuthorizedSpawn')\n }\n const authorized = freezeDetachedProfile(decision.profile)\n const childExecution = canonicalExecution(\n authorized,\n spawnContext.task,\n decision.execution,\n `supervise spawn ${JSON.stringify(spawnContext.label)}`,\n )\n const authorizedContext = Object.freeze({\n ...spawnContext,\n ...(childExecution.ref ? { execution: childExecution.ref } : {}),\n })\n const postAuthorizationContext: AuthorizedSpawnContext = freezeDetached({\n profile: authorized,\n parent,\n parentIdentity,\n execution: childExecution.identity,\n parentNodeId: spawnContext.parentNodeId,\n assignmentId: spawnContext.assignmentId,\n task: spawnContext.task,\n budget: spawnContext.budget,\n label: spawnContext.label,\n ...(spawnContext.key !== undefined ? { key: spawnContext.key } : {}),\n depth,\n })\n const security = validateAgentProfileSecurity(authorized, securityPolicy)\n if (!security.ok) {\n const details = security.issues\n .filter((issue) => issue.level === 'error')\n .map((issue) => `${issue.code}${issue.path ? ` at ${issue.path}` : ''}`)\n .join(', ')\n throw new ValidationError(`supervise: spawned AgentProfile refused: ${details}`)\n }\n assertProfileModelsAllowed(authorized, options.allowedModels)\n const selectedDeliverable = options.resolveDeliverable?.(postAuthorizationContext)\n const childDeliverable =\n selectedDeliverable === undefined\n ? deliverable\n : captureDeliverable(\n selectedDeliverable,\n `supervise deliverable for ${JSON.stringify(spawnContext.label)}`,\n )\n // A Runtime tool grant makes this a managed persistent node. `spawn_worker` is one\n // capability on that node, not a hidden role bit: an IC can submit a result, ask a parent,\n // or call a product tool without also being allowed to delegate.\n const usesRuntimeCoordination = declaredRuntimeToolNames(authorized).length > 0\n if (!usesRuntimeCoordination) {\n if (childDeliverable !== deliverable && !options.backend) {\n throw new ValidationError(\n 'supervise: resolveDeliverable selected a per-spawn deliverable but there is no backend to derive that leaf from; makeLeafAgent owns its own completion check',\n )\n }\n const makeSelectedLeaf =\n childDeliverable === deliverable\n ? makeLeaf\n : withRetry(workerFromBackend(options.backend as ExecutorConfig, childDeliverable))\n return makeSelectedLeaf(\n authorized,\n Object.freeze({\n ...authorizedContext,\n assignmentId: workerAssignmentNamespace(\n runNamespace,\n parentOwnerId,\n spawnContext.assignmentId,\n ),\n }),\n )\n }\n const ownerId = childCoordinationOwner(\n parentOwnerId,\n childExecution.identity,\n spawnContext,\n depth,\n )\n const nestedDriveHarness = isExternalSupervisor(authorized)\n ? driveHarnessForOwner(\n freezeDetached({\n runId,\n runNamespace,\n ownerId,\n depth,\n identity: childExecution.identity,\n assignmentId: spawnContext.assignmentId,\n profile: authorized,\n task: spawnContext.task,\n }),\n )\n : undefined\n if (isExternalSupervisor(authorized) && !nestedDriveHarness) {\n throw new ValidationError(\n `supervise: authored external supervisor profile.harness=${JSON.stringify(authorized.harness)} requires a local bridge, a provider with authenticated coordination.publicUrl and runtime MCP attachments, or an explicit driveHarness with reachable coordination transport`,\n )\n }\n assertProfileContract(\n authorized,\n isExternalSupervisor(authorized)\n ? (driverMaterialization as ProfileMaterializationContract)\n : promptModelProfileMaterialization,\n `supervise driver ${JSON.stringify(spawnContext.label)}`,\n true,\n )\n if (managerBackend) {\n assertBridgeProfileMaterializes(\n profileWithoutDeclaredRuntimeCoordinationTools(authorized),\n managerBackend,\n `supervise driver ${JSON.stringify(spawnContext.label)}`,\n )\n }\n\n const childFactory = makeRecursiveWorkerFor(\n authorized,\n childExecution.identity,\n depth + 1,\n ownerId,\n )\n const nestedPerWorker = defaultPerWorker(spawnContext.budget)\n const authorizeNestedMessage = authorizeDownFor(authorized, depth + 1)\n let acceptedSubmission = false\n const nested = supervisorAgent(authorized, {\n blobs,\n makeWorkerAgent: childFactory,\n ...(authorizeNestedMessage ? { authorizeDownMessage: authorizeNestedMessage } : {}),\n perWorker: nestedPerWorker,\n ...(options.router ? { router: options.router } : {}),\n ...(nestedDriveHarness ? { driveHarness: nestedDriveHarness } : {}),\n ...(options.coordination && isExternalSupervisor(authorized)\n ? { coordination: options.coordination }\n : {}),\n nodeContext: {\n runId,\n runNamespace,\n ownerId,\n depth,\n identity: childExecution.identity,\n assignmentId: spawnContext.assignmentId,\n },\n ...(options.resolveSupervisorTools\n ? { resolveSupervisorTools: options.resolveSupervisorTools }\n : {}),\n ...(observeNodeEvent ? { observeNodeEvent, replaySettlements: true } : {}),\n ...(analysts ? { analysts } : {}),\n ...(options.analyzeOnSettle ? { analyzeOnSettle: options.analyzeOnSettle } : {}),\n ...(options.watchWorkers ? { watchWorkers: options.watchWorkers } : {}),\n ...(options.stallAfterMs !== undefined ? { stallAfterMs: options.stallAfterMs } : {}),\n ...(options.continuityByProfile\n ? { continuityByProfile: options.continuityByProfile }\n : {}),\n ...(spawnPreflight ? { preflightSpawn: spawnPreflight } : {}),\n ...(options.resolveSpawnProfile\n ? { resolveSpawnProfile: options.resolveSpawnProfile }\n : {}),\n ...(options.peerMail ? { peerMail: options.peerMail } : {}),\n ...(options.stopRule ? { stopRule: options.stopRule } : {}),\n ...(options.onProgressStop ? { onProgressStop: options.onProgressStop } : {}),\n ...(options.maxTurns !== undefined ? { maxTurns: options.maxTurns } : {}),\n ...(options.compaction ? { compaction: options.compaction } : {}),\n ...(options.driverRetry ? { driverRetry: options.driverRetry } : {}),\n ...(options.onDriverAttempt ? { onDriverAttempt: options.onDriverAttempt } : {}),\n // A managed child receives its assignment's independent completion check. It can submit\n // work itself, delegate, or do both under the same profile contract.\n ...(childDeliverable ? { deliverable: childDeliverable } : {}),\n ...(childDeliverable\n ? {\n onAcceptedSubmission: () => {\n acceptedSubmission = true\n },\n }\n : {}),\n ...(options.repromptOnUnmet !== undefined\n ? { repromptOnUnmet: options.repromptOnUnmet }\n : {}),\n ...(options.onUnmetContract ? { onUnmetContract: options.onUnmetContract } : {}),\n ...(log\n ? {\n onEvent: (_event, record) => log.append(runId, record, ownerId),\n loadPriorCoordination: () => log.load(runId, ownerId),\n }\n : {}),\n ...(finalizer ? { finalizer } : {}),\n // A nested manager acknowledges cancels for ITS direct children from the same layout\n // dir as the root — subtree-scoped, so exact node ids route to the one manager that\n // parents them and label references stay the root's alone.\n ...(options.runDir === undefined\n ? {}\n : {\n controlDir: resolve(options.runDir),\n controlScope: 'subtree' as const,\n abortRun: cancelDurableRun,\n }),\n })\n return driverChild(\n authorized,\n nested,\n journal,\n childExecution.ref,\n () => acceptedSubmission,\n recoveryFactories.get(childFactory),\n )\n }\n if (\n options.makeLeafAgent === undefined &&\n options.backend?.backend === 'provider' &&\n !options.backend.steering\n ) {\n const factory = registerRetainedExecutorPreparation(\n createExecutor(options.backend),\n ({ spawned, profile, task }) => {\n if (\n !spawned.ownedTreeRoot ||\n !spawned.parent ||\n !spawned.assignmentId ||\n !spawned.identity\n )\n return undefined\n const execution = {\n ...(spawned.identity.candidateDigest\n ? { candidateDigest: spawned.identity.candidateDigest }\n : {}),\n ...(spawned.identity.correlation\n ? { correlation: spawned.identity.correlation }\n : {}),\n }\n const reconstructed = makeRecursiveWorker(\n profile,\n {\n assignmentId: spawned.assignmentId,\n parentNodeId: spawned.parent,\n budget: spawned.budget,\n task,\n label: spawned.label,\n ...(spawned.key === undefined ? {} : { key: spawned.key }),\n execution,\n },\n true,\n )\n const spec = (reconstructed as Agent<unknown, unknown> & { executorSpec?: AgentSpec })\n .executorSpec\n if (!spec || !isDriverSpec(spec)) return undefined\n return { spec, factory: driverExecutorFactory }\n },\n )\n recoveryFactories.set(makeRecursiveWorker, factory)\n }\n return makeRecursiveWorker\n }\n\n makeWorkerAgent = makeRecursiveWorkerFor(\n canonicalProfile,\n rootExecution.identity,\n 1,\n rootOwnerId,\n )\n }\n // Share one root control with every manager's pre-attempt cancellation fence.\n const runControl =\n options.rootHandle ?? (options.runDir === undefined ? undefined : createRootHandle<unknown>())\n const durableCancellation = new AbortController()\n const cancelDurableRun = (\n reason: string,\n request?: import('./run-layout').RunCancelRequest,\n ): void => {\n durableCancellation.abort(\n request === undefined\n ? new Error(reason)\n : new RunCancellationReason(request.source, reason, request.operationId),\n )\n }\n const workerFactory = makeWorkerAgent\n\n // Every configuration fault above throws SYNCHRONOUSLY — a caller that guards with\n // `expect(() => supervise(...)).toThrow` still sees the throw, and no compute starts. Only the\n // durable coordination replay needs to await, so the run begins inside this closure.\n const start = async () => {\n // The durable coordination side-log (file contexts only) loads prior questions, findings, and\n // authorized instruction receipts, then appends this process's evidence as it publishes. The\n // router arm receives all three in its resume brief; the external arm seeds prior questions and\n // leaves the other evidence in the log. No prior instruction is auto-delivered.\n const priorCoordination = log ? await log.load(runId, rootOwnerId) : undefined\n\n const authorizeRootMessage = authorizeDownFor(canonicalProfile, 1)\n const agentDeps = {\n blobs,\n makeWorkerAgent: workerFactory,\n ...(authorizeRootMessage ? { authorizeDownMessage: authorizeRootMessage } : {}),\n perWorker,\n ...(log\n ? {\n onEvent: (_event, record) => log.append(runId, record, rootOwnerId),\n }\n : {}),\n ...(deliverable ? { deliverable } : {}),\n onProviderModel(model: string | undefined) {\n rootProviderModels.push(model)\n },\n ...(priorCoordination &&\n (priorCoordination.questions.length > 0 ||\n priorCoordination.findings.length > 0 ||\n priorCoordination.continuations.length > 0 ||\n priorCoordination.deliveryEvidence.length > 0 ||\n priorCoordination.records.some((record) => record.event.type === 'submission'))\n ? { priorCoordination }\n : {}),\n ...(finalizer ? { finalizer } : {}),\n ...(options.coordination && isExternalSupervisor(canonicalProfile)\n ? { coordination: options.coordination }\n : {}),\n ...(spawnPreflight ? { preflightSpawn: spawnPreflight } : {}),\n ...(options.resolveSpawnProfile ? { resolveSpawnProfile: options.resolveSpawnProfile } : {}),\n ...(spawnResourceRoot === undefined ? {} : { spawnResourceRoot }),\n ...(options.peerMail ? { peerMail: options.peerMail } : {}),\n ...(options.maxLiveWorkers !== undefined ? { maxLiveWorkers: options.maxLiveWorkers } : {}),\n ...(options.router ? { router: options.router } : {}),\n ...(rootDriveHarness ? { driveHarness: rootDriveHarness } : {}),\n nodeContext: {\n runId,\n runNamespace,\n ownerId: rootOwnerId,\n depth: 0,\n identity: rootExecution.identity,\n },\n ...(options.resolveSupervisorTools\n ? { resolveSupervisorTools: options.resolveSupervisorTools }\n : {}),\n ...(observeNodeEvent ? { observeNodeEvent, replaySettlements: true } : {}),\n ...(options.extraTools ? { extraTools: options.extraTools } : {}),\n ...(options.executeExtraTool ? { executeExtraTool: options.executeExtraTool } : {}),\n ...(analysts ? { analysts } : {}),\n ...(options.analyzeOnSettle ? { analyzeOnSettle: options.analyzeOnSettle } : {}),\n ...(options.watchWorkers ? { watchWorkers: options.watchWorkers } : {}),\n ...(options.stallAfterMs !== undefined ? { stallAfterMs: options.stallAfterMs } : {}),\n ...(options.continuityByProfile ? { continuityByProfile: options.continuityByProfile } : {}),\n ...(options.stopRule ? { stopRule: options.stopRule } : {}),\n ...(options.onProgressStop ? { onProgressStop: options.onProgressStop } : {}),\n ...(options.maxTurns !== undefined ? { maxTurns: options.maxTurns } : {}),\n ...(options.compaction ? { compaction: options.compaction } : {}),\n ...(options.driverRetry ? { driverRetry: options.driverRetry } : {}),\n ...(options.onDriverAttempt ? { onDriverAttempt: options.onDriverAttempt } : {}),\n ...(options.repromptOnUnmet !== undefined\n ? { repromptOnUnmet: options.repromptOnUnmet }\n : {}),\n ...(options.onUnmetContract ? { onUnmetContract: options.onUnmetContract } : {}),\n // A durable run's layout dir doubles as the worker-cancel control surface: every\n // router-arm manager's turn loop acknowledges the `cancelWorker` requests it OWNS — the\n // root (default 'run' scope) resolves its direct children plus label/profile references,\n // each nested manager (above) its own direct-child node ids only. The root ALSO applies the\n // run-scoped request (`cancelRun`) through the run's one cascade controller.\n ...(options.runDir === undefined || runControl === undefined\n ? {}\n : {\n controlDir: resolve(options.runDir),\n abortRun: cancelDurableRun,\n }),\n } satisfies SupervisorAgentDeps\n const agent =\n testBrain === undefined\n ? supervisorAgent(canonicalProfile, agentDeps)\n : supervisorAgentWithTestBrain(canonicalProfile, { ...agentDeps, brain: testBrain })\n\n // Built ONLY when `otel` is configured AND an exporter resolves, so the default path allocates\n // nothing and passes no `hooks` at all — byte-for-byte the wiring every existing caller gets.\n spans = options.otel ? createSupervisorSpanRecorder({ runId, ...options.otel, now }) : undefined\n const recorder = spans\n const hooks = recorder ? composeRuntimeHooks(options.hooks, recorder.hooks) : options.hooks\n\n const supervisor = createSupervisor<unknown, unknown>()\n if (runControl !== undefined) supervisor.attach(runControl)\n // The run owns cancellation until every descendant has drained, even after its director returns.\n const cancellation =\n options.runDir !== undefined && runControl !== undefined\n ? watchRunCancellation(resolve(options.runDir), cancelDurableRun)\n : undefined\n try {\n cancellation?.check()\n } catch (error) {\n cancellation?.close()\n throw error\n }\n const run = supervisor.run(agent, canonicalTask, {\n budget: options.budget,\n runId,\n journal,\n blobs,\n executors: ctx.executors,\n ...(recoveryFactories.get(workerFactory)\n ? { recoverExecutor: recoveryFactories.get(workerFactory) }\n : {}),\n rootIdentity: rootExecution.identity,\n ...(rootOwnerRuntime === undefined\n ? {}\n : {\n rootMaterialization: {\n runtime: rootOwnerRuntime,\n declaration: 'deferred' as const,\n authoredProfile: canonicalProfile,\n },\n }),\n maxDepth: options.maxDepth ?? 8,\n ...(options.childSettleGraceMs !== undefined\n ? { childSettleGraceMs: options.childSettleGraceMs }\n : {}),\n ...(options.retainedAtSettlement !== undefined\n ? { retainedAtSettlement: options.retainedAtSettlement }\n : {}),\n ...(options.maxLiveWorkers !== undefined ? { maxLiveWorkers: options.maxLiveWorkers } : {}),\n ...(probes ? { probes } : {}),\n ...(ctx.resume === true ? { resume: true } : {}),\n ...(options.now ? { now: options.now } : {}),\n signal: options.signal\n ? AbortSignal.any([options.signal, durableCancellation.signal])\n : durableCancellation.signal,\n ...(hooks ? { hooks } : {}),\n // Only a run that actually records spans hands trace context down to its workers; with no\n // recorder this key is absent and no spawned worker's environment is touched.\n ...(recorder ? { workerTrace: recorder.workerTrace } : {}),\n // A traced run on a backend with NO propagation channel journals each severed hop\n // (`trace-unpropagated`) instead of silently producing disconnected child traces.\n ...(recorder && traceUnpropagated ? { workerTraceUnpropagated: traceUnpropagated } : {}),\n ...(options.runDir === undefined ? {} : { interactiveBindingDir: resolve(options.runDir) }),\n })\n const settle = async () => {\n let result: Awaited<typeof run>\n try {\n result = await run\n } finally {\n cancellation?.close()\n cancellation?.check()\n }\n recordRunCancellationOutcome(options.runDir, result, now)\n const rootProviderModel =\n ctx.resume === true\n ? rootProviderModelEvidence([])\n : rootProviderModels.length > 0\n ? rootProviderModelEvidence(rootProviderModels)\n : rootDriveHarness === undefined\n ? rootProviderModelEvidence([])\n : rootProviderModelEvidenceFromExecution(\n runtimeOwnedDriveHarnessProviderEvidence(rootDriveHarness),\n )\n return {\n ...result,\n rootProviderModel,\n }\n }\n if (!recorder) return settle()\n // The recorder closes the root span on BOTH exits and never rethrows, so tracing can neither\n // change the result nor swallow the run's own rejection.\n try {\n const result = await settle()\n await recorder.finish({ result })\n return result\n } catch (error) {\n await recorder.finish({ error })\n throw error\n }\n }\n\n return start()\n}\n\n/** Historical unclassified input is already charged; replay cannot refund it with a class-only delta. */\nfunction unmeteredOwnerCache(total: Spend['tokens'], committed: Spend['tokens']) {\n const cache = {\n ...(total.freshInput === undefined\n ? {}\n : { freshInput: Math.max(0, total.freshInput - (committed.freshInput ?? 0)) }),\n ...(total.cacheRead === undefined\n ? {}\n : { cacheRead: Math.max(0, total.cacheRead - (committed.cacheRead ?? 0)) }),\n ...(total.cacheWrite === undefined\n ? {}\n : { cacheWrite: Math.max(0, total.cacheWrite - (committed.cacheWrite ?? 0)) }),\n }\n if (\n (cache.freshInput ?? 0) + (cache.cacheRead ?? 0) + (cache.cacheWrite ?? 0) >\n Math.max(0, total.input - committed.input)\n ) {\n return { cacheBreakdownKnown: false as const }\n }\n return {\n ...cache,\n ...(total.cacheBreakdownKnown === false ? { cacheBreakdownKnown: false as const } : {}),\n }\n}\n\nfunction rootProviderModelEvidence(\n observations: ReadonlyArray<string | undefined>,\n): RootProviderModelEvidence {\n const attempts = Object.freeze(\n observations.map((model) =>\n Object.freeze({ observations: Object.freeze(model === undefined ? [] : [model]) }),\n ),\n )\n const models = [...new Set(observations.filter((model): model is string => model !== undefined))]\n if (observations.length === 0 || observations.some((model) => model === undefined)) {\n return Object.freeze({\n status: 'unknown' as const,\n attempts,\n models: Object.freeze(models),\n reason: 'provider-model-missing' as const,\n })\n }\n return Object.freeze({ status: 'known' as const, attempts, models: Object.freeze(models) })\n}\n\nfunction rootProviderModelEvidenceFromExecution(\n evidence: RootProviderModelEvidence | undefined,\n): RootProviderModelEvidence {\n return evidence ?? rootProviderModelEvidence([])\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,kBACd,OACA,aACe;CACf,IAAI;CAEJ,MAAM,QAAQ,OAAO,KAAU,cAAgD;EAC7E,IAAI;EACJ,IAAI;GACF,YAAa,MAAM,YAAY,MAAM,GAAG,MAAO;EACjD,QAAQ;GACN,YAAY;EACd;EACA,OAAO;GAAE,OAAO;GAAW,OAAO,cAAc,YAAY,IAAI;EAAG;CACrE;;;;;;;CAQA,MAAM,gBAAgB,YAA2B;EAC/C,IAAI;EACJ,IAAI;GACF,MAAM,MAAM,eAAe;EAC7B,QAAQ;GACN;EACF;EACA,QAAQ,MAAM,MAAM,IAAI,KAAK,IAAI,SAAS,KAAK;CACjD;CAiEA,OAAO,uCAAuC,OAAO;EA9DnD,SAAS,MAAM;EACf,GAAI,MAAM,iBAAiB,KAAA,IAAY,EAAE,cAAc,MAAM,aAAa,IAAI,CAAC;EAC/E,GAAI,MAAM,UAAU,EAAE,UAAU,MAAe,MAAM,UAAU,CAAC,EAAE,IAAI,CAAC;EASvE,GAAI,MAAM,WAAW,EAAE,gBAAgB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