@tangle-network/agent-runtime 0.319.3 → 0.319.7

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 (36) hide show
  1. package/dist/{activation-ClcJ6wO1.js → activation-CcfUmnAe.js} +2 -2
  2. package/dist/{activation-ClcJ6wO1.js.map → activation-CcfUmnAe.js.map} +1 -1
  3. package/dist/agent.js +2 -2
  4. package/dist/{coordination-driver-Culvomn2.js → coordination-driver-Dim6ig4M.js} +2 -2
  5. package/dist/{coordination-driver-Culvomn2.js.map → coordination-driver-Dim6ig4M.js.map} +1 -1
  6. package/dist/{delegate-CpMbpiIR.js → delegate-STDZnzjY.js} +2 -2
  7. package/dist/{delegate-CpMbpiIR.js.map → delegate-STDZnzjY.js.map} +1 -1
  8. package/dist/durable.js +2 -2
  9. package/dist/{graph-DnfSGUM8.js → graph-Df65qgYK.js} +4 -4
  10. package/dist/{graph-DnfSGUM8.js.map → graph-Df65qgYK.js.map} +1 -1
  11. package/dist/{improvement-cycle-xnQwUaC3.js → improvement-cycle-Bb5kkUi6.js} +18 -149
  12. package/dist/{improvement-cycle-xnQwUaC3.js.map → improvement-cycle-Bb5kkUi6.js.map} +1 -1
  13. package/dist/index.js +7 -7
  14. package/dist/intelligence.js +3 -3
  15. package/dist/kernel.js +8 -8
  16. package/dist/{loop-runner-bin-uoeGHNZA.js → loop-runner-bin-BaGWLMYN.js} +3 -3
  17. package/dist/{loop-runner-bin-uoeGHNZA.js.map → loop-runner-bin-BaGWLMYN.js.map} +1 -1
  18. package/dist/loop-runner-bin.js +1 -1
  19. package/dist/mcp/bin.js +3 -3
  20. package/dist/mcp/index.js +4 -4
  21. package/dist/{provision-supervisor-DiZTjzdp.js → provision-supervisor-CS_Negf6.js} +3 -3
  22. package/dist/{provision-supervisor-DiZTjzdp.js.map → provision-supervisor-CS_Negf6.js.map} +1 -1
  23. package/dist/{runtime-6qzuLTJ7.js → runtime-HY1z-MOb.js} +8 -8
  24. package/dist/{runtime-6qzuLTJ7.js.map → runtime-HY1z-MOb.js.map} +1 -1
  25. package/dist/{search-executor-DlaLafvy.js → search-executor-OIy7kg74.js} +2 -2
  26. package/dist/{search-executor-DlaLafvy.js.map → search-executor-OIy7kg74.js.map} +1 -1
  27. package/dist/{server-sLrmWqKw.js → server-BMG_Uted.js} +3 -3
  28. package/dist/{server-sLrmWqKw.js.map → server-BMG_Uted.js.map} +1 -1
  29. package/dist/{supervise-D4CnC-cl.js → supervise-CDn-1ThW.js} +3 -3
  30. package/dist/{supervise-D4CnC-cl.js.map → supervise-CDn-1ThW.js.map} +1 -1
  31. package/dist/{supervisor-Cqhu3xH-.js → supervisor-B_mWdKva.js} +56 -7
  32. package/dist/supervisor-B_mWdKva.js.map +1 -0
  33. package/dist/testing.js +12 -12
  34. package/dist/tui/index.js +1 -1
  35. package/package.json +3 -3
  36. package/dist/supervisor-Cqhu3xH-.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"supervise-D4CnC-cl.js","names":["record","fsConstants","coordinationVerbNameSet","isAsyncIterable","profileMaterializationAxes","runtimeSleep","addRetainedSpend"],"sources":["../src/mcp/tools/coordination-request-context.ts","../src/runtime/supervise/coordination-http.ts","../src/runtime/supervise/coordination-preflight.ts","../src/runtime/supervise/single-flight-tools.ts","../src/runtime/supervise/coordination-mcp.ts","../src/runtime/supervise/otel-spans.ts","../src/runtime/supervise/reentry.ts","../src/runtime/supervise/root-stream.ts","../src/runtime/supervise/run-traces.ts","../src/runtime/supervise/worker-control-observer.ts","../src/runtime/supervise/supervisor-agent.ts","../src/runtime/supervise/worker-retry.ts","../src/runtime/supervise/supervise.ts"],"sourcesContent":["/** The tool-call timeout Runtime asks harnesses to give its coordination server. The Tangle\n * profile materializer writes it as `MCP_TOOL_TIMEOUT` (Claude Code) and `tool_timeout_sec`\n * (Codex) when an attachment declares `metadata.toolTimeoutMs`, so a fenced coordination call\n * that holds its response for its whole fence is never cut off at the 60 s harness default. */\nexport const COORDINATION_CLIENT_TOOL_TIMEOUT_MS = 300_000\n","import type { IncomingMessage, ServerResponse } from 'node:http'\nimport { ConfigError } from '../../errors'\nimport type { JsonRpcMessage, JsonRpcResponse } from '../../mcp/protocol'\n\n/** Why the coordination boundary refused a request. The refusal's JSON-RPC error body names it, so\n * an agent reads more than a bare status, and its audit event records it. */\nexport type CoordinationRejectReason =\n | 'method-not-allowed'\n | 'unknown-path'\n | 'wrong-host'\n | 'origin-refused'\n | 'listener-closed'\n | 'scope-stopped'\n | 'credential-refused'\n | 'unsupported-content-type'\n | 'body-too-large'\n | 'malformed-request'\n | 'request-limit'\n | 'body-timeout'\n | 'action-timeout'\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 /** Why a `rejected` request was refused. */\n readonly reason?: CoordinationRejectReason\n}\n\n/** A refusal before any action runs: its HTTP status and the reason the client is told. */\nexport interface CoordinationRejection {\n readonly status: number\n readonly reason: CoordinationRejectReason\n}\n\n/** The JSON-RPC error a refusal carries. MCP clients put a non-2xx body into the error the agent\n * sees, so without it the agent reads only `Error POSTing to endpoint:` and a status at best. The\n * messages are fixed text: never a credential, a request body or an arbitrary error string. */\nfunction rejectionBody(\n reason: CoordinationRejectReason | 'handler-failed',\n limits: ReturnType<typeof coordinationHttpLimits>,\n) {\n const messages: Record<CoordinationRejectReason | 'handler-failed', string> = {\n 'method-not-allowed': 'coordination accepts only POST',\n 'unknown-path': 'no coordination endpoint at this path',\n 'wrong-host': 'this coordination endpoint does not serve the requested host',\n 'origin-refused': 'coordination refuses requests from this browser origin',\n 'listener-closed': 'this coordination endpoint is closed: the manager it served has ended',\n 'scope-stopped': 'the manager this coordination endpoint serves has been stopped',\n 'credential-refused': 'the coordination credential is missing, invalid, expired or revoked',\n 'unsupported-content-type': 'coordination requests must be application/json',\n 'body-too-large': `coordination request bodies are limited to ${limits.maxRequestBytes} bytes`,\n 'malformed-request': 'the request is not one JSON-RPC 2.0 message',\n 'request-limit': `coordination admits ${limits.maxConcurrentRequests} concurrent requests and ${limits.requestsPerMinute} a minute; retry shortly`,\n 'body-timeout': `the request body did not arrive within ${limits.requestTimeoutMs} ms`,\n 'action-timeout': `the action did not finish within ${limits.requestTimeoutMs} ms and may still complete; read its outcome before repeating it`,\n 'handler-failed': 'the coordination handler failed',\n }\n return {\n jsonrpc: '2.0',\n id: null,\n error: { code: -32000, message: messages[reason], data: { reason } },\n }\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 // Twice the response fence (coordinationResponseFenceMs), so a held answer leaves well before\n // the server's own timeout.\n const requestTimeoutMs = positive('requestTimeoutMs', options.requestTimeoutMs, 90_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): CoordinationRejection | 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 reason?: CoordinationRejectReason,\n ) => {\n await input.options.onAudit?.({\n ...input.identity,\n outcome,\n status,\n ...(action ? { action } : {}),\n ...(reason ? { reason } : {}),\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, reason }: CoordinationRejection) => {\n respond(status, rejectionBody(reason, limits))\n void audit('rejected', status, action, reason).catch(() => undefined)\n req.resume()\n }\n req.on('error', () => reject({ status: 400, reason: 'malformed-request' }))\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({ status: 405, reason: 'method-not-allowed' })\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({ status: 403, reason: 'origin-refused' })\n return\n }\n if (\n req.headers['content-type']?.split(';', 1)[0]?.trim().toLowerCase() !== 'application/json'\n ) {\n reject({ status: 415, reason: 'unsupported-content-type' })\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({ status: 413, reason: 'body-too-large' })\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({ status: 429, reason: 'request-limit' })\n return\n }\n controlActive++\n } else {\n requests++\n active++\n }\n admitted = true\n timer = setTimeout(() => {\n timedOut = true\n reject(\n executing\n ? { status: 504, reason: 'action-timeout' }\n : { status: 408, reason: 'body-timeout' },\n )\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({ status: 413, reason: 'body-too-large' })\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({ status: 400, reason: 'malformed-request' })\n return\n }\n message = value as JsonRpcMessage\n } catch {\n reject({ status: 400, reason: 'malformed-request' })\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({ status: 429, reason: 'request-limit' })\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, rejectionBody('handler-failed', limits))\n } finally {\n executing = false\n release()\n }\n })()\n })\n }\n}\n","import { ConfigError } from '../../errors'\nimport { PROTOCOL_VERSION } from '../../mcp/tool-server'\nimport { linkAbort, runAbortable } from './abortable'\n\nconst MAX_RESPONSE_BYTES = 1024 * 1024\n\nclass CoordinationPreflightError extends ConfigError {\n constructor(reason: string) {\n super(`coordination public endpoint preflight failed: ${reason}`)\n }\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Check the operator's route before it becomes a provider attachment. This does not prove cloud egress. */\nexport async function preflightPublicCoordination(input: {\n url: string\n headers: Readonly<Record<string, string>>\n signal: AbortSignal\n requestTimeoutMs: number\n toolNames: readonly string[]\n}): Promise<void> {\n const deadline = new AbortController()\n const linked = linkAbort(input.signal, deadline.signal)\n const timer = setTimeout(() => deadline.abort(), Math.min(input.requestTimeoutMs, 10_000))\n timer.unref()\n const rpc = async (method: string, params?: unknown): Promise<Record<string, unknown>> => {\n const response = await fetch(input.url, {\n method: 'POST',\n headers: { ...input.headers, 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify({ jsonrpc: '2.0', id: method, method, ...(params ? { params } : {}) }),\n redirect: 'manual',\n signal: linked.signal,\n })\n if (response.status !== 200) {\n void response.body?.cancel().catch(() => undefined)\n throw new CoordinationPreflightError(`HTTP ${response.status}`)\n }\n const reader = response.body?.getReader()\n if (!reader) throw new CoordinationPreflightError('invalid MCP response')\n let size = 0\n const chunks: Uint8Array[] = []\n try {\n for (;;) {\n const part = await reader.read()\n if (part.done) break\n size += part.value.byteLength\n if (size > MAX_RESPONSE_BYTES) {\n void reader.cancel().catch(() => undefined)\n throw new CoordinationPreflightError('response too large')\n }\n chunks.push(part.value)\n }\n } finally {\n reader.releaseLock()\n }\n let body: unknown\n try {\n body = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)))\n } catch {\n throw new CoordinationPreflightError('invalid MCP response')\n }\n if (\n !record(body) ||\n body.jsonrpc !== '2.0' ||\n body.id !== method ||\n body.error ||\n !record(body.result)\n ) {\n throw new CoordinationPreflightError('invalid MCP response')\n }\n return body.result\n }\n try {\n await runAbortable(\n async () => {\n const initialized = await rpc('initialize', {\n protocolVersion: PROTOCOL_VERSION,\n capabilities: {},\n clientInfo: { name: 'agent-runtime-coordination-preflight', version: '1' },\n })\n if (\n initialized.protocolVersion !== PROTOCOL_VERSION ||\n !record(initialized.serverInfo) ||\n initialized.serverInfo.name !== 'coordination' ||\n !record(initialized.capabilities) ||\n !record(initialized.capabilities.tools)\n )\n throw new CoordinationPreflightError('invalid MCP initialization')\n const listing = await rpc('tools/list')\n if (\n !Array.isArray(listing.tools) ||\n listing.tools.some((tool) => !record(tool) || typeof tool.name !== 'string')\n ) {\n throw new CoordinationPreflightError('invalid MCP tool list')\n }\n const names = listing.tools.map((tool) => tool.name).sort()\n if (JSON.stringify(names) !== JSON.stringify([...input.toolNames].sort())) {\n throw new CoordinationPreflightError('coordination tool grants differ')\n }\n },\n linked.signal,\n 'coordination public endpoint preflight cancelled',\n )\n } catch (error) {\n // Neither a response body nor an upstream exception is safe to retain: both can echo credentials.\n if (input.signal.aborted) throw new CoordinationPreflightError('cancelled')\n if (deadline.signal.aborted) throw new CoordinationPreflightError('timed out')\n if (error instanceof CoordinationPreflightError) throw error\n throw new CoordinationPreflightError('transport unavailable')\n } finally {\n clearTimeout(timer)\n linked.release()\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 settled. The handler is not invoked again.\n * 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\n * call returns a receipt. The handler keeps running, and its outcome is published to the\n * manager's inbox, where its next wake delivers it. Nothing has to call again to collect it.\n *\n * An invocation's identity ends when its handler settles. The next identical call is a fresh run,\n * 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 */\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 /** Set when a call's fence elapsed first: the outcome then goes to the inbox under it. */\n receipt: string | undefined\n}\n\n/** The answer for a call whose handler is still running when its fence elapses. */\nexport interface ToolCallReceipt {\n readonly running: true\n readonly receipt: string\n readonly tool: string\n readonly elapsedMs: number\n readonly instruction: string\n}\n\n/** Where a receipted call's outcome goes: the manager's inbox (`CoordinationTools`). */\nexport interface ToolReceiptSink {\n openToolReceipt(tool: string): string\n settleToolReceipt(\n receipt: string,\n outcome:\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly error: unknown },\n ): Promise<void>\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: {\n readonly fenceMs: number\n readonly receipts: ToolReceiptSink\n readonly now?: () => number\n },\n): SingleFlightTools {\n const { fenceMs, receipts } = 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-entries 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, key: string): 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 receipt: undefined,\n }\n void invocation.settled.then(async (outcome) => {\n if (invocations.get(key) === invocation) invocations.delete(key)\n if (invocation.receipt !== undefined) {\n await receipts.settleToolReceipt(invocation.receipt, outcome).catch((error: unknown) => {\n console.error('Runtime could not publish a receipted tool outcome', {\n tool: tool.name,\n receipt: invocation.receipt,\n error: error instanceof Error ? error.message : String(error),\n })\n })\n }\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, key)\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) {\n invocation.receipt ??= receipts.openToolReceipt(tool.name)\n return toolCallReceipt(tool.name, invocation.receipt, now() - invocation.startedAt)\n }\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 toolCallReceipt(tool: string, receipt: string, elapsedMs: number): ToolCallReceipt {\n return {\n running: true,\n receipt,\n tool,\n elapsedMs,\n instruction:\n `${tool} is still running; nothing failed. Do not call it again: its result arrives with ` +\n `receipt ${receipt} when you are next woken. Continue other work, or end your turn to wait.`,\n }\n}\n","/**\n *\n * Serve the coordination verbs (spawn_worker / observe_agent / steer_agent / submit_result / 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 createCoordinationToolsForManager,\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 SuperviseProfileEntry,\n type WorkerWatchOptions,\n} from '../../mcp/tools/coordination'\nimport type { SpawnResourceReader } from '../../mcp/tools/spawn-resource-paths'\nimport { runAbortable } from './abortable'\nimport {\n type CoordinationHttpOptions,\n coordinationHttpHandler,\n coordinationHttpLimits,\n} from './coordination-http'\nimport { preflightPublicCoordination } from './coordination-preflight'\nimport {\n noteScopeRetainedOwnerCoordination,\n scopeRetainedOwnerResourceReader,\n} from './retained-scope-owner'\nimport { singleFlightTools } from './single-flight-tools'\n\nexport type {\n CoordinationHttpAudit,\n CoordinationHttpOptions,\n CoordinationRejectReason,\n} 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 /** The current credential's expiry under `authentication.ttlMs`; undefined when it lives as long\n * as the scope. */\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 finishAnalysis: CoordinationTools['finishAnalysis']\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 /** Explicit finite lifetime. Omission binds the credential to the live scope: it is refused once\n * the scope stops or the listener closes. A child's own time box does not stop its scope. */\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 /** Listener lifetime: aborts on close, failed setup, manager cancellation, or deadline. */\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 (\n ttl !== undefined &&\n (!Number.isSafeInteger(ttl) || ttl <= 0 || !Number.isSafeInteger(Date.now() + ttl))\n ) {\n throw new ConfigError(\n 'coordination credential ttlMs must be a positive safe integer with a safe expiry',\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 coordination verb that runs an injected deliverable's check inside its request, so its work\n * can outlast one request and it is served like `nodeTools`. src/mcp/tools/coordination.ts builds it\n * exactly when a deliverable is injected.\n */\nconst DELIVERABLE_VERB = 'submit_result'\n\n/** The longest any coordination call holds its response, whatever the request timeout: under the\n * 60 s MCP tool-call timeout Claude Code and Codex apply by default. */\nconst RESPONSE_FENCE_CAP_MS = 45_000\n\n/**\n * The longest a fenced coordination call (`submit_result` and every method-supplied node tool)\n * holds its HTTP response before it answers with a receipt instead. The call keeps running, and\n * its outcome reaches the manager in its next wake.\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 * and at most {@link RESPONSE_FENCE_CAP_MS}.\n */\nexport function coordinationResponseFenceMs(requestTimeoutMs: number): number {\n return Math.max(1, Math.min(RESPONSE_FENCE_CAP_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`. The check runs\n * inside that call, so the call is served single-flight and fenced like `nodeTools`: a check\n * still running at the fence returns a receipt, and the verdict reaches the manager in its\n * next wake. */\n deliverable?: DeliverableSpec<unknown>\n /** Serve `read_continuation` from the manager's continuation records. */\n readContinuation?: (continuation: number | undefined) => unknown\n /** Called once when the external manager accepts a result or declares completion. */\n onStop?: (reason: string | undefined) => void\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 /** Trusted source refs for this manager’s existing observe_agent capability. */\n sourceEvidenceRefs?: ReadonlyArray<string>\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 running call, and a call still running at the fence returns a receipt whose outcome\n * reaches the manager in its next wake. */\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 /** Composition of each authored child profile before identity is fixed —\n * `CoordinationToolsOptions.composeSpawnProfile`. */\n composeSpawnProfile?: (profile: AgentProfile) => AgentProfile\n /** The run's validated profiles table — `CoordinationToolsOptions.profiles`. */\n profiles?: ReadonlyMap<string, SuperviseProfileEntry>\n /** See `CoordinationToolsOptions.spawnResourceRoot`. */\n spawnResourceRoot?: string\n /** See `CoordinationToolsOptions.spawnResourceReader`. */\n spawnResourceReader?: SpawnResourceReader\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?: (\n tools: ReadonlyArray<McpToolDescriptor>,\n coordination: Pick<CoordinationTools, 'awaitSettlement'>,\n ) => void\n },\n): Promise<CoordinationMcpHandle> {\n return (await serveCoordinationMcpForManager(opts)).handle\n}\n\n/** Runtime-only binding: operator controls stay off the public MCP handle and tool grants. */\nexport async function serveCoordinationMcpForManager(\n opts: Parameters<typeof serveCoordinationMcp>[0],\n lifetime?: AbortSignal,\n): Promise<{ handle: CoordinationMcpHandle; controls: CoordinationTools }> {\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 // Without `ttlMs` the credential carries no expiry: it lives as long as the scope\n // (`refusedCredential`), and a scope's deadline is not always its stop.\n const expiresAt = auth?.ttlMs === undefined ? undefined : Date.now() + auth.ttlMs\n if (expiresAt !== undefined && !Number.isSafeInteger(expiresAt)) {\n throw new ConfigError('coordination credential expiry must remain a safe integer')\n }\n for (const [credential, expiry] of revoked) {\n if (expiry <= Date.now()) revoked.delete(credential)\n }\n if (token) revoked.set(token.toString(), credentialExpiresAt ?? Number.POSITIVE_INFINITY)\n credentialExpiresAt = expiresAt\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 ?? null,\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 /**\n * Why a supplied credential is refused, or undefined when it is valid. A credential lives as\n * long as the scope it fronts: until the scope's signal aborts, within an explicit `ttlMs`, and\n * until rotation revokes it. Every stop aborts that signal: cancellation, the run's deadline, and\n * a lead stopping its child. A child's own time box does not: its lead checks it in and keeps it\n * running (`deadline.ts` `DeadlineCheckIn`), and the check-in asks it to record its state and\n * submit through these very tools. Refusing at the time box left a checked-in child unable to do\n * either (2026-10-10: eu-datacenter-power-2030-20261010b:s3, every call for its last 41 minutes).\n */\n const refusedCredential = (\n supplied: Buffer,\n ): 'scope-stopped' | 'credential-refused' | undefined => {\n if (opts.scope.signal.aborted) return 'scope-stopped'\n return validCredential(supplied) ? undefined : 'credential-refused'\n }\n const validCredential = (supplied: Buffer): boolean => {\n if (revoked.has(supplied.toString())) return false\n if (!signingKeys)\n return (\n token !== undefined &&\n (credentialExpiresAt === undefined || 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 // Revocation keys use the wire token; alternate encodings must not alias it.\n signature.toString('base64url') === parts[1] &&\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 ((claims.expires === null && auth?.ttlMs === undefined) ||\n (Number.isSafeInteger(claims.expires) && 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 // Same precedence as the router arm in coordination-driver: a caller-supplied reader, else a\n // host directory, else the manager's own environment through its scope's retained owner. A\n // provider-backed root and every nested manager come through THIS arm, so a fallback wired\n // only in the driver arm would leave a sandbox director refused by path exactly as before.\n const ownerReader =\n opts.spawnResourceReader ??\n (opts.spawnResourceRoot === undefined\n ? scopeRetainedOwnerResourceReader(opts.scope)\n : undefined)\n // Bound once the served set exists: `report_blocked` probes only what this manager was granted.\n let probeableByName: ReadonlyMap<string, McpToolDescriptor> | undefined\n const coord = createCoordinationToolsForManager(\n {\n resolveProbeTool: (name) => probeableByName?.get(name),\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.readContinuation ? { readContinuation: opts.readContinuation } : {}),\n ...(opts.onStop ? { onStop: opts.onStop } : {}),\n ...(opts.analysts ? { analysts: opts.analysts } : {}),\n ...(opts.analyzeOnSettle ? { analyzeOnSettle: opts.analyzeOnSettle } : {}),\n ...(opts.sourceEvidenceRefs ? { sourceEvidenceRefs: opts.sourceEvidenceRefs } : {}),\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.composeSpawnProfile ? { composeSpawnProfile: opts.composeSpawnProfile } : {}),\n ...(opts.profiles ? { profiles: opts.profiles } : {}),\n ...(opts.spawnResourceRoot ? { spawnResourceRoot: opts.spawnResourceRoot } : {}),\n ...(ownerReader ? { spawnResourceReader: ownerReader } : {}),\n ...(opts.peerMail\n ? {\n peerMail:\n typeof opts.peerMail === 'object' && opts.peerMail.limits\n ? { limits: opts.peerMail.limits }\n : {},\n }\n : {}),\n },\n lifetime,\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 ?? [], {\n fenceMs: responseFenceMs,\n receipts: coord,\n })\n // `submit_result` runs the injected completion check inside its request, and a product check can\n // re-run a build and a model review for minutes. Unfenced, the transport answered 504 at\n // `requestTimeoutMs` while the check kept running, so the manager never saw the verdict or its\n // reason: 25 of 25 submits in one 2026-09-22 factory run. Fenced, the call answers with a receipt\n // and the verdict reaches the manager in its next wake, from the same check.\n const fencedVerbs = singleFlightTools(\n coord.tools.filter((tool) => tool.name === DELIVERABLE_VERB),\n { fenceMs: responseFenceMs, receipts: coord },\n )\n // A rename in src/mcp/tools/coordination.ts must fail here, not leave the check unfenced and bring\n // back the 504. The test is the one that passed the deliverable to the coordination tools above.\n if (opts.deliverable && fencedVerbs.tools.length !== 1) {\n throw new ValidationError(\n `serveCoordinationMcp: a deliverable is injected but the coordination verbs lack ${DELIVERABLE_VERB}, so its check would run unfenced`,\n )\n }\n const fencedByName = new Map(fencedVerbs.tools.map((tool) => [tool.name, tool]))\n const availableTools = [\n ...coord.tools.map((tool) => fencedByName.get(tool.name) ?? tool),\n ...nodeTools.tools,\n ]\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 probeableByName = new Map(servedTools.map((tool) => [tool.name, tool]))\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()], coord)\n\n const server: Server = createServer(\n coordinationHttpHandler({\n options: opts,\n identity,\n toolNames: new Set(servedTools.map((tool) => tool.name)),\n handle: async (message) => {\n const response = await mcp.handle(message)\n // A coordination call is where a manager commits work, so it is when its workspace is\n // worth a checkpoint (`retained-scope-owner`, rate-limited, off the request path).\n if (message.method === 'tools/call') noteScopeRetainedOwnerCoordination(opts.scope)\n return response\n },\n backgroundActions: () => nodeTools.background() + fencedVerbs.background(),\n authorize: (req) => {\n if (!paths.has(req.url ?? '')) return { status: 404, reason: 'unknown-path' }\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)\n return { status: 403, reason: 'wrong-host' }\n if (closed) return { status: 401, reason: 'listener-closed' }\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 const refused = refusedCredential(supplied)\n return refused === undefined ? undefined : { status: 401, reason: refused }\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 addressLifetime = new AbortController()\n const abortAddress = () => addressLifetime.abort(opts.scope.signal.reason)\n opts.scope.signal.addEventListener('abort', abortAddress, { once: true })\n if (opts.scope.signal.aborted) abortAddress()\n const releaseAddress = () => {\n opts.scope.signal.removeEventListener('abort', abortAddress)\n if (!addressLifetime.signal.aborted)\n addressLifetime.abort(new Error('coordination listener closed'))\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: addressLifetime.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 if (configured !== undefined) {\n await preflightPublicCoordination({\n url,\n headers,\n signal: opts.scope.signal,\n requestTimeoutMs,\n toolNames: selectedNames,\n })\n }\n } catch (error) {\n releaseAddress()\n closed = true\n await new Promise<void>((resolve) => {\n server.close(() => resolve())\n server.closeAllConnections()\n })\n throw error\n }\n\n const mailbox = coord.peerMail\n const mailListener = mailbox === undefined ? undefined : await servePeerMail(mailbox, host)\n\n const handle: CoordinationMcpHandle = {\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 finishAnalysis: (input) => coord.finishAnalysis(input),\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 releaseAddress()\n closed = true\n await new Promise<void>((resolve) => {\n server.close(() => resolve())\n })\n await mailListener?.close()\n },\n }\n return { handle, controls: coord }\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 { ATTR } from '@tangle-network/agent-trace-contract'\nimport { contentAddress } from '../../durable/spawn-journal'\nimport type { OtelExportConfig, OtelExporter, OtelExportStats, 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 `namespace` and `runId`, so a resumed run lands in the SAME trace as the\n * process that started it while two copies of one run id in different places never share one.\n */\n readonly traceId?: string\n /**\n * The run's storage identity. `supervise()` supplies its run namespace: the run context's own,\n * or a digest of `runDir` and `runId` for a durable run. Absent, the trace derives from `runId`.\n */\n readonly namespace?: 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 /** What this run's exporter has delivered and lost so far. Also surfaced once, as a\n * `console.warn`, on `finish()` when the closing flush dropped spans. */\n stats(): OtelExportStats\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, opts.namespace)\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 /**\n * The span a node's event hangs under. A parent node whose span this recorder never opened (it\n * ran in an earlier process) leaves the child on the root span, which is a placeholder, not a\n * recorded parent.\n */\n const parentSpan = (\n parentId: string | undefined,\n ): { spanId: string; confidence: 'explicit' | 'unknown' } => {\n const spanId = parentId === undefined ? undefined : spanIdOf.get(parentId)\n return spanId\n ? { spanId, confidence: 'explicit' }\n : { spanId: rootSpanId, confidence: 'unknown' }\n }\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 attrs: Attrs = {\n ...base,\n [ATTR.spanKind]: 'AGENT',\n 'agent.name': label,\n 'tangle.supervise.node.id': childId,\n 'tangle.supervise.node.label': label,\n 'tangle.supervise.node.kind': '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 // Retry safety: every try of one keyed assignment shares its operation id and carries its own\n // attempt id, and the key is what makes a re-spawn re-attach instead of running twice.\n const key = str(p.key)\n const operation = str(p.assignmentId) ?? key\n if (operation) attrs[ATTR.operationId] = operation\n const attempt = str(p.attemptId)\n if (attempt) attrs[ATTR.attemptId] = attempt\n if (key) attrs[ATTR.idempotencyKey] = key\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 parent = parentSpan(event.parentId)\n attrs[ATTR.parentConfidence] = parent.confidence\n\n const spanId = generateSpanId()\n spanIdOf.set(childId, spanId)\n open.set(childId, {\n spanId,\n parentSpanId: parent.spanId,\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 // A turn with no node is the root manager's own.\n const parent = parentId ? parentSpan(parentId) : { spanId: rootSpanId, confidence: 'explicit' }\n const parentSpanId = parent.spanId\n const attrs: Attrs = {\n ...base,\n [ATTR.parentConfidence]: parent.confidence,\n [ATTR.spanKind]: '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 {\n ...rootAttrs(base, opts.agentName ?? 'supervisor', outcome),\n ...(opts.parentSpanId ? { [ATTR.parentConfidence]: 'explicit' } : {}),\n },\n rootStatus(outcome),\n rootMessage(outcome),\n ),\n )\n } catch {\n // Telemetry is not the work: a failure building or emitting the closing\n // spans above must never reach the run.\n }\n // Flush and shutdown run outside the span-building try so a rejected\n // flush cannot skip shutdown, and are surfaced instead of swallowed: a\n // 401 or a dead collector was previously silent even to someone\n // awaiting finish(). One warning per finish() call, not per span.\n try {\n await exporter.flush()\n } catch (error) {\n const s = exporter.stats()\n console.warn(\n `[agent-runtime] supervisor span export dropped ${s.dropped} span(s): ${s.lastError ?? String(error)}`,\n )\n } finally {\n if (ownsExporter) await exporter.shutdown()\n }\n },\n stats: () => exporter.stats(),\n }\n}\n\n// ── Attribute mapping ─────────────────────────────────────────────────────────\n\nfunction rootAttrs(base: Attrs, agentName: string, outcome?: SupervisorSpanOutcome): Attrs {\n const attrs: Attrs = {\n ...base,\n [ATTR.spanKind]: '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 by content address — deterministic, so a resumed run\n * rejoins the trace its first process opened rather than forking a new one. The default covers the\n * namespace as well as the run id, because run ids repeat across copies of a run.\n */\nfunction normalizeTraceId(\n traceId: string | undefined,\n runId: string,\n namespace: string | undefined,\n): string {\n if (traceId && /^[0-9a-f]{32}$/i.test(traceId)) return traceId.toLowerCase()\n const source = traceId ?? (namespace === undefined ? runId : `${namespace}\\u0000${runId}`)\n return contentAddress(source).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 * The task a re-entered external driver receives, composed from Runtime's own records.\n *\n * A re-prompt used to send the unmet items alone, on the claim that it re-entered the SAME live\n * session. That holds on a backend that reattaches the harness session. It does not hold when the\n * previous environment is gone: the driver then starts in a new sandbox, with a new harness\n * session, and the unmet-items text is all it knows. Measured in Autopsy A (2026-09-16): three\n * root attempts, each in a new sandbox; the third reported an empty workspace, spent 20 minutes\n * and about 2.0M input tokens investigating infrastructure, and never consumed the child result\n * that had settled while it was gone.\n *\n * So the composer takes the drive harness's statement of what the next drive continues, and\n * writes the whole run state whenever the harness session is not proven continuous: the original\n * objective and completion contract, where the journal was read to, the events waiting and the\n * events delivered to a turn that died, every live and settled worker, the last refusal, and what\n * became of the workspace. A proven-continuous session gets the unmet items plus what changed.\n */\n\nimport type { ManagerReentryState } from '../../mcp/tools/coordination'\nimport type { DriverReentry } from './driver-retry'\n\n/** What the next drive continues, as the drive harness can prove it before the turn starts. */\nexport interface ReentryContinuity {\n /** `continued`: the next turn is sent into the harness session that received the last one.\n * `new`: a new harness session, which knows only what its task says. */\n readonly session: 'continued' | 'new'\n /** Whether the next drive runs in the environment the previous drive used. `replaced` names a\n * previous environment the provider no longer holds. */\n readonly environment: 'same' | 'replaced' | 'unknown'\n readonly environmentId?: string\n readonly previousEnvironmentId?: string\n /** What the next environment holds of the previous one's files. `restored`: the files as of\n * the checkpoint taken at `checkpointAt`; anything written after it is gone. */\n readonly workspace: 'kept' | 'restored' | 'lost' | 'unknown'\n readonly checkpointAt?: string\n}\n\n/** Continuity when nothing is proven: compose the full state. */\nexport const UNPROVEN_CONTINUITY: ReentryContinuity = Object.freeze({\n session: 'new',\n environment: 'unknown',\n workspace: 'unknown',\n})\n\nexport interface ReentryTaskInput {\n /** The run's original task, exactly as the first drive received it. */\n readonly originalTask: unknown\n /** What the completion check requires, when the caller described it. */\n readonly contract?: string\n /** Coordination tools served to this manager. Absent means none are proven available. */\n readonly tools?: ReadonlyArray<string>\n readonly reentry: DriverReentry\n readonly continuity: ReentryContinuity\n readonly state: ManagerReentryState\n /** 1-based driver attempt this task starts. */\n readonly attempt: number\n}\n\n/** Compose the task for one re-entered drive. */\nexport function composeReentryTask(input: ReentryTaskInput): string {\n const { reentry, continuity, state } = input\n if (reentry.reason === 'unmet-contract' && continuity.session === 'continued') {\n const changes = stateLines(state, false, input.tools)\n return [reentry.steer, ...(changes.length > 0 ? ['', ...changes] : [])].join('\\n')\n }\n // A woken manager in the same session already holds everything but what happened.\n if (reentry.reason === 'wake' && continuity.session === 'continued') return reentry.input\n const lines: string[] = [\n `You are re-entering a run that is already in progress (driver attempt ${input.attempt}). ` +\n 'This is the same run and the same objective, not a new one.',\n whyLine(reentry),\n environmentLine(continuity),\n '',\n '## Objective',\n '',\n 'This is the original task of the run, unchanged:',\n '',\n taskText(input.originalTask),\n '',\n '## Completion check',\n '',\n ...(input.tools?.includes('submit_result') === true\n ? ['Call submit_result to request acceptance through the independent check.']\n : []),\n input.contract === undefined || input.contract.trim().length === 0\n ? 'No completion requirement was described.'\n : `The declared completion requirement is: ${input.contract.trim()}`,\n ...(reentry.reason === 'unmet-contract' ? ['', 'What is still unmet:', '', reentry.steer] : []),\n ...(reentry.reason === 'wake' ? ['', '## What woke you', '', reentry.input] : []),\n '',\n '## Run state, from the coordinator',\n '',\n ...stateLines(state, true, input.tools),\n '',\n '## What to do now',\n '',\n 'Continue the run from this state.',\n // Measured 2026-09-24 (autopsy-a-restore-after-20260924c): the restored workspace held the\n // first turn's objective.md, and the re-entered director, told only that its files were\n // restored, re-ran the task's first step and overwrote the file without reading it.\n ...(continuity.workspace === 'kept' || continuity.workspace === 'restored'\n ? [\n 'Read the files you already wrote before you repeat any step of the task. A step whose file is there is done, and its content stands.',\n ]\n : []),\n ...(input.tools?.includes('observe_agent') === true\n ? [\n 'Read the output of every settled worker with observe_agent before you spawn anything new.',\n ]\n : []),\n 'Do not spawn a replacement for a worker that is running or has settled.',\n 'Your coordination tools are served by the same coordinator as before, and the state above comes from it.',\n ]\n return lines.join('\\n')\n}\n\n/**\n * Why the driver is back, in one clause. The failure's own text stays in the attempt records and\n * never reaches the driver: measured 2026-09-11, a continuation told the details of a provider\n * failure spent two of its first four children probing the infrastructure, while its peer, told\n * only what to continue, spent all forty-five on the research.\n */\nfunction whyLine(reentry: DriverReentry): string {\n if (reentry.reason === 'unmet-contract') {\n return `Your previous turn ended with the completion check unmet (continuation ${reentry.continuation}).`\n }\n if (reentry.reason === 'wake') {\n return 'Your previous turn ended while your workers ran, and Runtime woke you with what happened.'\n }\n // A pause names no provider and no code: the operator owns the upstream, and the driver's\n // budget belongs to the objective.\n return reentry.reason === 'upstream-unavailable'\n ? 'Your previous turn was interrupted before it finished; the run itself is intact.'\n : `Your previous turn ended before it finished (retry ${reentry.retry}); the run itself is intact.`\n}\n\nfunction environmentLine(continuity: ReentryContinuity): string {\n if (continuity.environment === 'same') {\n return `You run in the same environment as before${continuity.environmentId === undefined ? '' : ` (${continuity.environmentId})`}, and your files are where you left them.`\n }\n if (continuity.environment === 'replaced') {\n return (\n `Your previous environment${continuity.previousEnvironmentId === undefined ? '' : ` (${continuity.previousEnvironmentId})`} is gone, and you run in a new one. ` +\n (continuity.workspace === 'kept'\n ? 'Its files were carried over.'\n : continuity.workspace === 'restored'\n ? `Its files were restored from a checkpoint taken at ${continuity.checkpointAt ?? 'your last coordination call'}; anything you wrote after that is not here. The coordinator and the knowledge store kept everything below.`\n : 'Files you wrote there are not here. The coordinator and the knowledge store kept everything below.')\n )\n }\n return 'You may be in a new environment. Check for files before you rely on them; the coordinator kept everything below.'\n}\n\nfunction stateLines(\n state: ManagerReentryState,\n full: boolean,\n tools: ReadonlyArray<string> | undefined,\n): string[] {\n const lines: string[] = []\n if (full || state.journalRows > state.journalReadTo) {\n lines.push(\n `Journal: ${state.journalRows} rows. You last read up to row ${state.journalReadTo}.` +\n (tools?.includes('read_journal') === true\n ? ` Call read_journal with sinceRow ${state.journalReadTo} to read what happened since, or sinceRow 0 to read the whole run.`\n : ''),\n )\n }\n if (state.live.length > 0) {\n lines.push(\n `Workers running: ${state.live.map((worker) => `${worker.id} (${worker.label}, ${worker.status})`).join('; ')}.`,\n )\n } else if (full) {\n lines.push('Workers running: none.')\n }\n const settled = full ? state.settled : state.settled.filter((worker) => !worker.delivered)\n if (settled.length > 0) {\n lines.push(\n `Workers settled${full ? '' : ' that you have not received'}: ${settled\n .map(\n (worker) =>\n `${worker.id} (${worker.status}${worker.valid === undefined ? '' : worker.valid ? ', passed its check' : ', did not pass its check'}${worker.delivered ? '' : ', not yet received'})`,\n )\n .join('; ')}.` +\n (tools?.includes('observe_agent') === true\n ? ' Read an output with observe_agent and the worker id.'\n : ''),\n )\n } else if (full) {\n lines.push('Workers settled: none.')\n }\n if (state.waiting.length > 0) {\n lines.push(\n `Events waiting for you: ${state.waiting.length} (${state.waiting\n .map((event) =>\n event.worker === undefined ? event.type : `${event.type} from ${event.worker}`,\n )\n .join('; ')}).`,\n )\n } else if (full) {\n lines.push('Events waiting for you: none.')\n }\n if (state.unacknowledged.length > 0) {\n lines.push(\n `Events delivered to a turn that has not finished, so treat them as unread: ${state.unacknowledged\n .map(\n (event) =>\n `#${event.seq} ${event.type}${event.worker === undefined ? '' : ` from ${event.worker}`}`,\n )\n .join('; ')}.`,\n )\n }\n if (state.lastRejection !== undefined) {\n lines.push(`Your last submit_result was refused: ${state.lastRejection.reason}`)\n }\n return lines\n}\n\nfunction taskText(task: unknown): string {\n if (typeof task === 'string') return task\n try {\n return JSON.stringify(task, null, 2) ?? String(task)\n } catch {\n return String(task)\n }\n}\n","/**\n * The root manager's own provider stream, retained where Runtime owns it.\n *\n * Measured motive (agent-runtime#1233, 2026-09-15): a CHILD's full event stream — reasoning, text,\n * and tool parts, 28k to 76k reasoning characters per child — is retained in the blob its\n * `settled` record names as `outRef`. The ROOT's stream reached nobody: `driveHarnessFromBackend`\n * drained the root executor for accounting and discarded every `progress` event, and on a\n * `winner` run `result.outRef` is the SELECTED CHILD's artifact, not the root's. A root that died\n * at its join barrier (fourier-e, 63 children) left a 607-byte `failure.json` and nothing it\n * thought; the Lab's only transcript of a root was a post-hoc scrape of the harness's own\n * database.\n *\n * `<runDir>/root-stream.jsonl` is the record: one JSONL line per `ExecutorProgressEvent`, written\n * AS IT ARRIVES, so a root whose process is killed mid-turn keeps every line already written. The\n * file itself is the evidence; the receipt (`ref`, the content address of the file's bytes, and\n * `events`, its committed line count) is what `result.json` and `failure.json` carry. The winner's\n * `outRef` keeps its meaning; this is a separate reference.\n *\n * Durability boundary: each line is written synchronously to an `O_APPEND` descriptor before the\n * next event is drained, and the file is fsynced at every drive-attempt boundary and at close, not\n * per line. Measured 2026-09-15 on this host's APFS: an fsync per line cost 7.1 ms per event over\n * 1,000 events and 8.1 ms over 5,000 (~80 s for a root emitting ten thousand text deltas, all of\n * it serialized inside the drain loop that also meters the budget); an async `FileHandle.write`\n * still cost 0.9 to 1.1 ms per line in the thread pool the children's journal writes share; a\n * `writeSync` costs 6 µs. A process kill loses nothing written; only a kernel crash or power\n * loss can drop lines written since the last fsync, and the reader's torn-tail rule keeps such a\n * file readable.\n *\n * The bridge wire carries text and tool calls only: cli-bridge's SSE frames decode\n * `delta.content` and `delta.tool_calls`, never a reasoning delta. A bridge-placed root's retained\n * stream is therefore text plus tool calls; reasoning arrives only on the provider/sandbox path,\n * which projects `message.part.updated` reasoning parts to `reasoning_delta`.\n */\n\nimport { createHash } from 'node:crypto'\nimport { closeSync, constants as fsConstants, fsyncSync, openSync, writeSync } from 'node:fs'\nimport { mkdir } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { isNoEntError, prepareJsonlAppend, readCommittedJsonLines } from '../../durable/jsonl-file'\nimport { errorMessage } from '../util'\nimport { assertNoSymlinkDescendant } from './durable-file'\nimport type { ExecutorProgressEvent, RootStreamReceipt } from './types'\n\nexport type { RootStreamReceipt } from './types'\n\n/** The root stream: one JSONL line per progress event the root's executor observed. */\nexport const ROOT_STREAM_FILE = 'root-stream.jsonl'\n\n/** One line of `root-stream.jsonl`. */\nexport type RootStreamRecord = {\n /** 1-based position in the file, continuing across drive attempts and across processes. */\n readonly seq: number\n /** ISO instant the line was appended, from the run's own clock. */\n readonly at: string\n /** The 1-based drive attempt of the root that produced it: a driver retry or re-prompt\n * re-enters the harness and continues the same file with the next attempt number. */\n readonly attempt: number\n} & (\n | { readonly event: ExecutorProgressEvent }\n | {\n /** The event could not be written as JSON; its kind and the reason stand in so the gap\n * is recorded in the file itself instead of silently narrowing the stream. */\n readonly dropped: { readonly kind: ExecutorProgressEvent['kind']; readonly reason: string }\n }\n)\n\n/** The append-only writer one root drive holds. */\nexport interface RootStreamSink {\n /** Mark the next drive attempt; opens the file on the first call. */\n beginAttempt(): Promise<void>\n /** Append one event; the line is in the kernel when this returns. */\n append(event: ExecutorProgressEvent): void\n /** Fsync, close the writer, and return the receipt, or `undefined` when no attempt ever began. */\n close(): Promise<RootStreamReceipt | undefined>\n}\n\n/** Create the writer for `<runDir>/root-stream.jsonl`. Nothing touches disk until the first\n * `beginAttempt`, so a run whose root never drives leaves no file and no receipt. */\nexport function createRootStreamSink(runDir: string, now: () => number): RootStreamSink {\n const dir = resolve(runDir)\n const path = resolve(dir, ROOT_STREAM_FILE)\n let fd: number | undefined\n let attempt = 0\n let seq = 0\n let closed = false\n\n const openOnce = async (): Promise<void> => {\n if (fd !== undefined) return\n await mkdir(dir, { recursive: true })\n assertNoSymlinkDescendant(dir, path, 'root stream')\n // A resumed run continues the same file. Recovery scans the tail once, so a torn line from a\n // process that died mid-write is truncated rather than followed by a record it would corrupt.\n const needsSeparator = await prepareJsonlAppend(path)\n seq = 0\n for await (const _record of readCommittedJsonLines<RootStreamRecord>(path, {\n allowMissing: true,\n })) {\n seq += 1\n }\n fd = openSync(\n path,\n fsConstants.O_APPEND |\n fsConstants.O_CREAT |\n fsConstants.O_WRONLY |\n (typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0),\n 0o600,\n )\n if (needsSeparator) writeLine(fd, '')\n }\n\n return {\n async beginAttempt() {\n if (closed) throw new Error('root stream: beginAttempt after close')\n attempt += 1\n // A retry re-enters the harness after the previous attempt's lines; make them durable\n // before the next attempt appends after them.\n if (fd !== undefined) fsyncSync(fd)\n await openOnce()\n },\n append(event) {\n if (closed) throw new Error('root stream: append after close')\n if (fd === undefined) throw new Error('root stream: append before beginAttempt')\n const at = new Date(now()).toISOString()\n const record = { seq: seq + 1, at, attempt, event }\n // A progress payload is JSON the wire already parsed, so this branch is a guard, not a\n // path: a value JSON cannot encode (a BigInt, a cycle, a hostile `toJSON`) is recorded as\n // a dropped line so the turn continues and the file still says something was lost.\n let line: string | undefined\n try {\n line = JSON.stringify(record)\n } catch (error) {\n line = JSON.stringify({\n seq: seq + 1,\n at,\n attempt,\n dropped: { kind: event.kind, reason: errorMessage(error) },\n })\n }\n if (line === undefined) {\n line = JSON.stringify({\n seq: seq + 1,\n at,\n attempt,\n dropped: { kind: event.kind, reason: 'event serialized to nothing' },\n })\n }\n writeLine(fd, line)\n seq += 1\n },\n async close() {\n if (closed) throw new Error('root stream: closed twice')\n closed = true\n if (fd === undefined) return undefined\n try {\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n fd = undefined\n }\n return readRootStreamReceipt(dir)\n },\n }\n}\n\n/** `writeSync` may legally make a short write; loop until the whole line and its newline land. */\nfunction writeLine(fd: number, line: string): void {\n const bytes = Buffer.from(`${line}\\n`, 'utf8')\n let offset = 0\n while (offset < bytes.byteLength) {\n const written = writeSync(fd, bytes, offset, bytes.byteLength - offset)\n if (written <= 0) throw new Error(`root stream: append made no progress at byte ${offset}`)\n offset += written\n }\n}\n\n/**\n * The receipt for the root stream a run directory holds, recomputed from the file's bytes, or\n * `undefined` when the directory holds none. This is what a run that never settled — a root that\n * died mid-turn — gets on its failure record, and it equals what `close()` returned for a run\n * that did.\n */\nexport async function readRootStreamReceipt(\n runDir: string,\n): Promise<RootStreamReceipt | undefined> {\n const path = resolve(runDir, ROOT_STREAM_FILE)\n const hash = createHash('sha256')\n let events = 0\n try {\n for await (const _record of readCommittedJsonLines<RootStreamRecord>(path, {\n onBytes: (bytes) => {\n hash.update(bytes)\n },\n })) {\n events += 1\n }\n } catch (error) {\n if (isNoEntError(error)) return undefined\n throw error\n }\n return Object.freeze({ ref: `sha256:${hash.digest('hex')}`, events })\n}\n\n/** Every committed line of the root stream, in order, or `undefined` when there is no file. A\n * torn final line from a process that died mid-write is not a record and is left out. */\nexport async function readRootStream(runDir: string): Promise<RootStreamRecord[] | undefined> {\n const path = resolve(runDir, ROOT_STREAM_FILE)\n const records: RootStreamRecord[] = []\n try {\n for await (const record of readCommittedJsonLines<RootStreamRecord>(path)) records.push(record)\n } catch (error) {\n if (isNoEntError(error)) return undefined\n throw error\n }\n return records\n}\n","/**\n * A manager's own run as one trace store: what the continuation's question panel reads.\n *\n * The panel asks about the director's own work and about its workers' (discovery\n * `docs/38-one-loop-and-continuation.md`, section 5), so it reads both: the director's root stream\n * (`root-stream.jsonl`) and each settled worker's structured tool trace. Each agent is one trace,\n * named by its node id, so a `{worker}` question and a `trace://<worker id>/<span id>` citation\n * name the same worker.\n *\n * The root stream is progress events, not spans. Each tool call becomes one span with its result,\n * and each run of the director's text, and of its reasoning, between two other events becomes one\n * span named for what it is (`assistant_text`, `assistant_reasoning`): the director's claims live in\n * its text, and a panel that saw only its tool calls could not check them. Span ids are the\n * record's `seq`, which is unique in the file and stable across reads.\n */\n\nimport {\n type ToolSpan,\n type TraceAnalysisStore,\n toolSpansToTraceAnalysisStore,\n} from '@tangle-network/agent-eval'\nimport { ValidationError } from '../../errors'\nimport type { RootStreamRecord } from './root-stream'\nimport { parseWorkerToolTraceArtifact } from './trace-evidence'\nimport type { ResultBlobStore, WorkerTraceEvidence } from './types'\n\n/** The span a run of the director's text becomes. */\nexport const ASSISTANT_TEXT_SPAN = 'assistant_text'\n/** The span a run of the director's reasoning becomes. */\nexport const ASSISTANT_REASONING_SPAN = 'assistant_reasoning'\n\n/** The director's root stream as tool spans in one trace named `traceId`. */\nexport function rootStreamToolSpans(\n records: ReadonlyArray<RootStreamRecord>,\n traceId: string,\n): ToolSpan[] {\n const spans: ToolSpan[] = []\n // Open calls by attempt and call id, or by tool name for a harness that sends no call id.\n const open = new Map<string, ToolSpan>()\n let prose: { span: ToolSpan; text: string; kind: string; attempt: number } | undefined\n const at = (record: RootStreamRecord) => {\n const ms = Date.parse(record.at)\n if (!Number.isFinite(ms)) {\n throw new ValidationError(`root stream line ${record.seq} has no valid time`)\n }\n return ms\n }\n const base = (record: RootStreamRecord, name: string) => ({\n kind: 'tool' as const,\n spanId: `s${record.seq}`,\n runId: traceId,\n name,\n toolName: name,\n startedAt: at(record),\n attributes: { attempt: record.attempt, seq: record.seq },\n })\n for (const record of records) {\n if (!('event' in record)) {\n prose = undefined\n continue\n }\n const { event } = record\n if (event.kind === 'text_delta' || event.kind === 'reasoning_delta') {\n if (prose !== undefined && prose.kind === event.kind && prose.attempt === record.attempt) {\n prose.text += event.text\n prose.span.result = prose.text\n prose.span.endedAt = at(record)\n continue\n }\n const name = event.kind === 'text_delta' ? ASSISTANT_TEXT_SPAN : ASSISTANT_REASONING_SPAN\n const span: ToolSpan = {\n ...base(record, name),\n args: {},\n result: event.text,\n endedAt: at(record),\n }\n spans.push(span)\n prose = { span, text: event.text, kind: event.kind, attempt: record.attempt }\n continue\n }\n prose = undefined\n if (event.kind === 'tool_call') {\n const span: ToolSpan = {\n ...base(record, event.toolName),\n args: event.args,\n ...(event.args === undefined ? { argsCaptured: false } : {}),\n endedAt: at(record),\n }\n if (event.toolCallId !== undefined) {\n span.attributes = { ...span.attributes, toolCallId: event.toolCallId }\n }\n spans.push(span)\n open.set(`${record.attempt}\\u0000${event.toolCallId ?? `name:${event.toolName}`}`, span)\n continue\n }\n if (event.kind === 'tool_result') {\n const key = `${record.attempt}\\u0000${event.toolCallId ?? `name:${event.toolName}`}`\n const call = open.get(key)\n if (call !== undefined) {\n open.delete(key)\n call.result = event.result\n call.endedAt = at(record)\n continue\n }\n // A result whose call the stream never recorded keeps its own span.\n spans.push({\n ...base(record, event.toolName),\n args: undefined,\n argsCaptured: false,\n result: event.result,\n endedAt: at(record),\n })\n }\n // Interaction requests and native child-task updates are not tool evidence; the child's own\n // trace is the worker's, which this store reads separately.\n }\n return spans\n}\n\n/** One worker's persisted tool spans, re-keyed to the worker's node id. Unavailable: none. */\nasync function workerSpans(\n worker: { readonly id: string; readonly trace: WorkerTraceEvidence },\n blobs: Pick<ResultBlobStore, 'get'>,\n): Promise<ToolSpan[]> {\n if (worker.trace.status !== 'available') return []\n const raw = await blobs.get(worker.trace.traceRef)\n if (raw === undefined) {\n throw new ValidationError(\n `worker ${worker.id}'s trace blob '${worker.trace.traceRef}' is missing; its settlement evidence is incomplete`,\n )\n }\n const { spans } = parseWorkerToolTraceArtifact(raw, worker.trace.traceRef)\n return spans.map((span) => ({\n ...span,\n runId: worker.id,\n ...(span.runId === worker.id\n ? {}\n : { attributes: { ...span.attributes, sourceRunId: span.runId } }),\n }))\n}\n\n/**\n * The store over a manager's run: its own root stream when it has one, and every settled worker's\n * tool trace. `undefined` when the run has recorded no span yet, which is not a store a panel can\n * read: agent-eval refuses an empty trace, because it cannot tell a tool-free run from a failed\n * capture.\n */\nexport async function runTraceAnalysisStore(input: {\n readonly root?: {\n readonly id: string\n readonly read: () => Promise<ReadonlyArray<RootStreamRecord> | undefined>\n }\n readonly workers: ReadonlyArray<{ readonly id: string; readonly trace: WorkerTraceEvidence }>\n readonly blobs: Pick<ResultBlobStore, 'get'>\n}): Promise<TraceAnalysisStore | undefined> {\n const records = input.root === undefined ? undefined : await input.root.read()\n const spans = [\n ...(records === undefined || input.root === undefined\n ? []\n : rootStreamToolSpans(records, input.root.id)),\n ...(await Promise.all(input.workers.map((worker) => workerSpans(worker, input.blobs)))).flat(),\n ]\n return spans.length === 0 ? undefined : toolSpansToTraceAnalysisStore(spans)\n}\n","import type { CoordinationTools } from '../../mcp/tools/coordination'\nimport { createCancelAcknowledger, createSteerAcknowledger } from './coordination-driver'\nimport type { Scope } from './types'\n\n/** Observe durable worker controls while the native harness owns the manager's turn loop. */\nexport function observeWorkerControls(options: {\n dir?: string\n steerDir?: string\n coord: CoordinationTools\n scope: Scope<unknown>\n signal: AbortSignal\n controlScope: 'run' | 'subtree'\n /** Root's existing inbox only; omitted for every nested manager. */\n deliverRoot?: (message: { steer: string; interrupt: boolean }) => boolean\n /** Root delivery readiness; checked before a durable steer is claimed. */\n deliverRootReady?: () => boolean\n onError: (error: unknown) => void\n}): { close(): Promise<void> } {\n const { dir, coord, scope, signal, controlScope, onError } = options\n const steerDir = options.steerDir ?? dir\n const deps = { coord, scope, signal, now: Date.now, ownerId: scope.view.root, controlScope }\n const steers =\n steerDir === undefined\n ? undefined\n : createSteerAcknowledger({\n ...deps,\n dir: steerDir,\n deliverRoot: options.deliverRoot,\n deliverRootReady: options.deliverRootReady,\n })\n const cancellations = dir === undefined ? undefined : createCancelAcknowledger({ ...deps, dir })\n let active = true\n let timer: ReturnType<typeof setInterval> | undefined\n let steering = false\n let inFlight = Promise.resolve()\n let failure: { error: unknown } | undefined\n let closing: Promise<void> | undefined\n\n const stop = (): void => {\n active = false\n clearInterval(timer)\n signal.removeEventListener('abort', stop)\n }\n const fail = (error: unknown): void => {\n failure = { error }\n stop()\n onError(error)\n }\n const poll = (): void => {\n if (!active) return\n try {\n // Cancellation stays available while an earlier steer awaits durable event capture.\n cancellations?.pass('turn')\n if (steers === undefined || steering) return\n steering = true\n inFlight = steers\n .pass('turn')\n .catch(fail)\n .finally(() => {\n steering = false\n })\n } catch (error) {\n fail(error)\n }\n }\n signal.addEventListener('abort', stop, { once: true })\n if (signal.aborted) stop()\n else {\n timer = setInterval(poll, 100)\n timer.unref()\n poll()\n }\n\n const finish = async (): Promise<void> => {\n stop()\n await inFlight\n try {\n await steers?.pass('final')\n cancellations?.pass('final')\n } finally {\n cancellations?.finish()\n }\n if (failure) throw failure.error\n }\n return {\n close: () => (closing ??= finish()),\n }\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 quality-accepted.\n */\nimport { dirname } from 'node:path'\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 CoordinationTools,\n EscalateQuestion,\n MakeWorkerAgent,\n SpawnPreflight,\n SuperviseProfileEntry,\n WorkerWatchOptions,\n} from '../../mcp/tools/coordination'\nimport { coordinationVerbNames } from '../../mcp/tools/coordination'\nimport type { SpawnResourceReader } from '../../mcp/tools/spawn-resource-paths'\nimport { agentHarness } from '../harness-role'\nimport type { HarnessTranscriptCapture } from '../harness-transcript'\nimport { type RouterTransportConfig, routerBrain } from '../router-client'\nimport type { ToolLoopChat, ToolLoopCompactionOptions } from '../tool-loop'\nimport { linkAbort, runAbortable } from './abortable'\nimport type { DeliverableSpec } from './completion-gate'\nimport {\n admitContinuationPolicy,\n bestComposite,\n CheckUnavailableError,\n type ContinuationKeeper,\n type ContinuationPolicy,\n checkVerdictOf,\n createContinuationKeeper,\n} from './continuation'\nimport { driverAgent } from './coordination-driver'\nimport type { PriorCoordination } from './coordination-log'\nimport {\n assertCoordinationTransport,\n type CoordinationTransportOptions,\n serveCoordinationMcpForManager,\n} from './coordination-mcp'\nimport {\n type DriverAttemptRecord,\n type DriverContinuationRecord,\n type DriverProgressMark,\n type DriverReentry,\n type DriverRetryPolicy,\n runDriverWithRetry,\n summarizeDriverAttempts,\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 { isLiveNodeStatus } from './node-status'\nimport type { PeerMailLimits } from './peer-mail'\nimport type { ExecutorProgress } from './progress'\nimport {\n coordinationMcpAlias,\n coordinationProfileToolPrefix,\n providerVisibleProfile,\n} from './provider-visible-profile'\nimport { composeReentryTask, type ReentryContinuity, UNPROVEN_CONTINUITY } from './reentry'\nimport { abandonScopeRetainedOwnerInvocation } from './retained-scope-owner'\nimport { readRootStream } from './root-stream'\nimport { createRouterTranscript } from './router-transcript'\nimport { applyRunCancellation } from './run-cancellation'\nimport { runTraceAnalysisStore } from './run-traces'\nimport {\n beginScopeOwnerAttempt,\n recordScopeOwnerDriverAttempt,\n recordScopeOwnerPause,\n} 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 {\n Agent,\n Budget,\n ExecutorResult,\n NodeExecutionIdentity,\n ResultBlobStore,\n Scope,\n} from './types'\nimport {\n composeWakeInput,\n deadlineWarningAt,\n type ManagerWakePolicy,\n resolveWakePolicy,\n} from './wake'\nimport { observeWorkerControls } from './worker-control-observer'\n\nexport {\n coordinationMcpAlias,\n coordinationProfileToolPrefix,\n providerVisibleProfile,\n} from './provider-visible-profile'\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 if (declaredRuntimeToolNames(profile).includes('await_event')) {\n return `the profile declares ${JSON.stringify(`${coordinationProfileToolPrefix}await_event`)}, which no longer exists: a manager ends its turn to wait, and Runtime wakes it with what happened. Remove the grant`\n }\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/** 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, the worker-slot queue, 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 /** Wait in code until at least one of `{ workerIds }` has settled; returns `{ settled: ids }`.\n * Takes nothing from the manager's inbox, so the manager still hears of each settlement. */\n awaitSettlement(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(\n tools: ReadonlyArray<McpToolDescriptor>,\n coordination: Pick<CoordinationTools, 'awaitSettlement'>,\n ): void\n}\n\nfunction createVerbSlot(): VerbSlot {\n let bound: ReadonlyArray<McpToolDescriptor> | undefined\n let waits: Pick<CoordinationTools, 'awaitSettlement'> | 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 awaitSettlement: async (args: unknown): Promise<unknown> => {\n if (waits === undefined) {\n throw new ValidationError(\n 'supervisorAgent: coordination verb \"awaitSettlement\" was called before this manager\\'s coordination tools were bound',\n )\n }\n const ids = (args as { workerIds?: unknown } | undefined)?.workerIds\n if (!Array.isArray(ids) || !ids.every((id) => typeof id === 'string' && id.length > 0)) {\n throw new ValidationError('awaitSettlement: workerIds must be an array of worker ids')\n }\n return { settled: await waits.awaitSettlement(ids as string[]) }\n },\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, coordination): void {\n bound = tools\n waits = coordination\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 / observe_agent / submit_result 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 profile the run registered, when `authoredProfile` is another segment of it (a resumed root moved to\n * another model or harness). Materialization receipts are attributed to it, so a run's materialization chain\n * keeps one authored profile across segments. Absent when the two are the same. */\n readonly registeredProfile?: 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 /** Present when this drive re-enters the run. `task` then carries the original objective and\n * the coordinator's run state, which is right for any backend. A harness that can prove what\n * the next turn continues composes the task from that proof instead, and reports it. */\n readonly reentry?: {\n /** Why Runtime is re-entering; a typed usage limit may advance an authored seat chain. */\n readonly reason: DriverReentry\n readonly compose: (continuity: ReentryContinuity) => string\n readonly onContinuity?: (continuity: ReentryContinuity) => void\n }\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 readiness predicate for the live inbox. Root steers remain durable and unclaimed\n * until this returns `true`; it is checked only while the harness invocation is active. */\n deliverReady?(): 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 /** Terminal artifact from the newest successfully completed invocation. A child without a\n * completion check retains its output as unassessed evidence for its parent. */\n resultArtifact?(): ExecutorResult<unknown> | undefined\n /** Optional capture of the manager's own harness session from its newest attempt. */\n harnessTranscript?(): HarnessTranscriptCapture | undefined\n /** Resolves once {@link harnessTranscript} is final (`Executor.harnessTranscriptSettled`). */\n harnessTranscriptSettled?(): Promise<void>\n /** Close the last subscription segment at this logical manager's settlement. */\n closeSeatSegment?(reason: 'completed' | 'failed' | 'cancelled' | 'paused'): Promise<void>\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 /** Keep an inference turn available when recursive admission holds budget for this manager. */\n readonly preserveOwnerTurns?: true\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 /** Reports that a nested unchecked manager returned its own harness evidence, not a checked\n * finalizer result. Recursive settlement must preserve the absence of a quality verdict. */\n readonly onUnassessedOutput?: (result: unknown) => void\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 /** The profile this manager was registered with, when it executes another segment of it (a resumed root moved\n * to another model or harness, `SuperviseOptions.segment`). Its materialization stays attributed to the\n * registered profile, as a seat's does to the profile that authored the seat; the executed profile is its\n * effective profile. Omit = the executed profile is the registered one. */\n readonly registeredProfile?: AgentProfile\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 /** Called once when the external driver loop ends, returned or thrown, with what it did. */\n readonly onDriverLoopSettled?: (record: DriverContinuationRecord) => void\n /** How an EXTERNAL manager with `deliverable` is sent back when its turn ends with the check\n * unmet: the deadline, `maxBarren`, and the note's profile and switches (`./continuation.ts`).\n * Required with `deliverable` on the external arm, refused without one, and refused for a\n * router-brained supervisor, which runs its own turn loop in process. The harness owns its own\n * turn loop, so it can end while the run has delivered nothing — 376 of 376 winning\n * discovery-lab runs (2026-09-01) ended on the driver's own completion. A continuation reuses the\n * retry path: same scope, same coordination server, same live children, same bounds. */\n readonly continuation?: ContinuationPolicy\n /** Where this manager's continuation files go (`<dir>/<n>/note.md`, `verdict.json`,\n * `panel.jsonl`). Omit to keep them in memory, where `read_continuation` still serves them. */\n readonly continuationDir?: string\n /** The root manager's `root-stream.jsonl`; the question panel reads it as the director's trace. */\n readonly rootStreamPath?: string\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 /** Trusted source refs for this manager’s existing observe_agent capability. */\n readonly sourceEvidenceRefs?: ReadonlyArray<string>\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 /** How Runtime wakes this manager after it ends a turn with work open (both arms). Omit = the\n * defaults in `./wake`. */\n readonly wake?: ManagerWakePolicy\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 /** Composition of each authored child profile before identity is fixed —\n * `CoordinationToolsOptions.composeSpawnProfile`. */\n readonly composeSpawnProfile?: (profile: AgentProfile) => AgentProfile\n /** The run's validated profiles table — `CoordinationToolsOptions.profiles`. */\n readonly profiles?: ReadonlyMap<string, SuperviseProfileEntry>\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 /** See `CoordinationToolsOptions.spawnResourceReader`: the manager's own environment as the\n * source of a by-path resource, for a manager whose workspace is a sandbox this process\n * cannot open. */\n readonly spawnResourceReader?: SpawnResourceReader\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 control directory. Both arms acknowledge worker requests; external managers observe\n * them throughout the harness invocation. See `DriverAgentOptions.controlDir`. */\n readonly controlDir?: string\n /** Durable steer directory when it differs from the run-control directory. */\n readonly steerDir?: 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 registeredProfile =\n deps.registeredProfile === undefined\n ? stableProfile\n : detachedSnapshot(\n agentProfileSchema.parse(deps.registeredProfile),\n 'supervisorAgent registered profile',\n )\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 (harness === null && deps.continuation !== undefined) {\n throw new ValidationError(\n 'supervisorAgent: continuation applies to an EXTERNAL-harness supervisor only (profile.harness ' +\n 'set). A router-brained supervisor runs its own turn loop in process, so the policy would ' +\n 'be silently ignored.',\n )\n }\n if (deps.continuation !== undefined && deps.deliverable === undefined) {\n throw new ValidationError(\n 'supervisorAgent: continuation needs a `deliverable` completion check — with no check there ' +\n 'is no contract that can be unmet',\n )\n }\n if (harness !== null && deps.deliverable !== undefined && deps.continuation === undefined) {\n throw new ValidationError(\n 'supervisorAgent: a manager with a completion check needs a continuation policy (deadline, ' +\n 'maxBarren, the note profile and switches). Runtime supplies no default: how long to send ' +\n \"a director back, and what to tell it, is the record's decision\",\n )\n }\n // One way out: a manager with a check ends when the check passes or when a bound ends it.\n // Refused before any compute, on both arms.\n if (deps.deliverable !== undefined && runtimeToolNames.includes('stop')) {\n throw new ValidationError(\n `supervisorAgent: the profile grants ${coordinationProfileToolPrefix}stop to a manager with a ` +\n 'completion check. Such a manager ends only through submit_result (the check passes) or a ' +\n 'bound (deadline, budget, cancellation, no progress); remove stop from its tools',\n )\n }\n const continuationDeadlineMs =\n deps.continuation === undefined\n ? undefined\n : admitContinuationPolicy(deps.continuation, 'supervisorAgent')\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 // One conversation per agent, whichever driver `act` builds for an attempt.\n const transcript = createRouterTranscript()\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 transcript,\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 ...(deps.preserveOwnerTurns ? { preserveOwnerTurns: true as const } : {}),\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.extraTools ? { extraTools: deps.extraTools } : {}),\n ...(deps.executeExtraTool ? { executeExtraTool: deps.executeExtraTool } : {}),\n ...(deps.analysts ? { analysts: deps.analysts } : {}),\n ...(deps.analyzeOnSettle ? { analyzeOnSettle: deps.analyzeOnSettle } : {}),\n ...(deps.sourceEvidenceRefs ? { sourceEvidenceRefs: deps.sourceEvidenceRefs } : {}),\n ...(deps.escalateQuestion ? { escalateQuestion: deps.escalateQuestion } : {}),\n ...(deps.watchWorkers ? { watchWorkers: deps.watchWorkers } : {}),\n ...(deps.stallAfterMs !== undefined ? { stallAfterMs: deps.stallAfterMs } : {}),\n ...(deps.wake !== undefined ? { wake: deps.wake } : {}),\n ...(deps.continuityByProfile ? { continuityByProfile: deps.continuityByProfile } : {}),\n ...(deps.preflightSpawn ? { preflightSpawn: deps.preflightSpawn } : {}),\n ...(deps.resolveSpawnProfile ? { resolveSpawnProfile: deps.resolveSpawnProfile } : {}),\n ...(deps.composeSpawnProfile ? { composeSpawnProfile: deps.composeSpawnProfile } : {}),\n ...(deps.profiles ? { profiles: deps.profiles } : {}),\n ...(deps.spawnResourceRoot ? { spawnResourceRoot: deps.spawnResourceRoot } : {}),\n ...(deps.spawnResourceReader ? { spawnResourceReader: deps.spawnResourceReader } : {}),\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\n ? { onCoordinationTools: (tools, coordination) => slot.bind(tools, coordination) }\n : {}),\n ...(deps.controlDir === undefined ? {} : { controlDir: deps.controlDir }),\n ...(deps.steerDir === undefined ? {} : { steerDir: deps.steerDir }),\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 harnessTranscript: () => transcript.capture(),\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 rawDeliverReady = driveHarness.deliverReady\n if (rawDeliverReady !== undefined && typeof rawDeliverReady !== 'function') {\n throw new ValidationError(\n 'supervisorAgent: driveHarness.deliverReady must be a function when provided',\n )\n }\n const deliverReady = rawDeliverReady?.bind(driveHarness)\n const wakePolicy = resolveWakePolicy(deps.wake)\n // Set while `act` runs: where a message from this manager's lead goes. A harness with a live\n // inbox takes it inside the running turn; otherwise it is the input of the manager's next wake.\n // Before, a manager on an executor with no inbox refused every steer as `runtime-has-no-inbox`.\n let managerInbox: ((message: unknown) => boolean) | undefined\n // The workers this manager is waiting on, while it waits between turns.\n let waitingOn: number | undefined\n // The coordinator of the running `act`. Its submission is set only once the accepted result is\n // durable, so it is what `resultAccepted` reads.\n let liveCoordinator: { submittedResult(): unknown } | undefined\n const externalAgent: Agent<unknown, unknown> = {\n name,\n deliver(message: unknown): boolean {\n return managerInbox?.(message) ?? false\n },\n resultAccepted: () => Boolean(liveCoordinator?.submittedResult()),\n traceSource: () => driveHarness.traceSource?.(),\n progress: () => {\n const harnessProgress = driveHarness.progress?.()\n if (waitingOn === undefined) return harnessProgress\n return {\n ...harnessProgress,\n note: `waiting for ${waitingOn} worker${waitingOn === 1 ? '' : 's'}; Runtime wakes it when one reports`,\n }\n },\n // Present only when the harness has a transcript port, so an absent one still settles as\n // `executor-exposes-no-transcript` rather than as a capture that did not run.\n ...(driveHarness.harnessTranscript\n ? { harnessTranscript: () => driveHarness.harnessTranscript?.() }\n : {}),\n ...(driveHarness.harnessTranscriptSettled\n ? {\n harnessTranscriptSettled: () =>\n driveHarness.harnessTranscriptSettled?.() ?? Promise.resolve(),\n }\n : {}),\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 const coordinationLifetime = linkAbort(scope.signal)\n let harnessInvocationActive = false\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 // Built once the coordinator exists, because it reads the check's reads from it.\n let keeper: ContinuationKeeper | undefined\n const { handle: mcp, controls } = await serveCoordinationMcpForManager(\n {\n scope,\n blobs: deps.blobs,\n makeWorkerAgent: deps.makeWorkerAgent,\n ...(deps.authorizeDownMessage ? { authorizeDownMessage: deps.authorizeDownMessage } : {}),\n perWorker: deps.perWorker,\n ...(coordination ?? {}),\n ...(context\n ? { identity: { runId: context.runNamespace, actorId: context.ownerId } }\n : {}),\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 ...(deps.continuation\n ? {\n readContinuation: (n: number | undefined) =>\n keeper?.read(n) ?? { found: false, reason: 'no continuation has been sent' },\n }\n : {}),\n onStop: (reason) => {\n if (!stopController.signal.aborted) {\n stopController.abort(reason ?? 'coordination stop')\n }\n },\n ...(deps.analysts ? { analysts: deps.analysts } : {}),\n ...(deps.analyzeOnSettle ? { analyzeOnSettle: deps.analyzeOnSettle } : {}),\n ...(deps.sourceEvidenceRefs ? { sourceEvidenceRefs: deps.sourceEvidenceRefs } : {}),\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 // Fence the awaited event transaction itself. Racing only the control poll would leave\n // its late continuation able to deliver an instruction after the manager stopped.\n onEvent: async (event, record) => {\n await runAbortable(\n async () => {\n await onEvent?.(event, record)\n },\n coordinationLifetime.signal,\n 'supervisor coordination stopped',\n )\n },\n ...(deps.replaySettlements ? { replaySettlements: true } : {}),\n ...(deps.preflightSpawn ? { preflightSpawn: deps.preflightSpawn } : {}),\n ...(deps.resolveSpawnProfile ? { resolveSpawnProfile: deps.resolveSpawnProfile } : {}),\n ...(deps.composeSpawnProfile ? { composeSpawnProfile: deps.composeSpawnProfile } : {}),\n ...(deps.profiles ? { profiles: deps.profiles } : {}),\n ...(deps.spawnResourceRoot ? { spawnResourceRoot: deps.spawnResourceRoot } : {}),\n ...(deps.spawnResourceReader ? { spawnResourceReader: deps.spawnResourceReader } : {}),\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, coordination) => slot.bind(tools, coordination),\n },\n coordinationLifetime.signal,\n ).catch((error: unknown) => {\n coordinationLifetime.abort(error)\n throw error\n })\n ledger = mcp\n liveCoordinator = mcp\n managerInbox = (message) => {\n if (\n deliver !== undefined &&\n harnessInvocationActive &&\n (deliverReady === undefined || deliverReady()) &&\n deliver(message)\n ) {\n return true\n }\n return controls.receiveLeadMessage(message)\n }\n const coordinationTools = slot.descriptors()\n const providerProfile = detachedSnapshot(\n providerVisibleProfile(stableProfile),\n 'supervisorAgent provider-visible profile',\n )\n let controlObserver: ReturnType<typeof observeWorkerControls> | undefined\n try {\n if (deps.controlDir !== undefined || deps.steerDir !== undefined) {\n controlObserver = observeWorkerControls({\n ...(deps.controlDir === undefined ? {} : { dir: deps.controlDir }),\n ...(deps.steerDir === undefined ? {} : { steerDir: deps.steerDir }),\n coord: controls,\n scope,\n signal: coordinationLifetime.signal,\n controlScope: deps.controlScope ?? 'run',\n ...(deps.controlScope === 'subtree'\n ? {}\n : {\n deliverRoot: (message: { steer: string; interrupt: boolean }) =>\n managerInbox?.(message) ?? false,\n // Between turns a root steer is the input of the next wake, so it is always\n // deliverable once the coordinator exists.\n deliverRootReady: () => true,\n }),\n onError: (error) => {\n coordinationLifetime.abort(error)\n stopController.abort(error)\n },\n })\n }\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 continuation = deps.continuation\n if (continuation !== undefined && deps.deliverable !== undefined) {\n keeper = createContinuationKeeper({\n policy: continuation,\n task,\n ...(deps.deliverable.describe === undefined ? {} : { owed: deps.deliverable.describe }),\n ...(deps.deliverable.feedback === undefined\n ? {}\n : { feedback: deps.deliverable.feedback }),\n ...(deps.deliverable.sealed === true ? { sealed: true } : {}),\n reads: () => controls.checkReads(),\n workers: () => {\n const labels = new Map(\n ((scope as Partial<Scope<unknown>>).view?.nodes ?? []).map((node) => [\n node.id,\n node.label,\n ]),\n )\n return mcp\n .settled()\n .map((worker) => ({ id: worker.id, label: labels.get(worker.id) ?? worker.id }))\n },\n ...(deps.continuationDir === undefined ? {} : { dir: deps.continuationDir }),\n traces: () => {\n const rootStreamPath = deps.rootStreamPath\n return runTraceAnalysisStore({\n ...(rootStreamPath === undefined\n ? {}\n : {\n root: {\n id: scope.view.root,\n read: () => readRootStream(dirname(rootStreamPath)),\n },\n }),\n workers: mcp.settled(),\n blobs: deps.blobs,\n })\n },\n canReadMore: runtimeToolNames.includes('read_continuation'),\n canSubmitResult: runtimeToolNames.includes('submit_result'),\n })\n }\n let candidate: unknown\n // The finalizer's check of the best delivered child is a check read like any other: the\n // continuation note reports what the check said about the candidate the run would return.\n const finalizerDeliverable =\n deps.deliverable === undefined\n ? undefined\n : {\n ...deps.deliverable,\n check: async (out: unknown) => {\n let verdict: ReturnType<typeof checkVerdictOf>\n try {\n verdict = checkVerdictOf(await deps.deliverable?.check(out))\n } catch (error) {\n controls.recordCheckRead({\n source: 'turn-end',\n unavailable: error instanceof Error ? error.message : String(error),\n })\n throw error\n }\n controls.recordCheckRead({ source: 'turn-end', verdict })\n return verdict\n },\n }\n const finalize = () =>\n runFinalizer(deps.finalizer ?? bestDelivered, {\n settled: mcp.settled(),\n blobs: deps.blobs,\n tree: runTree(scope),\n budget: scope.budget,\n ...(finalizerDeliverable ? { deliverable: finalizerDeliverable } : {}),\n })\n const readProgress = (): DriverProgressMark => {\n const settled = mcp.settled()\n // Child delivery is progress, but its check may cover only the child's assignment.\n const deliveredCount = settled.filter(\n (w) => w.status === 'done' && w.valid === true,\n ).length\n const submitted = Boolean(mcp.submittedResult())\n const composite = bestComposite(controls.checkReads())\n return {\n poolTokensSpent: baseTokensLeft - scope.budget.tokensLeft,\n settledCount: settled.length,\n submitted,\n deliveredCount,\n contract: !contractDeclared\n ? 'none'\n : submitted || candidate !== undefined\n ? 'met'\n : 'unmet',\n ...(composite === undefined ? {} : { composite }),\n }\n }\n /**\n * The check runs when a turn ends without an accepted result. A read already taken in this\n * turn stands (the manager just heard it); otherwise a check that judges state reads the\n * run now. A check that could not run is not a verdict: the loop pauses.\n */\n const readCheckAtTurnEnd = async (attempt: number): Promise<void> => {\n const deliverable = deps.deliverable\n if (deliverable === undefined) return\n const thisTurn = controls.checkReads().filter((read) => read.attempt === attempt)\n const last = thisTurn.at(-1)\n if (last === undefined && deliverable.checkState !== undefined) {\n try {\n const verdict = checkVerdictOf(await deliverable.checkState())\n controls.recordCheckRead({ source: 'turn-end', verdict })\n return\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n controls.recordCheckRead({ source: 'turn-end', unavailable: message })\n throw new CheckUnavailableError(`the completion check could not run: ${message}`, {\n cause: error,\n })\n }\n }\n if (last?.unavailable !== undefined) {\n throw new CheckUnavailableError(\n `the completion check could not run: ${last.unavailable}`,\n )\n }\n }\n const loopRecords: DriverAttemptRecord[] = []\n let deadlineWarned = false\n const managerStartedAt = Date.now()\n let environmentReplacements = 0\n let workspaceRestores = 0\n const describe = deps.deliverable?.describe\n const settleLoop = () => {\n const stopReason = controls.stopReason() ?? progressStopReason\n const closedBy: DriverContinuationRecord['closedBy'] = mcp.submittedResult()\n ? 'result-accepted'\n : mcp.isStopped()\n ? 'stop'\n : progressStopReason !== undefined\n ? 'stop-rule'\n : undefined\n const blocked = controls.blocked()\n deps.onDriverLoopSettled?.({\n ...summarizeDriverAttempts(loopRecords),\n environmentReplacements,\n workspaceRestores,\n ...(closedBy === undefined ? {} : { closedBy }),\n ...(blocked.length === 0 ? {} : { blocked }),\n ...(stopReason === undefined ? {} : { stopReason }),\n continuations: keeper?.entries() ?? [],\n })\n }\n let driverFailed = true\n try {\n await runDriverWithRetry({\n drive: async (attempt, reentry) => {\n candidate = undefined\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 controls.beginDriverAttempt(attempt)\n // A re-entered drive receives the original objective and the coordinator's run state\n // unless the harness proves the turn continues the same session. The unmet items\n // alone are the whole turn only then: a replacement sandbox knows nothing else.\n const compose =\n reentry === undefined\n ? undefined\n : (continuity: ReentryContinuity) =>\n composeReentryTask({\n originalTask: task,\n tools: runtimeToolNames,\n ...(describe === undefined ? {} : { contract: describe }),\n reentry,\n continuity,\n state: controls.reentryState(),\n attempt,\n })\n harnessInvocationActive = true\n let completed = false\n try {\n await driveHarness({\n profile: providerProfile,\n authoredProfile: stableProfile,\n ...(registeredProfile === stableProfile ? {} : { registeredProfile }),\n ...(profilePrompt !== undefined ? { systemPrompt: profilePrompt } : {}),\n task: compose === undefined ? task : compose(UNPROVEN_CONTINUITY),\n ...(compose === undefined\n ? {}\n : {\n reentry: {\n reason: reentry!,\n compose,\n onContinuity: (continuity: ReentryContinuity) => {\n if (continuity.environment === 'replaced') environmentReplacements += 1\n if (continuity.workspace === 'restored') workspaceRestores += 1\n },\n },\n }),\n scope,\n coordinationMcpUrl: mcp.url,\n coordinationMcpHeaders: mcp.headers,\n stopSignal: stopController.signal,\n coordinationTools,\n })\n completed = true\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 completed = true\n } finally {\n harnessInvocationActive = false\n // A completed turn processed what it received; a failed one leaves it for the next\n // re-entry to name. Recorded before the retry decision reads the run.\n if (completed) await controls.endDriverAttempt('completed')\n else await controls.endDriverAttempt('failed').catch(() => undefined)\n }\n // Decide this parent's completion before the retry loop reads progress. Cache the\n // checked candidate so neither the finalizer nor its oracle runs twice on return.\n // A turn that ended with work open is a wait: the manager decides when it is done.\n if (contractDeclared && !mcp.submittedResult() && !controls.hasOpenWork()) {\n await mcp.drainResolved()\n candidate = await finalize()\n if (candidate === undefined && !mcp.isStopped()) await readCheckAtTurnEnd(attempt)\n }\n },\n progress: readProgress,\n budget: () => scope.budget,\n signal: scope.signal,\n resolvePending: (failure, failures) =>\n abandonScopeRetainedOwnerInvocation(scope, failure, failures),\n wait: {\n open: () =>\n !mcp.submittedResult() &&\n !mcp.isStopped() &&\n progressStopReason === undefined &&\n controls.hasOpenWork(),\n wake: async (nextAttempt) => {\n const deadlineMs = scope.budget.deadlineMs\n const warnAt = deadlineWarningAt(\n deadlineMs,\n wakePolicy,\n deadlineWarned,\n managerStartedAt,\n )\n waitingOn = scope.view.nodes.filter(\n (node) => node.id !== scope.view.root && isLiveNodeStatus(node.status),\n ).length\n try {\n const wake = await controls.awaitWake({\n attempt: nextAttempt,\n // A stop (accepted result, stop rule, the manager's own stop) ends the wait too.\n signal: AbortSignal.any([scope.signal, stopController.signal]),\n heartbeatMs: wakePolicy.heartbeatMs,\n debounceMs: wakePolicy.debounceMs,\n ...(warnAt === undefined ? {} : { deadlineAt: warnAt }),\n })\n if (wake === undefined || stopController.signal.aborted) return undefined\n if (wake.reason === 'deadline') deadlineWarned = true\n return {\n input: composeWakeInput(wake, {\n tools: runtimeToolNames,\n deadlineMs,\n now: Date.now(),\n }),\n idleMs: wake.idleMs,\n }\n } finally {\n waitingOn = undefined\n }\n },\n },\n ...(deps.driverRetry ? { policy: deps.driverRetry } : {}),\n ...(continuation !== undefined && keeper !== undefined && continuationDeadlineMs\n ? {\n continuation: {\n maxBarren: continuation.maxBarren,\n deadlineMs: continuationDeadlineMs,\n compose: (context) => (keeper as ContinuationKeeper).compose(context),\n // A run the coordination server closed ended on purpose — the manager's own\n // `stop` (served only without a check), or a progress stop rule that aborted\n // the stop signal. A continuation would re-enter a harness told to stop.\n closed: () => mcp.isStopped() || progressStopReason !== undefined,\n },\n }\n : {}),\n onAttempt: async (record) => {\n loopRecords.push(record)\n await recordScopeOwnerDriverAttempt(scope, record)\n // A pause on an unavailable upstream is infrastructure time, so the run's own\n // journal records it; the caller's observer still sees every attempt.\n if (record.classification === 'unavailable' && record.retryInMs !== undefined) {\n await recordScopeOwnerPause(scope, {\n attempt: record.attempt,\n signal: record.unavailableSignal ?? 'unavailable',\n cause: record.error ?? '',\n attemptMs: record.durationMs,\n pauseMs: record.retryInMs,\n madeProgress: record.madeProgress,\n })\n }\n await deps.onDriverAttempt?.(record)\n },\n })\n driverFailed = false\n } finally {\n await driveHarness.closeSeatSegment?.(\n scope.signal.aborted ? 'cancelled' : driverFailed ? 'failed' : 'completed',\n )\n settleLoop()\n }\n // Without a parent oracle, preserve the single finalization after the driver finishes.\n if (!contractDeclared) 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 await mcp.finishAnalysis({ status: 'done', output: submitted.result })\n return submitted.result\n }\n if (contractDeclared) {\n await mcp.finishAnalysis({ status: 'done', output: candidate })\n return candidate\n }\n const finalized = await finalize()\n if (finalized !== undefined) {\n await mcp.finishAnalysis({ status: 'done', output: finalized })\n return finalized\n }\n // An unchecked child may do direct work. Retain its terminal report through the same\n // settlement and blob reader, without treating native completion as quality acceptance.\n const harnessResult = driveHarness.resultArtifact?.()\n if (\n nodeContextSeed !== undefined &&\n nodeContextSeed.depth > 0 &&\n harnessResult?.out !== undefined &&\n harnessResult.out !== null\n ) {\n deps.onUnassessedOutput?.(harnessResult.out)\n await mcp.finishAnalysis({ status: 'done', output: harnessResult.out })\n return harnessResult.out\n }\n await mcp.finishAnalysis({ status: 'done' })\n return undefined\n } catch (error) {\n await mcp.finishAnalysis({\n status: 'down',\n reason: error instanceof Error ? error.message : String(error),\n })\n throw error\n } finally {\n managerInbox = undefined\n coordinationLifetime.abort(new Error('supervisor manager stopped'))\n try {\n await controlObserver?.close()\n } finally {\n await mcp.close()\n }\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 { isAsyncIterable, sleep } from '../util'\nimport { teardownSurfaces } from './deadline'\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.harnessTranscript ? { harnessTranscript: () => inner.harnessTranscript?.() } : {}),\n ...(inner.harnessTranscriptSettled\n ? { harnessTranscriptSettled: () => inner.harnessTranscriptSettled?.() ?? Promise.resolve() }\n : {}),\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<UsageEvent>(first)\n ? retryStream(first, restart, signal)\n : retryOneShot(first, restart, signal)\n },\n teardown: (grace) => inner.teardown(grace),\n ...teardownSurfaces(inner),\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<UsageEvent>(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<UsageEvent>(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\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 sleep(ms, signal)\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 */\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 ReasoningEffort,\n type Sha256Digest,\n validateAgentProfileSecurity,\n} from '@tangle-network/agent-interface'\nimport { withProfileKb } from '@tangle-network/agent-interface/profile-kb'\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, RuntimeRunStateError, ValidationError } from '../../errors'\nimport {\n type AnalystRegistry,\n type AnalyzeOnSettleRoute,\n type AuthorizeDownMessage,\n type AuthorizedDownMessage,\n type ContinuityMode,\n type CoordinationEvent,\n coordinationVerbNames,\n type DownMessageAuthorizationInput,\n type EscalateQuestion,\n type MakeWorkerAgent,\n type SpawnPreflight,\n type SuperviseProfileEntry,\n type WorkerSpawnContext,\n type WorkerWatchOptions,\n} from '../../mcp/tools/coordination'\nimport { COORDINATION_CLIENT_TOOL_TIMEOUT_MS } from '../../mcp/tools/coordination-request-context'\nimport { composeRuntimeHooks, type RuntimeHooks } from '../../runtime-hooks'\nimport { resolveAgentEnvironmentProvider } from '../environment-provider'\nimport { agentHarness, harnessRunsAgent } from '../harness-role'\nimport {\n type HarnessTranscriptCapture,\n persistHarnessTranscript,\n readHarnessTranscript,\n} from '../harness-transcript'\nimport type { RouterTransportConfig } from '../router-client'\nimport type { ToolLoopChat, ToolLoopCompactionOptions } from '../tool-loop'\nimport {\n addSpend as addRetainedSpend,\n sleep as runtimeSleep,\n unmeteredSpend,\n zeroSpend,\n} from '../util'\nimport { RunCancellationReason } from './abortable'\nimport { assertValidBudget, meterUsageEvent, newUsageTotals, spendFromUsageTotals } from './budget'\nimport { type DeliverableSpec, gateOnDeliverable } from './completion-gate'\nimport { CONTINUATIONS_DIR, type ContinuationPolicy } from './continuation'\nimport { isLoopbackHost } from './coordination-mcp'\nimport { DEFAULT_SUCCESSFUL_SHUTDOWN_MS, type DeadlineCheckIn, teardownExecutor } from './deadline'\nimport { driverChild, driverExecutorFactory, isDriverSpec } from './driver-executor'\nimport {\n type DriverAttemptRecord,\n type DriverContinuationRecord,\n type DriverRetryPolicy,\n HarnessTurnFailedError,\n} from './driver-retry'\nimport { errMessage } from './error-message'\nimport type { BusRecord } from './event-bus'\nimport { executorFailure } from './executor-outcome'\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 { createActivityLog } from './progress'\nimport { type ReentryContinuity, UNPROVEN_CONTINUITY } from './reentry'\nimport { addResourceSpend, resourceTelemetry, withBudgetResources } from './resources'\nimport { registerRetainedExecutorPreparation, retainedExecutorSeamKey } from './retained-executor'\nimport {\n beginScopeRetainedOwnerDrive,\n bindScopeRetainedOwnerEnvironmentId,\n bindScopeRetainedOwnerProvider,\n consumeScopeRetainedOwnerResult,\n prepareScopeRetainedOwnerSeatSwitch,\n prepareScopeRetainedOwnerTask,\n reconcileScopeRetainedOwnerEnvironment,\n scopeRetainedOwnerContext,\n scopeRetainedOwnerJournalRoot,\n scopeRetainedOwnerPriorSpend,\n scopeRetainedOwnerRestorePoint,\n scopeRetainedOwnerResult,\n scopeRetainedOwnerTurnEnded,\n} from './retained-scope-owner'\nimport { createRootStreamSink, ROOT_STREAM_FILE, type RootStreamSink } from './root-stream'\nimport { watchRunCancellation } from './run-cancellation'\nimport {\n createFileRunContext,\n createInMemoryRunContext,\n type RunContext,\n withRunContext,\n} 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 assertRecursiveReservationPolicy,\n deriveNodeExecutionIdentity,\n meterRuntimeOwnedAccounting,\n meterRuntimeOwnedProviderAttempt,\n recordScopeOwnerMaterialization,\n restoreScopeOwnerAcceptedExecution,\n scopeOwnerExecutorNodeContext,\n} from './scope'\nimport {\n type ActiveSeat,\n authoredSeatStages,\n SeatChain,\n SeatChainExhaustedError,\n type SeatSegment,\n type SelectSeat,\n seatExecutionProfile,\n} from './seat-chain'\nimport { detachedSnapshot } from './snapshot'\nimport { type PlateauOptions, plateau, type StopRule } from './stop-rules'\nimport { createRootHandle, createSupervisor, DEFAULT_MAX_DEPTH } 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 ExecutorProgressEvent,\n ExecutorResult,\n NodeExecutionIdentity,\n ProviderModelAttemptEvidence,\n ProviderModelExecutionEvidence,\n RecursiveReservationPolicy,\n ResultBlobStore,\n RootHandle,\n RootProviderModelEvidence,\n RootSegment,\n RootStreamReceipt,\n Scope,\n SpawnJournal,\n Spend,\n SupervisedResult,\n UsageEvent,\n} from './types'\nimport type { ManagerWakePolicy } from './wake'\nimport {\n type WorkerSpawnRetryAttempt,\n type WorkerSpawnRetryPolicy,\n withWorkerSpawnRetry,\n} from './worker-retry'\nimport type { WorkerSlots } from './worker-slots'\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 */\n/** The child with its manager's Runtime coordination grants, unless the child's author wrote any\n * coordination entry: an explicit grant or refusal is the author's choice and stands. A refusal\n * (`false`) grants nothing, so it is removed once it has decided the child stays a leaf; a\n * harness-less leaf carries no tools axis at all. */\nfunction withInheritedSpawnRights(parent: AgentProfile, child: AgentProfile): AgentProfile {\n const childTools = child.tools ?? {}\n const authored = Object.entries(childTools).filter(([name]) =>\n name.startsWith(coordinationProfileToolPrefix),\n )\n if (authored.length > 0) {\n if (authored.every(([, enabled]) => enabled !== false)) return child\n const kept = Object.entries(childTools).filter(\n ([name, enabled]) => !(name.startsWith(coordinationProfileToolPrefix) && enabled === false),\n )\n const { tools: _tools, ...rest } = child\n return agentProfileSchema.parse(\n kept.length === 0 ? rest : { ...rest, tools: Object.fromEntries(kept) },\n )\n }\n const inherited = Object.entries(parent.tools ?? {}).filter(\n ([name, enabled]) =>\n enabled === true &&\n name.startsWith(coordinationProfileToolPrefix) &&\n coordinationVerbNameSet.has(name.slice(coordinationProfileToolPrefix.length)),\n )\n if (!inherited.some(([name]) => name === `${coordinationProfileToolPrefix}spawn_worker`)) {\n return child\n }\n // A worker that becomes a manager must still be able to deliver work it does itself.\n return agentProfileSchema.parse({\n ...child,\n tools: {\n ...childTools,\n ...Object.fromEntries(inherited),\n [`${coordinationProfileToolPrefix}submit_result`]: true,\n },\n })\n}\n\nconst coordinationVerbNameSet: ReadonlySet<string> = new Set<string>(coordinationVerbNames)\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\n/**\n * A manager keeps a dedicated environment. It serves its coordination credential through\n * create-time environment, and every co-tenant of a shared box could read it.\n */\nfunction managerExecutorConfig(config: ExecutorConfig): ExecutorConfig {\n if (config.backend !== 'provider' || config.shared === undefined) return config\n const { shared: _shared, ...dedicated } = config\n return Object.freeze(dedicated)\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/**\n * A manager waits between turns, and a wake can come much later than five minutes after its last\n * turn. Claude Code 2.1.289 writes its prompt cache with a five-minute lifetime unless this variable\n * is set; a wake after the cache expired re-writes the manager's whole context, about 140K tokens\n * per turn on a Discovery root measured 2026-10-05. That root ran on a subscription and already\n * wrote one-hour entries; the variable makes the hour hold for every claude-code manager, whatever\n * its credential. A value the caller set wins.\n */\nconst CLAUDE_CODE_ONE_HOUR_CACHE = 'ENABLE_PROMPT_CACHING_1H'\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 rootStream?: RootStreamSink,\n seatSelection?: {\n readonly select: SelectSeat\n readonly journal: SpawnJournal\n readonly rootId: string\n readonly onSegment: (\n nodeId: string,\n segment: SeatSegment,\n phase: 'started' | 'ended',\n ) => Promise<void>\n readonly onPause: (\n nodeId: string,\n resumeAt: string,\n phase: 'paused' | 'resumed',\n ) => Promise<void>\n },\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 = managerExecutorConfig(\n captureReusableExecutorConfig(backend, 'driveHarnessFromBackend'),\n )\n let boundBackend = bindReusableExecutorExecutionId(capturedBackend, executionId)\n let baseFactory = createExecutor(boundBackend)\n let ownerRuntime =\n boundBackend.backend === 'provider'\n ? (boundBackend.runtime ??\n resolveAgentEnvironmentProvider(boundBackend.provider, boundBackend.registry).name)\n : 'cli'\n let activeExecutor: Executor<unknown> | undefined\n // What this manager's harness has been doing, from the progress events its drives stream. An\n // executor that keeps no activity log of its own (a provider) otherwise reads as idle to the\n // lead that observes it: measured 2026-10-05, a director mid-turn read `turns: 0`, `idleMs`\n // 463967, `stalled: true`.\n const driveActivity = createActivityLog()\n let driveTurns = 0\n const noteDriveProgress = (event: ExecutorProgressEvent): void => {\n const at = Date.now()\n if (event.kind === 'tool_call') {\n driveActivity.push({ at, kind: 'tool', label: event.toolName })\n } else if (event.kind === 'tool_result') {\n driveActivity.push({ at, kind: 'tool', label: event.toolName, status: 'ok' })\n } else if (event.kind === 'text_delta' || event.kind === 'reasoning_delta') {\n const last = driveActivity.last()\n // One note per stretch of model output, refreshed every 30 s, so deltas cannot flood the ring.\n if (last === undefined || last.kind !== 'turn' || at - last.at > 30_000) {\n driveActivity.push({ at, kind: 'turn', label: 'model output' })\n }\n }\n }\n // The manager's own harness session, as the newest attempt captured it.\n let managerTranscript: HarnessTranscriptCapture | undefined\n let managerArtifact: ExecutorResult<unknown> | undefined\n const committedTranscriptDigest = (artifact: ExecutorResult<unknown> | undefined): string => {\n if (artifact === undefined)\n return 'Prior committed transcript: no bounded turn content was captured.'\n const out = artifact.out\n if (out === null || typeof out !== 'object') {\n return `Prior committed transcript ref: ${artifact.outRef}; no structured turn content was captured.`\n }\n const record = out as { content?: unknown; events?: unknown }\n const events = Array.isArray(record.events) ? record.events : []\n const kinds = events.slice(-16).flatMap((event) => {\n if (event === null || typeof event !== 'object') return []\n const kind = (event as { type?: unknown }).type\n return typeof kind === 'string' ? [kind.slice(0, 80)] : []\n })\n const content = typeof record.content === 'string' ? record.content.slice(-4_000) : ''\n return [\n `Prior committed transcript ref: ${artifact.outRef}; ${events.length} events captured.`,\n ...(kinds.length > 0 ? [`Recent event kinds: ${kinds.join(', ')}.`] : []),\n ...(content ? [`Last captured answer excerpt: ${content}`] : []),\n ].join('\\n')\n }\n let seatChain: SeatChain | undefined\n let activeSeat: ActiveSeat | undefined\n let switchedProviderCheckpointAt: string | undefined\n const drive: DriveHarness = async ({\n profile,\n authoredProfile,\n registeredProfile,\n task,\n scope,\n coordinationMcpUrl,\n coordinationMcpHeaders,\n stopSignal,\n coordinationTools,\n reentry,\n }) => {\n const priorCommittedArtifact = managerArtifact\n managerArtifact = undefined\n switchedProviderCheckpointAt = undefined\n const stages = authoredSeatStages(authoredProfile)\n if (stages !== undefined) {\n if (!seatSelection) {\n throw new ValidationError('AgentProfile.seats requires SuperviseOptions.selectSeat')\n }\n if (activeSeat === undefined) {\n // A coordinator crash after a provider committed a failed turn must restore that exact\n // outcome before selecting a replacement. No new seat may start while the old call is\n // still in doubt, and the next retry carries the typed usage-limit reason.\n const accepted = await scopeRetainedOwnerResult(scope)\n const reported = accepted === undefined ? undefined : executorFailure(accepted)\n if (reported !== undefined) {\n await restoreScopeOwnerAcceptedExecution(scope)\n consumeScopeRetainedOwnerResult(scope)\n managerArtifact = accepted\n throw new HarnessTurnFailedError(ownerRuntime, reported)\n }\n }\n const seatJournalRoot = scopeRetainedOwnerJournalRoot(scope) ?? seatSelection.rootId\n seatChain ??= new SeatChain(\n authoredProfile,\n scope.view.root,\n seatJournalRoot,\n seatSelection.journal,\n seatSelection.select,\n now,\n (segment, phase) => seatSelection.onSegment(scope.view.root, segment, phase),\n async (selection, previous) => {\n if (previous && previous.seat !== selection.seat) {\n const sameEnvironment =\n previous.provider === selection.stage.provider &&\n previous.harness === selection.stage.harness\n const checkpoint = await prepareScopeRetainedOwnerSeatSwitch(\n scope,\n sameEnvironment ? 'same-environment' : 'replace-environment',\n )\n if (!sameEnvironment) switchedProviderCheckpointAt = checkpoint.checkpointAt\n }\n },\n )\n const usageLimit =\n reentry?.reason.reason === 'upstream-unavailable' &&\n reentry.reason.signal === 'subscription-usage-limit'\n if (activeSeat === undefined || usageLimit) {\n let afterRecheck = false\n for (;;) {\n try {\n activeSeat = await seatChain.next(usageLimit && !afterRecheck, afterRecheck)\n if (afterRecheck) await seatSelection.onPause(scope.view.root, '', 'resumed')\n break\n } catch (error) {\n if (!(error instanceof SeatChainExhaustedError)) throw error\n await seatSelection.journal.appendEvent(seatJournalRoot, {\n kind: 'seat-paused',\n id: scope.view.root,\n resumeAt: error.resumeAt,\n seq: Date.parse(error.resumeAt),\n at: new Date(now()).toISOString(),\n })\n await seatSelection.onPause(scope.view.root, error.resumeAt, 'paused')\n const waitMs = Math.max(1_000, Date.parse(error.resumeAt) - now())\n await runtimeSleep(waitMs, scope.signal, false)\n afterRecheck = true\n }\n }\n boundBackend = bindReusableExecutorExecutionId(\n managerExecutorConfig(\n captureReusableExecutorConfig(\n {\n ...activeSeat.backend,\n // Let the supervisor see a terminal typed usage limit. The provider executor's\n // default unavailable loop would otherwise retry this seat inside one invocation.\n unavailablePause: false,\n },\n 'selectSeat',\n ),\n ),\n `${executionId}:segment:${activeSeat.segmentIndex}`,\n )\n baseFactory = createExecutor(boundBackend)\n ownerRuntime =\n boundBackend.backend === 'provider'\n ? (boundBackend.runtime ??\n resolveAgentEnvironmentProvider(boundBackend.provider, boundBackend.registry).name)\n : 'cli'\n }\n }\n const retainedOwner =\n boundBackend.backend === 'provider' ? scopeRetainedOwnerContext(scope) : undefined\n if (retainedOwner && boundBackend.backend === 'provider') {\n bindScopeRetainedOwnerProvider(\n scope,\n resolveAgentEnvironmentProvider(boundBackend.provider, boundBackend.registry),\n boundBackend.workspaceRetention === undefined\n ? undefined\n : { port: boundBackend.workspaceRetention, profile },\n )\n // The manager's current box, for a spawn that names a resource by path. Read from the\n // active executor's receipt at spawn time, not captured: the environment does not exist\n // yet here, and a retry re-enters `drive` with a fresh executor.\n bindScopeRetainedOwnerEnvironmentId(scope, () => {\n if (activeExecutor === undefined) return undefined\n const execution = runtimeOwnedExecutorMaterialization(activeExecutor)?.execution\n return execution?.kind === 'environment' ? execution.id : undefined\n })\n // The workspace capture the previous turn handed over reads the environment this turn\n // would change, and its receipt belongs to that turn's invocation: it finishes first.\n await scopeRetainedOwnerTurnEnded(scope)\n }\n // What this drive continues decides what a re-entered driver must be told. Only a proven\n // same-session turn gets the unmet items alone; a replacement environment gets the objective\n // and the coordinator's run state.\n let driveTask = task\n if (reentry !== undefined) {\n const continuity: ReentryContinuity =\n switchedProviderCheckpointAt === undefined\n ? await reentryContinuity(boundBackend, scope, retainedOwner !== undefined)\n : {\n session: 'new',\n environment: 'replaced',\n workspace: 'restored',\n checkpointAt: switchedProviderCheckpointAt,\n }\n if (\n activeSeat?.previous &&\n activeSeat.previous.seat !== activeSeat.seat &&\n activeSeat.previous.provider === activeSeat.stage.provider &&\n activeSeat.previous.harness === activeSeat.stage.harness &&\n (continuity.session !== 'continued' || continuity.environment !== 'same')\n ) {\n throw new ValidationError('same-provider seat continuation lost its native environment')\n }\n reentry.onContinuity?.(continuity)\n driveTask = reentry.compose(continuity)\n if (\n activeSeat?.previous &&\n (activeSeat.previous.provider !== activeSeat.stage.provider ||\n activeSeat.previous.harness !== activeSeat.stage.harness)\n ) {\n driveTask = [\n String(driveTask),\n '',\n '## Harness handoff',\n '',\n 'This is the same logical agent in a different harness or provider. Read the restored workspace,',\n 'especially its STATE, NEXT, and RESULT pages and knowledge pages, before acting.',\n 'A prior tool call may have executed. Check its committed output or workspace effect',\n 'before repeating it.',\n committedTranscriptDigest(priorCommittedArtifact),\n ].join('\\n')\n }\n }\n const originalTask = retainedOwner\n ? await prepareScopeRetainedOwnerTask(scope, driveTask)\n : driveTask\n const acceptedOwner = retainedOwner ? await scopeRetainedOwnerResult(scope) : undefined\n if (acceptedOwner) {\n await restoreScopeOwnerAcceptedExecution(scope)\n consumeScopeRetainedOwnerResult(scope)\n // A committed turn that failed is replayed as the failure it was, not as a delivered turn.\n // Its evidence is restored above, so the retry loop's next attempt starts a new invocation\n // in the same environment instead of this resume ending on the failed result.\n const replayedFailure = executorFailure(acceptedOwner)\n if (replayedFailure !== undefined) {\n throw new HarnessTurnFailedError(ownerRuntime, replayedFailure)\n }\n // The coordination journal still goes through the normal driver finalizer.\n managerArtifact = acceptedOwner\n return\n }\n const initialBudget = scope.budget\n const hasLiveCoordination = scope.view.inFlight > 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(\n activeSeat\n ? seatExecutionProfile(canonicalDriverProfile, activeSeat.stage)\n : canonicalDriverProfile,\n )\n if (activeSeat) {\n assertExecutableAgentProfile(expectedProviderProfile, 'selected seat')\n assertBackendProfileMaterialization(expectedProviderProfile, boundBackend, 'selected seat')\n assertBridgeProfileMaterializes(expectedProviderProfile, boundBackend, 'selected seat')\n }\n const providerDriverProfile = activeSeat\n ? expectedProviderProfile\n : 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 // The harness is asked for a 300 s tool-call timeout so a fenced tool can hold its response\n // longer than the 60 s harness default; a sidecar that applies it says so on each request.\n const attachment = {\n transport: 'http' as const,\n url: coordinationMcpUrl,\n ...(coordinationMcpHeaders ? { headers: coordinationMcpHeaders } : {}),\n metadata: { toolTimeoutMs: COORDINATION_CLIENT_TOOL_TIMEOUT_MS },\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: {\n ...(providerDriverProfile.harness === 'claude-code'\n ? { [CLAUDE_CODE_ONE_HOUR_CACHE]: '1' }\n : {}),\n ...(boundBackend.defaults?.env ?? {}),\n [credentialName]: authorization.slice(7),\n },\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 metadata: { toolTimeoutMs: COORDINATION_CLIENT_TOOL_TIMEOUT_MS },\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 // The check stops a driver that would run on past its budget or deadline. A stopped manager\n // is already ending this turn, and throwing here would discard the result it committed.\n if (effectiveStopSignal?.aborted === true) return\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 // Set when the turn reached its terminal result and that result reported failure. The turn\n // still COMPLETED: its accounting and materialization are captured and its environment is\n // released exactly as a successful turn's is. Only after that does it become a driver failure.\n let turnFailure: HarnessTurnFailedError | undefined\n let terminalArtifact: ExecutorResult<unknown> | undefined\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: the registered one, across every segment of the run.\n authoredProfile:\n registeredProfile === undefined\n ? canonicalDriverProfile\n : agentProfileSchema.parse(registeredProfile),\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 // The owner's release waits for this drive to end its turn, so it reads the turn's receipt.\n const endDrive = retainedOwner ? beginScopeRetainedOwnerDrive(scope) : () => {}\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 // The stream file opens at the first attempt that actually runs an executor, so a resumed\n // owner whose accepted result was restored above leaves it untouched.\n await rootStream?.beginAttempt()\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 driveTurns += 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: it is\n // retained in the run directory as it arrives and never reaches a meter.\n rootStream?.append(event.progress)\n noteDriveProgress(event.progress)\n } else {\n pendingUsage.push(event)\n }\n }\n await meterPending()\n // `resultArtifact()` is typed without the envelope outcome; scope's child settlement reads\n // the same artifact through the same widening.\n const artifact = executor.resultArtifact() as ExecutorResult<unknown>\n terminalArtifact = artifact\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 const reported = executorFailure(artifact)\n if (reported !== undefined)\n turnFailure = new HarnessTurnFailedError(executor.runtime, reported)\n } else {\n const artifact = await run\n terminalArtifact = artifact\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 const reported = executorFailure(artifact)\n if (reported !== undefined)\n turnFailure = new HarnessTurnFailedError(executor.runtime, reported)\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 pool can reject before updating its readout. Preserve the provider diagnosis,\n // but keep failed accounting terminal even when the original failure was transient.\n failure = new RuntimeRunStateError(\n `${errMessage(failure)}; accounting failed: ${errMessage(error)}`,\n { cause: failure },\n )\n }\n }\n try {\n if (!retainedOwner?.preserveEnvironment || retainedOwner.admissions.length === 0) {\n await teardownOnce(completed ? DEFAULT_SUCCESSFUL_SHUTDOWN_MS : 'brutalKill')\n }\n } catch (error) {\n if (!failed) {\n failed = true\n failure = error\n }\n }\n // The provider executor reads the session store at the end of its stream, before any\n // teardown. A later attempt in the same environment reads that store again, longer, so the\n // newest capture wins; a capture never gives way to an attempt that captured nothing.\n const capture = executor.harnessTranscript?.()\n if (\n capture !== undefined &&\n (capture.status !== 'unavailable' ||\n managerTranscript?.status === 'unavailable' ||\n managerTranscript === undefined)\n ) {\n managerTranscript = capture\n }\n if (activeExecutor === executor) activeExecutor = undefined\n endDrive()\n }\n if (failed) throw failure\n if (turnFailure !== undefined) {\n managerArtifact = terminalArtifact\n throw turnFailure\n }\n managerArtifact = terminalArtifact\n }\n drive.resultArtifact = () => managerArtifact\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.deliverReady = (): boolean => activeExecutor !== undefined\n drive.traceSource = () => activeExecutor?.traceSource?.()\n drive.progress = () => {\n const fromExecutor = activeExecutor?.progress?.()\n const own = driveActivity.read()\n const recentActivity = [...(fromExecutor?.recentActivity ?? []), ...own]\n .sort((a, b) => a.at - b.at)\n .slice(-12)\n return {\n ...fromExecutor,\n turns: Math.max(fromExecutor?.turns ?? 0, driveTurns),\n ...(recentActivity.length > 0 ? { recentActivity } : {}),\n }\n }\n // Only the provider backend has a transcript port. Any other backend leaves the method off, so\n // its managers keep settling as `executor-exposes-no-transcript`.\n if (boundBackend.backend === 'provider') {\n drive.harnessTranscript = () => managerTranscript ?? activeExecutor?.harnessTranscript?.()\n drive.harnessTranscriptSettled = () =>\n activeExecutor?.harnessTranscriptSettled?.() ?? Promise.resolve()\n }\n drive.closeSeatSegment = async (reason) => {\n await seatChain?.close(reason)\n }\n return attestRuntimeOwnedScopeOwner(drive, ownerRuntime)\n}\n\n/**\n * What the next drive of a harness-brained manager continues, as far as its backend proves it.\n *\n * A bridge reattaches the harness session by its durable execution id. A retained provider owner\n * continues in the environment it last used while the provider still holds it, and a deliberate\n * later invocation there continues the same harness session. A provider without retained control\n * creates a new environment for every drive and releases the old one. Anything else is unproven.\n */\nasync function reentryContinuity(\n backend: ExecutorConfig,\n scope: Scope<unknown>,\n retainedOwner: boolean,\n): Promise<ReentryContinuity> {\n if (backend.backend === 'bridge') {\n return { session: 'continued', environment: 'same', workspace: 'kept' }\n }\n if (backend.backend !== 'provider' || !retainedOwner) return UNPROVEN_CONTINUITY\n const provider = resolveAgentEnvironmentProvider(backend.provider, backend.registry)\n const capabilities = await provider.capabilities()\n if (capabilities.retainedControl === undefined) {\n return { session: 'new', environment: 'replaced', workspace: 'lost' }\n }\n const environment = await reconcileScopeRetainedOwnerEnvironment(scope)\n if (environment.state === 'live') {\n return {\n session: 'continued',\n environment: 'same',\n environmentId: environment.environmentId,\n workspace: 'kept',\n }\n }\n if (environment.state === 'lost') {\n // The replacement starts from the lost environment's latest checkpoint when there is one.\n const restorePoint = await scopeRetainedOwnerRestorePoint(scope)\n return {\n session: 'new',\n environment: 'replaced',\n previousEnvironmentId: environment.environmentId,\n ...(restorePoint === undefined\n ? { workspace: 'lost' as const }\n : { workspace: 'restored' as const, checkpointAt: restorePoint.takenAt }),\n }\n }\n return UNPROVEN_CONTINUITY\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: construction stays the caller's,\n * lookup stays lazy, and a table backed by a file, a plugin loader, or a plain object all\n * satisfy one interface. */\nexport interface SuperviseRegistryTable<T> {\n resolve(name: string): T | undefined\n /** The names the table holds. The three code-valued tables may omit it, because a caller names\n * their entries from data it already has. The profiles table must list them, because a\n * director can choose only from a menu it can read. */\n names?(): readonly string[]\n}\n\n/**\n * The name→value tables that make the three CODE-valued options expressible as run DATA, and the\n * profiles a director may spawn by name.\n *\n * `deliverable` / `finalizer` / `analysts` 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 *\n * `profiles` is the profiles table: named AgentProfiles that every manager in the tree may spawn\n * with `spawn_worker({ profile: '<name>' })` instead of retyping them. The table is read once, when\n * `supervise` is called: each entry is validated like a root profile and frozen, so every spawn by\n * a name starts from the same bytes. Unless `profileGuidance` or `authorizeSpawn` rewrites the\n * profile, the journal records the entry's digest for the child. Omit the table, or list no names,\n * and nothing about the run changes: `spawn_worker` keeps its object-only `profile`.\n */\nexport interface SuperviseRegistry {\n readonly deliverables?: SuperviseRegistryTable<DeliverableSpec<unknown>>\n readonly finalizers?: SuperviseRegistryTable<SupervisorFinalizer>\n readonly analysts?: SuperviseRegistryTable<AnalystRegistry>\n readonly profiles?: SuperviseRegistryTable<SuperviseProfileEntry> & {\n names(): readonly string[]\n }\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('analysts',\n * 'deliverables', …)` does not compile. */\ninterface SuperviseRegistryTableFor {\n readonly deliverable: 'deliverables'\n readonly finalizer: 'finalizers'\n readonly analysts: 'analysts'\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\n/** Read the profiles table once, before anything is built or spent, and freeze what it returns.\n * Every entry must parse as an AgentProfile (the schema refuses a credential written as a public\n * value), be executable, use an allowed model, and carry its table name as `profile.name`.\n * `assertMountable` applies the spawn path's own mount checks, so an entry that can never be\n * mounted fails here instead of after a director spent a turn on it. A promoted entry's decision\n * must promote, and a treatment arm of its sealed play must name the entry's canonical digest;\n * the seal itself is verified by {@link verifyProfilePromotions}. An empty table is no table. */\nfunction snapshotProfileTable(\n table: SuperviseRegistry['profiles'],\n allowedModels: readonly string[] | undefined,\n assertMountable: ((profile: AgentProfile, context: string) => void) | undefined,\n): ReadonlyMap<string, SuperviseProfileEntry> | undefined {\n if (table === undefined) return undefined\n if (typeof table.names !== 'function' || typeof table.resolve !== 'function') {\n throw new ConfigError(\n 'supervise: opts.registry.profiles must implement resolve(name) and names(): a director ' +\n 'can spawn only the names it is shown',\n )\n }\n const entries = new Map<string, SuperviseProfileEntry>()\n for (const name of table.names()) {\n const at = `opts.registry.profiles ${JSON.stringify(name)}`\n if (typeof name !== 'string' || name.trim().length === 0 || name !== name.trim()) {\n throw new ConfigError(`supervise: ${at} is not a non-empty trimmed name`)\n }\n if (entries.has(name)) throw new ConfigError(`supervise: ${at} is listed twice`)\n const entry = table.resolve(name)\n if (entry === undefined) {\n throw new ConfigError(`supervise: ${at} is listed, but the table resolved no entry under it`)\n }\n const parsed = agentProfileSchema.safeParse(entry.profile)\n if (!parsed.success) {\n throw new ValidationError(\n `supervise: ${at} is not a valid AgentProfile: ${parsed.error.message}`,\n )\n }\n const profile = freezeDetached(parsed.data)\n if (profile.name !== name) {\n throw new ValidationError(\n `supervise: ${at} holds profile.name ${JSON.stringify(profile.name)}; a table entry is ` +\n 'spawned and continued by its name, so the two must be equal',\n )\n }\n assertExecutableAgentProfile(profile, `supervise: ${at}`)\n assertProfileModelsAllowed(profile, allowedModels)\n assertMountable?.(profile, `supervise: ${at} would be refused at mount`)\n const promotion = entry.promotion\n if (promotion !== undefined) {\n if (promotion.decision?.promote !== true) {\n throw new ValidationError(\n `supervise: ${at} cites a PairedPromotionDecision that did not promote; list it ` +\n 'without promotion to run it as exploratory',\n )\n }\n const digest = canonicalAgentProfileDigest(profile)\n const arms = promotion.experiment?.spec?.arms ?? []\n if (!arms.some((arm) => arm.role === 'treatment' && arm.profileDigest === digest)) {\n throw new ValidationError(\n `supervise: ${at} cites sealed play ` +\n `${JSON.stringify(promotion.experiment?.spec?.id)}, but no treatment arm of it names ` +\n `this profile's digest ${digest}`,\n )\n }\n }\n entries.set(\n name,\n Object.freeze({\n profile,\n ...(promotion === undefined ? {} : { promotion: freezeDetached(promotion) }),\n }),\n )\n }\n return entries.size === 0 ? undefined : entries\n}\n\n/** Verify the seal of every promoted profiles-table entry. Eval's seal check is asynchronous, so it\n * runs at the start of the run, before the first model call; a broken seal refuses the run. */\nasync function verifyProfilePromotions(\n table: ReadonlyMap<string, SuperviseProfileEntry> | undefined,\n): Promise<void> {\n const promoted = [...(table ?? [])].filter(([, entry]) => entry.promotion !== undefined)\n if (promoted.length === 0) return\n const { verifySealedExperiment } = await import('@tangle-network/agent-eval/experiment')\n for (const [name, entry] of promoted) {\n if (!(await verifySealedExperiment(entry.promotion!.experiment))) {\n throw new ValidationError(\n `supervise: opts.registry.profiles ${JSON.stringify(name)} cites a sealed play whose ` +\n 'digest does not match its spec',\n )\n }\n }\n}\n\nexport interface SuperviseOptions {\n /** Whole-run persistence and ownership. SQL contexts are acquired before replay and compute. */\n readonly runContext?: RunContext\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 /** Resolve an authored subscription stage to one eligible seat and a backend pinned to its\n * credential reference. The callback may report stage exhaustion with `resumeAt`; Runtime\n * advances the authored chain and never writes credentials into its record. */\n readonly selectSeat?: SelectSeat\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`, or `null` to omit this child's assignment check and continuation.\n * Null does not turn completion into acceptance or erase existing backend/descendant verdicts.\n * An unchecked child must declare compatible tools: disable inherited spawn rights and author its\n * coordination grants without `submit_result` or `read_continuation`. Explicit incompatible\n * grants remain refused; the authorized profile is never rewritten after this callback. */\n readonly resolveDeliverable?: (\n input: DeliverableResolutionInput,\n ) => DeliverableSpec<unknown> | null | 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 /** Reconstruct executors for interrupted children on resume, for a run that owns its worker\n * factory (`makeWorkerAgent`/`makeLeafAgent`). Backend-derived recursive managers register one\n * automatically; a caller-owned factory cannot be, so a leaf whose execution can RE-ATTACH\n * across a process boundary (a sandbox session, a CLI bridge session — an executor that\n * journals its admission through the retained seam) needs this for a resume to recover the\n * in-flight child instead of refusing its key `in-doubt`. The factory receives the\n * reconstructed spec and the child's journaled context, including its prior admissions. */\n readonly recoverExecutor?: ExecutorFactory<unknown>\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 /** OPT-IN standing guidance from the profile knowledge base\n * (`@tangle-network/agent-interface/profile-kb`). `'profile-kb'` composes harness guidance,\n * then model guidance, then the profile's own text into the root profile and into every\n * profile a manager spawns, before identity is fixed, so receipts bind the prompt that ran.\n * Omit to run profiles exactly as authored: Runtime selects no standing guidance by itself. */\n readonly profileGuidance?: 'profile-kb'\n /** Whether a spawned profile that declares no Runtime coordination tool receives its manager's\n * coordination grants (`spawn_worker`, `observe_agent`, and the rest, plus `submit_result` so it\n * can still deliver work it does itself), so every child can lead children of its own. Default\n * `true`. A child whose author wrote any coordination entry, true or false, keeps what was\n * written (a `false` entry is dropped once it has kept the child a leaf). A child this run\n * cannot drive as a manager (no driver for its harness, or no `router` for a harness-less one)\n * stays a leaf, and so does every child of a run with no completion check (`deliverable` or\n * `resolveDeliverable`), since a manager delivers its own work only through `submit_result`.\n * `false` runs every authored profile exactly as written. Applies to backend-derived workers;\n * a caller-owned `makeWorkerAgent` decides its own children. */\n readonly inheritSpawnRights?: boolean\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 an EXTERNAL-harness manager with a completion check is sent back when its turn ends with\n * the check unmet: the deadline, `maxBarren`, and the continuation note's profile and switches.\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. By\n * 2026-09-24, 650 recorded inputs had chosen seven different re-prompt counts, and the note the\n * director heard held no line of the check's verdict.\n *\n * A continuation is the retry path, not a second loop: same scope, same coordination server,\n * same live children, and the same budget, deadline, and abort bounds. There is no count: the\n * loop ends when the check passes, at this deadline, on the budget, after `maxBarren` turns in\n * a row without progress, or on cancellation. A turn that ends, a blocked tool, and a lost\n * stream are segment boundaries, never the end of the run. Runtime writes the note from the check's verdict (`./continuation.ts`); the\n * profile owns its words, and `append` may add a section but never replace one.\n *\n * Required with `deliverable` (or `resolveDeliverable`) for an external manager, and applied to\n * every external manager with a completion check in the tree. Refused for a router-brained\n * manager, which runs its turn loop in process.\n */\n readonly continuation?: ContinuationPolicy\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 * How long settlement keeps retrying a child teardown the executor has not confirmed, with\n * exponential backoff, before naming the child in `teardownUnconfirmed` with the provider\n * environment ids a sweeper deletes. `0` makes one attempt only. Default: 300000 (5 minutes).\n * See `SupervisorOpts.teardownConfirmMs`.\n */\n readonly teardownConfirmMs?: number\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 and close\n * each released child's cursor slot with a terminal record marked `retainedExecution:\n * 'released'`, or `'keep'` them for a later call that resumes this run. Default: `'keep'` with\n * `runDir` (re-running the same `runDir` and `runId` resumes), `'release'` without it (nothing\n * can resume an in-memory 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, worker-slot\n * queue, 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 /** The root's default slice for a child whose manager names no `budget`. Defaults to a quarter\n * of the part of the pool children may reserve (the pool less any owner share). A nested\n * manager always divides its own slice that way; `spawn_worker`'s `budget` overrides per spawn. */\n readonly perWorker?: Budget\n /** Opt-in owner share: every manager, the root included, keeps this fraction of its own slice\n * free of its children's reservations, so its own turns keep budget. Default slices shrink to fit\n * beside it. Default: off. */\n readonly reservationPolicy?: RecursiveReservationPolicy\n /** What a child's own time box (a `spawn_worker` `budget.deadlineMs`) does. Default: a check-in;\n * the child is told to save its state and submit what it has, and is stopped only once it then\n * makes no progress for 30 min. `false` stops it at the time box. The run's own deadline always\n * stops every node. See `deadline.ts` `DeadlineCheckIn`. */\n readonly deadlineCheckIn?: DeadlineCheckIn\n /** Bound on concurrently WORKING agents across the whole recursive tree: a number, or one\n * `createWorkerSlots` allocator that several runs in this process share. A spawn past it keeps\n * its budget slice and waits in a queue (deepest first) instead of being refused, and a manager\n * lends its slot to its first running child, so nested waits cannot deadlock. The root holds no\n * slot. Omit/`<= 0` = no bound (the conserved pool stays the only bound). */\n readonly workerSlots?: number | WorkerSlots\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 receives in its next wake 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 (in its next wake)\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 /** How Runtime wakes a manager that ended its turn with work open: the heartbeat, the debounce\n * that coalesces events into one wake, and the deadline warning. Omit = the defaults in\n * `./wake` (15 min, 2 s, 15 min). */\n readonly wake?: ManagerWakePolicy\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 /** Advanced test seam: opt into resume-first when the durable stores are caller-supplied\n * (`journal` + `blobs` / `runContext`) instead of derived from `runDir`. The normal durable path\n * is `runDir` or a `runContext` (see `docs/durability.md`). Exactly what the file\n * context sets automatically: load the prior tree for `runId` before starting fresh, refuse a\n * reused id without it. Ignored when `runDir` is also set — the file context owns the flag. */\n readonly resume?: boolean\n /**\n * The segment this entry runs the root in. A run keeps one id for its whole life: a turn that\n * ends, a lost stream and a dead supervisor are boundaries between entries, and a resume may move\n * the root to another model, provider, reasoning effort or harness, or onto another stack, as a\n * new segment of the same run. `profile` stays the root profile the run recorded, so its identity,\n * coordination owner and settled children resume unchanged; the root executes that profile with\n * `model.provider`, `model.default`, `model.reasoningEffort` and `harness` replaced where given. `stack` names the\n * package versions the caller runs this entry under, its Runtime among them; Runtime records it\n * and never reads it. When the segment differs from the one the run last ran, the journal gains\n * one `root-segment` record with the time and `reason`. A different task, or any other profile\n * change, is still a resume identity mismatch: that is a new run. A fresh run records its first\n * segment and refuses a model or harness change: a new run takes them from its profile.\n *\n * A harness change starts a new native session: a session of one harness cannot continue in\n * another. The root re-enters with its objective and the run's state, in a workspace restored\n * from its latest checkpoint when the provider holds one.\n */\n readonly segment?: {\n readonly provider?: string\n readonly model?: string\n readonly reasoningEffort?: ReasoningEffort\n readonly harness?: AgentProfile['harness']\n readonly stack?: Readonly<Record<string, string>>\n readonly reason: string\n }\n /** Durable steer directory when it differs from the run-control directory. */\n readonly steerDir?: 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 /**\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 * A record may declare the plateau rule as data, `{ plateau: { window, minDelta } }`, so no\n * product module builds it.\n */\n readonly stopRule?: StopRule | { readonly plateau: PlateauOptions }\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 /** Recursion ceiling for the tree (root = 0). The conserved pool is what bounds depth, since each\n * level's slice comes out of the level above; this only stops a runaway recursion. Omit =\n * `DEFAULT_MAX_DEPTH` (16). */\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' | 'namespace'>\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 'selectSeat',\n 'blobs',\n 'budget',\n 'childSettleGraceMs',\n 'teardownConfirmMs',\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 'inheritSpawnRights',\n 'journal',\n 'makeLeafAgent',\n 'makeWorkerAgent',\n 'escalateQuestion',\n 'maxDepth',\n 'maxTurns',\n 'now',\n 'onCoordinationEvent',\n 'onDriverAttempt',\n 'onProgressStop',\n 'otel',\n 'peerMail',\n 'perWorker',\n 'reservationPolicy',\n 'deadlineCheckIn',\n 'profileGuidance',\n 'profileSecurity',\n 'registry',\n 'resolveDeliverable',\n 'resolveDriveHarness',\n 'resolveSpawnProfile',\n 'resolveSupervisorTools',\n 'rootDriverFromBackend',\n 'rootHandle',\n 'router',\n 'runDir',\n 'resume',\n 'segment',\n 'runContext',\n 'runId',\n 'signal',\n 'stallAfterMs',\n 'wake',\n 'steerDir',\n 'stopRule',\n 'watchWorkers',\n 'continuation',\n 'workerRetry',\n 'onWorkerRetry',\n 'workerSlots',\n 'recoverExecutor',\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 if (deliverable.checkState !== undefined && typeof deliverable.checkState !== 'function') {\n throw new ValidationError(`${context}: deliverable.checkState must be a function`)\n }\n if (\n deliverable.feedback !== undefined &&\n deliverable.feedback !== 'verbatim' &&\n deliverable.feedback !== 'pass-only'\n ) {\n throw new ValidationError(`${context}: deliverable.feedback must be 'verbatim' or 'pass-only'`)\n }\n return Object.freeze({\n ...detachedSnapshot(\n {\n describe: deliverable.describe,\n ...(deliverable.feedback === undefined ? {} : { feedback: deliverable.feedback }),\n ...(deliverable.sealed === undefined ? {} : { sealed: deliverable.sealed === true }),\n },\n `${context} configuration`,\n ),\n check: deliverable.check,\n ...(deliverable.checkState === undefined ? {} : { checkState: deliverable.checkState }),\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 the retired `onUnmetContract`: added with the re-prompt path in 0.186.0,\n * accepted by the option-key check, forwarded by `supervisorAgent`, read by the retry loop, and\n * never destructured here. Every `supervisePursuit` run that passed the callback failed at\n * construction on 0.186.0, 0.187.1 and 0.188.0, and the only working configuration was the number\n * 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 'onWorkerRetry',\n 'recoverExecutor',\n 'resolveDeliverable',\n 'resolveDriveHarness',\n 'resolveSpawnProfile',\n 'selectSeat',\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 selectSeat,\n coordination,\n driverBackend,\n deliverable,\n resolveDeliverable,\n router,\n compaction,\n watchWorkers,\n analysts,\n makeWorkerAgent,\n makeLeafAgent,\n recoverExecutor,\n resume,\n resolveSpawnProfile,\n blobs,\n journal,\n runContext,\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 continuation,\n workerRetry,\n onWorkerRetry,\n finalizer,\n now,\n signal,\n rootHandle,\n workerSlots,\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 // The policy is decision data except its two functions, which are captured by reference.\n const capturedContinuation =\n continuation === undefined\n ? undefined\n : (() => {\n const { runPanel, append, ...policy } = continuation\n return Object.freeze({\n ...detachedSnapshot(policy, 'supervise continuation'),\n ...(runPanel === undefined ? {} : { runPanel }),\n ...(append === undefined ? {} : { append }),\n })\n })()\n\n return Object.freeze({\n ...capturedData,\n ...(capturedCoordination === undefined ? {} : { coordination: capturedCoordination }),\n ...(capturedBackend === undefined ? {} : { backend: capturedBackend }),\n ...(selectSeat === undefined ? {} : { selectSeat }),\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 ...(recoverExecutor === undefined ? {} : { recoverExecutor }),\n ...(resolveSpawnProfile === undefined ? {} : { resolveSpawnProfile }),\n ...(blobs === undefined ? {} : { blobs }),\n ...(journal === undefined ? {} : { journal }),\n ...(resume === undefined ? {} : { resume }),\n ...(runContext === undefined ? {} : { runContext }),\n // A number is decision data; a shared allocator is a live collaborator other runs also hold.\n ...(workerSlots === undefined ? {} : { workerSlots }),\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 ...(capturedContinuation === undefined ? {} : { continuation: capturedContinuation }),\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 ...(request.operator === undefined ? {} : { operator: request.operator }),\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\n .map((node) =>\n node.environments?.length\n ? `${node.id} (${node.environments.map((environment) => `${environment.provider}:${environment.environmentId}`).join(', ')})`\n : node.id,\n )\n .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\n/** The slice a child gets when its manager names none: a quarter of the part of the manager's\n * budget its children may reserve, so four default children fill that part and the manager's\n * own share stays free for its turns. Each nested manager divides its own slice the same way. */\nfunction defaultPerWorker(budget: Budget, ownerShare: number): Budget {\n const share = (1 - ownerShare) / 4\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 * share) },\n ]),\n ),\n }),\n maxIterations: Math.max(1, Math.floor(budget.maxIterations * share)),\n maxTokens: Math.max(1, Math.floor(budget.maxTokens * share)),\n ...(budget.maxUsd !== undefined ? { maxUsd: budget.maxUsd * share } : {}),\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 superviseWithContext(profile, task, opts)\n}\n\n/** A stop rule as a function, or the declared plateau form a record carries as data. */\nfunction stopRuleOf(rule: NonNullable<SuperviseOptions['stopRule']>): StopRule {\n if (typeof rule === 'function') return rule\n if (typeof rule === 'object' && rule !== null && 'plateau' in rule) return plateau(rule.plateau)\n throw new ValidationError(\n 'supervise: stopRule must be a StopRule or { plateau: { window, minDelta } }',\n )\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 superviseWithContext(profile, task, runtimeOptions, brain)\n}\n\n/**\n * The composer `profileGuidance` selects, or `undefined` when no guidance is selected. The result\n * is re-validated as an AgentProfile, and a composition that breaks the schema is refused as a\n * ValidationError. `supervise` applies it to the root and to authored spawns; `runGraph` applies\n * it to pinned node profiles.\n */\nexport function profileGuidanceComposer(\n guidance: SuperviseOptions['profileGuidance'],\n): ((profile: AgentProfile) => AgentProfile) | undefined {\n if (guidance === undefined) return undefined\n if (guidance !== 'profile-kb') {\n throw new ValidationError(\n `supervise: profileGuidance must be 'profile-kb' when set, got ${JSON.stringify(guidance)}`,\n )\n }\n return (profile) => {\n const composed = agentProfileSchema.safeParse(withProfileKb(profile))\n if (!composed.success) {\n throw new ValidationError(\n `supervise: profile-kb guidance produced an invalid AgentProfile: ${composed.error.message}`,\n )\n }\n return composed.data\n }\n}\n\n/**\n * The exact root profile `supervise` executes: `profile` parsed as an AgentProfile, with the\n * selected `profileGuidance` composed. The root's journaled `identity.profileDigest` is this\n * value's digest, so a reader that must match a recorded root derives it here, not by hand.\n */\nexport function superviseRootProfile(\n profile: SupervisorProfile,\n profileGuidance: SuperviseOptions['profileGuidance'],\n): AgentProfile {\n const parsedProfile = agentProfileSchema.safeParse(profile)\n if (!parsedProfile.success) {\n throw new ValidationError(`supervise: invalid AgentProfile: ${parsedProfile.error.message}`)\n }\n const compose = profileGuidanceComposer(profileGuidance)\n return freezeDetachedProfile(compose ? compose(parsedProfile.data) : parsedProfile.data)\n}\n\n/** What a root profile runs on, as a `root-segment` record names it. */\nfunction rootSegmentOf(profile: AgentProfile): RootSegment {\n return {\n ...(profile.model?.provider === undefined ? {} : { provider: profile.model.provider }),\n ...(profile.model?.default === undefined ? {} : { model: profile.model.default }),\n ...(profile.model?.reasoningEffort === undefined\n ? {}\n : { reasoningEffort: profile.model.reasoningEffort }),\n ...(profile.harness === undefined ? {} : { harness: profile.harness }),\n }\n}\n\n/** Refuse a segment that names nothing usable before any compute. */\nfunction admitSegment(segment: NonNullable<SuperviseOptions['segment']>): void {\n if (typeof segment !== 'object' || segment === null) {\n throw new ValidationError('supervise: segment must be an object')\n }\n for (const key of ['provider', 'model', 'harness'] as const) {\n const value = segment[key]\n if (value !== undefined && (typeof value !== 'string' || value.trim().length === 0)) {\n throw new ValidationError(`supervise: segment.${key} must name a ${key}`)\n }\n }\n if (typeof segment.reason !== 'string' || segment.reason.trim().length === 0) {\n throw new ValidationError('supervise: segment.reason must say why the segment starts')\n }\n if (segment.stack !== undefined) {\n if (\n typeof segment.stack !== 'object' ||\n segment.stack === null ||\n Array.isArray(segment.stack)\n ) {\n throw new ValidationError('supervise: segment.stack must map package names to versions')\n }\n for (const [name, version] of Object.entries(segment.stack)) {\n if (typeof version !== 'string' || version.length === 0) {\n throw new ValidationError(`supervise: segment.stack.${name} must be a version string`)\n }\n }\n }\n}\n\n/** The recorded root profile with only its provider, model, reasoning effort and harness replaced\n * where the segment names them. */\nfunction withRootSegment(\n profile: AgentProfile,\n segment: NonNullable<SuperviseOptions['segment']>,\n): AgentProfile {\n if (\n segment.provider === undefined &&\n segment.model === undefined &&\n segment.reasoningEffort === undefined &&\n segment.harness === undefined\n ) {\n return profile\n }\n return superviseRootProfile(\n {\n ...profile,\n ...(segment.harness === undefined ? {} : { harness: segment.harness }),\n model: {\n ...profile.model,\n ...(segment.provider === undefined ? {} : { provider: segment.provider }),\n ...(segment.model === undefined ? {} : { default: segment.model }),\n ...(segment.reasoningEffort === undefined\n ? {}\n : { reasoningEffort: segment.reasoningEffort }),\n },\n },\n undefined,\n )\n}\n\nfunction superviseWithContext(\n profile: SupervisorProfile,\n task: unknown,\n opts: SuperviseOptions,\n brain?: ToolLoopChat,\n): ReturnType<typeof superviseInternal> {\n if (opts.runContext?.acquire === undefined) return superviseInternal(profile, task, opts, brain)\n const options = captureSuperviseOptions(opts)\n const capturedProfile = freezeDetached(profile)\n const capturedTask = freezeDetached(task)\n return withRunContext(opts.runContext, options.signal, (runContext, signal) =>\n superviseInternal(\n capturedProfile,\n capturedTask,\n {\n ...options,\n runContext,\n ...(signal === undefined ? {} : { signal }),\n },\n brain,\n ),\n )\n}\n\nfunction superviseInternal(\n profile: SupervisorProfile,\n task: unknown,\n opts: SuperviseOptions,\n testBrain?: ToolLoopChat,\n) {\n const options = captureSuperviseOptions(opts)\n if (options.runContext?.durability === 'sql') {\n if (\n options.runDir !== undefined ||\n (options.journal !== undefined && options.journal !== options.runContext.journal) ||\n (options.blobs !== undefined && options.blobs !== options.runContext.blobs) ||\n (options.runId !== undefined && options.runId !== options.runContext.runId)\n ) {\n throw new ValidationError(\n 'supervise: SQL runContext cannot be mixed with another run identity or persistence path',\n )\n }\n if (\n options.backend?.backend !== 'provider' ||\n options.makeWorkerAgent ||\n options.makeLeafAgent\n ) {\n throw new ValidationError(\n 'supervise: SQL runContext requires backend-derived retained provider workers',\n )\n }\n }\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 composeSpawnProfile = profileGuidanceComposer(options.profileGuidance)\n // The recorded root profile fixes the run's identity; a segment only alters what it executes.\n const registeredProfile = superviseRootProfile(profile, options.profileGuidance)\n if (options.segment !== undefined) admitSegment(options.segment)\n const canonicalProfile =\n options.segment === undefined\n ? registeredProfile\n : withRootSegment(registeredProfile, options.segment)\n assertExecutableAgentProfile(canonicalProfile, 'supervise root')\n if (authoredSeatStages(canonicalProfile) !== undefined && options.selectSeat === undefined) {\n throw new ValidationError('supervise: AgentProfile.seats requires selectSeat before execution')\n }\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 registeredProfile,\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 for (const stage of authoredSeatStages(canonicalProfile) ?? []) {\n assertModelAllowed(stage.model, options.allowedModels)\n }\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 // The spawn path applies these checks to the profile `authorizeSpawn` returns, so they can run\n // early only when no caller-owned authorization or worker seam sits between the entry and mount.\n const profileTable = snapshotProfileTable(\n options.registry?.profiles,\n options.allowedModels,\n options.makeWorkerAgent === undefined && options.authorizeSpawn === undefined\n ? (entry, context) => {\n const security = validateAgentProfileSecurity(\n entry,\n options.profileSecurity ?? DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY,\n )\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(`${context}: ${details}`)\n }\n // A leaf runs on the worker backend, which refuses any profile axis it cannot carry.\n if (\n options.backend !== undefined &&\n options.makeLeafAgent === undefined &&\n declaredRuntimeToolNames(entry).length === 0\n ) {\n assertBackendProfileMaterialization(entry, options.backend, context)\n }\n }\n : undefined,\n )\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.runContext ??\n (options.runDir !== undefined\n ? createFileRunContext(options.runDir, { withDriver: true })\n : createInMemoryRunContext({ withDriver: true }))\n const blobs = options.blobs ?? ctx.blobs\n assertRecursiveReservationPolicy(options.reservationPolicy)\n const ownerShare = options.reservationPolicy?.ownerShare ?? 0\n const perWorker = options.perWorker ?? defaultPerWorker(options.budget, ownerShare)\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 settles with\n // a `budgetViolation` against that smaller reservation, which reads as a budget outcome rather\n // than a 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 ?? ctx.runId ?? 'supervise'\n const runNamespace = ctx.namespace ?? supervisionRunNamespace(options.runDir, runId)\n const log = ctx.coordinationLog\n const rootOwnerId = rootCoordinationOwner(rootExecution.identity)\n const rootProviderModels: Array<string | undefined> = []\n // The root's own provider stream is retained only where a run directory can hold it. Nested\n // managers share this harness and are left unretained here; a per-owner file is a later step.\n const rootStreamSink =\n options.runDir === undefined\n ? undefined\n : createRootStreamSink(resolve(options.runDir), options.now ?? Date.now)\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 // Every child that this run can drive as a manager inherits its manager's coordination grants,\n // so depth is the director's choice rather than an author's omission. A profile's own explicit\n // grants win; a child with no driver for its harness stays a leaf rather than failing to start.\n const externalManagersAvailable =\n hasCustomDriveHarness ||\n (managerBackend !== undefined &&\n automaticDriverBackendSupported(managerBackend, options.coordination))\n const canLead = (child: AgentProfile): boolean =>\n isExternalSupervisor(child) ? externalManagersAvailable : options.router !== undefined\n // A manager delivers its own work only through `submit_result`, which exists only under a\n // completion check. Without one, a worker turned manager could not finish work it did itself.\n const childrenCanSubmit = deliverable !== undefined || options.resolveDeliverable !== undefined\n const composeSpawnProfileFor = (\n parent: AgentProfile,\n ): ((profile: AgentProfile) => AgentProfile) | undefined => {\n if (\n options.inheritSpawnRights === false ||\n options.makeWorkerAgent !== undefined ||\n !childrenCanSubmit\n ) {\n return composeSpawnProfile\n }\n return (authored) => {\n const composed = composeSpawnProfile ? composeSpawnProfile(authored) : authored\n // A seat chain is an explicit execution policy. Inheriting manager grants would turn a\n // seat-bearing leaf into a manager and change the authored profile before selection.\n return composed.seats || !canLead(composed)\n ? composed\n : withInheritedSpawnRights(parent, composed)\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 deliverReady: unknown = harness.deliverReady\n if (deliverReady !== undefined && typeof deliverReady !== 'function') {\n throw new ValidationError(\n 'supervise: driveHarness.deliverReady must be a function when provided',\n )\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 context.depth === 0 ? rootStreamSink : undefined,\n options.selectSeat === undefined\n ? undefined\n : {\n select: options.selectSeat,\n journal,\n rootId: runId,\n onSegment: async (nodeId, segment, phase) => {\n await options.hooks?.onEvent?.(\n {\n id: `${nodeId}:seat:${segment.startedAt}:${phase}`,\n runId,\n target: 'agent.seat',\n phase: 'event',\n timestamp: options.now?.() ?? Date.now(),\n parentId: nodeId,\n payload: { nodeId, phase, segment },\n },\n {},\n )\n },\n onPause: async (nodeId, resumeAt, phase) => {\n await options.hooks?.onEvent?.(\n {\n id: `${nodeId}:seat:${phase}:${resumeAt || (options.now?.() ?? Date.now())}`,\n runId,\n target: 'agent.seat',\n phase: 'event',\n timestamp: options.now?.() ?? Date.now(),\n parentId: nodeId,\n payload: { nodeId, phase, ...(resumeAt ? { resumeAt } : {}) },\n },\n {},\n )\n },\n },\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 analystLineage = false,\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 : selectedDeliverable === null\n ? undefined\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 seatManagedLeaf =\n authoredSeatStages(authorized) !== undefined &&\n declaredRuntimeToolNames(authorized).length === 0 &&\n isExternalSupervisor(authorized)\n const usesRuntimeCoordination =\n declaredRuntimeToolNames(authorized).length > 0 || seatManagedLeaf\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 analystLineage ||\n spawnContext.analyst !== undefined ||\n spawnContext.assignmentId.startsWith('analyst:'),\n )\n const nestedPerWorker = defaultPerWorker(spawnContext.budget, ownerShare)\n const authorizeNestedMessage = authorizeDownFor(authorized, depth + 1)\n let acceptedSubmission = false\n let unassessedOutput = false\n const nested = supervisorAgent(authorized, {\n blobs,\n onUnassessedOutput: () => {\n unassessedOutput = true\n },\n ...(spawnResourceRoot === undefined ? {} : { spawnResourceRoot }),\n makeWorkerAgent: childFactory,\n ...(spawnContext.sourceEvidenceRefs\n ? { sourceEvidenceRefs: spawnContext.sourceEvidenceRefs }\n : {}),\n ...(authorizeNestedMessage ? { authorizeDownMessage: authorizeNestedMessage } : {}),\n perWorker: nestedPerWorker,\n ...(ownerShare > 0 ? { preserveOwnerTurns: true } : {}),\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.escalateQuestion ? { escalateQuestion: options.escalateQuestion } : {}),\n ...(!analystLineage &&\n spawnContext.analyst === undefined &&\n !spawnContext.assignmentId.startsWith('analyst:') &&\n options.analyzeOnSettle\n ? { analyzeOnSettle: options.analyzeOnSettle }\n : {}),\n ...(options.watchWorkers ? { watchWorkers: options.watchWorkers } : {}),\n ...(options.stallAfterMs !== undefined ? { stallAfterMs: options.stallAfterMs } : {}),\n ...(options.wake !== undefined ? { wake: options.wake } : {}),\n ...(options.continuityByProfile\n ? { continuityByProfile: options.continuityByProfile }\n : {}),\n ...(spawnPreflight ? { preflightSpawn: spawnPreflight } : {}),\n ...(options.resolveSpawnProfile\n ? { resolveSpawnProfile: options.resolveSpawnProfile }\n : {}),\n ...(composeSpawnProfileFor(authorized)\n ? { composeSpawnProfile: composeSpawnProfileFor(authorized) }\n : {}),\n ...(profileTable ? { profiles: profileTable } : {}),\n ...(options.peerMail ? { peerMail: options.peerMail } : {}),\n ...(options.stopRule ? { stopRule: stopRuleOf(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 && !seatManagedLeaf ? { deliverable: childDeliverable } : {}),\n ...(childDeliverable && !seatManagedLeaf\n ? {\n onAcceptedSubmission: () => {\n acceptedSubmission = true\n },\n }\n : {}),\n // Every external manager with a check in the tree is sent back under the run's one\n // continuation policy. Its files sit beside the root's, under its own owner id.\n ...(childDeliverable &&\n !seatManagedLeaf &&\n options.continuation &&\n isExternalSupervisor(authorized)\n ? {\n continuation: options.continuation,\n ...(options.runDir === undefined\n ? {}\n : {\n continuationDir: resolve(\n options.runDir,\n CONTINUATIONS_DIR,\n 'managers',\n encodeURIComponent(ownerId),\n ),\n }),\n }\n : {}),\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 owns only its subtree's durable controls. Root-level labels remain\n // the root's even when steering uses a separate directory from cancellation.\n ...(options.runDir === undefined\n ? {}\n : {\n controlDir: resolve(options.runDir),\n abortRun: cancelDurableRun,\n }),\n ...(options.steerDir === undefined ? {} : { steerDir: resolve(options.steerDir) }),\n ...(options.runDir === undefined && options.steerDir === undefined\n ? {}\n : { controlScope: 'subtree' as const }),\n })\n return driverChild(\n authorized,\n nested,\n journal,\n childExecution.ref,\n () => acceptedSubmission,\n recoveryFactories.get(childFactory),\n () => unassessedOutput,\n seatManagedLeaf ? childDeliverable : undefined,\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 // The root driver loop reports what it did once it ends; the settle record carries it.\n let rootContinuation: DriverContinuationRecord | undefined\n const start = async () => {\n if (ctx.durability === 'sql') {\n if (\n options.backend?.backend !== 'provider' ||\n options.backend.steering ||\n options.driveHarness ||\n options.resolveDriveHarness ||\n options.driverBackend\n ) {\n throw new ValidationError(\n 'supervise: SQL runContext requires a local coordinator and non-steering retained provider workers',\n )\n }\n const provider = resolveAgentEnvironmentProvider(\n options.backend.provider,\n options.backend.registry,\n )\n const capabilities = await provider.capabilities()\n if (\n !capabilities.retainedControl ||\n !capabilities.streaming.turnIdempotency ||\n !capabilities.streaming.replay ||\n !provider.get\n ) {\n throw new ValidationError(\n 'supervise: SQL runContext requires retainedControl, replay, turn idempotency, and provider.get',\n )\n }\n }\n await verifyProfilePromotions(profileTable)\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 ...(ownerShare > 0 ? { preserveOwnerTurns: true } : {}),\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 onDriverLoopSettled(record: DriverContinuationRecord) {\n rootContinuation = record\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.length > 0)\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 ...(composeSpawnProfileFor(canonicalProfile)\n ? { composeSpawnProfile: composeSpawnProfileFor(canonicalProfile) }\n : {}),\n ...(profileTable ? { profiles: profileTable } : {}),\n ...(spawnResourceRoot === undefined ? {} : { spawnResourceRoot }),\n ...(options.peerMail ? { peerMail: options.peerMail } : {}),\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.escalateQuestion ? { escalateQuestion: options.escalateQuestion } : {}),\n ...(options.analyzeOnSettle ? { analyzeOnSettle: options.analyzeOnSettle } : {}),\n ...(options.watchWorkers ? { watchWorkers: options.watchWorkers } : {}),\n ...(options.stallAfterMs !== undefined ? { stallAfterMs: options.stallAfterMs } : {}),\n ...(options.wake !== undefined ? { wake: options.wake } : {}),\n ...(options.continuityByProfile ? { continuityByProfile: options.continuityByProfile } : {}),\n ...(options.stopRule ? { stopRule: stopRuleOf(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 ...(deliverable && options.continuation && isExternalSupervisor(canonicalProfile)\n ? {\n continuation: options.continuation,\n ...(options.runDir === undefined\n ? {}\n : {\n continuationDir: resolve(options.runDir, CONTINUATIONS_DIR),\n rootStreamPath: resolve(options.runDir, ROOT_STREAM_FILE),\n }),\n }\n : {}),\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 ...(options.steerDir === undefined ? {} : { steerDir: resolve(options.steerDir) }),\n // A root executing another segment of its registered profile attributes its materialization to the registered one.\n ...(canonicalProfile === registeredProfile ? {} : { registeredProfile }),\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\n ? createSupervisorSpanRecorder({ runId, namespace: runNamespace, ...options.otel, now })\n : 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 // A caller-supplied recovery factory wins: it owns the worker seam (makeWorkerAgent /\n // makeLeafAgent), so only it can reconstruct an interrupted child's executor. The derived\n // registration below serves backend-built recursive managers, which no caller can name.\n ...((options.recoverExecutor ?? recoveryFactories.get(workerFactory))\n ? { recoverExecutor: options.recoverExecutor ?? recoveryFactories.get(workerFactory) }\n : {}),\n rootIdentity: rootExecution.identity,\n ...(options.segment === undefined\n ? {}\n : {\n rootSegment: {\n registered: rootSegmentOf(registeredProfile),\n current: {\n ...rootSegmentOf(canonicalProfile),\n ...(options.segment.stack === undefined\n ? {}\n : { stack: { ...options.segment.stack } }),\n },\n reason: options.segment.reason,\n },\n }),\n ...(rootOwnerRuntime === undefined\n ? {}\n : {\n rootMaterialization: {\n runtime: rootOwnerRuntime,\n declaration: 'deferred' as const,\n // Every segment's materialization is attributed to the registered root profile.\n authoredProfile: registeredProfile,\n },\n }),\n maxDepth: options.maxDepth ?? DEFAULT_MAX_DEPTH,\n ...(options.childSettleGraceMs !== undefined\n ? { childSettleGraceMs: options.childSettleGraceMs }\n : {}),\n ...(options.teardownConfirmMs !== undefined\n ? { teardownConfirmMs: options.teardownConfirmMs }\n : {}),\n ...(options.retainedAtSettlement !== undefined\n ? { retainedAtSettlement: options.retainedAtSettlement }\n : {}),\n ownerWorkspaceRetention:\n managerBackend?.backend === 'provider' && managerBackend.workspaceRetention !== undefined,\n ...(options.workerSlots !== undefined ? { workerSlots: options.workerSlots } : {}),\n ...(options.reservationPolicy ? { reservationPolicy: options.reservationPolicy } : {}),\n ...(options.deadlineCheckIn === undefined\n ? {}\n : { deadlineCheckIn: options.deadlineCheckIn }),\n ...(ctx.resume === true || (options.runDir === undefined && options.resume === true)\n ? { resume: true }\n : {}),\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 let rootStream: RootStreamReceipt | undefined\n try {\n result = await run\n } finally {\n // Closed on BOTH exits. A run that throws releases the file here, and whoever records\n // the failure recomputes the same receipt from the bytes on disk.\n try {\n rootStream = await rootStreamSink?.close()\n } finally {\n cancellation?.close()\n cancellation?.check()\n }\n }\n recordRunCancellationOutcome(options.runDir, result, now)\n // A nested manager's session rides its settle record (#1359). The root has no settle\n // record, so its session had no receipt anywhere: 312 of 312 Discovery roots of\n // 2026-09-23/24 settled without one, and 27 of the 57 harness subagent calls seen in those\n // runs were the roots' own (#1264). The result carries it, persisted the same way.\n const rootHarnessTranscript =\n rootDriveHarness === undefined\n ? undefined\n : await persistHarnessTranscript(readHarnessTranscript(rootDriveHarness), blobs)\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 ...(rootStream === undefined ? {} : { rootStream }),\n ...(rootHarnessTranscript === undefined ? {} : { rootHarnessTranscript }),\n ...(rootContinuation === undefined ? {} : { continuation: rootContinuation }),\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":";;;;;;;;;;;;;;;;;;;;;;;;AAIA,MAAa,sCAAsC;;;;;;ACoCnD,SAAS,cACP,QACA,QACA;CAiBA,OAAO;EACL,SAAS;EACT,IAAI;EACJ,OAAO;GAAE,MAAM;GAAQ,SAAS;IAlBhC,sBAAsB;IACtB,gBAAgB;IAChB,cAAc;IACd,kBAAkB;IAClB,mBAAmB;IACnB,iBAAiB;IACjB,sBAAsB;IACtB,4BAA4B;IAC5B,kBAAkB,8CAA8C,OAAO,gBAAgB;IACvF,qBAAqB;IACrB,iBAAiB,uBAAuB,OAAO,sBAAsB,2BAA2B,OAAO,kBAAkB;IACzH,gBAAgB,0CAA0C,OAAO,iBAAiB;IAClF,kBAAkB,oCAAoC,OAAO,iBAAiB;IAC9E,kBAAkB;GAKqB,EAAE;GAAS,MAAM,EAAE,OAAO;EAAE;CACrE;AACF;AAcA,SAAgB,uBAAuB,SAAkC;CACvE,MAAM,YAAY,MAAc,OAA2B,aAAqB;EAC9E,MAAM,WAAW,SAAS;EAC1B,IAAI,CAAC,OAAO,cAAc,QAAQ,KAAK,YAAY,GACjD,MAAM,IAAI,YAAY,gBAAgB,KAAK,iCAAiC;EAE9E,OAAO;CACT;CACA,MAAM,UAAU,IAAI,IAAI,QAAQ,kBAAkB,CAAC,CAAC;CACpD,KAAK,MAAM,UAAU,SAAS;EAC5B,MAAM,SAAS,IAAI,IAAI,MAAM;EAC7B,IAAI,OAAO,WAAW,UAAU,CAAC,CAAC,SAAS,QAAQ,CAAC,CAAC,SAAS,OAAO,QAAQ,GAC3E,MAAM,IAAI,YAAY,iEAAiE;CAE3F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ThW.js","names":["record","fsConstants","coordinationVerbNameSet","isAsyncIterable","profileMaterializationAxes","runtimeSleep","addRetainedSpend"],"sources":["../src/mcp/tools/coordination-request-context.ts","../src/runtime/supervise/coordination-http.ts","../src/runtime/supervise/coordination-preflight.ts","../src/runtime/supervise/single-flight-tools.ts","../src/runtime/supervise/coordination-mcp.ts","../src/runtime/supervise/otel-spans.ts","../src/runtime/supervise/reentry.ts","../src/runtime/supervise/root-stream.ts","../src/runtime/supervise/run-traces.ts","../src/runtime/supervise/worker-control-observer.ts","../src/runtime/supervise/supervisor-agent.ts","../src/runtime/supervise/worker-retry.ts","../src/runtime/supervise/supervise.ts"],"sourcesContent":["/** The tool-call timeout Runtime asks harnesses to give its coordination server. The Tangle\n * profile materializer writes it as `MCP_TOOL_TIMEOUT` (Claude Code) and `tool_timeout_sec`\n * (Codex) when an attachment declares `metadata.toolTimeoutMs`, so a fenced coordination call\n * that holds its response for its whole fence is never cut off at the 60 s harness default. */\nexport const COORDINATION_CLIENT_TOOL_TIMEOUT_MS = 300_000\n","import type { IncomingMessage, ServerResponse } from 'node:http'\nimport { ConfigError } from '../../errors'\nimport type { JsonRpcMessage, JsonRpcResponse } from '../../mcp/protocol'\n\n/** Why the coordination boundary refused a request. The refusal's JSON-RPC error body names it, so\n * an agent reads more than a bare status, and its audit event records it. */\nexport type CoordinationRejectReason =\n | 'method-not-allowed'\n | 'unknown-path'\n | 'wrong-host'\n | 'origin-refused'\n | 'listener-closed'\n | 'scope-stopped'\n | 'credential-refused'\n | 'unsupported-content-type'\n | 'body-too-large'\n | 'malformed-request'\n | 'request-limit'\n | 'body-timeout'\n | 'action-timeout'\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 /** Why a `rejected` request was refused. */\n readonly reason?: CoordinationRejectReason\n}\n\n/** A refusal before any action runs: its HTTP status and the reason the client is told. */\nexport interface CoordinationRejection {\n readonly status: number\n readonly reason: CoordinationRejectReason\n}\n\n/** The JSON-RPC error a refusal carries. MCP clients put a non-2xx body into the error the agent\n * sees, so without it the agent reads only `Error POSTing to endpoint:` and a status at best. The\n * messages are fixed text: never a credential, a request body or an arbitrary error string. */\nfunction rejectionBody(\n reason: CoordinationRejectReason | 'handler-failed',\n limits: ReturnType<typeof coordinationHttpLimits>,\n) {\n const messages: Record<CoordinationRejectReason | 'handler-failed', string> = {\n 'method-not-allowed': 'coordination accepts only POST',\n 'unknown-path': 'no coordination endpoint at this path',\n 'wrong-host': 'this coordination endpoint does not serve the requested host',\n 'origin-refused': 'coordination refuses requests from this browser origin',\n 'listener-closed': 'this coordination endpoint is closed: the manager it served has ended',\n 'scope-stopped': 'the manager this coordination endpoint serves has been stopped',\n 'credential-refused': 'the coordination credential is missing, invalid, expired or revoked',\n 'unsupported-content-type': 'coordination requests must be application/json',\n 'body-too-large': `coordination request bodies are limited to ${limits.maxRequestBytes} bytes`,\n 'malformed-request': 'the request is not one JSON-RPC 2.0 message',\n 'request-limit': `coordination admits ${limits.maxConcurrentRequests} concurrent requests and ${limits.requestsPerMinute} a minute; retry shortly`,\n 'body-timeout': `the request body did not arrive within ${limits.requestTimeoutMs} ms`,\n 'action-timeout': `the action did not finish within ${limits.requestTimeoutMs} ms and may still complete; read its outcome before repeating it`,\n 'handler-failed': 'the coordination handler failed',\n }\n return {\n jsonrpc: '2.0',\n id: null,\n error: { code: -32000, message: messages[reason], data: { reason } },\n }\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 // Twice the response fence (coordinationResponseFenceMs), so a held answer leaves well before\n // the server's own timeout.\n const requestTimeoutMs = positive('requestTimeoutMs', options.requestTimeoutMs, 90_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): CoordinationRejection | 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 reason?: CoordinationRejectReason,\n ) => {\n await input.options.onAudit?.({\n ...input.identity,\n outcome,\n status,\n ...(action ? { action } : {}),\n ...(reason ? { reason } : {}),\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, reason }: CoordinationRejection) => {\n respond(status, rejectionBody(reason, limits))\n void audit('rejected', status, action, reason).catch(() => undefined)\n req.resume()\n }\n req.on('error', () => reject({ status: 400, reason: 'malformed-request' }))\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({ status: 405, reason: 'method-not-allowed' })\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({ status: 403, reason: 'origin-refused' })\n return\n }\n if (\n req.headers['content-type']?.split(';', 1)[0]?.trim().toLowerCase() !== 'application/json'\n ) {\n reject({ status: 415, reason: 'unsupported-content-type' })\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({ status: 413, reason: 'body-too-large' })\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({ status: 429, reason: 'request-limit' })\n return\n }\n controlActive++\n } else {\n requests++\n active++\n }\n admitted = true\n timer = setTimeout(() => {\n timedOut = true\n reject(\n executing\n ? { status: 504, reason: 'action-timeout' }\n : { status: 408, reason: 'body-timeout' },\n )\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({ status: 413, reason: 'body-too-large' })\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({ status: 400, reason: 'malformed-request' })\n return\n }\n message = value as JsonRpcMessage\n } catch {\n reject({ status: 400, reason: 'malformed-request' })\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({ status: 429, reason: 'request-limit' })\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, rejectionBody('handler-failed', limits))\n } finally {\n executing = false\n release()\n }\n })()\n })\n }\n}\n","import { ConfigError } from '../../errors'\nimport { PROTOCOL_VERSION } from '../../mcp/tool-server'\nimport { linkAbort, runAbortable } from './abortable'\n\nconst MAX_RESPONSE_BYTES = 1024 * 1024\n\nclass CoordinationPreflightError extends ConfigError {\n constructor(reason: string) {\n super(`coordination public endpoint preflight failed: ${reason}`)\n }\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Check the operator's route before it becomes a provider attachment. This does not prove cloud egress. */\nexport async function preflightPublicCoordination(input: {\n url: string\n headers: Readonly<Record<string, string>>\n signal: AbortSignal\n requestTimeoutMs: number\n toolNames: readonly string[]\n}): Promise<void> {\n const deadline = new AbortController()\n const linked = linkAbort(input.signal, deadline.signal)\n const timer = setTimeout(() => deadline.abort(), Math.min(input.requestTimeoutMs, 10_000))\n timer.unref()\n const rpc = async (method: string, params?: unknown): Promise<Record<string, unknown>> => {\n const response = await fetch(input.url, {\n method: 'POST',\n headers: { ...input.headers, 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify({ jsonrpc: '2.0', id: method, method, ...(params ? { params } : {}) }),\n redirect: 'manual',\n signal: linked.signal,\n })\n if (response.status !== 200) {\n void response.body?.cancel().catch(() => undefined)\n throw new CoordinationPreflightError(`HTTP ${response.status}`)\n }\n const reader = response.body?.getReader()\n if (!reader) throw new CoordinationPreflightError('invalid MCP response')\n let size = 0\n const chunks: Uint8Array[] = []\n try {\n for (;;) {\n const part = await reader.read()\n if (part.done) break\n size += part.value.byteLength\n if (size > MAX_RESPONSE_BYTES) {\n void reader.cancel().catch(() => undefined)\n throw new CoordinationPreflightError('response too large')\n }\n chunks.push(part.value)\n }\n } finally {\n reader.releaseLock()\n }\n let body: unknown\n try {\n body = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)))\n } catch {\n throw new CoordinationPreflightError('invalid MCP response')\n }\n if (\n !record(body) ||\n body.jsonrpc !== '2.0' ||\n body.id !== method ||\n body.error ||\n !record(body.result)\n ) {\n throw new CoordinationPreflightError('invalid MCP response')\n }\n return body.result\n }\n try {\n await runAbortable(\n async () => {\n const initialized = await rpc('initialize', {\n protocolVersion: PROTOCOL_VERSION,\n capabilities: {},\n clientInfo: { name: 'agent-runtime-coordination-preflight', version: '1' },\n })\n if (\n initialized.protocolVersion !== PROTOCOL_VERSION ||\n !record(initialized.serverInfo) ||\n initialized.serverInfo.name !== 'coordination' ||\n !record(initialized.capabilities) ||\n !record(initialized.capabilities.tools)\n )\n throw new CoordinationPreflightError('invalid MCP initialization')\n const listing = await rpc('tools/list')\n if (\n !Array.isArray(listing.tools) ||\n listing.tools.some((tool) => !record(tool) || typeof tool.name !== 'string')\n ) {\n throw new CoordinationPreflightError('invalid MCP tool list')\n }\n const names = listing.tools.map((tool) => tool.name).sort()\n if (JSON.stringify(names) !== JSON.stringify([...input.toolNames].sort())) {\n throw new CoordinationPreflightError('coordination tool grants differ')\n }\n },\n linked.signal,\n 'coordination public endpoint preflight cancelled',\n )\n } catch (error) {\n // Neither a response body nor an upstream exception is safe to retain: both can echo credentials.\n if (input.signal.aborted) throw new CoordinationPreflightError('cancelled')\n if (deadline.signal.aborted) throw new CoordinationPreflightError('timed out')\n if (error instanceof CoordinationPreflightError) throw error\n throw new CoordinationPreflightError('transport unavailable')\n } finally {\n clearTimeout(timer)\n linked.release()\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 settled. The handler is not invoked again.\n * 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\n * call returns a receipt. The handler keeps running, and its outcome is published to the\n * manager's inbox, where its next wake delivers it. Nothing has to call again to collect it.\n *\n * An invocation's identity ends when its handler settles. The next identical call is a fresh run,\n * 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 */\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 /** Set when a call's fence elapsed first: the outcome then goes to the inbox under it. */\n receipt: string | undefined\n}\n\n/** The answer for a call whose handler is still running when its fence elapses. */\nexport interface ToolCallReceipt {\n readonly running: true\n readonly receipt: string\n readonly tool: string\n readonly elapsedMs: number\n readonly instruction: string\n}\n\n/** Where a receipted call's outcome goes: the manager's inbox (`CoordinationTools`). */\nexport interface ToolReceiptSink {\n openToolReceipt(tool: string): string\n settleToolReceipt(\n receipt: string,\n outcome:\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly error: unknown },\n ): Promise<void>\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: {\n readonly fenceMs: number\n readonly receipts: ToolReceiptSink\n readonly now?: () => number\n },\n): SingleFlightTools {\n const { fenceMs, receipts } = 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-entries 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, key: string): 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 receipt: undefined,\n }\n void invocation.settled.then(async (outcome) => {\n if (invocations.get(key) === invocation) invocations.delete(key)\n if (invocation.receipt !== undefined) {\n await receipts.settleToolReceipt(invocation.receipt, outcome).catch((error: unknown) => {\n console.error('Runtime could not publish a receipted tool outcome', {\n tool: tool.name,\n receipt: invocation.receipt,\n error: error instanceof Error ? error.message : String(error),\n })\n })\n }\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, key)\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) {\n invocation.receipt ??= receipts.openToolReceipt(tool.name)\n return toolCallReceipt(tool.name, invocation.receipt, now() - invocation.startedAt)\n }\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 toolCallReceipt(tool: string, receipt: string, elapsedMs: number): ToolCallReceipt {\n return {\n running: true,\n receipt,\n tool,\n elapsedMs,\n instruction:\n `${tool} is still running; nothing failed. Do not call it again: its result arrives with ` +\n `receipt ${receipt} when you are next woken. Continue other work, or end your turn to wait.`,\n }\n}\n","/**\n *\n * Serve the coordination verbs (spawn_worker / observe_agent / steer_agent / submit_result / 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 createCoordinationToolsForManager,\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 SuperviseProfileEntry,\n type WorkerWatchOptions,\n} from '../../mcp/tools/coordination'\nimport type { SpawnResourceReader } from '../../mcp/tools/spawn-resource-paths'\nimport { runAbortable } from './abortable'\nimport {\n type CoordinationHttpOptions,\n coordinationHttpHandler,\n coordinationHttpLimits,\n} from './coordination-http'\nimport { preflightPublicCoordination } from './coordination-preflight'\nimport {\n noteScopeRetainedOwnerCoordination,\n scopeRetainedOwnerResourceReader,\n} from './retained-scope-owner'\nimport { singleFlightTools } from './single-flight-tools'\n\nexport type {\n CoordinationHttpAudit,\n CoordinationHttpOptions,\n CoordinationRejectReason,\n} 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 /** The current credential's expiry under `authentication.ttlMs`; undefined when it lives as long\n * as the scope. */\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 finishAnalysis: CoordinationTools['finishAnalysis']\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 /** Explicit finite lifetime. Omission binds the credential to the live scope: it is refused once\n * the scope stops or the listener closes. A child's own time box does not stop its scope. */\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 /** Listener lifetime: aborts on close, failed setup, manager cancellation, or deadline. */\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 (\n ttl !== undefined &&\n (!Number.isSafeInteger(ttl) || ttl <= 0 || !Number.isSafeInteger(Date.now() + ttl))\n ) {\n throw new ConfigError(\n 'coordination credential ttlMs must be a positive safe integer with a safe expiry',\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 coordination verb that runs an injected deliverable's check inside its request, so its work\n * can outlast one request and it is served like `nodeTools`. src/mcp/tools/coordination.ts builds it\n * exactly when a deliverable is injected.\n */\nconst DELIVERABLE_VERB = 'submit_result'\n\n/** The longest any coordination call holds its response, whatever the request timeout: under the\n * 60 s MCP tool-call timeout Claude Code and Codex apply by default. */\nconst RESPONSE_FENCE_CAP_MS = 45_000\n\n/**\n * The longest a fenced coordination call (`submit_result` and every method-supplied node tool)\n * holds its HTTP response before it answers with a receipt instead. The call keeps running, and\n * its outcome reaches the manager in its next wake.\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 * and at most {@link RESPONSE_FENCE_CAP_MS}.\n */\nexport function coordinationResponseFenceMs(requestTimeoutMs: number): number {\n return Math.max(1, Math.min(RESPONSE_FENCE_CAP_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`. The check runs\n * inside that call, so the call is served single-flight and fenced like `nodeTools`: a check\n * still running at the fence returns a receipt, and the verdict reaches the manager in its\n * next wake. */\n deliverable?: DeliverableSpec<unknown>\n /** Serve `read_continuation` from the manager's continuation records. */\n readContinuation?: (continuation: number | undefined) => unknown\n /** Called once when the external manager accepts a result or declares completion. */\n onStop?: (reason: string | undefined) => void\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 /** Trusted source refs for this manager’s existing observe_agent capability. */\n sourceEvidenceRefs?: ReadonlyArray<string>\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 running call, and a call still running at the fence returns a receipt whose outcome\n * reaches the manager in its next wake. */\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 /** Composition of each authored child profile before identity is fixed —\n * `CoordinationToolsOptions.composeSpawnProfile`. */\n composeSpawnProfile?: (profile: AgentProfile) => AgentProfile\n /** The run's validated profiles table — `CoordinationToolsOptions.profiles`. */\n profiles?: ReadonlyMap<string, SuperviseProfileEntry>\n /** See `CoordinationToolsOptions.spawnResourceRoot`. */\n spawnResourceRoot?: string\n /** See `CoordinationToolsOptions.spawnResourceReader`. */\n spawnResourceReader?: SpawnResourceReader\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?: (\n tools: ReadonlyArray<McpToolDescriptor>,\n coordination: Pick<CoordinationTools, 'awaitSettlement'>,\n ) => void\n },\n): Promise<CoordinationMcpHandle> {\n return (await serveCoordinationMcpForManager(opts)).handle\n}\n\n/** Runtime-only binding: operator controls stay off the public MCP handle and tool grants. */\nexport async function serveCoordinationMcpForManager(\n opts: Parameters<typeof serveCoordinationMcp>[0],\n lifetime?: AbortSignal,\n): Promise<{ handle: CoordinationMcpHandle; controls: CoordinationTools }> {\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 // Without `ttlMs` the credential carries no expiry: it lives as long as the scope\n // (`refusedCredential`), and a scope's deadline is not always its stop.\n const expiresAt = auth?.ttlMs === undefined ? undefined : Date.now() + auth.ttlMs\n if (expiresAt !== undefined && !Number.isSafeInteger(expiresAt)) {\n throw new ConfigError('coordination credential expiry must remain a safe integer')\n }\n for (const [credential, expiry] of revoked) {\n if (expiry <= Date.now()) revoked.delete(credential)\n }\n if (token) revoked.set(token.toString(), credentialExpiresAt ?? Number.POSITIVE_INFINITY)\n credentialExpiresAt = expiresAt\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 ?? null,\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 /**\n * Why a supplied credential is refused, or undefined when it is valid. A credential lives as\n * long as the scope it fronts: until the scope's signal aborts, within an explicit `ttlMs`, and\n * until rotation revokes it. Every stop aborts that signal: cancellation, the run's deadline, and\n * a lead stopping its child. A child's own time box does not: its lead checks it in and keeps it\n * running (`deadline.ts` `DeadlineCheckIn`), and the check-in asks it to record its state and\n * submit through these very tools. Refusing at the time box left a checked-in child unable to do\n * either (2026-10-10: eu-datacenter-power-2030-20261010b:s3, every call for its last 41 minutes).\n */\n const refusedCredential = (\n supplied: Buffer,\n ): 'scope-stopped' | 'credential-refused' | undefined => {\n if (opts.scope.signal.aborted) return 'scope-stopped'\n return validCredential(supplied) ? undefined : 'credential-refused'\n }\n const validCredential = (supplied: Buffer): boolean => {\n if (revoked.has(supplied.toString())) return false\n if (!signingKeys)\n return (\n token !== undefined &&\n (credentialExpiresAt === undefined || 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 // Revocation keys use the wire token; alternate encodings must not alias it.\n signature.toString('base64url') === parts[1] &&\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 ((claims.expires === null && auth?.ttlMs === undefined) ||\n (Number.isSafeInteger(claims.expires) && 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 // Same precedence as the router arm in coordination-driver: a caller-supplied reader, else a\n // host directory, else the manager's own environment through its scope's retained owner. A\n // provider-backed root and every nested manager come through THIS arm, so a fallback wired\n // only in the driver arm would leave a sandbox director refused by path exactly as before.\n const ownerReader =\n opts.spawnResourceReader ??\n (opts.spawnResourceRoot === undefined\n ? scopeRetainedOwnerResourceReader(opts.scope)\n : undefined)\n // Bound once the served set exists: `report_blocked` probes only what this manager was granted.\n let probeableByName: ReadonlyMap<string, McpToolDescriptor> | undefined\n const coord = createCoordinationToolsForManager(\n {\n resolveProbeTool: (name) => probeableByName?.get(name),\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.readContinuation ? { readContinuation: opts.readContinuation } : {}),\n ...(opts.onStop ? { onStop: opts.onStop } : {}),\n ...(opts.analysts ? { analysts: opts.analysts } : {}),\n ...(opts.analyzeOnSettle ? { analyzeOnSettle: opts.analyzeOnSettle } : {}),\n ...(opts.sourceEvidenceRefs ? { sourceEvidenceRefs: opts.sourceEvidenceRefs } : {}),\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.composeSpawnProfile ? { composeSpawnProfile: opts.composeSpawnProfile } : {}),\n ...(opts.profiles ? { profiles: opts.profiles } : {}),\n ...(opts.spawnResourceRoot ? { spawnResourceRoot: opts.spawnResourceRoot } : {}),\n ...(ownerReader ? { spawnResourceReader: ownerReader } : {}),\n ...(opts.peerMail\n ? {\n peerMail:\n typeof opts.peerMail === 'object' && opts.peerMail.limits\n ? { limits: opts.peerMail.limits }\n : {},\n }\n : {}),\n },\n lifetime,\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 ?? [], {\n fenceMs: responseFenceMs,\n receipts: coord,\n })\n // `submit_result` runs the injected completion check inside its request, and a product check can\n // re-run a build and a model review for minutes. Unfenced, the transport answered 504 at\n // `requestTimeoutMs` while the check kept running, so the manager never saw the verdict or its\n // reason: 25 of 25 submits in one 2026-09-22 factory run. Fenced, the call answers with a receipt\n // and the verdict reaches the manager in its next wake, from the same check.\n const fencedVerbs = singleFlightTools(\n coord.tools.filter((tool) => tool.name === DELIVERABLE_VERB),\n { fenceMs: responseFenceMs, receipts: coord },\n )\n // A rename in src/mcp/tools/coordination.ts must fail here, not leave the check unfenced and bring\n // back the 504. The test is the one that passed the deliverable to the coordination tools above.\n if (opts.deliverable && fencedVerbs.tools.length !== 1) {\n throw new ValidationError(\n `serveCoordinationMcp: a deliverable is injected but the coordination verbs lack ${DELIVERABLE_VERB}, so its check would run unfenced`,\n )\n }\n const fencedByName = new Map(fencedVerbs.tools.map((tool) => [tool.name, tool]))\n const availableTools = [\n ...coord.tools.map((tool) => fencedByName.get(tool.name) ?? tool),\n ...nodeTools.tools,\n ]\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 probeableByName = new Map(servedTools.map((tool) => [tool.name, tool]))\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()], coord)\n\n const server: Server = createServer(\n coordinationHttpHandler({\n options: opts,\n identity,\n toolNames: new Set(servedTools.map((tool) => tool.name)),\n handle: async (message) => {\n const response = await mcp.handle(message)\n // A coordination call is where a manager commits work, so it is when its workspace is\n // worth a checkpoint (`retained-scope-owner`, rate-limited, off the request path).\n if (message.method === 'tools/call') noteScopeRetainedOwnerCoordination(opts.scope)\n return response\n },\n backgroundActions: () => nodeTools.background() + fencedVerbs.background(),\n authorize: (req) => {\n if (!paths.has(req.url ?? '')) return { status: 404, reason: 'unknown-path' }\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)\n return { status: 403, reason: 'wrong-host' }\n if (closed) return { status: 401, reason: 'listener-closed' }\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 const refused = refusedCredential(supplied)\n return refused === undefined ? undefined : { status: 401, reason: refused }\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 addressLifetime = new AbortController()\n const abortAddress = () => addressLifetime.abort(opts.scope.signal.reason)\n opts.scope.signal.addEventListener('abort', abortAddress, { once: true })\n if (opts.scope.signal.aborted) abortAddress()\n const releaseAddress = () => {\n opts.scope.signal.removeEventListener('abort', abortAddress)\n if (!addressLifetime.signal.aborted)\n addressLifetime.abort(new Error('coordination listener closed'))\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: addressLifetime.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 if (configured !== undefined) {\n await preflightPublicCoordination({\n url,\n headers,\n signal: opts.scope.signal,\n requestTimeoutMs,\n toolNames: selectedNames,\n })\n }\n } catch (error) {\n releaseAddress()\n closed = true\n await new Promise<void>((resolve) => {\n server.close(() => resolve())\n server.closeAllConnections()\n })\n throw error\n }\n\n const mailbox = coord.peerMail\n const mailListener = mailbox === undefined ? undefined : await servePeerMail(mailbox, host)\n\n const handle: CoordinationMcpHandle = {\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 finishAnalysis: (input) => coord.finishAnalysis(input),\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 releaseAddress()\n closed = true\n await new Promise<void>((resolve) => {\n server.close(() => resolve())\n })\n await mailListener?.close()\n },\n }\n return { handle, controls: coord }\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 { ATTR } from '@tangle-network/agent-trace-contract'\nimport { contentAddress } from '../../durable/spawn-journal'\nimport type { OtelExportConfig, OtelExporter, OtelExportStats, 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 `namespace` and `runId`, so a resumed run lands in the SAME trace as the\n * process that started it while two copies of one run id in different places never share one.\n */\n readonly traceId?: string\n /**\n * The run's storage identity. `supervise()` supplies its run namespace: the run context's own,\n * or a digest of `runDir` and `runId` for a durable run. Absent, the trace derives from `runId`.\n */\n readonly namespace?: 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 /** What this run's exporter has delivered and lost so far. Also surfaced once, as a\n * `console.warn`, on `finish()` when the closing flush dropped spans. */\n stats(): OtelExportStats\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, opts.namespace)\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 /**\n * The span a node's event hangs under. A parent node whose span this recorder never opened (it\n * ran in an earlier process) leaves the child on the root span, which is a placeholder, not a\n * recorded parent.\n */\n const parentSpan = (\n parentId: string | undefined,\n ): { spanId: string; confidence: 'explicit' | 'unknown' } => {\n const spanId = parentId === undefined ? undefined : spanIdOf.get(parentId)\n return spanId\n ? { spanId, confidence: 'explicit' }\n : { spanId: rootSpanId, confidence: 'unknown' }\n }\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 attrs: Attrs = {\n ...base,\n [ATTR.spanKind]: 'AGENT',\n 'agent.name': label,\n 'tangle.supervise.node.id': childId,\n 'tangle.supervise.node.label': label,\n 'tangle.supervise.node.kind': '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 // Retry safety: every try of one keyed assignment shares its operation id and carries its own\n // attempt id, and the key is what makes a re-spawn re-attach instead of running twice.\n const key = str(p.key)\n const operation = str(p.assignmentId) ?? key\n if (operation) attrs[ATTR.operationId] = operation\n const attempt = str(p.attemptId)\n if (attempt) attrs[ATTR.attemptId] = attempt\n if (key) attrs[ATTR.idempotencyKey] = key\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 parent = parentSpan(event.parentId)\n attrs[ATTR.parentConfidence] = parent.confidence\n\n const spanId = generateSpanId()\n spanIdOf.set(childId, spanId)\n open.set(childId, {\n spanId,\n parentSpanId: parent.spanId,\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 // A turn with no node is the root manager's own.\n const parent = parentId ? parentSpan(parentId) : { spanId: rootSpanId, confidence: 'explicit' }\n const parentSpanId = parent.spanId\n const attrs: Attrs = {\n ...base,\n [ATTR.parentConfidence]: parent.confidence,\n [ATTR.spanKind]: '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 {\n ...rootAttrs(base, opts.agentName ?? 'supervisor', outcome),\n ...(opts.parentSpanId ? { [ATTR.parentConfidence]: 'explicit' } : {}),\n },\n rootStatus(outcome),\n rootMessage(outcome),\n ),\n )\n } catch {\n // Telemetry is not the work: a failure building or emitting the closing\n // spans above must never reach the run.\n }\n // Flush and shutdown run outside the span-building try so a rejected\n // flush cannot skip shutdown, and are surfaced instead of swallowed: a\n // 401 or a dead collector was previously silent even to someone\n // awaiting finish(). One warning per finish() call, not per span.\n try {\n await exporter.flush()\n } catch (error) {\n const s = exporter.stats()\n console.warn(\n `[agent-runtime] supervisor span export dropped ${s.dropped} span(s): ${s.lastError ?? String(error)}`,\n )\n } finally {\n if (ownsExporter) await exporter.shutdown()\n }\n },\n stats: () => exporter.stats(),\n }\n}\n\n// ── Attribute mapping ─────────────────────────────────────────────────────────\n\nfunction rootAttrs(base: Attrs, agentName: string, outcome?: SupervisorSpanOutcome): Attrs {\n const attrs: Attrs = {\n ...base,\n [ATTR.spanKind]: '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 by content address — deterministic, so a resumed run\n * rejoins the trace its first process opened rather than forking a new one. The default covers the\n * namespace as well as the run id, because run ids repeat across copies of a run.\n */\nfunction normalizeTraceId(\n traceId: string | undefined,\n runId: string,\n namespace: string | undefined,\n): string {\n if (traceId && /^[0-9a-f]{32}$/i.test(traceId)) return traceId.toLowerCase()\n const source = traceId ?? (namespace === undefined ? runId : `${namespace}\\u0000${runId}`)\n return contentAddress(source).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 * The task a re-entered external driver receives, composed from Runtime's own records.\n *\n * A re-prompt used to send the unmet items alone, on the claim that it re-entered the SAME live\n * session. That holds on a backend that reattaches the harness session. It does not hold when the\n * previous environment is gone: the driver then starts in a new sandbox, with a new harness\n * session, and the unmet-items text is all it knows. Measured in Autopsy A (2026-09-16): three\n * root attempts, each in a new sandbox; the third reported an empty workspace, spent 20 minutes\n * and about 2.0M input tokens investigating infrastructure, and never consumed the child result\n * that had settled while it was gone.\n *\n * So the composer takes the drive harness's statement of what the next drive continues, and\n * writes the whole run state whenever the harness session is not proven continuous: the original\n * objective and completion contract, where the journal was read to, the events waiting and the\n * events delivered to a turn that died, every live and settled worker, the last refusal, and what\n * became of the workspace. A proven-continuous session gets the unmet items plus what changed.\n */\n\nimport type { ManagerReentryState } from '../../mcp/tools/coordination'\nimport type { DriverReentry } from './driver-retry'\n\n/** What the next drive continues, as the drive harness can prove it before the turn starts. */\nexport interface ReentryContinuity {\n /** `continued`: the next turn is sent into the harness session that received the last one.\n * `new`: a new harness session, which knows only what its task says. */\n readonly session: 'continued' | 'new'\n /** Whether the next drive runs in the environment the previous drive used. `replaced` names a\n * previous environment the provider no longer holds. */\n readonly environment: 'same' | 'replaced' | 'unknown'\n readonly environmentId?: string\n readonly previousEnvironmentId?: string\n /** What the next environment holds of the previous one's files. `restored`: the files as of\n * the checkpoint taken at `checkpointAt`; anything written after it is gone. */\n readonly workspace: 'kept' | 'restored' | 'lost' | 'unknown'\n readonly checkpointAt?: string\n}\n\n/** Continuity when nothing is proven: compose the full state. */\nexport const UNPROVEN_CONTINUITY: ReentryContinuity = Object.freeze({\n session: 'new',\n environment: 'unknown',\n workspace: 'unknown',\n})\n\nexport interface ReentryTaskInput {\n /** The run's original task, exactly as the first drive received it. */\n readonly originalTask: unknown\n /** What the completion check requires, when the caller described it. */\n readonly contract?: string\n /** Coordination tools served to this manager. Absent means none are proven available. */\n readonly tools?: ReadonlyArray<string>\n readonly reentry: DriverReentry\n readonly continuity: ReentryContinuity\n readonly state: ManagerReentryState\n /** 1-based driver attempt this task starts. */\n readonly attempt: number\n}\n\n/** Compose the task for one re-entered drive. */\nexport function composeReentryTask(input: ReentryTaskInput): string {\n const { reentry, continuity, state } = input\n if (reentry.reason === 'unmet-contract' && continuity.session === 'continued') {\n const changes = stateLines(state, false, input.tools)\n return [reentry.steer, ...(changes.length > 0 ? ['', ...changes] : [])].join('\\n')\n }\n // A woken manager in the same session already holds everything but what happened.\n if (reentry.reason === 'wake' && continuity.session === 'continued') return reentry.input\n const lines: string[] = [\n `You are re-entering a run that is already in progress (driver attempt ${input.attempt}). ` +\n 'This is the same run and the same objective, not a new one.',\n whyLine(reentry),\n environmentLine(continuity),\n '',\n '## Objective',\n '',\n 'This is the original task of the run, unchanged:',\n '',\n taskText(input.originalTask),\n '',\n '## Completion check',\n '',\n ...(input.tools?.includes('submit_result') === true\n ? ['Call submit_result to request acceptance through the independent check.']\n : []),\n input.contract === undefined || input.contract.trim().length === 0\n ? 'No completion requirement was described.'\n : `The declared completion requirement is: ${input.contract.trim()}`,\n ...(reentry.reason === 'unmet-contract' ? ['', 'What is still unmet:', '', reentry.steer] : []),\n ...(reentry.reason === 'wake' ? ['', '## What woke you', '', reentry.input] : []),\n '',\n '## Run state, from the coordinator',\n '',\n ...stateLines(state, true, input.tools),\n '',\n '## What to do now',\n '',\n 'Continue the run from this state.',\n // Measured 2026-09-24 (autopsy-a-restore-after-20260924c): the restored workspace held the\n // first turn's objective.md, and the re-entered director, told only that its files were\n // restored, re-ran the task's first step and overwrote the file without reading it.\n ...(continuity.workspace === 'kept' || continuity.workspace === 'restored'\n ? [\n 'Read the files you already wrote before you repeat any step of the task. A step whose file is there is done, and its content stands.',\n ]\n : []),\n ...(input.tools?.includes('observe_agent') === true\n ? [\n 'Read the output of every settled worker with observe_agent before you spawn anything new.',\n ]\n : []),\n 'Do not spawn a replacement for a worker that is running or has settled.',\n 'Your coordination tools are served by the same coordinator as before, and the state above comes from it.',\n ]\n return lines.join('\\n')\n}\n\n/**\n * Why the driver is back, in one clause. The failure's own text stays in the attempt records and\n * never reaches the driver: measured 2026-09-11, a continuation told the details of a provider\n * failure spent two of its first four children probing the infrastructure, while its peer, told\n * only what to continue, spent all forty-five on the research.\n */\nfunction whyLine(reentry: DriverReentry): string {\n if (reentry.reason === 'unmet-contract') {\n return `Your previous turn ended with the completion check unmet (continuation ${reentry.continuation}).`\n }\n if (reentry.reason === 'wake') {\n return 'Your previous turn ended while your workers ran, and Runtime woke you with what happened.'\n }\n // A pause names no provider and no code: the operator owns the upstream, and the driver's\n // budget belongs to the objective.\n return reentry.reason === 'upstream-unavailable'\n ? 'Your previous turn was interrupted before it finished; the run itself is intact.'\n : `Your previous turn ended before it finished (retry ${reentry.retry}); the run itself is intact.`\n}\n\nfunction environmentLine(continuity: ReentryContinuity): string {\n if (continuity.environment === 'same') {\n return `You run in the same environment as before${continuity.environmentId === undefined ? '' : ` (${continuity.environmentId})`}, and your files are where you left them.`\n }\n if (continuity.environment === 'replaced') {\n return (\n `Your previous environment${continuity.previousEnvironmentId === undefined ? '' : ` (${continuity.previousEnvironmentId})`} is gone, and you run in a new one. ` +\n (continuity.workspace === 'kept'\n ? 'Its files were carried over.'\n : continuity.workspace === 'restored'\n ? `Its files were restored from a checkpoint taken at ${continuity.checkpointAt ?? 'your last coordination call'}; anything you wrote after that is not here. The coordinator and the knowledge store kept everything below.`\n : 'Files you wrote there are not here. The coordinator and the knowledge store kept everything below.')\n )\n }\n return 'You may be in a new environment. Check for files before you rely on them; the coordinator kept everything below.'\n}\n\nfunction stateLines(\n state: ManagerReentryState,\n full: boolean,\n tools: ReadonlyArray<string> | undefined,\n): string[] {\n const lines: string[] = []\n if (full || state.journalRows > state.journalReadTo) {\n lines.push(\n `Journal: ${state.journalRows} rows. You last read up to row ${state.journalReadTo}.` +\n (tools?.includes('read_journal') === true\n ? ` Call read_journal with sinceRow ${state.journalReadTo} to read what happened since, or sinceRow 0 to read the whole run.`\n : ''),\n )\n }\n if (state.live.length > 0) {\n lines.push(\n `Workers running: ${state.live.map((worker) => `${worker.id} (${worker.label}, ${worker.status})`).join('; ')}.`,\n )\n } else if (full) {\n lines.push('Workers running: none.')\n }\n const settled = full ? state.settled : state.settled.filter((worker) => !worker.delivered)\n if (settled.length > 0) {\n lines.push(\n `Workers settled${full ? '' : ' that you have not received'}: ${settled\n .map(\n (worker) =>\n `${worker.id} (${worker.status}${worker.valid === undefined ? '' : worker.valid ? ', passed its check' : ', did not pass its check'}${worker.delivered ? '' : ', not yet received'})`,\n )\n .join('; ')}.` +\n (tools?.includes('observe_agent') === true\n ? ' Read an output with observe_agent and the worker id.'\n : ''),\n )\n } else if (full) {\n lines.push('Workers settled: none.')\n }\n if (state.waiting.length > 0) {\n lines.push(\n `Events waiting for you: ${state.waiting.length} (${state.waiting\n .map((event) =>\n event.worker === undefined ? event.type : `${event.type} from ${event.worker}`,\n )\n .join('; ')}).`,\n )\n } else if (full) {\n lines.push('Events waiting for you: none.')\n }\n if (state.unacknowledged.length > 0) {\n lines.push(\n `Events delivered to a turn that has not finished, so treat them as unread: ${state.unacknowledged\n .map(\n (event) =>\n `#${event.seq} ${event.type}${event.worker === undefined ? '' : ` from ${event.worker}`}`,\n )\n .join('; ')}.`,\n )\n }\n if (state.lastRejection !== undefined) {\n lines.push(`Your last submit_result was refused: ${state.lastRejection.reason}`)\n }\n return lines\n}\n\nfunction taskText(task: unknown): string {\n if (typeof task === 'string') return task\n try {\n return JSON.stringify(task, null, 2) ?? String(task)\n } catch {\n return String(task)\n }\n}\n","/**\n * The root manager's own provider stream, retained where Runtime owns it.\n *\n * Measured motive (agent-runtime#1233, 2026-09-15): a CHILD's full event stream — reasoning, text,\n * and tool parts, 28k to 76k reasoning characters per child — is retained in the blob its\n * `settled` record names as `outRef`. The ROOT's stream reached nobody: `driveHarnessFromBackend`\n * drained the root executor for accounting and discarded every `progress` event, and on a\n * `winner` run `result.outRef` is the SELECTED CHILD's artifact, not the root's. A root that died\n * at its join barrier (fourier-e, 63 children) left a 607-byte `failure.json` and nothing it\n * thought; the Lab's only transcript of a root was a post-hoc scrape of the harness's own\n * database.\n *\n * `<runDir>/root-stream.jsonl` is the record: one JSONL line per `ExecutorProgressEvent`, written\n * AS IT ARRIVES, so a root whose process is killed mid-turn keeps every line already written. The\n * file itself is the evidence; the receipt (`ref`, the content address of the file's bytes, and\n * `events`, its committed line count) is what `result.json` and `failure.json` carry. The winner's\n * `outRef` keeps its meaning; this is a separate reference.\n *\n * Durability boundary: each line is written synchronously to an `O_APPEND` descriptor before the\n * next event is drained, and the file is fsynced at every drive-attempt boundary and at close, not\n * per line. Measured 2026-09-15 on this host's APFS: an fsync per line cost 7.1 ms per event over\n * 1,000 events and 8.1 ms over 5,000 (~80 s for a root emitting ten thousand text deltas, all of\n * it serialized inside the drain loop that also meters the budget); an async `FileHandle.write`\n * still cost 0.9 to 1.1 ms per line in the thread pool the children's journal writes share; a\n * `writeSync` costs 6 µs. A process kill loses nothing written; only a kernel crash or power\n * loss can drop lines written since the last fsync, and the reader's torn-tail rule keeps such a\n * file readable.\n *\n * The bridge wire carries text and tool calls only: cli-bridge's SSE frames decode\n * `delta.content` and `delta.tool_calls`, never a reasoning delta. A bridge-placed root's retained\n * stream is therefore text plus tool calls; reasoning arrives only on the provider/sandbox path,\n * which projects `message.part.updated` reasoning parts to `reasoning_delta`.\n */\n\nimport { createHash } from 'node:crypto'\nimport { closeSync, constants as fsConstants, fsyncSync, openSync, writeSync } from 'node:fs'\nimport { mkdir } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { isNoEntError, prepareJsonlAppend, readCommittedJsonLines } from '../../durable/jsonl-file'\nimport { errorMessage } from '../util'\nimport { assertNoSymlinkDescendant } from './durable-file'\nimport type { ExecutorProgressEvent, RootStreamReceipt } from './types'\n\nexport type { RootStreamReceipt } from './types'\n\n/** The root stream: one JSONL line per progress event the root's executor observed. */\nexport const ROOT_STREAM_FILE = 'root-stream.jsonl'\n\n/** One line of `root-stream.jsonl`. */\nexport type RootStreamRecord = {\n /** 1-based position in the file, continuing across drive attempts and across processes. */\n readonly seq: number\n /** ISO instant the line was appended, from the run's own clock. */\n readonly at: string\n /** The 1-based drive attempt of the root that produced it: a driver retry or re-prompt\n * re-enters the harness and continues the same file with the next attempt number. */\n readonly attempt: number\n} & (\n | { readonly event: ExecutorProgressEvent }\n | {\n /** The event could not be written as JSON; its kind and the reason stand in so the gap\n * is recorded in the file itself instead of silently narrowing the stream. */\n readonly dropped: { readonly kind: ExecutorProgressEvent['kind']; readonly reason: string }\n }\n)\n\n/** The append-only writer one root drive holds. */\nexport interface RootStreamSink {\n /** Mark the next drive attempt; opens the file on the first call. */\n beginAttempt(): Promise<void>\n /** Append one event; the line is in the kernel when this returns. */\n append(event: ExecutorProgressEvent): void\n /** Fsync, close the writer, and return the receipt, or `undefined` when no attempt ever began. */\n close(): Promise<RootStreamReceipt | undefined>\n}\n\n/** Create the writer for `<runDir>/root-stream.jsonl`. Nothing touches disk until the first\n * `beginAttempt`, so a run whose root never drives leaves no file and no receipt. */\nexport function createRootStreamSink(runDir: string, now: () => number): RootStreamSink {\n const dir = resolve(runDir)\n const path = resolve(dir, ROOT_STREAM_FILE)\n let fd: number | undefined\n let attempt = 0\n let seq = 0\n let closed = false\n\n const openOnce = async (): Promise<void> => {\n if (fd !== undefined) return\n await mkdir(dir, { recursive: true })\n assertNoSymlinkDescendant(dir, path, 'root stream')\n // A resumed run continues the same file. Recovery scans the tail once, so a torn line from a\n // process that died mid-write is truncated rather than followed by a record it would corrupt.\n const needsSeparator = await prepareJsonlAppend(path)\n seq = 0\n for await (const _record of readCommittedJsonLines<RootStreamRecord>(path, {\n allowMissing: true,\n })) {\n seq += 1\n }\n fd = openSync(\n path,\n fsConstants.O_APPEND |\n fsConstants.O_CREAT |\n fsConstants.O_WRONLY |\n (typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0),\n 0o600,\n )\n if (needsSeparator) writeLine(fd, '')\n }\n\n return {\n async beginAttempt() {\n if (closed) throw new Error('root stream: beginAttempt after close')\n attempt += 1\n // A retry re-enters the harness after the previous attempt's lines; make them durable\n // before the next attempt appends after them.\n if (fd !== undefined) fsyncSync(fd)\n await openOnce()\n },\n append(event) {\n if (closed) throw new Error('root stream: append after close')\n if (fd === undefined) throw new Error('root stream: append before beginAttempt')\n const at = new Date(now()).toISOString()\n const record = { seq: seq + 1, at, attempt, event }\n // A progress payload is JSON the wire already parsed, so this branch is a guard, not a\n // path: a value JSON cannot encode (a BigInt, a cycle, a hostile `toJSON`) is recorded as\n // a dropped line so the turn continues and the file still says something was lost.\n let line: string | undefined\n try {\n line = JSON.stringify(record)\n } catch (error) {\n line = JSON.stringify({\n seq: seq + 1,\n at,\n attempt,\n dropped: { kind: event.kind, reason: errorMessage(error) },\n })\n }\n if (line === undefined) {\n line = JSON.stringify({\n seq: seq + 1,\n at,\n attempt,\n dropped: { kind: event.kind, reason: 'event serialized to nothing' },\n })\n }\n writeLine(fd, line)\n seq += 1\n },\n async close() {\n if (closed) throw new Error('root stream: closed twice')\n closed = true\n if (fd === undefined) return undefined\n try {\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n fd = undefined\n }\n return readRootStreamReceipt(dir)\n },\n }\n}\n\n/** `writeSync` may legally make a short write; loop until the whole line and its newline land. */\nfunction writeLine(fd: number, line: string): void {\n const bytes = Buffer.from(`${line}\\n`, 'utf8')\n let offset = 0\n while (offset < bytes.byteLength) {\n const written = writeSync(fd, bytes, offset, bytes.byteLength - offset)\n if (written <= 0) throw new Error(`root stream: append made no progress at byte ${offset}`)\n offset += written\n }\n}\n\n/**\n * The receipt for the root stream a run directory holds, recomputed from the file's bytes, or\n * `undefined` when the directory holds none. This is what a run that never settled — a root that\n * died mid-turn — gets on its failure record, and it equals what `close()` returned for a run\n * that did.\n */\nexport async function readRootStreamReceipt(\n runDir: string,\n): Promise<RootStreamReceipt | undefined> {\n const path = resolve(runDir, ROOT_STREAM_FILE)\n const hash = createHash('sha256')\n let events = 0\n try {\n for await (const _record of readCommittedJsonLines<RootStreamRecord>(path, {\n onBytes: (bytes) => {\n hash.update(bytes)\n },\n })) {\n events += 1\n }\n } catch (error) {\n if (isNoEntError(error)) return undefined\n throw error\n }\n return Object.freeze({ ref: `sha256:${hash.digest('hex')}`, events })\n}\n\n/** Every committed line of the root stream, in order, or `undefined` when there is no file. A\n * torn final line from a process that died mid-write is not a record and is left out. */\nexport async function readRootStream(runDir: string): Promise<RootStreamRecord[] | undefined> {\n const path = resolve(runDir, ROOT_STREAM_FILE)\n const records: RootStreamRecord[] = []\n try {\n for await (const record of readCommittedJsonLines<RootStreamRecord>(path)) records.push(record)\n } catch (error) {\n if (isNoEntError(error)) return undefined\n throw error\n }\n return records\n}\n","/**\n * A manager's own run as one trace store: what the continuation's question panel reads.\n *\n * The panel asks about the director's own work and about its workers' (discovery\n * `docs/38-one-loop-and-continuation.md`, section 5), so it reads both: the director's root stream\n * (`root-stream.jsonl`) and each settled worker's structured tool trace. Each agent is one trace,\n * named by its node id, so a `{worker}` question and a `trace://<worker id>/<span id>` citation\n * name the same worker.\n *\n * The root stream is progress events, not spans. Each tool call becomes one span with its result,\n * and each run of the director's text, and of its reasoning, between two other events becomes one\n * span named for what it is (`assistant_text`, `assistant_reasoning`): the director's claims live in\n * its text, and a panel that saw only its tool calls could not check them. Span ids are the\n * record's `seq`, which is unique in the file and stable across reads.\n */\n\nimport {\n type ToolSpan,\n type TraceAnalysisStore,\n toolSpansToTraceAnalysisStore,\n} from '@tangle-network/agent-eval'\nimport { ValidationError } from '../../errors'\nimport type { RootStreamRecord } from './root-stream'\nimport { parseWorkerToolTraceArtifact } from './trace-evidence'\nimport type { ResultBlobStore, WorkerTraceEvidence } from './types'\n\n/** The span a run of the director's text becomes. */\nexport const ASSISTANT_TEXT_SPAN = 'assistant_text'\n/** The span a run of the director's reasoning becomes. */\nexport const ASSISTANT_REASONING_SPAN = 'assistant_reasoning'\n\n/** The director's root stream as tool spans in one trace named `traceId`. */\nexport function rootStreamToolSpans(\n records: ReadonlyArray<RootStreamRecord>,\n traceId: string,\n): ToolSpan[] {\n const spans: ToolSpan[] = []\n // Open calls by attempt and call id, or by tool name for a harness that sends no call id.\n const open = new Map<string, ToolSpan>()\n let prose: { span: ToolSpan; text: string; kind: string; attempt: number } | undefined\n const at = (record: RootStreamRecord) => {\n const ms = Date.parse(record.at)\n if (!Number.isFinite(ms)) {\n throw new ValidationError(`root stream line ${record.seq} has no valid time`)\n }\n return ms\n }\n const base = (record: RootStreamRecord, name: string) => ({\n kind: 'tool' as const,\n spanId: `s${record.seq}`,\n runId: traceId,\n name,\n toolName: name,\n startedAt: at(record),\n attributes: { attempt: record.attempt, seq: record.seq },\n })\n for (const record of records) {\n if (!('event' in record)) {\n prose = undefined\n continue\n }\n const { event } = record\n if (event.kind === 'text_delta' || event.kind === 'reasoning_delta') {\n if (prose !== undefined && prose.kind === event.kind && prose.attempt === record.attempt) {\n prose.text += event.text\n prose.span.result = prose.text\n prose.span.endedAt = at(record)\n continue\n }\n const name = event.kind === 'text_delta' ? ASSISTANT_TEXT_SPAN : ASSISTANT_REASONING_SPAN\n const span: ToolSpan = {\n ...base(record, name),\n args: {},\n result: event.text,\n endedAt: at(record),\n }\n spans.push(span)\n prose = { span, text: event.text, kind: event.kind, attempt: record.attempt }\n continue\n }\n prose = undefined\n if (event.kind === 'tool_call') {\n const span: ToolSpan = {\n ...base(record, event.toolName),\n args: event.args,\n ...(event.args === undefined ? { argsCaptured: false } : {}),\n endedAt: at(record),\n }\n if (event.toolCallId !== undefined) {\n span.attributes = { ...span.attributes, toolCallId: event.toolCallId }\n }\n spans.push(span)\n open.set(`${record.attempt}\\u0000${event.toolCallId ?? `name:${event.toolName}`}`, span)\n continue\n }\n if (event.kind === 'tool_result') {\n const key = `${record.attempt}\\u0000${event.toolCallId ?? `name:${event.toolName}`}`\n const call = open.get(key)\n if (call !== undefined) {\n open.delete(key)\n call.result = event.result\n call.endedAt = at(record)\n continue\n }\n // A result whose call the stream never recorded keeps its own span.\n spans.push({\n ...base(record, event.toolName),\n args: undefined,\n argsCaptured: false,\n result: event.result,\n endedAt: at(record),\n })\n }\n // Interaction requests and native child-task updates are not tool evidence; the child's own\n // trace is the worker's, which this store reads separately.\n }\n return spans\n}\n\n/** One worker's persisted tool spans, re-keyed to the worker's node id. Unavailable: none. */\nasync function workerSpans(\n worker: { readonly id: string; readonly trace: WorkerTraceEvidence },\n blobs: Pick<ResultBlobStore, 'get'>,\n): Promise<ToolSpan[]> {\n if (worker.trace.status !== 'available') return []\n const raw = await blobs.get(worker.trace.traceRef)\n if (raw === undefined) {\n throw new ValidationError(\n `worker ${worker.id}'s trace blob '${worker.trace.traceRef}' is missing; its settlement evidence is incomplete`,\n )\n }\n const { spans } = parseWorkerToolTraceArtifact(raw, worker.trace.traceRef)\n return spans.map((span) => ({\n ...span,\n runId: worker.id,\n ...(span.runId === worker.id\n ? {}\n : { attributes: { ...span.attributes, sourceRunId: span.runId } }),\n }))\n}\n\n/**\n * The store over a manager's run: its own root stream when it has one, and every settled worker's\n * tool trace. `undefined` when the run has recorded no span yet, which is not a store a panel can\n * read: agent-eval refuses an empty trace, because it cannot tell a tool-free run from a failed\n * capture.\n */\nexport async function runTraceAnalysisStore(input: {\n readonly root?: {\n readonly id: string\n readonly read: () => Promise<ReadonlyArray<RootStreamRecord> | undefined>\n }\n readonly workers: ReadonlyArray<{ readonly id: string; readonly trace: WorkerTraceEvidence }>\n readonly blobs: Pick<ResultBlobStore, 'get'>\n}): Promise<TraceAnalysisStore | undefined> {\n const records = input.root === undefined ? undefined : await input.root.read()\n const spans = [\n ...(records === undefined || input.root === undefined\n ? []\n : rootStreamToolSpans(records, input.root.id)),\n ...(await Promise.all(input.workers.map((worker) => workerSpans(worker, input.blobs)))).flat(),\n ]\n return spans.length === 0 ? undefined : toolSpansToTraceAnalysisStore(spans)\n}\n","import type { CoordinationTools } from '../../mcp/tools/coordination'\nimport { createCancelAcknowledger, createSteerAcknowledger } from './coordination-driver'\nimport type { Scope } from './types'\n\n/** Observe durable worker controls while the native harness owns the manager's turn loop. */\nexport function observeWorkerControls(options: {\n dir?: string\n steerDir?: string\n coord: CoordinationTools\n scope: Scope<unknown>\n signal: AbortSignal\n controlScope: 'run' | 'subtree'\n /** Root's existing inbox only; omitted for every nested manager. */\n deliverRoot?: (message: { steer: string; interrupt: boolean }) => boolean\n /** Root delivery readiness; checked before a durable steer is claimed. */\n deliverRootReady?: () => boolean\n onError: (error: unknown) => void\n}): { close(): Promise<void> } {\n const { dir, coord, scope, signal, controlScope, onError } = options\n const steerDir = options.steerDir ?? dir\n const deps = { coord, scope, signal, now: Date.now, ownerId: scope.view.root, controlScope }\n const steers =\n steerDir === undefined\n ? undefined\n : createSteerAcknowledger({\n ...deps,\n dir: steerDir,\n deliverRoot: options.deliverRoot,\n deliverRootReady: options.deliverRootReady,\n })\n const cancellations = dir === undefined ? undefined : createCancelAcknowledger({ ...deps, dir })\n let active = true\n let timer: ReturnType<typeof setInterval> | undefined\n let steering = false\n let inFlight = Promise.resolve()\n let failure: { error: unknown } | undefined\n let closing: Promise<void> | undefined\n\n const stop = (): void => {\n active = false\n clearInterval(timer)\n signal.removeEventListener('abort', stop)\n }\n const fail = (error: unknown): void => {\n failure = { error }\n stop()\n onError(error)\n }\n const poll = (): void => {\n if (!active) return\n try {\n // Cancellation stays available while an earlier steer awaits durable event capture.\n cancellations?.pass('turn')\n if (steers === undefined || steering) return\n steering = true\n inFlight = steers\n .pass('turn')\n .catch(fail)\n .finally(() => {\n steering = false\n })\n } catch (error) {\n fail(error)\n }\n }\n signal.addEventListener('abort', stop, { once: true })\n if (signal.aborted) stop()\n else {\n timer = setInterval(poll, 100)\n timer.unref()\n poll()\n }\n\n const finish = async (): Promise<void> => {\n stop()\n await inFlight\n try {\n await steers?.pass('final')\n cancellations?.pass('final')\n } finally {\n cancellations?.finish()\n }\n if (failure) throw failure.error\n }\n return {\n close: () => (closing ??= finish()),\n }\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 quality-accepted.\n */\nimport { dirname } from 'node:path'\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 CoordinationTools,\n EscalateQuestion,\n MakeWorkerAgent,\n SpawnPreflight,\n SuperviseProfileEntry,\n WorkerWatchOptions,\n} from '../../mcp/tools/coordination'\nimport { coordinationVerbNames } from '../../mcp/tools/coordination'\nimport type { SpawnResourceReader } from '../../mcp/tools/spawn-resource-paths'\nimport { agentHarness } from '../harness-role'\nimport type { HarnessTranscriptCapture } from '../harness-transcript'\nimport { type RouterTransportConfig, routerBrain } from '../router-client'\nimport type { ToolLoopChat, ToolLoopCompactionOptions } from '../tool-loop'\nimport { linkAbort, runAbortable } from './abortable'\nimport type { DeliverableSpec } from './completion-gate'\nimport {\n admitContinuationPolicy,\n bestComposite,\n CheckUnavailableError,\n type ContinuationKeeper,\n type ContinuationPolicy,\n checkVerdictOf,\n createContinuationKeeper,\n} from './continuation'\nimport { driverAgent } from './coordination-driver'\nimport type { PriorCoordination } from './coordination-log'\nimport {\n assertCoordinationTransport,\n type CoordinationTransportOptions,\n serveCoordinationMcpForManager,\n} from './coordination-mcp'\nimport {\n type DriverAttemptRecord,\n type DriverContinuationRecord,\n type DriverProgressMark,\n type DriverReentry,\n type DriverRetryPolicy,\n runDriverWithRetry,\n summarizeDriverAttempts,\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 { isLiveNodeStatus } from './node-status'\nimport type { PeerMailLimits } from './peer-mail'\nimport type { ExecutorProgress } from './progress'\nimport {\n coordinationMcpAlias,\n coordinationProfileToolPrefix,\n providerVisibleProfile,\n} from './provider-visible-profile'\nimport { composeReentryTask, type ReentryContinuity, UNPROVEN_CONTINUITY } from './reentry'\nimport { abandonScopeRetainedOwnerInvocation } from './retained-scope-owner'\nimport { readRootStream } from './root-stream'\nimport { createRouterTranscript } from './router-transcript'\nimport { applyRunCancellation } from './run-cancellation'\nimport { runTraceAnalysisStore } from './run-traces'\nimport {\n beginScopeOwnerAttempt,\n recordScopeOwnerDriverAttempt,\n recordScopeOwnerPause,\n} 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 {\n Agent,\n Budget,\n ExecutorResult,\n NodeExecutionIdentity,\n ResultBlobStore,\n Scope,\n} from './types'\nimport {\n composeWakeInput,\n deadlineWarningAt,\n type ManagerWakePolicy,\n resolveWakePolicy,\n} from './wake'\nimport { observeWorkerControls } from './worker-control-observer'\n\nexport {\n coordinationMcpAlias,\n coordinationProfileToolPrefix,\n providerVisibleProfile,\n} from './provider-visible-profile'\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 if (declaredRuntimeToolNames(profile).includes('await_event')) {\n return `the profile declares ${JSON.stringify(`${coordinationProfileToolPrefix}await_event`)}, which no longer exists: a manager ends its turn to wait, and Runtime wakes it with what happened. Remove the grant`\n }\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/** 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, the worker-slot queue, 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 /** Wait in code until at least one of `{ workerIds }` has settled; returns `{ settled: ids }`.\n * Takes nothing from the manager's inbox, so the manager still hears of each settlement. */\n awaitSettlement(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(\n tools: ReadonlyArray<McpToolDescriptor>,\n coordination: Pick<CoordinationTools, 'awaitSettlement'>,\n ): void\n}\n\nfunction createVerbSlot(): VerbSlot {\n let bound: ReadonlyArray<McpToolDescriptor> | undefined\n let waits: Pick<CoordinationTools, 'awaitSettlement'> | 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 awaitSettlement: async (args: unknown): Promise<unknown> => {\n if (waits === undefined) {\n throw new ValidationError(\n 'supervisorAgent: coordination verb \"awaitSettlement\" was called before this manager\\'s coordination tools were bound',\n )\n }\n const ids = (args as { workerIds?: unknown } | undefined)?.workerIds\n if (!Array.isArray(ids) || !ids.every((id) => typeof id === 'string' && id.length > 0)) {\n throw new ValidationError('awaitSettlement: workerIds must be an array of worker ids')\n }\n return { settled: await waits.awaitSettlement(ids as string[]) }\n },\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, coordination): void {\n bound = tools\n waits = coordination\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 / observe_agent / submit_result 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 profile the run registered, when `authoredProfile` is another segment of it (a resumed root moved to\n * another model or harness). Materialization receipts are attributed to it, so a run's materialization chain\n * keeps one authored profile across segments. Absent when the two are the same. */\n readonly registeredProfile?: 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 /** Present when this drive re-enters the run. `task` then carries the original objective and\n * the coordinator's run state, which is right for any backend. A harness that can prove what\n * the next turn continues composes the task from that proof instead, and reports it. */\n readonly reentry?: {\n /** Why Runtime is re-entering; a typed usage limit may advance an authored seat chain. */\n readonly reason: DriverReentry\n readonly compose: (continuity: ReentryContinuity) => string\n readonly onContinuity?: (continuity: ReentryContinuity) => void\n }\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 readiness predicate for the live inbox. Root steers remain durable and unclaimed\n * until this returns `true`; it is checked only while the harness invocation is active. */\n deliverReady?(): 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 /** Terminal artifact from the newest successfully completed invocation. A child without a\n * completion check retains its output as unassessed evidence for its parent. */\n resultArtifact?(): ExecutorResult<unknown> | undefined\n /** Optional capture of the manager's own harness session from its newest attempt. */\n harnessTranscript?(): HarnessTranscriptCapture | undefined\n /** Resolves once {@link harnessTranscript} is final (`Executor.harnessTranscriptSettled`). */\n harnessTranscriptSettled?(): Promise<void>\n /** Close the last subscription segment at this logical manager's settlement. */\n closeSeatSegment?(reason: 'completed' | 'failed' | 'cancelled' | 'paused'): Promise<void>\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 /** Keep an inference turn available when recursive admission holds budget for this manager. */\n readonly preserveOwnerTurns?: true\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 /** Reports that a nested unchecked manager returned its own harness evidence, not a checked\n * finalizer result. Recursive settlement must preserve the absence of a quality verdict. */\n readonly onUnassessedOutput?: (result: unknown) => void\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 /** The profile this manager was registered with, when it executes another segment of it (a resumed root moved\n * to another model or harness, `SuperviseOptions.segment`). Its materialization stays attributed to the\n * registered profile, as a seat's does to the profile that authored the seat; the executed profile is its\n * effective profile. Omit = the executed profile is the registered one. */\n readonly registeredProfile?: AgentProfile\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 /** Called once when the external driver loop ends, returned or thrown, with what it did. */\n readonly onDriverLoopSettled?: (record: DriverContinuationRecord) => void\n /** How an EXTERNAL manager with `deliverable` is sent back when its turn ends with the check\n * unmet: the deadline, `maxBarren`, and the note's profile and switches (`./continuation.ts`).\n * Required with `deliverable` on the external arm, refused without one, and refused for a\n * router-brained supervisor, which runs its own turn loop in process. The harness owns its own\n * turn loop, so it can end while the run has delivered nothing — 376 of 376 winning\n * discovery-lab runs (2026-09-01) ended on the driver's own completion. A continuation reuses the\n * retry path: same scope, same coordination server, same live children, same bounds. */\n readonly continuation?: ContinuationPolicy\n /** Where this manager's continuation files go (`<dir>/<n>/note.md`, `verdict.json`,\n * `panel.jsonl`). Omit to keep them in memory, where `read_continuation` still serves them. */\n readonly continuationDir?: string\n /** The root manager's `root-stream.jsonl`; the question panel reads it as the director's trace. */\n readonly rootStreamPath?: string\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 /** Trusted source refs for this manager’s existing observe_agent capability. */\n readonly sourceEvidenceRefs?: ReadonlyArray<string>\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 /** How Runtime wakes this manager after it ends a turn with work open (both arms). Omit = the\n * defaults in `./wake`. */\n readonly wake?: ManagerWakePolicy\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 /** Composition of each authored child profile before identity is fixed —\n * `CoordinationToolsOptions.composeSpawnProfile`. */\n readonly composeSpawnProfile?: (profile: AgentProfile) => AgentProfile\n /** The run's validated profiles table — `CoordinationToolsOptions.profiles`. */\n readonly profiles?: ReadonlyMap<string, SuperviseProfileEntry>\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 /** See `CoordinationToolsOptions.spawnResourceReader`: the manager's own environment as the\n * source of a by-path resource, for a manager whose workspace is a sandbox this process\n * cannot open. */\n readonly spawnResourceReader?: SpawnResourceReader\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 control directory. Both arms acknowledge worker requests; external managers observe\n * them throughout the harness invocation. See `DriverAgentOptions.controlDir`. */\n readonly controlDir?: string\n /** Durable steer directory when it differs from the run-control directory. */\n readonly steerDir?: 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 registeredProfile =\n deps.registeredProfile === undefined\n ? stableProfile\n : detachedSnapshot(\n agentProfileSchema.parse(deps.registeredProfile),\n 'supervisorAgent registered profile',\n )\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 (harness === null && deps.continuation !== undefined) {\n throw new ValidationError(\n 'supervisorAgent: continuation applies to an EXTERNAL-harness supervisor only (profile.harness ' +\n 'set). A router-brained supervisor runs its own turn loop in process, so the policy would ' +\n 'be silently ignored.',\n )\n }\n if (deps.continuation !== undefined && deps.deliverable === undefined) {\n throw new ValidationError(\n 'supervisorAgent: continuation needs a `deliverable` completion check — with no check there ' +\n 'is no contract that can be unmet',\n )\n }\n if (harness !== null && deps.deliverable !== undefined && deps.continuation === undefined) {\n throw new ValidationError(\n 'supervisorAgent: a manager with a completion check needs a continuation policy (deadline, ' +\n 'maxBarren, the note profile and switches). Runtime supplies no default: how long to send ' +\n \"a director back, and what to tell it, is the record's decision\",\n )\n }\n // One way out: a manager with a check ends when the check passes or when a bound ends it.\n // Refused before any compute, on both arms.\n if (deps.deliverable !== undefined && runtimeToolNames.includes('stop')) {\n throw new ValidationError(\n `supervisorAgent: the profile grants ${coordinationProfileToolPrefix}stop to a manager with a ` +\n 'completion check. Such a manager ends only through submit_result (the check passes) or a ' +\n 'bound (deadline, budget, cancellation, no progress); remove stop from its tools',\n )\n }\n const continuationDeadlineMs =\n deps.continuation === undefined\n ? undefined\n : admitContinuationPolicy(deps.continuation, 'supervisorAgent')\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 // One conversation per agent, whichever driver `act` builds for an attempt.\n const transcript = createRouterTranscript()\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 transcript,\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 ...(deps.preserveOwnerTurns ? { preserveOwnerTurns: true as const } : {}),\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.extraTools ? { extraTools: deps.extraTools } : {}),\n ...(deps.executeExtraTool ? { executeExtraTool: deps.executeExtraTool } : {}),\n ...(deps.analysts ? { analysts: deps.analysts } : {}),\n ...(deps.analyzeOnSettle ? { analyzeOnSettle: deps.analyzeOnSettle } : {}),\n ...(deps.sourceEvidenceRefs ? { sourceEvidenceRefs: deps.sourceEvidenceRefs } : {}),\n ...(deps.escalateQuestion ? { escalateQuestion: deps.escalateQuestion } : {}),\n ...(deps.watchWorkers ? { watchWorkers: deps.watchWorkers } : {}),\n ...(deps.stallAfterMs !== undefined ? { stallAfterMs: deps.stallAfterMs } : {}),\n ...(deps.wake !== undefined ? { wake: deps.wake } : {}),\n ...(deps.continuityByProfile ? { continuityByProfile: deps.continuityByProfile } : {}),\n ...(deps.preflightSpawn ? { preflightSpawn: deps.preflightSpawn } : {}),\n ...(deps.resolveSpawnProfile ? { resolveSpawnProfile: deps.resolveSpawnProfile } : {}),\n ...(deps.composeSpawnProfile ? { composeSpawnProfile: deps.composeSpawnProfile } : {}),\n ...(deps.profiles ? { profiles: deps.profiles } : {}),\n ...(deps.spawnResourceRoot ? { spawnResourceRoot: deps.spawnResourceRoot } : {}),\n ...(deps.spawnResourceReader ? { spawnResourceReader: deps.spawnResourceReader } : {}),\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\n ? { onCoordinationTools: (tools, coordination) => slot.bind(tools, coordination) }\n : {}),\n ...(deps.controlDir === undefined ? {} : { controlDir: deps.controlDir }),\n ...(deps.steerDir === undefined ? {} : { steerDir: deps.steerDir }),\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 harnessTranscript: () => transcript.capture(),\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 rawDeliverReady = driveHarness.deliverReady\n if (rawDeliverReady !== undefined && typeof rawDeliverReady !== 'function') {\n throw new ValidationError(\n 'supervisorAgent: driveHarness.deliverReady must be a function when provided',\n )\n }\n const deliverReady = rawDeliverReady?.bind(driveHarness)\n const wakePolicy = resolveWakePolicy(deps.wake)\n // Set while `act` runs: where a message from this manager's lead goes. A harness with a live\n // inbox takes it inside the running turn; otherwise it is the input of the manager's next wake.\n // Before, a manager on an executor with no inbox refused every steer as `runtime-has-no-inbox`.\n let managerInbox: ((message: unknown) => boolean) | undefined\n // The workers this manager is waiting on, while it waits between turns.\n let waitingOn: number | undefined\n // The coordinator of the running `act`. Its submission is set only once the accepted result is\n // durable, so it is what `resultAccepted` reads.\n let liveCoordinator: { submittedResult(): unknown } | undefined\n const externalAgent: Agent<unknown, unknown> = {\n name,\n deliver(message: unknown): boolean {\n return managerInbox?.(message) ?? false\n },\n resultAccepted: () => Boolean(liveCoordinator?.submittedResult()),\n traceSource: () => driveHarness.traceSource?.(),\n progress: () => {\n const harnessProgress = driveHarness.progress?.()\n if (waitingOn === undefined) return harnessProgress\n return {\n ...harnessProgress,\n note: `waiting for ${waitingOn} worker${waitingOn === 1 ? '' : 's'}; Runtime wakes it when one reports`,\n }\n },\n // Present only when the harness has a transcript port, so an absent one still settles as\n // `executor-exposes-no-transcript` rather than as a capture that did not run.\n ...(driveHarness.harnessTranscript\n ? { harnessTranscript: () => driveHarness.harnessTranscript?.() }\n : {}),\n ...(driveHarness.harnessTranscriptSettled\n ? {\n harnessTranscriptSettled: () =>\n driveHarness.harnessTranscriptSettled?.() ?? Promise.resolve(),\n }\n : {}),\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 const coordinationLifetime = linkAbort(scope.signal)\n let harnessInvocationActive = false\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 // Built once the coordinator exists, because it reads the check's reads from it.\n let keeper: ContinuationKeeper | undefined\n const { handle: mcp, controls } = await serveCoordinationMcpForManager(\n {\n scope,\n blobs: deps.blobs,\n makeWorkerAgent: deps.makeWorkerAgent,\n ...(deps.authorizeDownMessage ? { authorizeDownMessage: deps.authorizeDownMessage } : {}),\n perWorker: deps.perWorker,\n ...(coordination ?? {}),\n ...(context\n ? { identity: { runId: context.runNamespace, actorId: context.ownerId } }\n : {}),\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 ...(deps.continuation\n ? {\n readContinuation: (n: number | undefined) =>\n keeper?.read(n) ?? { found: false, reason: 'no continuation has been sent' },\n }\n : {}),\n onStop: (reason) => {\n if (!stopController.signal.aborted) {\n stopController.abort(reason ?? 'coordination stop')\n }\n },\n ...(deps.analysts ? { analysts: deps.analysts } : {}),\n ...(deps.analyzeOnSettle ? { analyzeOnSettle: deps.analyzeOnSettle } : {}),\n ...(deps.sourceEvidenceRefs ? { sourceEvidenceRefs: deps.sourceEvidenceRefs } : {}),\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 // Fence the awaited event transaction itself. Racing only the control poll would leave\n // its late continuation able to deliver an instruction after the manager stopped.\n onEvent: async (event, record) => {\n await runAbortable(\n async () => {\n await onEvent?.(event, record)\n },\n coordinationLifetime.signal,\n 'supervisor coordination stopped',\n )\n },\n ...(deps.replaySettlements ? { replaySettlements: true } : {}),\n ...(deps.preflightSpawn ? { preflightSpawn: deps.preflightSpawn } : {}),\n ...(deps.resolveSpawnProfile ? { resolveSpawnProfile: deps.resolveSpawnProfile } : {}),\n ...(deps.composeSpawnProfile ? { composeSpawnProfile: deps.composeSpawnProfile } : {}),\n ...(deps.profiles ? { profiles: deps.profiles } : {}),\n ...(deps.spawnResourceRoot ? { spawnResourceRoot: deps.spawnResourceRoot } : {}),\n ...(deps.spawnResourceReader ? { spawnResourceReader: deps.spawnResourceReader } : {}),\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, coordination) => slot.bind(tools, coordination),\n },\n coordinationLifetime.signal,\n ).catch((error: unknown) => {\n coordinationLifetime.abort(error)\n throw error\n })\n ledger = mcp\n liveCoordinator = mcp\n managerInbox = (message) => {\n if (\n deliver !== undefined &&\n harnessInvocationActive &&\n (deliverReady === undefined || deliverReady()) &&\n deliver(message)\n ) {\n return true\n }\n return controls.receiveLeadMessage(message)\n }\n const coordinationTools = slot.descriptors()\n const providerProfile = detachedSnapshot(\n providerVisibleProfile(stableProfile),\n 'supervisorAgent provider-visible profile',\n )\n let controlObserver: ReturnType<typeof observeWorkerControls> | undefined\n try {\n if (deps.controlDir !== undefined || deps.steerDir !== undefined) {\n controlObserver = observeWorkerControls({\n ...(deps.controlDir === undefined ? {} : { dir: deps.controlDir }),\n ...(deps.steerDir === undefined ? {} : { steerDir: deps.steerDir }),\n coord: controls,\n scope,\n signal: coordinationLifetime.signal,\n controlScope: deps.controlScope ?? 'run',\n ...(deps.controlScope === 'subtree'\n ? {}\n : {\n deliverRoot: (message: { steer: string; interrupt: boolean }) =>\n managerInbox?.(message) ?? false,\n // Between turns a root steer is the input of the next wake, so it is always\n // deliverable once the coordinator exists.\n deliverRootReady: () => true,\n }),\n onError: (error) => {\n coordinationLifetime.abort(error)\n stopController.abort(error)\n },\n })\n }\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 continuation = deps.continuation\n if (continuation !== undefined && deps.deliverable !== undefined) {\n keeper = createContinuationKeeper({\n policy: continuation,\n task,\n ...(deps.deliverable.describe === undefined ? {} : { owed: deps.deliverable.describe }),\n ...(deps.deliverable.feedback === undefined\n ? {}\n : { feedback: deps.deliverable.feedback }),\n ...(deps.deliverable.sealed === true ? { sealed: true } : {}),\n reads: () => controls.checkReads(),\n workers: () => {\n const labels = new Map(\n ((scope as Partial<Scope<unknown>>).view?.nodes ?? []).map((node) => [\n node.id,\n node.label,\n ]),\n )\n return mcp\n .settled()\n .map((worker) => ({ id: worker.id, label: labels.get(worker.id) ?? worker.id }))\n },\n ...(deps.continuationDir === undefined ? {} : { dir: deps.continuationDir }),\n traces: () => {\n const rootStreamPath = deps.rootStreamPath\n return runTraceAnalysisStore({\n ...(rootStreamPath === undefined\n ? {}\n : {\n root: {\n id: scope.view.root,\n read: () => readRootStream(dirname(rootStreamPath)),\n },\n }),\n workers: mcp.settled(),\n blobs: deps.blobs,\n })\n },\n canReadMore: runtimeToolNames.includes('read_continuation'),\n canSubmitResult: runtimeToolNames.includes('submit_result'),\n })\n }\n let candidate: unknown\n // The finalizer's check of the best delivered child is a check read like any other: the\n // continuation note reports what the check said about the candidate the run would return.\n const finalizerDeliverable =\n deps.deliverable === undefined\n ? undefined\n : {\n ...deps.deliverable,\n check: async (out: unknown) => {\n let verdict: ReturnType<typeof checkVerdictOf>\n try {\n verdict = checkVerdictOf(await deps.deliverable?.check(out))\n } catch (error) {\n controls.recordCheckRead({\n source: 'turn-end',\n unavailable: error instanceof Error ? error.message : String(error),\n })\n throw error\n }\n controls.recordCheckRead({ source: 'turn-end', verdict })\n return verdict\n },\n }\n const finalize = () =>\n runFinalizer(deps.finalizer ?? bestDelivered, {\n settled: mcp.settled(),\n blobs: deps.blobs,\n tree: runTree(scope),\n budget: scope.budget,\n ...(finalizerDeliverable ? { deliverable: finalizerDeliverable } : {}),\n })\n const readProgress = (): DriverProgressMark => {\n const settled = mcp.settled()\n // Child delivery is progress, but its check may cover only the child's assignment.\n const deliveredCount = settled.filter(\n (w) => w.status === 'done' && w.valid === true,\n ).length\n const submitted = Boolean(mcp.submittedResult())\n const composite = bestComposite(controls.checkReads())\n return {\n poolTokensSpent: baseTokensLeft - scope.budget.tokensLeft,\n settledCount: settled.length,\n submitted,\n deliveredCount,\n contract: !contractDeclared\n ? 'none'\n : submitted || candidate !== undefined\n ? 'met'\n : 'unmet',\n ...(composite === undefined ? {} : { composite }),\n }\n }\n /**\n * The check runs when a turn ends without an accepted result. A read already taken in this\n * turn stands (the manager just heard it); otherwise a check that judges state reads the\n * run now. A check that could not run is not a verdict: the loop pauses.\n */\n const readCheckAtTurnEnd = async (attempt: number): Promise<void> => {\n const deliverable = deps.deliverable\n if (deliverable === undefined) return\n const thisTurn = controls.checkReads().filter((read) => read.attempt === attempt)\n const last = thisTurn.at(-1)\n if (last === undefined && deliverable.checkState !== undefined) {\n try {\n const verdict = checkVerdictOf(await deliverable.checkState())\n controls.recordCheckRead({ source: 'turn-end', verdict })\n return\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n controls.recordCheckRead({ source: 'turn-end', unavailable: message })\n throw new CheckUnavailableError(`the completion check could not run: ${message}`, {\n cause: error,\n })\n }\n }\n if (last?.unavailable !== undefined) {\n throw new CheckUnavailableError(\n `the completion check could not run: ${last.unavailable}`,\n )\n }\n }\n const loopRecords: DriverAttemptRecord[] = []\n let deadlineWarned = false\n const managerStartedAt = Date.now()\n let environmentReplacements = 0\n let workspaceRestores = 0\n const describe = deps.deliverable?.describe\n const settleLoop = () => {\n const stopReason = controls.stopReason() ?? progressStopReason\n const closedBy: DriverContinuationRecord['closedBy'] = mcp.submittedResult()\n ? 'result-accepted'\n : mcp.isStopped()\n ? 'stop'\n : progressStopReason !== undefined\n ? 'stop-rule'\n : undefined\n const blocked = controls.blocked()\n deps.onDriverLoopSettled?.({\n ...summarizeDriverAttempts(loopRecords),\n environmentReplacements,\n workspaceRestores,\n ...(closedBy === undefined ? {} : { closedBy }),\n ...(blocked.length === 0 ? {} : { blocked }),\n ...(stopReason === undefined ? {} : { stopReason }),\n continuations: keeper?.entries() ?? [],\n })\n }\n let driverFailed = true\n try {\n await runDriverWithRetry({\n drive: async (attempt, reentry) => {\n candidate = undefined\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 controls.beginDriverAttempt(attempt)\n // A re-entered drive receives the original objective and the coordinator's run state\n // unless the harness proves the turn continues the same session. The unmet items\n // alone are the whole turn only then: a replacement sandbox knows nothing else.\n const compose =\n reentry === undefined\n ? undefined\n : (continuity: ReentryContinuity) =>\n composeReentryTask({\n originalTask: task,\n tools: runtimeToolNames,\n ...(describe === undefined ? {} : { contract: describe }),\n reentry,\n continuity,\n state: controls.reentryState(),\n attempt,\n })\n harnessInvocationActive = true\n let completed = false\n try {\n await driveHarness({\n profile: providerProfile,\n authoredProfile: stableProfile,\n ...(registeredProfile === stableProfile ? {} : { registeredProfile }),\n ...(profilePrompt !== undefined ? { systemPrompt: profilePrompt } : {}),\n task: compose === undefined ? task : compose(UNPROVEN_CONTINUITY),\n ...(compose === undefined\n ? {}\n : {\n reentry: {\n reason: reentry!,\n compose,\n onContinuity: (continuity: ReentryContinuity) => {\n if (continuity.environment === 'replaced') environmentReplacements += 1\n if (continuity.workspace === 'restored') workspaceRestores += 1\n },\n },\n }),\n scope,\n coordinationMcpUrl: mcp.url,\n coordinationMcpHeaders: mcp.headers,\n stopSignal: stopController.signal,\n coordinationTools,\n })\n completed = true\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 completed = true\n } finally {\n harnessInvocationActive = false\n // A completed turn processed what it received; a failed one leaves it for the next\n // re-entry to name. Recorded before the retry decision reads the run.\n if (completed) await controls.endDriverAttempt('completed')\n else await controls.endDriverAttempt('failed').catch(() => undefined)\n }\n // Decide this parent's completion before the retry loop reads progress. Cache the\n // checked candidate so neither the finalizer nor its oracle runs twice on return.\n // A turn that ended with work open is a wait: the manager decides when it is done.\n if (contractDeclared && !mcp.submittedResult() && !controls.hasOpenWork()) {\n await mcp.drainResolved()\n candidate = await finalize()\n if (candidate === undefined && !mcp.isStopped()) await readCheckAtTurnEnd(attempt)\n }\n },\n progress: readProgress,\n budget: () => scope.budget,\n signal: scope.signal,\n resolvePending: (failure, failures) =>\n abandonScopeRetainedOwnerInvocation(scope, failure, failures),\n wait: {\n open: () =>\n !mcp.submittedResult() &&\n !mcp.isStopped() &&\n progressStopReason === undefined &&\n controls.hasOpenWork(),\n wake: async (nextAttempt) => {\n const deadlineMs = scope.budget.deadlineMs\n const warnAt = deadlineWarningAt(\n deadlineMs,\n wakePolicy,\n deadlineWarned,\n managerStartedAt,\n )\n waitingOn = scope.view.nodes.filter(\n (node) => node.id !== scope.view.root && isLiveNodeStatus(node.status),\n ).length\n try {\n const wake = await controls.awaitWake({\n attempt: nextAttempt,\n // A stop (accepted result, stop rule, the manager's own stop) ends the wait too.\n signal: AbortSignal.any([scope.signal, stopController.signal]),\n heartbeatMs: wakePolicy.heartbeatMs,\n debounceMs: wakePolicy.debounceMs,\n ...(warnAt === undefined ? {} : { deadlineAt: warnAt }),\n })\n if (wake === undefined || stopController.signal.aborted) return undefined\n if (wake.reason === 'deadline') deadlineWarned = true\n return {\n input: composeWakeInput(wake, {\n tools: runtimeToolNames,\n deadlineMs,\n now: Date.now(),\n }),\n idleMs: wake.idleMs,\n }\n } finally {\n waitingOn = undefined\n }\n },\n },\n ...(deps.driverRetry ? { policy: deps.driverRetry } : {}),\n ...(continuation !== undefined && keeper !== undefined && continuationDeadlineMs\n ? {\n continuation: {\n maxBarren: continuation.maxBarren,\n deadlineMs: continuationDeadlineMs,\n compose: (context) => (keeper as ContinuationKeeper).compose(context),\n // A run the coordination server closed ended on purpose — the manager's own\n // `stop` (served only without a check), or a progress stop rule that aborted\n // the stop signal. A continuation would re-enter a harness told to stop.\n closed: () => mcp.isStopped() || progressStopReason !== undefined,\n },\n }\n : {}),\n onAttempt: async (record) => {\n loopRecords.push(record)\n await recordScopeOwnerDriverAttempt(scope, record)\n // A pause on an unavailable upstream is infrastructure time, so the run's own\n // journal records it; the caller's observer still sees every attempt.\n if (record.classification === 'unavailable' && record.retryInMs !== undefined) {\n await recordScopeOwnerPause(scope, {\n attempt: record.attempt,\n signal: record.unavailableSignal ?? 'unavailable',\n cause: record.error ?? '',\n attemptMs: record.durationMs,\n pauseMs: record.retryInMs,\n madeProgress: record.madeProgress,\n })\n }\n await deps.onDriverAttempt?.(record)\n },\n })\n driverFailed = false\n } finally {\n await driveHarness.closeSeatSegment?.(\n scope.signal.aborted ? 'cancelled' : driverFailed ? 'failed' : 'completed',\n )\n settleLoop()\n }\n // Without a parent oracle, preserve the single finalization after the driver finishes.\n if (!contractDeclared) 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 await mcp.finishAnalysis({ status: 'done', output: submitted.result })\n return submitted.result\n }\n if (contractDeclared) {\n await mcp.finishAnalysis({ status: 'done', output: candidate })\n return candidate\n }\n const finalized = await finalize()\n if (finalized !== undefined) {\n await mcp.finishAnalysis({ status: 'done', output: finalized })\n return finalized\n }\n // An unchecked child may do direct work. Retain its terminal report through the same\n // settlement and blob reader, without treating native completion as quality acceptance.\n const harnessResult = driveHarness.resultArtifact?.()\n if (\n nodeContextSeed !== undefined &&\n nodeContextSeed.depth > 0 &&\n harnessResult?.out !== undefined &&\n harnessResult.out !== null\n ) {\n deps.onUnassessedOutput?.(harnessResult.out)\n await mcp.finishAnalysis({ status: 'done', output: harnessResult.out })\n return harnessResult.out\n }\n await mcp.finishAnalysis({ status: 'done' })\n return undefined\n } catch (error) {\n await mcp.finishAnalysis({\n status: 'down',\n reason: error instanceof Error ? error.message : String(error),\n })\n throw error\n } finally {\n managerInbox = undefined\n coordinationLifetime.abort(new Error('supervisor manager stopped'))\n try {\n await controlObserver?.close()\n } finally {\n await mcp.close()\n }\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 { isAsyncIterable, sleep } from '../util'\nimport { teardownSurfaces } from './deadline'\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.harnessTranscript ? { harnessTranscript: () => inner.harnessTranscript?.() } : {}),\n ...(inner.harnessTranscriptSettled\n ? { harnessTranscriptSettled: () => inner.harnessTranscriptSettled?.() ?? Promise.resolve() }\n : {}),\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<UsageEvent>(first)\n ? retryStream(first, restart, signal)\n : retryOneShot(first, restart, signal)\n },\n teardown: (grace) => inner.teardown(grace),\n ...teardownSurfaces(inner),\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<UsageEvent>(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<UsageEvent>(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\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 sleep(ms, signal)\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 */\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 ReasoningEffort,\n type Sha256Digest,\n validateAgentProfileSecurity,\n} from '@tangle-network/agent-interface'\nimport { withProfileKb } from '@tangle-network/agent-interface/profile-kb'\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, RuntimeRunStateError, ValidationError } from '../../errors'\nimport {\n type AnalystRegistry,\n type AnalyzeOnSettleRoute,\n type AuthorizeDownMessage,\n type AuthorizedDownMessage,\n type ContinuityMode,\n type CoordinationEvent,\n coordinationVerbNames,\n type DownMessageAuthorizationInput,\n type EscalateQuestion,\n type MakeWorkerAgent,\n type SpawnPreflight,\n type SuperviseProfileEntry,\n type WorkerSpawnContext,\n type WorkerWatchOptions,\n} from '../../mcp/tools/coordination'\nimport { COORDINATION_CLIENT_TOOL_TIMEOUT_MS } from '../../mcp/tools/coordination-request-context'\nimport { composeRuntimeHooks, type RuntimeHooks } from '../../runtime-hooks'\nimport { resolveAgentEnvironmentProvider } from '../environment-provider'\nimport { agentHarness, harnessRunsAgent } from '../harness-role'\nimport {\n type HarnessTranscriptCapture,\n persistHarnessTranscript,\n readHarnessTranscript,\n} from '../harness-transcript'\nimport type { RouterTransportConfig } from '../router-client'\nimport type { ToolLoopChat, ToolLoopCompactionOptions } from '../tool-loop'\nimport {\n addSpend as addRetainedSpend,\n sleep as runtimeSleep,\n unmeteredSpend,\n zeroSpend,\n} from '../util'\nimport { RunCancellationReason } from './abortable'\nimport { assertValidBudget, meterUsageEvent, newUsageTotals, spendFromUsageTotals } from './budget'\nimport { type DeliverableSpec, gateOnDeliverable } from './completion-gate'\nimport { CONTINUATIONS_DIR, type ContinuationPolicy } from './continuation'\nimport { isLoopbackHost } from './coordination-mcp'\nimport { DEFAULT_SUCCESSFUL_SHUTDOWN_MS, type DeadlineCheckIn, teardownExecutor } from './deadline'\nimport { driverChild, driverExecutorFactory, isDriverSpec } from './driver-executor'\nimport {\n type DriverAttemptRecord,\n type DriverContinuationRecord,\n type DriverRetryPolicy,\n HarnessTurnFailedError,\n} from './driver-retry'\nimport { errMessage } from './error-message'\nimport type { BusRecord } from './event-bus'\nimport { executorFailure } from './executor-outcome'\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 { createActivityLog } from './progress'\nimport { type ReentryContinuity, UNPROVEN_CONTINUITY } from './reentry'\nimport { addResourceSpend, resourceTelemetry, withBudgetResources } from './resources'\nimport { registerRetainedExecutorPreparation, retainedExecutorSeamKey } from './retained-executor'\nimport {\n beginScopeRetainedOwnerDrive,\n bindScopeRetainedOwnerEnvironmentId,\n bindScopeRetainedOwnerProvider,\n consumeScopeRetainedOwnerResult,\n prepareScopeRetainedOwnerSeatSwitch,\n prepareScopeRetainedOwnerTask,\n reconcileScopeRetainedOwnerEnvironment,\n scopeRetainedOwnerContext,\n scopeRetainedOwnerJournalRoot,\n scopeRetainedOwnerPriorSpend,\n scopeRetainedOwnerRestorePoint,\n scopeRetainedOwnerResult,\n scopeRetainedOwnerTurnEnded,\n} from './retained-scope-owner'\nimport { createRootStreamSink, ROOT_STREAM_FILE, type RootStreamSink } from './root-stream'\nimport { watchRunCancellation } from './run-cancellation'\nimport {\n createFileRunContext,\n createInMemoryRunContext,\n type RunContext,\n withRunContext,\n} 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 assertRecursiveReservationPolicy,\n deriveNodeExecutionIdentity,\n meterRuntimeOwnedAccounting,\n meterRuntimeOwnedProviderAttempt,\n recordScopeOwnerMaterialization,\n restoreScopeOwnerAcceptedExecution,\n scopeOwnerExecutorNodeContext,\n} from './scope'\nimport {\n type ActiveSeat,\n authoredSeatStages,\n SeatChain,\n SeatChainExhaustedError,\n type SeatSegment,\n type SelectSeat,\n seatExecutionProfile,\n} from './seat-chain'\nimport { detachedSnapshot } from './snapshot'\nimport { type PlateauOptions, plateau, type StopRule } from './stop-rules'\nimport { createRootHandle, createSupervisor, DEFAULT_MAX_DEPTH } 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 ExecutorProgressEvent,\n ExecutorResult,\n NodeExecutionIdentity,\n ProviderModelAttemptEvidence,\n ProviderModelExecutionEvidence,\n RecursiveReservationPolicy,\n ResultBlobStore,\n RootHandle,\n RootProviderModelEvidence,\n RootSegment,\n RootStreamReceipt,\n Scope,\n SpawnJournal,\n Spend,\n SupervisedResult,\n UsageEvent,\n} from './types'\nimport type { ManagerWakePolicy } from './wake'\nimport {\n type WorkerSpawnRetryAttempt,\n type WorkerSpawnRetryPolicy,\n withWorkerSpawnRetry,\n} from './worker-retry'\nimport type { WorkerSlots } from './worker-slots'\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 */\n/** The child with its manager's Runtime coordination grants, unless the child's author wrote any\n * coordination entry: an explicit grant or refusal is the author's choice and stands. A refusal\n * (`false`) grants nothing, so it is removed once it has decided the child stays a leaf; a\n * harness-less leaf carries no tools axis at all. */\nfunction withInheritedSpawnRights(parent: AgentProfile, child: AgentProfile): AgentProfile {\n const childTools = child.tools ?? {}\n const authored = Object.entries(childTools).filter(([name]) =>\n name.startsWith(coordinationProfileToolPrefix),\n )\n if (authored.length > 0) {\n if (authored.every(([, enabled]) => enabled !== false)) return child\n const kept = Object.entries(childTools).filter(\n ([name, enabled]) => !(name.startsWith(coordinationProfileToolPrefix) && enabled === false),\n )\n const { tools: _tools, ...rest } = child\n return agentProfileSchema.parse(\n kept.length === 0 ? rest : { ...rest, tools: Object.fromEntries(kept) },\n )\n }\n const inherited = Object.entries(parent.tools ?? {}).filter(\n ([name, enabled]) =>\n enabled === true &&\n name.startsWith(coordinationProfileToolPrefix) &&\n coordinationVerbNameSet.has(name.slice(coordinationProfileToolPrefix.length)),\n )\n if (!inherited.some(([name]) => name === `${coordinationProfileToolPrefix}spawn_worker`)) {\n return child\n }\n // A worker that becomes a manager must still be able to deliver work it does itself.\n return agentProfileSchema.parse({\n ...child,\n tools: {\n ...childTools,\n ...Object.fromEntries(inherited),\n [`${coordinationProfileToolPrefix}submit_result`]: true,\n },\n })\n}\n\nconst coordinationVerbNameSet: ReadonlySet<string> = new Set<string>(coordinationVerbNames)\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\n/**\n * A manager keeps a dedicated environment. It serves its coordination credential through\n * create-time environment, and every co-tenant of a shared box could read it.\n */\nfunction managerExecutorConfig(config: ExecutorConfig): ExecutorConfig {\n if (config.backend !== 'provider' || config.shared === undefined) return config\n const { shared: _shared, ...dedicated } = config\n return Object.freeze(dedicated)\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/**\n * A manager waits between turns, and a wake can come much later than five minutes after its last\n * turn. Claude Code 2.1.289 writes its prompt cache with a five-minute lifetime unless this variable\n * is set; a wake after the cache expired re-writes the manager's whole context, about 140K tokens\n * per turn on a Discovery root measured 2026-10-05. That root ran on a subscription and already\n * wrote one-hour entries; the variable makes the hour hold for every claude-code manager, whatever\n * its credential. A value the caller set wins.\n */\nconst CLAUDE_CODE_ONE_HOUR_CACHE = 'ENABLE_PROMPT_CACHING_1H'\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 rootStream?: RootStreamSink,\n seatSelection?: {\n readonly select: SelectSeat\n readonly journal: SpawnJournal\n readonly rootId: string\n readonly onSegment: (\n nodeId: string,\n segment: SeatSegment,\n phase: 'started' | 'ended',\n ) => Promise<void>\n readonly onPause: (\n nodeId: string,\n resumeAt: string,\n phase: 'paused' | 'resumed',\n ) => Promise<void>\n },\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 = managerExecutorConfig(\n captureReusableExecutorConfig(backend, 'driveHarnessFromBackend'),\n )\n let boundBackend = bindReusableExecutorExecutionId(capturedBackend, executionId)\n let baseFactory = createExecutor(boundBackend)\n let ownerRuntime =\n boundBackend.backend === 'provider'\n ? (boundBackend.runtime ??\n resolveAgentEnvironmentProvider(boundBackend.provider, boundBackend.registry).name)\n : 'cli'\n let activeExecutor: Executor<unknown> | undefined\n // What this manager's harness has been doing, from the progress events its drives stream. An\n // executor that keeps no activity log of its own (a provider) otherwise reads as idle to the\n // lead that observes it: measured 2026-10-05, a director mid-turn read `turns: 0`, `idleMs`\n // 463967, `stalled: true`.\n const driveActivity = createActivityLog()\n let driveTurns = 0\n const noteDriveProgress = (event: ExecutorProgressEvent): void => {\n const at = Date.now()\n if (event.kind === 'tool_call') {\n driveActivity.push({ at, kind: 'tool', label: event.toolName })\n } else if (event.kind === 'tool_result') {\n driveActivity.push({ at, kind: 'tool', label: event.toolName, status: 'ok' })\n } else if (event.kind === 'text_delta' || event.kind === 'reasoning_delta') {\n const last = driveActivity.last()\n // One note per stretch of model output, refreshed every 30 s, so deltas cannot flood the ring.\n if (last === undefined || last.kind !== 'turn' || at - last.at > 30_000) {\n driveActivity.push({ at, kind: 'turn', label: 'model output' })\n }\n }\n }\n // The manager's own harness session, as the newest attempt captured it.\n let managerTranscript: HarnessTranscriptCapture | undefined\n let managerArtifact: ExecutorResult<unknown> | undefined\n const committedTranscriptDigest = (artifact: ExecutorResult<unknown> | undefined): string => {\n if (artifact === undefined)\n return 'Prior committed transcript: no bounded turn content was captured.'\n const out = artifact.out\n if (out === null || typeof out !== 'object') {\n return `Prior committed transcript ref: ${artifact.outRef}; no structured turn content was captured.`\n }\n const record = out as { content?: unknown; events?: unknown }\n const events = Array.isArray(record.events) ? record.events : []\n const kinds = events.slice(-16).flatMap((event) => {\n if (event === null || typeof event !== 'object') return []\n const kind = (event as { type?: unknown }).type\n return typeof kind === 'string' ? [kind.slice(0, 80)] : []\n })\n const content = typeof record.content === 'string' ? record.content.slice(-4_000) : ''\n return [\n `Prior committed transcript ref: ${artifact.outRef}; ${events.length} events captured.`,\n ...(kinds.length > 0 ? [`Recent event kinds: ${kinds.join(', ')}.`] : []),\n ...(content ? [`Last captured answer excerpt: ${content}`] : []),\n ].join('\\n')\n }\n let seatChain: SeatChain | undefined\n let activeSeat: ActiveSeat | undefined\n let switchedProviderCheckpointAt: string | undefined\n const drive: DriveHarness = async ({\n profile,\n authoredProfile,\n registeredProfile,\n task,\n scope,\n coordinationMcpUrl,\n coordinationMcpHeaders,\n stopSignal,\n coordinationTools,\n reentry,\n }) => {\n const priorCommittedArtifact = managerArtifact\n managerArtifact = undefined\n switchedProviderCheckpointAt = undefined\n const stages = authoredSeatStages(authoredProfile)\n if (stages !== undefined) {\n if (!seatSelection) {\n throw new ValidationError('AgentProfile.seats requires SuperviseOptions.selectSeat')\n }\n if (activeSeat === undefined) {\n // A coordinator crash after a provider committed a failed turn must restore that exact\n // outcome before selecting a replacement. No new seat may start while the old call is\n // still in doubt, and the next retry carries the typed usage-limit reason.\n const accepted = await scopeRetainedOwnerResult(scope)\n const reported = accepted === undefined ? undefined : executorFailure(accepted)\n if (reported !== undefined) {\n await restoreScopeOwnerAcceptedExecution(scope)\n consumeScopeRetainedOwnerResult(scope)\n managerArtifact = accepted\n throw new HarnessTurnFailedError(ownerRuntime, reported)\n }\n }\n const seatJournalRoot = scopeRetainedOwnerJournalRoot(scope) ?? seatSelection.rootId\n seatChain ??= new SeatChain(\n authoredProfile,\n scope.view.root,\n seatJournalRoot,\n seatSelection.journal,\n seatSelection.select,\n now,\n (segment, phase) => seatSelection.onSegment(scope.view.root, segment, phase),\n async (selection, previous) => {\n if (previous && previous.seat !== selection.seat) {\n const sameEnvironment =\n previous.provider === selection.stage.provider &&\n previous.harness === selection.stage.harness\n const checkpoint = await prepareScopeRetainedOwnerSeatSwitch(\n scope,\n sameEnvironment ? 'same-environment' : 'replace-environment',\n )\n if (!sameEnvironment) switchedProviderCheckpointAt = checkpoint.checkpointAt\n }\n },\n )\n const usageLimit =\n reentry?.reason.reason === 'upstream-unavailable' &&\n reentry.reason.signal === 'subscription-usage-limit'\n if (activeSeat === undefined || usageLimit) {\n let afterRecheck = false\n for (;;) {\n try {\n activeSeat = await seatChain.next(usageLimit && !afterRecheck, afterRecheck)\n if (afterRecheck) await seatSelection.onPause(scope.view.root, '', 'resumed')\n break\n } catch (error) {\n if (!(error instanceof SeatChainExhaustedError)) throw error\n await seatSelection.journal.appendEvent(seatJournalRoot, {\n kind: 'seat-paused',\n id: scope.view.root,\n resumeAt: error.resumeAt,\n seq: Date.parse(error.resumeAt),\n at: new Date(now()).toISOString(),\n })\n await seatSelection.onPause(scope.view.root, error.resumeAt, 'paused')\n const waitMs = Math.max(1_000, Date.parse(error.resumeAt) - now())\n await runtimeSleep(waitMs, scope.signal, false)\n afterRecheck = true\n }\n }\n boundBackend = bindReusableExecutorExecutionId(\n managerExecutorConfig(\n captureReusableExecutorConfig(\n {\n ...activeSeat.backend,\n // Let the supervisor see a terminal typed usage limit. The provider executor's\n // default unavailable loop would otherwise retry this seat inside one invocation.\n unavailablePause: false,\n },\n 'selectSeat',\n ),\n ),\n `${executionId}:segment:${activeSeat.segmentIndex}`,\n )\n baseFactory = createExecutor(boundBackend)\n ownerRuntime =\n boundBackend.backend === 'provider'\n ? (boundBackend.runtime ??\n resolveAgentEnvironmentProvider(boundBackend.provider, boundBackend.registry).name)\n : 'cli'\n }\n }\n const retainedOwner =\n boundBackend.backend === 'provider' ? scopeRetainedOwnerContext(scope) : undefined\n if (retainedOwner && boundBackend.backend === 'provider') {\n bindScopeRetainedOwnerProvider(\n scope,\n resolveAgentEnvironmentProvider(boundBackend.provider, boundBackend.registry),\n boundBackend.workspaceRetention === undefined\n ? undefined\n : { port: boundBackend.workspaceRetention, profile },\n )\n // The manager's current box, for a spawn that names a resource by path. Read from the\n // active executor's receipt at spawn time, not captured: the environment does not exist\n // yet here, and a retry re-enters `drive` with a fresh executor.\n bindScopeRetainedOwnerEnvironmentId(scope, () => {\n if (activeExecutor === undefined) return undefined\n const execution = runtimeOwnedExecutorMaterialization(activeExecutor)?.execution\n return execution?.kind === 'environment' ? execution.id : undefined\n })\n // The workspace capture the previous turn handed over reads the environment this turn\n // would change, and its receipt belongs to that turn's invocation: it finishes first.\n await scopeRetainedOwnerTurnEnded(scope)\n }\n // What this drive continues decides what a re-entered driver must be told. Only a proven\n // same-session turn gets the unmet items alone; a replacement environment gets the objective\n // and the coordinator's run state.\n let driveTask = task\n if (reentry !== undefined) {\n const continuity: ReentryContinuity =\n switchedProviderCheckpointAt === undefined\n ? await reentryContinuity(boundBackend, scope, retainedOwner !== undefined)\n : {\n session: 'new',\n environment: 'replaced',\n workspace: 'restored',\n checkpointAt: switchedProviderCheckpointAt,\n }\n if (\n activeSeat?.previous &&\n activeSeat.previous.seat !== activeSeat.seat &&\n activeSeat.previous.provider === activeSeat.stage.provider &&\n activeSeat.previous.harness === activeSeat.stage.harness &&\n (continuity.session !== 'continued' || continuity.environment !== 'same')\n ) {\n throw new ValidationError('same-provider seat continuation lost its native environment')\n }\n reentry.onContinuity?.(continuity)\n driveTask = reentry.compose(continuity)\n if (\n activeSeat?.previous &&\n (activeSeat.previous.provider !== activeSeat.stage.provider ||\n activeSeat.previous.harness !== activeSeat.stage.harness)\n ) {\n driveTask = [\n String(driveTask),\n '',\n '## Harness handoff',\n '',\n 'This is the same logical agent in a different harness or provider. Read the restored workspace,',\n 'especially its STATE, NEXT, and RESULT pages and knowledge pages, before acting.',\n 'A prior tool call may have executed. Check its committed output or workspace effect',\n 'before repeating it.',\n committedTranscriptDigest(priorCommittedArtifact),\n ].join('\\n')\n }\n }\n const originalTask = retainedOwner\n ? await prepareScopeRetainedOwnerTask(scope, driveTask)\n : driveTask\n const acceptedOwner = retainedOwner ? await scopeRetainedOwnerResult(scope) : undefined\n if (acceptedOwner) {\n await restoreScopeOwnerAcceptedExecution(scope)\n consumeScopeRetainedOwnerResult(scope)\n // A committed turn that failed is replayed as the failure it was, not as a delivered turn.\n // Its evidence is restored above, so the retry loop's next attempt starts a new invocation\n // in the same environment instead of this resume ending on the failed result.\n const replayedFailure = executorFailure(acceptedOwner)\n if (replayedFailure !== undefined) {\n throw new HarnessTurnFailedError(ownerRuntime, replayedFailure)\n }\n // The coordination journal still goes through the normal driver finalizer.\n managerArtifact = acceptedOwner\n return\n }\n const initialBudget = scope.budget\n const hasLiveCoordination = scope.view.inFlight > 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(\n activeSeat\n ? seatExecutionProfile(canonicalDriverProfile, activeSeat.stage)\n : canonicalDriverProfile,\n )\n if (activeSeat) {\n assertExecutableAgentProfile(expectedProviderProfile, 'selected seat')\n assertBackendProfileMaterialization(expectedProviderProfile, boundBackend, 'selected seat')\n assertBridgeProfileMaterializes(expectedProviderProfile, boundBackend, 'selected seat')\n }\n const providerDriverProfile = activeSeat\n ? expectedProviderProfile\n : 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 // The harness is asked for a 300 s tool-call timeout so a fenced tool can hold its response\n // longer than the 60 s harness default; a sidecar that applies it says so on each request.\n const attachment = {\n transport: 'http' as const,\n url: coordinationMcpUrl,\n ...(coordinationMcpHeaders ? { headers: coordinationMcpHeaders } : {}),\n metadata: { toolTimeoutMs: COORDINATION_CLIENT_TOOL_TIMEOUT_MS },\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: {\n ...(providerDriverProfile.harness === 'claude-code'\n ? { [CLAUDE_CODE_ONE_HOUR_CACHE]: '1' }\n : {}),\n ...(boundBackend.defaults?.env ?? {}),\n [credentialName]: authorization.slice(7),\n },\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 metadata: { toolTimeoutMs: COORDINATION_CLIENT_TOOL_TIMEOUT_MS },\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 // The check stops a driver that would run on past its budget or deadline. A stopped manager\n // is already ending this turn, and throwing here would discard the result it committed.\n if (effectiveStopSignal?.aborted === true) return\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 // Set when the turn reached its terminal result and that result reported failure. The turn\n // still COMPLETED: its accounting and materialization are captured and its environment is\n // released exactly as a successful turn's is. Only after that does it become a driver failure.\n let turnFailure: HarnessTurnFailedError | undefined\n let terminalArtifact: ExecutorResult<unknown> | undefined\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: the registered one, across every segment of the run.\n authoredProfile:\n registeredProfile === undefined\n ? canonicalDriverProfile\n : agentProfileSchema.parse(registeredProfile),\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 // The owner's release waits for this drive to end its turn, so it reads the turn's receipt.\n const endDrive = retainedOwner ? beginScopeRetainedOwnerDrive(scope) : () => {}\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 // The stream file opens at the first attempt that actually runs an executor, so a resumed\n // owner whose accepted result was restored above leaves it untouched.\n await rootStream?.beginAttempt()\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 driveTurns += 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: it is\n // retained in the run directory as it arrives and never reaches a meter.\n rootStream?.append(event.progress)\n noteDriveProgress(event.progress)\n } else {\n pendingUsage.push(event)\n }\n }\n await meterPending()\n // `resultArtifact()` is typed without the envelope outcome; scope's child settlement reads\n // the same artifact through the same widening.\n const artifact = executor.resultArtifact() as ExecutorResult<unknown>\n terminalArtifact = artifact\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 const reported = executorFailure(artifact)\n if (reported !== undefined)\n turnFailure = new HarnessTurnFailedError(executor.runtime, reported)\n } else {\n const artifact = await run\n terminalArtifact = artifact\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 const reported = executorFailure(artifact)\n if (reported !== undefined)\n turnFailure = new HarnessTurnFailedError(executor.runtime, reported)\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 pool can reject before updating its readout. Preserve the provider diagnosis,\n // but keep failed accounting terminal even when the original failure was transient.\n failure = new RuntimeRunStateError(\n `${errMessage(failure)}; accounting failed: ${errMessage(error)}`,\n { cause: failure },\n )\n }\n }\n try {\n if (!retainedOwner?.preserveEnvironment || retainedOwner.admissions.length === 0) {\n await teardownOnce(completed ? DEFAULT_SUCCESSFUL_SHUTDOWN_MS : 'brutalKill')\n }\n } catch (error) {\n if (!failed) {\n failed = true\n failure = error\n }\n }\n // The provider executor reads the session store at the end of its stream, before any\n // teardown. A later attempt in the same environment reads that store again, longer, so the\n // newest capture wins; a capture never gives way to an attempt that captured nothing.\n const capture = executor.harnessTranscript?.()\n if (\n capture !== undefined &&\n (capture.status !== 'unavailable' ||\n managerTranscript?.status === 'unavailable' ||\n managerTranscript === undefined)\n ) {\n managerTranscript = capture\n }\n if (activeExecutor === executor) activeExecutor = undefined\n endDrive()\n }\n if (failed) throw failure\n if (turnFailure !== undefined) {\n managerArtifact = terminalArtifact\n throw turnFailure\n }\n managerArtifact = terminalArtifact\n }\n drive.resultArtifact = () => managerArtifact\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.deliverReady = (): boolean => activeExecutor !== undefined\n drive.traceSource = () => activeExecutor?.traceSource?.()\n drive.progress = () => {\n const fromExecutor = activeExecutor?.progress?.()\n const own = driveActivity.read()\n const recentActivity = [...(fromExecutor?.recentActivity ?? []), ...own]\n .sort((a, b) => a.at - b.at)\n .slice(-12)\n return {\n ...fromExecutor,\n turns: Math.max(fromExecutor?.turns ?? 0, driveTurns),\n ...(recentActivity.length > 0 ? { recentActivity } : {}),\n }\n }\n // Only the provider backend has a transcript port. Any other backend leaves the method off, so\n // its managers keep settling as `executor-exposes-no-transcript`.\n if (boundBackend.backend === 'provider') {\n drive.harnessTranscript = () => managerTranscript ?? activeExecutor?.harnessTranscript?.()\n drive.harnessTranscriptSettled = () =>\n activeExecutor?.harnessTranscriptSettled?.() ?? Promise.resolve()\n }\n drive.closeSeatSegment = async (reason) => {\n await seatChain?.close(reason)\n }\n return attestRuntimeOwnedScopeOwner(drive, ownerRuntime)\n}\n\n/**\n * What the next drive of a harness-brained manager continues, as far as its backend proves it.\n *\n * A bridge reattaches the harness session by its durable execution id. A retained provider owner\n * continues in the environment it last used while the provider still holds it, and a deliberate\n * later invocation there continues the same harness session. A provider without retained control\n * creates a new environment for every drive and releases the old one. Anything else is unproven.\n */\nasync function reentryContinuity(\n backend: ExecutorConfig,\n scope: Scope<unknown>,\n retainedOwner: boolean,\n): Promise<ReentryContinuity> {\n if (backend.backend === 'bridge') {\n return { session: 'continued', environment: 'same', workspace: 'kept' }\n }\n if (backend.backend !== 'provider' || !retainedOwner) return UNPROVEN_CONTINUITY\n const provider = resolveAgentEnvironmentProvider(backend.provider, backend.registry)\n const capabilities = await provider.capabilities()\n if (capabilities.retainedControl === undefined) {\n return { session: 'new', environment: 'replaced', workspace: 'lost' }\n }\n const environment = await reconcileScopeRetainedOwnerEnvironment(scope)\n if (environment.state === 'live') {\n return {\n session: 'continued',\n environment: 'same',\n environmentId: environment.environmentId,\n workspace: 'kept',\n }\n }\n if (environment.state === 'lost') {\n // The replacement starts from the lost environment's latest checkpoint when there is one.\n const restorePoint = await scopeRetainedOwnerRestorePoint(scope)\n return {\n session: 'new',\n environment: 'replaced',\n previousEnvironmentId: environment.environmentId,\n ...(restorePoint === undefined\n ? { workspace: 'lost' as const }\n : { workspace: 'restored' as const, checkpointAt: restorePoint.takenAt }),\n }\n }\n return UNPROVEN_CONTINUITY\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: construction stays the caller's,\n * lookup stays lazy, and a table backed by a file, a plugin loader, or a plain object all\n * satisfy one interface. */\nexport interface SuperviseRegistryTable<T> {\n resolve(name: string): T | undefined\n /** The names the table holds. The three code-valued tables may omit it, because a caller names\n * their entries from data it already has. The profiles table must list them, because a\n * director can choose only from a menu it can read. */\n names?(): readonly string[]\n}\n\n/**\n * The name→value tables that make the three CODE-valued options expressible as run DATA, and the\n * profiles a director may spawn by name.\n *\n * `deliverable` / `finalizer` / `analysts` 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 *\n * `profiles` is the profiles table: named AgentProfiles that every manager in the tree may spawn\n * with `spawn_worker({ profile: '<name>' })` instead of retyping them. The table is read once, when\n * `supervise` is called: each entry is validated like a root profile and frozen, so every spawn by\n * a name starts from the same bytes. Unless `profileGuidance` or `authorizeSpawn` rewrites the\n * profile, the journal records the entry's digest for the child. Omit the table, or list no names,\n * and nothing about the run changes: `spawn_worker` keeps its object-only `profile`.\n */\nexport interface SuperviseRegistry {\n readonly deliverables?: SuperviseRegistryTable<DeliverableSpec<unknown>>\n readonly finalizers?: SuperviseRegistryTable<SupervisorFinalizer>\n readonly analysts?: SuperviseRegistryTable<AnalystRegistry>\n readonly profiles?: SuperviseRegistryTable<SuperviseProfileEntry> & {\n names(): readonly string[]\n }\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('analysts',\n * 'deliverables', …)` does not compile. */\ninterface SuperviseRegistryTableFor {\n readonly deliverable: 'deliverables'\n readonly finalizer: 'finalizers'\n readonly analysts: 'analysts'\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\n/** Read the profiles table once, before anything is built or spent, and freeze what it returns.\n * Every entry must parse as an AgentProfile (the schema refuses a credential written as a public\n * value), be executable, use an allowed model, and carry its table name as `profile.name`.\n * `assertMountable` applies the spawn path's own mount checks, so an entry that can never be\n * mounted fails here instead of after a director spent a turn on it. A promoted entry's decision\n * must promote, and a treatment arm of its sealed play must name the entry's canonical digest;\n * the seal itself is verified by {@link verifyProfilePromotions}. An empty table is no table. */\nfunction snapshotProfileTable(\n table: SuperviseRegistry['profiles'],\n allowedModels: readonly string[] | undefined,\n assertMountable: ((profile: AgentProfile, context: string) => void) | undefined,\n): ReadonlyMap<string, SuperviseProfileEntry> | undefined {\n if (table === undefined) return undefined\n if (typeof table.names !== 'function' || typeof table.resolve !== 'function') {\n throw new ConfigError(\n 'supervise: opts.registry.profiles must implement resolve(name) and names(): a director ' +\n 'can spawn only the names it is shown',\n )\n }\n const entries = new Map<string, SuperviseProfileEntry>()\n for (const name of table.names()) {\n const at = `opts.registry.profiles ${JSON.stringify(name)}`\n if (typeof name !== 'string' || name.trim().length === 0 || name !== name.trim()) {\n throw new ConfigError(`supervise: ${at} is not a non-empty trimmed name`)\n }\n if (entries.has(name)) throw new ConfigError(`supervise: ${at} is listed twice`)\n const entry = table.resolve(name)\n if (entry === undefined) {\n throw new ConfigError(`supervise: ${at} is listed, but the table resolved no entry under it`)\n }\n const parsed = agentProfileSchema.safeParse(entry.profile)\n if (!parsed.success) {\n throw new ValidationError(\n `supervise: ${at} is not a valid AgentProfile: ${parsed.error.message}`,\n )\n }\n const profile = freezeDetached(parsed.data)\n if (profile.name !== name) {\n throw new ValidationError(\n `supervise: ${at} holds profile.name ${JSON.stringify(profile.name)}; a table entry is ` +\n 'spawned and continued by its name, so the two must be equal',\n )\n }\n assertExecutableAgentProfile(profile, `supervise: ${at}`)\n assertProfileModelsAllowed(profile, allowedModels)\n assertMountable?.(profile, `supervise: ${at} would be refused at mount`)\n const promotion = entry.promotion\n if (promotion !== undefined) {\n if (promotion.decision?.promote !== true) {\n throw new ValidationError(\n `supervise: ${at} cites a PairedPromotionDecision that did not promote; list it ` +\n 'without promotion to run it as exploratory',\n )\n }\n const digest = canonicalAgentProfileDigest(profile)\n const arms = promotion.experiment?.spec?.arms ?? []\n if (!arms.some((arm) => arm.role === 'treatment' && arm.profileDigest === digest)) {\n throw new ValidationError(\n `supervise: ${at} cites sealed play ` +\n `${JSON.stringify(promotion.experiment?.spec?.id)}, but no treatment arm of it names ` +\n `this profile's digest ${digest}`,\n )\n }\n }\n entries.set(\n name,\n Object.freeze({\n profile,\n ...(promotion === undefined ? {} : { promotion: freezeDetached(promotion) }),\n }),\n )\n }\n return entries.size === 0 ? undefined : entries\n}\n\n/** Verify the seal of every promoted profiles-table entry. Eval's seal check is asynchronous, so it\n * runs at the start of the run, before the first model call; a broken seal refuses the run. */\nasync function verifyProfilePromotions(\n table: ReadonlyMap<string, SuperviseProfileEntry> | undefined,\n): Promise<void> {\n const promoted = [...(table ?? [])].filter(([, entry]) => entry.promotion !== undefined)\n if (promoted.length === 0) return\n const { verifySealedExperiment } = await import('@tangle-network/agent-eval/experiment')\n for (const [name, entry] of promoted) {\n if (!(await verifySealedExperiment(entry.promotion!.experiment))) {\n throw new ValidationError(\n `supervise: opts.registry.profiles ${JSON.stringify(name)} cites a sealed play whose ` +\n 'digest does not match its spec',\n )\n }\n }\n}\n\nexport interface SuperviseOptions {\n /** Whole-run persistence and ownership. SQL contexts are acquired before replay and compute. */\n readonly runContext?: RunContext\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 /** Resolve an authored subscription stage to one eligible seat and a backend pinned to its\n * credential reference. The callback may report stage exhaustion with `resumeAt`; Runtime\n * advances the authored chain and never writes credentials into its record. */\n readonly selectSeat?: SelectSeat\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`, or `null` to omit this child's assignment check and continuation.\n * Null does not turn completion into acceptance or erase existing backend/descendant verdicts.\n * An unchecked child must declare compatible tools: disable inherited spawn rights and author its\n * coordination grants without `submit_result` or `read_continuation`. Explicit incompatible\n * grants remain refused; the authorized profile is never rewritten after this callback. */\n readonly resolveDeliverable?: (\n input: DeliverableResolutionInput,\n ) => DeliverableSpec<unknown> | null | 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 /** Reconstruct executors for interrupted children on resume, for a run that owns its worker\n * factory (`makeWorkerAgent`/`makeLeafAgent`). Backend-derived recursive managers register one\n * automatically; a caller-owned factory cannot be, so a leaf whose execution can RE-ATTACH\n * across a process boundary (a sandbox session, a CLI bridge session — an executor that\n * journals its admission through the retained seam) needs this for a resume to recover the\n * in-flight child instead of refusing its key `in-doubt`. The factory receives the\n * reconstructed spec and the child's journaled context, including its prior admissions. */\n readonly recoverExecutor?: ExecutorFactory<unknown>\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 /** OPT-IN standing guidance from the profile knowledge base\n * (`@tangle-network/agent-interface/profile-kb`). `'profile-kb'` composes harness guidance,\n * then model guidance, then the profile's own text into the root profile and into every\n * profile a manager spawns, before identity is fixed, so receipts bind the prompt that ran.\n * Omit to run profiles exactly as authored: Runtime selects no standing guidance by itself. */\n readonly profileGuidance?: 'profile-kb'\n /** Whether a spawned profile that declares no Runtime coordination tool receives its manager's\n * coordination grants (`spawn_worker`, `observe_agent`, and the rest, plus `submit_result` so it\n * can still deliver work it does itself), so every child can lead children of its own. Default\n * `true`. A child whose author wrote any coordination entry, true or false, keeps what was\n * written (a `false` entry is dropped once it has kept the child a leaf). A child this run\n * cannot drive as a manager (no driver for its harness, or no `router` for a harness-less one)\n * stays a leaf, and so does every child of a run with no completion check (`deliverable` or\n * `resolveDeliverable`), since a manager delivers its own work only through `submit_result`.\n * `false` runs every authored profile exactly as written. Applies to backend-derived workers;\n * a caller-owned `makeWorkerAgent` decides its own children. */\n readonly inheritSpawnRights?: boolean\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 an EXTERNAL-harness manager with a completion check is sent back when its turn ends with\n * the check unmet: the deadline, `maxBarren`, and the continuation note's profile and switches.\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. By\n * 2026-09-24, 650 recorded inputs had chosen seven different re-prompt counts, and the note the\n * director heard held no line of the check's verdict.\n *\n * A continuation is the retry path, not a second loop: same scope, same coordination server,\n * same live children, and the same budget, deadline, and abort bounds. There is no count: the\n * loop ends when the check passes, at this deadline, on the budget, after `maxBarren` turns in\n * a row without progress, or on cancellation. A turn that ends, a blocked tool, and a lost\n * stream are segment boundaries, never the end of the run. Runtime writes the note from the check's verdict (`./continuation.ts`); the\n * profile owns its words, and `append` may add a section but never replace one.\n *\n * Required with `deliverable` (or `resolveDeliverable`) for an external manager, and applied to\n * every external manager with a completion check in the tree. Refused for a router-brained\n * manager, which runs its turn loop in process.\n */\n readonly continuation?: ContinuationPolicy\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 * How long settlement keeps retrying a child teardown the executor has not confirmed, with\n * exponential backoff, before naming the child in `teardownUnconfirmed` with the provider\n * environment ids a sweeper deletes. `0` makes one attempt only. Default: 300000 (5 minutes).\n * See `SupervisorOpts.teardownConfirmMs`.\n */\n readonly teardownConfirmMs?: number\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 and close\n * each released child's cursor slot with a terminal record marked `retainedExecution:\n * 'released'`, or `'keep'` them for a later call that resumes this run. Default: `'keep'` with\n * `runDir` (re-running the same `runDir` and `runId` resumes), `'release'` without it (nothing\n * can resume an in-memory 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, worker-slot\n * queue, 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 /** The root's default slice for a child whose manager names no `budget`. Defaults to a quarter\n * of the part of the pool children may reserve (the pool less any owner share). A nested\n * manager always divides its own slice that way; `spawn_worker`'s `budget` overrides per spawn. */\n readonly perWorker?: Budget\n /** Opt-in owner share: every manager, the root included, keeps this fraction of its own slice\n * free of its children's reservations, so its own turns keep budget. Default slices shrink to fit\n * beside it. Default: off. */\n readonly reservationPolicy?: RecursiveReservationPolicy\n /** What a child's own time box (a `spawn_worker` `budget.deadlineMs`) does. Default: a check-in;\n * the child is told to save its state and submit what it has, and is stopped only once it then\n * makes no progress for 30 min. `false` stops it at the time box. The run's own deadline always\n * stops every node. See `deadline.ts` `DeadlineCheckIn`. */\n readonly deadlineCheckIn?: DeadlineCheckIn\n /** Bound on concurrently WORKING agents across the whole recursive tree: a number, or one\n * `createWorkerSlots` allocator that several runs in this process share. A spawn past it keeps\n * its budget slice and waits in a queue (deepest first) instead of being refused, and a manager\n * lends its slot to its first running child, so nested waits cannot deadlock. The root holds no\n * slot. Omit/`<= 0` = no bound (the conserved pool stays the only bound). */\n readonly workerSlots?: number | WorkerSlots\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 receives in its next wake 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 (in its next wake)\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 /** How Runtime wakes a manager that ended its turn with work open: the heartbeat, the debounce\n * that coalesces events into one wake, and the deadline warning. Omit = the defaults in\n * `./wake` (15 min, 2 s, 15 min). */\n readonly wake?: ManagerWakePolicy\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 /** Advanced test seam: opt into resume-first when the durable stores are caller-supplied\n * (`journal` + `blobs` / `runContext`) instead of derived from `runDir`. The normal durable path\n * is `runDir` or a `runContext` (see `docs/durability.md`). Exactly what the file\n * context sets automatically: load the prior tree for `runId` before starting fresh, refuse a\n * reused id without it. Ignored when `runDir` is also set — the file context owns the flag. */\n readonly resume?: boolean\n /**\n * The segment this entry runs the root in. A run keeps one id for its whole life: a turn that\n * ends, a lost stream and a dead supervisor are boundaries between entries, and a resume may move\n * the root to another model, provider, reasoning effort or harness, or onto another stack, as a\n * new segment of the same run. `profile` stays the root profile the run recorded, so its identity,\n * coordination owner and settled children resume unchanged; the root executes that profile with\n * `model.provider`, `model.default`, `model.reasoningEffort` and `harness` replaced where given. `stack` names the\n * package versions the caller runs this entry under, its Runtime among them; Runtime records it\n * and never reads it. When the segment differs from the one the run last ran, the journal gains\n * one `root-segment` record with the time and `reason`. A different task, or any other profile\n * change, is still a resume identity mismatch: that is a new run. A fresh run records its first\n * segment and refuses a model or harness change: a new run takes them from its profile.\n *\n * A harness change starts a new native session: a session of one harness cannot continue in\n * another. The root re-enters with its objective and the run's state, in a workspace restored\n * from its latest checkpoint when the provider holds one.\n */\n readonly segment?: {\n readonly provider?: string\n readonly model?: string\n readonly reasoningEffort?: ReasoningEffort\n readonly harness?: AgentProfile['harness']\n readonly stack?: Readonly<Record<string, string>>\n readonly reason: string\n }\n /** Durable steer directory when it differs from the run-control directory. */\n readonly steerDir?: 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 /**\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 * A record may declare the plateau rule as data, `{ plateau: { window, minDelta } }`, so no\n * product module builds it.\n */\n readonly stopRule?: StopRule | { readonly plateau: PlateauOptions }\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 /** Recursion ceiling for the tree (root = 0). The conserved pool is what bounds depth, since each\n * level's slice comes out of the level above; this only stops a runaway recursion. Omit =\n * `DEFAULT_MAX_DEPTH` (16). */\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' | 'namespace'>\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 'selectSeat',\n 'blobs',\n 'budget',\n 'childSettleGraceMs',\n 'teardownConfirmMs',\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 'inheritSpawnRights',\n 'journal',\n 'makeLeafAgent',\n 'makeWorkerAgent',\n 'escalateQuestion',\n 'maxDepth',\n 'maxTurns',\n 'now',\n 'onCoordinationEvent',\n 'onDriverAttempt',\n 'onProgressStop',\n 'otel',\n 'peerMail',\n 'perWorker',\n 'reservationPolicy',\n 'deadlineCheckIn',\n 'profileGuidance',\n 'profileSecurity',\n 'registry',\n 'resolveDeliverable',\n 'resolveDriveHarness',\n 'resolveSpawnProfile',\n 'resolveSupervisorTools',\n 'rootDriverFromBackend',\n 'rootHandle',\n 'router',\n 'runDir',\n 'resume',\n 'segment',\n 'runContext',\n 'runId',\n 'signal',\n 'stallAfterMs',\n 'wake',\n 'steerDir',\n 'stopRule',\n 'watchWorkers',\n 'continuation',\n 'workerRetry',\n 'onWorkerRetry',\n 'workerSlots',\n 'recoverExecutor',\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 if (deliverable.checkState !== undefined && typeof deliverable.checkState !== 'function') {\n throw new ValidationError(`${context}: deliverable.checkState must be a function`)\n }\n if (\n deliverable.feedback !== undefined &&\n deliverable.feedback !== 'verbatim' &&\n deliverable.feedback !== 'pass-only'\n ) {\n throw new ValidationError(`${context}: deliverable.feedback must be 'verbatim' or 'pass-only'`)\n }\n return Object.freeze({\n ...detachedSnapshot(\n {\n describe: deliverable.describe,\n ...(deliverable.feedback === undefined ? {} : { feedback: deliverable.feedback }),\n ...(deliverable.sealed === undefined ? {} : { sealed: deliverable.sealed === true }),\n },\n `${context} configuration`,\n ),\n check: deliverable.check,\n ...(deliverable.checkState === undefined ? {} : { checkState: deliverable.checkState }),\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 the retired `onUnmetContract`: added with the re-prompt path in 0.186.0,\n * accepted by the option-key check, forwarded by `supervisorAgent`, read by the retry loop, and\n * never destructured here. Every `supervisePursuit` run that passed the callback failed at\n * construction on 0.186.0, 0.187.1 and 0.188.0, and the only working configuration was the number\n * 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 'onWorkerRetry',\n 'recoverExecutor',\n 'resolveDeliverable',\n 'resolveDriveHarness',\n 'resolveSpawnProfile',\n 'selectSeat',\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 selectSeat,\n coordination,\n driverBackend,\n deliverable,\n resolveDeliverable,\n router,\n compaction,\n watchWorkers,\n analysts,\n makeWorkerAgent,\n makeLeafAgent,\n recoverExecutor,\n resume,\n resolveSpawnProfile,\n blobs,\n journal,\n runContext,\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 continuation,\n workerRetry,\n onWorkerRetry,\n finalizer,\n now,\n signal,\n rootHandle,\n workerSlots,\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 // The policy is decision data except its two functions, which are captured by reference.\n const capturedContinuation =\n continuation === undefined\n ? undefined\n : (() => {\n const { runPanel, append, ...policy } = continuation\n return Object.freeze({\n ...detachedSnapshot(policy, 'supervise continuation'),\n ...(runPanel === undefined ? {} : { runPanel }),\n ...(append === undefined ? {} : { append }),\n })\n })()\n\n return Object.freeze({\n ...capturedData,\n ...(capturedCoordination === undefined ? {} : { coordination: capturedCoordination }),\n ...(capturedBackend === undefined ? {} : { backend: capturedBackend }),\n ...(selectSeat === undefined ? {} : { selectSeat }),\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 ...(recoverExecutor === undefined ? {} : { recoverExecutor }),\n ...(resolveSpawnProfile === undefined ? {} : { resolveSpawnProfile }),\n ...(blobs === undefined ? {} : { blobs }),\n ...(journal === undefined ? {} : { journal }),\n ...(resume === undefined ? {} : { resume }),\n ...(runContext === undefined ? {} : { runContext }),\n // A number is decision data; a shared allocator is a live collaborator other runs also hold.\n ...(workerSlots === undefined ? {} : { workerSlots }),\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 ...(capturedContinuation === undefined ? {} : { continuation: capturedContinuation }),\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 ...(request.operator === undefined ? {} : { operator: request.operator }),\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\n .map((node) =>\n node.environments?.length\n ? `${node.id} (${node.environments.map((environment) => `${environment.provider}:${environment.environmentId}`).join(', ')})`\n : node.id,\n )\n .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\n/** The slice a child gets when its manager names none: a quarter of the part of the manager's\n * budget its children may reserve, so four default children fill that part and the manager's\n * own share stays free for its turns. Each nested manager divides its own slice the same way. */\nfunction defaultPerWorker(budget: Budget, ownerShare: number): Budget {\n const share = (1 - ownerShare) / 4\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 * share) },\n ]),\n ),\n }),\n maxIterations: Math.max(1, Math.floor(budget.maxIterations * share)),\n maxTokens: Math.max(1, Math.floor(budget.maxTokens * share)),\n ...(budget.maxUsd !== undefined ? { maxUsd: budget.maxUsd * share } : {}),\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 superviseWithContext(profile, task, opts)\n}\n\n/** A stop rule as a function, or the declared plateau form a record carries as data. */\nfunction stopRuleOf(rule: NonNullable<SuperviseOptions['stopRule']>): StopRule {\n if (typeof rule === 'function') return rule\n if (typeof rule === 'object' && rule !== null && 'plateau' in rule) return plateau(rule.plateau)\n throw new ValidationError(\n 'supervise: stopRule must be a StopRule or { plateau: { window, minDelta } }',\n )\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 superviseWithContext(profile, task, runtimeOptions, brain)\n}\n\n/**\n * The composer `profileGuidance` selects, or `undefined` when no guidance is selected. The result\n * is re-validated as an AgentProfile, and a composition that breaks the schema is refused as a\n * ValidationError. `supervise` applies it to the root and to authored spawns; `runGraph` applies\n * it to pinned node profiles.\n */\nexport function profileGuidanceComposer(\n guidance: SuperviseOptions['profileGuidance'],\n): ((profile: AgentProfile) => AgentProfile) | undefined {\n if (guidance === undefined) return undefined\n if (guidance !== 'profile-kb') {\n throw new ValidationError(\n `supervise: profileGuidance must be 'profile-kb' when set, got ${JSON.stringify(guidance)}`,\n )\n }\n return (profile) => {\n const composed = agentProfileSchema.safeParse(withProfileKb(profile))\n if (!composed.success) {\n throw new ValidationError(\n `supervise: profile-kb guidance produced an invalid AgentProfile: ${composed.error.message}`,\n )\n }\n return composed.data\n }\n}\n\n/**\n * The exact root profile `supervise` executes: `profile` parsed as an AgentProfile, with the\n * selected `profileGuidance` composed. The root's journaled `identity.profileDigest` is this\n * value's digest, so a reader that must match a recorded root derives it here, not by hand.\n */\nexport function superviseRootProfile(\n profile: SupervisorProfile,\n profileGuidance: SuperviseOptions['profileGuidance'],\n): AgentProfile {\n const parsedProfile = agentProfileSchema.safeParse(profile)\n if (!parsedProfile.success) {\n throw new ValidationError(`supervise: invalid AgentProfile: ${parsedProfile.error.message}`)\n }\n const compose = profileGuidanceComposer(profileGuidance)\n return freezeDetachedProfile(compose ? compose(parsedProfile.data) : parsedProfile.data)\n}\n\n/** What a root profile runs on, as a `root-segment` record names it. */\nfunction rootSegmentOf(profile: AgentProfile): RootSegment {\n return {\n ...(profile.model?.provider === undefined ? {} : { provider: profile.model.provider }),\n ...(profile.model?.default === undefined ? {} : { model: profile.model.default }),\n ...(profile.model?.reasoningEffort === undefined\n ? {}\n : { reasoningEffort: profile.model.reasoningEffort }),\n ...(profile.harness === undefined ? {} : { harness: profile.harness }),\n }\n}\n\n/** Refuse a segment that names nothing usable before any compute. */\nfunction admitSegment(segment: NonNullable<SuperviseOptions['segment']>): void {\n if (typeof segment !== 'object' || segment === null) {\n throw new ValidationError('supervise: segment must be an object')\n }\n for (const key of ['provider', 'model', 'harness'] as const) {\n const value = segment[key]\n if (value !== undefined && (typeof value !== 'string' || value.trim().length === 0)) {\n throw new ValidationError(`supervise: segment.${key} must name a ${key}`)\n }\n }\n if (typeof segment.reason !== 'string' || segment.reason.trim().length === 0) {\n throw new ValidationError('supervise: segment.reason must say why the segment starts')\n }\n if (segment.stack !== undefined) {\n if (\n typeof segment.stack !== 'object' ||\n segment.stack === null ||\n Array.isArray(segment.stack)\n ) {\n throw new ValidationError('supervise: segment.stack must map package names to versions')\n }\n for (const [name, version] of Object.entries(segment.stack)) {\n if (typeof version !== 'string' || version.length === 0) {\n throw new ValidationError(`supervise: segment.stack.${name} must be a version string`)\n }\n }\n }\n}\n\n/** The recorded root profile with only its provider, model, reasoning effort and harness replaced\n * where the segment names them. */\nfunction withRootSegment(\n profile: AgentProfile,\n segment: NonNullable<SuperviseOptions['segment']>,\n): AgentProfile {\n if (\n segment.provider === undefined &&\n segment.model === undefined &&\n segment.reasoningEffort === undefined &&\n segment.harness === undefined\n ) {\n return profile\n }\n return superviseRootProfile(\n {\n ...profile,\n ...(segment.harness === undefined ? {} : { harness: segment.harness }),\n model: {\n ...profile.model,\n ...(segment.provider === undefined ? {} : { provider: segment.provider }),\n ...(segment.model === undefined ? {} : { default: segment.model }),\n ...(segment.reasoningEffort === undefined\n ? {}\n : { reasoningEffort: segment.reasoningEffort }),\n },\n },\n undefined,\n )\n}\n\nfunction superviseWithContext(\n profile: SupervisorProfile,\n task: unknown,\n opts: SuperviseOptions,\n brain?: ToolLoopChat,\n): ReturnType<typeof superviseInternal> {\n if (opts.runContext?.acquire === undefined) return superviseInternal(profile, task, opts, brain)\n const options = captureSuperviseOptions(opts)\n const capturedProfile = freezeDetached(profile)\n const capturedTask = freezeDetached(task)\n return withRunContext(opts.runContext, options.signal, (runContext, signal) =>\n superviseInternal(\n capturedProfile,\n capturedTask,\n {\n ...options,\n runContext,\n ...(signal === undefined ? {} : { signal }),\n },\n brain,\n ),\n )\n}\n\nfunction superviseInternal(\n profile: SupervisorProfile,\n task: unknown,\n opts: SuperviseOptions,\n testBrain?: ToolLoopChat,\n) {\n const options = captureSuperviseOptions(opts)\n if (options.runContext?.durability === 'sql') {\n if (\n options.runDir !== undefined ||\n (options.journal !== undefined && options.journal !== options.runContext.journal) ||\n (options.blobs !== undefined && options.blobs !== options.runContext.blobs) ||\n (options.runId !== undefined && options.runId !== options.runContext.runId)\n ) {\n throw new ValidationError(\n 'supervise: SQL runContext cannot be mixed with another run identity or persistence path',\n )\n }\n if (\n options.backend?.backend !== 'provider' ||\n options.makeWorkerAgent ||\n options.makeLeafAgent\n ) {\n throw new ValidationError(\n 'supervise: SQL runContext requires backend-derived retained provider workers',\n )\n }\n }\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 composeSpawnProfile = profileGuidanceComposer(options.profileGuidance)\n // The recorded root profile fixes the run's identity; a segment only alters what it executes.\n const registeredProfile = superviseRootProfile(profile, options.profileGuidance)\n if (options.segment !== undefined) admitSegment(options.segment)\n const canonicalProfile =\n options.segment === undefined\n ? registeredProfile\n : withRootSegment(registeredProfile, options.segment)\n assertExecutableAgentProfile(canonicalProfile, 'supervise root')\n if (authoredSeatStages(canonicalProfile) !== undefined && options.selectSeat === undefined) {\n throw new ValidationError('supervise: AgentProfile.seats requires selectSeat before execution')\n }\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 registeredProfile,\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 for (const stage of authoredSeatStages(canonicalProfile) ?? []) {\n assertModelAllowed(stage.model, options.allowedModels)\n }\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 // The spawn path applies these checks to the profile `authorizeSpawn` returns, so they can run\n // early only when no caller-owned authorization or worker seam sits between the entry and mount.\n const profileTable = snapshotProfileTable(\n options.registry?.profiles,\n options.allowedModels,\n options.makeWorkerAgent === undefined && options.authorizeSpawn === undefined\n ? (entry, context) => {\n const security = validateAgentProfileSecurity(\n entry,\n options.profileSecurity ?? DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY,\n )\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(`${context}: ${details}`)\n }\n // A leaf runs on the worker backend, which refuses any profile axis it cannot carry.\n if (\n options.backend !== undefined &&\n options.makeLeafAgent === undefined &&\n declaredRuntimeToolNames(entry).length === 0\n ) {\n assertBackendProfileMaterialization(entry, options.backend, context)\n }\n }\n : undefined,\n )\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.runContext ??\n (options.runDir !== undefined\n ? createFileRunContext(options.runDir, { withDriver: true })\n : createInMemoryRunContext({ withDriver: true }))\n const blobs = options.blobs ?? ctx.blobs\n assertRecursiveReservationPolicy(options.reservationPolicy)\n const ownerShare = options.reservationPolicy?.ownerShare ?? 0\n const perWorker = options.perWorker ?? defaultPerWorker(options.budget, ownerShare)\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 settles with\n // a `budgetViolation` against that smaller reservation, which reads as a budget outcome rather\n // than a 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 ?? ctx.runId ?? 'supervise'\n const runNamespace = ctx.namespace ?? supervisionRunNamespace(options.runDir, runId)\n const log = ctx.coordinationLog\n const rootOwnerId = rootCoordinationOwner(rootExecution.identity)\n const rootProviderModels: Array<string | undefined> = []\n // The root's own provider stream is retained only where a run directory can hold it. Nested\n // managers share this harness and are left unretained here; a per-owner file is a later step.\n const rootStreamSink =\n options.runDir === undefined\n ? undefined\n : createRootStreamSink(resolve(options.runDir), options.now ?? Date.now)\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 // Every child that this run can drive as a manager inherits its manager's coordination grants,\n // so depth is the director's choice rather than an author's omission. A profile's own explicit\n // grants win; a child with no driver for its harness stays a leaf rather than failing to start.\n const externalManagersAvailable =\n hasCustomDriveHarness ||\n (managerBackend !== undefined &&\n automaticDriverBackendSupported(managerBackend, options.coordination))\n const canLead = (child: AgentProfile): boolean =>\n isExternalSupervisor(child) ? externalManagersAvailable : options.router !== undefined\n // A manager delivers its own work only through `submit_result`, which exists only under a\n // completion check. Without one, a worker turned manager could not finish work it did itself.\n const childrenCanSubmit = deliverable !== undefined || options.resolveDeliverable !== undefined\n const composeSpawnProfileFor = (\n parent: AgentProfile,\n ): ((profile: AgentProfile) => AgentProfile) | undefined => {\n if (\n options.inheritSpawnRights === false ||\n options.makeWorkerAgent !== undefined ||\n !childrenCanSubmit\n ) {\n return composeSpawnProfile\n }\n return (authored) => {\n const composed = composeSpawnProfile ? composeSpawnProfile(authored) : authored\n // A seat chain is an explicit execution policy. Inheriting manager grants would turn a\n // seat-bearing leaf into a manager and change the authored profile before selection.\n return composed.seats || !canLead(composed)\n ? composed\n : withInheritedSpawnRights(parent, composed)\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 deliverReady: unknown = harness.deliverReady\n if (deliverReady !== undefined && typeof deliverReady !== 'function') {\n throw new ValidationError(\n 'supervise: driveHarness.deliverReady must be a function when provided',\n )\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 context.depth === 0 ? rootStreamSink : undefined,\n options.selectSeat === undefined\n ? undefined\n : {\n select: options.selectSeat,\n journal,\n rootId: runId,\n onSegment: async (nodeId, segment, phase) => {\n await options.hooks?.onEvent?.(\n {\n id: `${nodeId}:seat:${segment.startedAt}:${phase}`,\n runId,\n target: 'agent.seat',\n phase: 'event',\n timestamp: options.now?.() ?? Date.now(),\n parentId: nodeId,\n payload: { nodeId, phase, segment },\n },\n {},\n )\n },\n onPause: async (nodeId, resumeAt, phase) => {\n await options.hooks?.onEvent?.(\n {\n id: `${nodeId}:seat:${phase}:${resumeAt || (options.now?.() ?? Date.now())}`,\n runId,\n target: 'agent.seat',\n phase: 'event',\n timestamp: options.now?.() ?? Date.now(),\n parentId: nodeId,\n payload: { nodeId, phase, ...(resumeAt ? { resumeAt } : {}) },\n },\n {},\n )\n },\n },\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 analystLineage = false,\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 : selectedDeliverable === null\n ? undefined\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 seatManagedLeaf =\n authoredSeatStages(authorized) !== undefined &&\n declaredRuntimeToolNames(authorized).length === 0 &&\n isExternalSupervisor(authorized)\n const usesRuntimeCoordination =\n declaredRuntimeToolNames(authorized).length > 0 || seatManagedLeaf\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 analystLineage ||\n spawnContext.analyst !== undefined ||\n spawnContext.assignmentId.startsWith('analyst:'),\n )\n const nestedPerWorker = defaultPerWorker(spawnContext.budget, ownerShare)\n const authorizeNestedMessage = authorizeDownFor(authorized, depth + 1)\n let acceptedSubmission = false\n let unassessedOutput = false\n const nested = supervisorAgent(authorized, {\n blobs,\n onUnassessedOutput: () => {\n unassessedOutput = true\n },\n ...(spawnResourceRoot === undefined ? {} : { spawnResourceRoot }),\n makeWorkerAgent: childFactory,\n ...(spawnContext.sourceEvidenceRefs\n ? { sourceEvidenceRefs: spawnContext.sourceEvidenceRefs }\n : {}),\n ...(authorizeNestedMessage ? { authorizeDownMessage: authorizeNestedMessage } : {}),\n perWorker: nestedPerWorker,\n ...(ownerShare > 0 ? { preserveOwnerTurns: true } : {}),\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.escalateQuestion ? { escalateQuestion: options.escalateQuestion } : {}),\n ...(!analystLineage &&\n spawnContext.analyst === undefined &&\n !spawnContext.assignmentId.startsWith('analyst:') &&\n options.analyzeOnSettle\n ? { analyzeOnSettle: options.analyzeOnSettle }\n : {}),\n ...(options.watchWorkers ? { watchWorkers: options.watchWorkers } : {}),\n ...(options.stallAfterMs !== undefined ? { stallAfterMs: options.stallAfterMs } : {}),\n ...(options.wake !== undefined ? { wake: options.wake } : {}),\n ...(options.continuityByProfile\n ? { continuityByProfile: options.continuityByProfile }\n : {}),\n ...(spawnPreflight ? { preflightSpawn: spawnPreflight } : {}),\n ...(options.resolveSpawnProfile\n ? { resolveSpawnProfile: options.resolveSpawnProfile }\n : {}),\n ...(composeSpawnProfileFor(authorized)\n ? { composeSpawnProfile: composeSpawnProfileFor(authorized) }\n : {}),\n ...(profileTable ? { profiles: profileTable } : {}),\n ...(options.peerMail ? { peerMail: options.peerMail } : {}),\n ...(options.stopRule ? { stopRule: stopRuleOf(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 && !seatManagedLeaf ? { deliverable: childDeliverable } : {}),\n ...(childDeliverable && !seatManagedLeaf\n ? {\n onAcceptedSubmission: () => {\n acceptedSubmission = true\n },\n }\n : {}),\n // Every external manager with a check in the tree is sent back under the run's one\n // continuation policy. Its files sit beside the root's, under its own owner id.\n ...(childDeliverable &&\n !seatManagedLeaf &&\n options.continuation &&\n isExternalSupervisor(authorized)\n ? {\n continuation: options.continuation,\n ...(options.runDir === undefined\n ? {}\n : {\n continuationDir: resolve(\n options.runDir,\n CONTINUATIONS_DIR,\n 'managers',\n encodeURIComponent(ownerId),\n ),\n }),\n }\n : {}),\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 owns only its subtree's durable controls. Root-level labels remain\n // the root's even when steering uses a separate directory from cancellation.\n ...(options.runDir === undefined\n ? {}\n : {\n controlDir: resolve(options.runDir),\n abortRun: cancelDurableRun,\n }),\n ...(options.steerDir === undefined ? {} : { steerDir: resolve(options.steerDir) }),\n ...(options.runDir === undefined && options.steerDir === undefined\n ? {}\n : { controlScope: 'subtree' as const }),\n })\n return driverChild(\n authorized,\n nested,\n journal,\n childExecution.ref,\n () => acceptedSubmission,\n recoveryFactories.get(childFactory),\n () => unassessedOutput,\n seatManagedLeaf ? childDeliverable : undefined,\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 // The root driver loop reports what it did once it ends; the settle record carries it.\n let rootContinuation: DriverContinuationRecord | undefined\n const start = async () => {\n if (ctx.durability === 'sql') {\n if (\n options.backend?.backend !== 'provider' ||\n options.backend.steering ||\n options.driveHarness ||\n options.resolveDriveHarness ||\n options.driverBackend\n ) {\n throw new ValidationError(\n 'supervise: SQL runContext requires a local coordinator and non-steering retained provider workers',\n )\n }\n const provider = resolveAgentEnvironmentProvider(\n options.backend.provider,\n options.backend.registry,\n )\n const capabilities = await provider.capabilities()\n if (\n !capabilities.retainedControl ||\n !capabilities.streaming.turnIdempotency ||\n !capabilities.streaming.replay ||\n !provider.get\n ) {\n throw new ValidationError(\n 'supervise: SQL runContext requires retainedControl, replay, turn idempotency, and provider.get',\n )\n }\n }\n await verifyProfilePromotions(profileTable)\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 ...(ownerShare > 0 ? { preserveOwnerTurns: true } : {}),\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 onDriverLoopSettled(record: DriverContinuationRecord) {\n rootContinuation = record\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.length > 0)\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 ...(composeSpawnProfileFor(canonicalProfile)\n ? { composeSpawnProfile: composeSpawnProfileFor(canonicalProfile) }\n : {}),\n ...(profileTable ? { profiles: profileTable } : {}),\n ...(spawnResourceRoot === undefined ? {} : { spawnResourceRoot }),\n ...(options.peerMail ? { peerMail: options.peerMail } : {}),\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.escalateQuestion ? { escalateQuestion: options.escalateQuestion } : {}),\n ...(options.analyzeOnSettle ? { analyzeOnSettle: options.analyzeOnSettle } : {}),\n ...(options.watchWorkers ? { watchWorkers: options.watchWorkers } : {}),\n ...(options.stallAfterMs !== undefined ? { stallAfterMs: options.stallAfterMs } : {}),\n ...(options.wake !== undefined ? { wake: options.wake } : {}),\n ...(options.continuityByProfile ? { continuityByProfile: options.continuityByProfile } : {}),\n ...(options.stopRule ? { stopRule: stopRuleOf(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 ...(deliverable && options.continuation && isExternalSupervisor(canonicalProfile)\n ? {\n continuation: options.continuation,\n ...(options.runDir === undefined\n ? {}\n : {\n continuationDir: resolve(options.runDir, CONTINUATIONS_DIR),\n rootStreamPath: resolve(options.runDir, ROOT_STREAM_FILE),\n }),\n }\n : {}),\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 ...(options.steerDir === undefined ? {} : { steerDir: resolve(options.steerDir) }),\n // A root executing another segment of its registered profile attributes its materialization to the registered one.\n ...(canonicalProfile === registeredProfile ? {} : { registeredProfile }),\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\n ? createSupervisorSpanRecorder({ runId, namespace: runNamespace, ...options.otel, now })\n : 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 // A caller-supplied recovery factory wins: it owns the worker seam (makeWorkerAgent /\n // makeLeafAgent), so only it can reconstruct an interrupted child's executor. The derived\n // registration below serves backend-built recursive managers, which no caller can name.\n ...((options.recoverExecutor ?? recoveryFactories.get(workerFactory))\n ? { recoverExecutor: options.recoverExecutor ?? recoveryFactories.get(workerFactory) }\n : {}),\n rootIdentity: rootExecution.identity,\n ...(options.segment === undefined\n ? {}\n : {\n rootSegment: {\n registered: rootSegmentOf(registeredProfile),\n current: {\n ...rootSegmentOf(canonicalProfile),\n ...(options.segment.stack === undefined\n ? {}\n : { stack: { ...options.segment.stack } }),\n },\n reason: options.segment.reason,\n },\n }),\n ...(rootOwnerRuntime === undefined\n ? {}\n : {\n rootMaterialization: {\n runtime: rootOwnerRuntime,\n declaration: 'deferred' as const,\n // Every segment's materialization is attributed to the registered root profile.\n authoredProfile: registeredProfile,\n },\n }),\n maxDepth: options.maxDepth ?? DEFAULT_MAX_DEPTH,\n ...(options.childSettleGraceMs !== undefined\n ? { childSettleGraceMs: options.childSettleGraceMs }\n : {}),\n ...(options.teardownConfirmMs !== undefined\n ? { teardownConfirmMs: options.teardownConfirmMs }\n : {}),\n ...(options.retainedAtSettlement !== undefined\n ? { retainedAtSettlement: options.retainedAtSettlement }\n : {}),\n ownerWorkspaceRetention:\n managerBackend?.backend === 'provider' && managerBackend.workspaceRetention !== undefined,\n ...(options.workerSlots !== undefined ? { workerSlots: options.workerSlots } : {}),\n ...(options.reservationPolicy ? { reservationPolicy: options.reservationPolicy } : {}),\n ...(options.deadlineCheckIn === undefined\n ? {}\n : { deadlineCheckIn: options.deadlineCheckIn }),\n ...(ctx.resume === true || (options.runDir === undefined && options.resume === true)\n ? { resume: true }\n : {}),\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 let rootStream: RootStreamReceipt | undefined\n try {\n result = await run\n } finally {\n // Closed on BOTH exits. A run that throws releases the file here, and whoever records\n // the failure recomputes the same receipt from the bytes on disk.\n try {\n rootStream = await rootStreamSink?.close()\n } finally {\n cancellation?.close()\n cancellation?.check()\n }\n }\n recordRunCancellationOutcome(options.runDir, result, now)\n // A nested manager's session rides its settle record (#1359). The root has no settle\n // record, so its session had no receipt anywhere: 312 of 312 Discovery roots of\n // 2026-09-23/24 settled without one, and 27 of the 57 harness subagent calls seen in those\n // runs were the roots' own (#1264). The result carries it, persisted the same way.\n const rootHarnessTranscript =\n rootDriveHarness === undefined\n ? undefined\n : await persistHarnessTranscript(readHarnessTranscript(rootDriveHarness), blobs)\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 ...(rootStream === undefined ? {} : { rootStream }),\n ...(rootHarnessTranscript === undefined ? {} : { rootHarnessTranscript }),\n ...(rootContinuation === undefined ? {} : { continuation: rootContinuation }),\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":";;;;;;;;;;;;;;;;;;;;;;;;AAIA,MAAa,sCAAsC;;;;;;ACoCnD,SAAS,cACP,QACA,QACA;CAiBA,OAAO;EACL,SAAS;EACT,IAAI;EACJ,OAAO;GAAE,MAAM;GAAQ,SAAS;IAlBhC,sBAAsB;IACtB,gBAAgB;IAChB,cAAc;IACd,kBAAkB;IAClB,mBAAmB;IACnB,iBAAiB;IACjB,sBAAsB;IACtB,4BAA4B;IAC5B,kBAAkB,8CAA8C,OAAO,gBAAgB;IACvF,qBAAqB;IACrB,iBAAiB,uBAAuB,OAAO,sBAAsB,2BAA2B,OAAO,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