@tangle-network/agent-runtime 0.79.2 → 0.79.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent.js +2 -2
- package/dist/{chunk-2DS6T46I.js → chunk-63MHOCIE.js} +3 -3
- package/dist/{chunk-75V2XXYJ.js → chunk-AG335EXG.js} +2 -2
- package/dist/chunk-AG335EXG.js.map +1 -0
- package/dist/{chunk-TSDKBFZP.js → chunk-KRULXIWS.js} +411 -110
- package/dist/chunk-KRULXIWS.js.map +1 -0
- package/dist/{chunk-SONQUREI.js → chunk-PVPFDTO3.js} +2 -2
- package/dist/{coordination-BoEPhGas.d.ts → coordination-DCmljYDf.d.ts} +29 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +4 -4
- package/dist/intelligence.d.ts +1 -1
- package/dist/{loop-runner-bin-DCr5OMe5.d.ts → loop-runner-bin-C4X0FZ2Z.d.ts} +1 -1
- package/dist/loop-runner-bin.d.ts +3 -3
- package/dist/loop-runner-bin.js +3 -3
- package/dist/loops.d.ts +48 -9
- package/dist/loops.js +2 -2
- package/dist/mcp/bin.js +1 -1
- package/dist/mcp/index.d.ts +5 -5
- package/dist/mcp/index.js +3 -3
- package/dist/{router-client-CMAWGv1h.d.ts → router-client-Ak2IGuXq.d.ts} +33 -1
- package/dist/{worktree-fanout-CtQrRDME.d.ts → worktree-fanout-CXGzHET4.d.ts} +4 -73
- package/dist/{worktree-CpptK3oF.d.ts → worktree-harness-Bmho9SH0.d.ts} +73 -1
- package/package.json +1 -1
- package/dist/chunk-75V2XXYJ.js.map +0 -1
- package/dist/chunk-TSDKBFZP.js.map +0 -1
- /package/dist/{chunk-2DS6T46I.js.map → chunk-63MHOCIE.js.map} +0 -0
- /package/dist/{chunk-SONQUREI.js.map → chunk-PVPFDTO3.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/runtime/supervise/model-policy.ts","../src/durable/spawn-journal.ts","../src/runtime-hooks.ts","../src/runtime/sandbox-acquire.ts","../src/runtime/sandbox-capabilities.ts","../src/runtime/sandbox-backend.ts","../src/runtime/sandbox-lineage.ts","../src/runtime/run-loop.ts","../src/runtime/supervise/scope.ts","../src/runtime/router-client.ts","../src/runtime/tool-loop.ts","../src/runtime/supervise/inbox.ts","../src/mcp/worktree.ts","../src/runtime/supervise/worktree-cli-executor.ts","../src/mcp/worktree-harness.ts","../src/runtime/supervise/runtime.ts","../src/runtime/supervise/budget.ts","../src/runtime/supervise/supervisor.ts","../src/runtime/supervise/completion-gate.ts","../src/runtime/supervise/authoring.ts","../src/runtime/supervise/event-bus.ts","../src/mcp/tools/coordination.ts","../src/runtime/supervise/coordination-driver.ts","../src/mcp/feedback-store.ts","../src/mcp/delegation-store.ts","../src/mcp/delegation-trace.ts","../src/mcp/task-queue.ts","../src/runtime/supervise/driver-executor.ts","../src/runtime/supervise/run-context.ts","../src/runtime/supervise/coordination-mcp.ts","../src/mcp/server.ts","../src/runtime/supervise/supervise.ts","../src/runtime/supervise/delegate.ts","../src/mcp/tools/delegate.ts","../src/mcp/tools/delegate-feedback.ts","../src/mcp/tools/delegate-ui-audit.ts","../src/mcp/tools/delegation-history.ts","../src/mcp/tools/delegation-status.ts","../src/runtime/supervise/supervisor-agent.ts"],"sourcesContent":["/**\n * `assertModelAllowed` — a fail-loud guard that restricts a run to a chosen subset of\n * models. The two front doors (`supervise()` / `improve()`) call it once per configured\n * model at resolve time, so a run that names a model outside the allowed set throws before\n * any compute is spent — never silently swapped or silently allowed.\n */\nimport { ConfigError } from '../../errors'\n\n/**\n * Throw a `ConfigError` when `allowed` is set, `model` is defined, and `model` is not a\n * member of `allowed`. No-op when `allowed` is unset (the unrestricted default) or when\n * `model` is undefined (nothing was configured to check).\n */\nexport function assertModelAllowed(\n model: string | undefined,\n allowed: readonly string[] | undefined,\n): void {\n if (!allowed || model === undefined) return\n if (!allowed.includes(model)) {\n throw new ConfigError(\n `model ${JSON.stringify(model)} is not in the allowed set ${JSON.stringify([...allowed])}`,\n )\n }\n}\n","/**\n * @experimental\n *\n * Event-sourced spawn journal for the recursive execution atom (build steps 3 + 7).\n *\n * The supervision tree is journaled as an append-only event log: every `spawned`,\n * `settled`, and `cancelled` is recorded AFTER it is observed-committed (never\n * speculative), mirroring `ConversationJournal`'s begin/append/load shape. The log\n * holds only the THIN decision record — ids, parentage, budget, the spend a decision\n * consumed, and a content-addressed `outRef`. The payloads the driver branched on\n * (the `out` artifacts) live in a separate `ResultBlobStore`, keyed by `outRef`, so\n * the journal stays small (decisions) and replay rehydrates the exact `Settled` from\n * the blob store (evidence). This is the decision/payload split the replay argument\n * rests on (B1/B2).\n *\n * Replay determinism (B2): `seq` is the monotonic cursor order `scope.next()` yielded\n * each settlement — NOT wall-clock. `replaySpawnTree` sorts strictly by `seq` before\n * touching the blob store, so the order in which rehydration `get`s resolve can never\n * reorder the replayed `Settled[]`; the result is identical regardless of blob latency.\n */\n\nimport { createHash } from 'node:crypto'\nimport type {\n NodeId,\n NodeSnapshot,\n NodeStatus,\n ResultBlobStore,\n Runtime,\n Settled,\n SpawnEvent,\n SpawnJournal,\n Spend,\n TreeView,\n} from '../runtime/supervise/types'\nimport { zeroTokenUsage } from '../runtime/util'\n\n// ── Content addressing ──────────────────────────────────────────────────────\n\n/**\n * Mint the content-addressed `outRef` for a result artifact: `sha256:<hex>` over a\n * stable JSON encoding. Producers call this to derive the `outRef` they journal and\n * `put`; the FS/in-mem stores re-derive it on `put` to verify the supplied ref\n * matches (fail loud on a mismatch — a forged ref breaks the replay invariant).\n *\n * Stable encoding: object keys are sorted recursively so two structurally-equal\n * artifacts hash identically regardless of key insertion order.\n */\nexport function contentAddress(artifact: unknown): string {\n const hex = createHash('sha256').update(stableStringify(artifact), 'utf-8').digest('hex')\n return `sha256:${hex}`\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null'\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(',')}}`\n}\n\n// ── Result blob store ─────────────────────────────────────────────────────────\n\n/**\n * In-memory `ResultBlobStore`. Content-addressed: `put` verifies the supplied\n * `outRef` matches the artifact's hash so a stale/forged ref fails loud rather than\n * silently rehydrating the wrong payload. Idempotent on an identical re-put.\n */\nexport class InMemoryResultBlobStore implements ResultBlobStore {\n private readonly blobs = new Map<string, unknown>()\n\n async put(outRef: string, artifact: unknown): Promise<void> {\n assertContentAddress(outRef, artifact)\n this.blobs.set(outRef, artifact)\n }\n\n async get(outRef: string): Promise<unknown | undefined> {\n return this.blobs.has(outRef) ? this.blobs.get(outRef) : undefined\n }\n}\n\n/**\n * FS `ResultBlobStore`. One JSON file per artifact under `dir`, named by a\n * filesystem-safe encoding of the `outRef` (`sha256:<hex>` → `sha256-<hex>.json`).\n * `put` fsyncs so a crash between writes never loses an acknowledged blob.\n */\nexport class FileResultBlobStore implements ResultBlobStore {\n constructor(private readonly dir: string) {}\n\n async put(outRef: string, artifact: unknown): Promise<void> {\n assertContentAddress(outRef, artifact)\n const fs = await import('node:fs/promises')\n await fs.mkdir(this.dir, { recursive: true })\n const fh = await fs.open(this.blobPath(outRef), 'w')\n try {\n await fh.write(JSON.stringify(artifact))\n await fh.sync()\n } finally {\n await fh.close()\n }\n }\n\n async get(outRef: string): Promise<unknown | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.blobPath(outRef), 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n return JSON.parse(text)\n }\n\n private blobPath(outRef: string): string {\n return `${this.dir}/${outRef.replace(/:/g, '-')}.json`\n }\n}\n\nfunction assertContentAddress(outRef: string, artifact: unknown): void {\n const expected = contentAddress(artifact)\n if (outRef !== expected) {\n throw new Error(\n `blob outRef '${outRef}' does not match the artifact content hash '${expected}'; ` +\n 'a content-addressed store refuses a mismatched ref (breaks the replay invariant)',\n )\n }\n}\n\n// ── Spawn journal ──────────────────────────────────────────────────────────────\n\n/**\n * In-memory `SpawnJournal`. Appends are observed-committed only; the impl enforces\n * the corruption guards a durable replay rests on:\n * - an event before `beginTree` is a corrupted tree (fail loud),\n * - a duplicate `seq` within a tree is a corrupted cursor (fail loud) — two\n * settlements cannot share the cursor position replay orders by.\n */\nexport class InMemorySpawnJournal implements SpawnJournal {\n private readonly trees = new Map<NodeId, { begunAt: string; events: SpawnEvent[] }>()\n\n async loadTree(root: NodeId): Promise<SpawnEvent[] | undefined> {\n const tree = this.trees.get(root)\n if (!tree) return undefined\n return tree.events.map((ev) => ({ ...ev }))\n }\n\n async beginTree(root: NodeId, at: string): Promise<void> {\n const existing = this.trees.get(root)\n if (existing) {\n if (existing.begunAt !== at) {\n throw new Error(\n `spawn tree '${root}' already begun at ${existing.begunAt}; refusing to overwrite with ${at}`,\n )\n }\n return\n }\n this.trees.set(root, { begunAt: at, events: [] })\n }\n\n async appendEvent(root: NodeId, ev: SpawnEvent): Promise<void> {\n const tree = this.trees.get(root)\n if (!tree) {\n throw new Error(`appendEvent called for unknown spawn tree '${root}'; call beginTree first`)\n }\n assertSeqUnique(root, tree.events, ev)\n tree.events.push({ ...ev })\n }\n}\n\n/**\n * JSONL on disk. One line per record: the first record is `begin`, subsequent records\n * are `event` envelopes wrapping a `SpawnEvent`. `loadTree` replays the whole file,\n * filtering by `root`, and applies the same begin-precedes-events + unique-seq\n * corruption guards as the in-memory impl. Each append fsyncs so a crash between\n * writes never loses an acknowledged event.\n */\nexport class FileSpawnJournal implements SpawnJournal {\n constructor(private readonly path: string) {}\n\n async loadTree(root: NodeId): Promise<SpawnEvent[] | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.path, 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n const lines = text.split('\\n').filter((line) => line.length > 0)\n let begun = false\n const events: SpawnEvent[] = []\n for (const line of lines) {\n const record = JSON.parse(line) as SpawnJournalRecord\n if (record.root !== root) continue\n if (record.kind === 'begin') {\n begun = true\n } else {\n if (!begun) {\n throw new Error(\n `spawn journal corrupted: event for tree '${root}' precedes its begin record`,\n )\n }\n assertSeqUnique(root, events, record.event)\n events.push(record.event)\n }\n }\n return begun ? events : undefined\n }\n\n async beginTree(root: NodeId, at: string): Promise<void> {\n const existing = await this.loadTreeBegin(root)\n if (existing) {\n if (existing !== at) {\n throw new Error(\n `spawn tree '${root}' already begun in ${this.path} at ${existing}; refusing to overwrite with ${at}`,\n )\n }\n return\n }\n await this.appendRecord({ kind: 'begin', root, at })\n }\n\n async appendEvent(root: NodeId, ev: SpawnEvent): Promise<void> {\n const events = await this.loadTree(root)\n if (events === undefined) {\n throw new Error(`appendEvent called for unknown spawn tree '${root}'; call beginTree first`)\n }\n assertSeqUnique(root, events, ev)\n await this.appendRecord({ kind: 'event', root, event: ev })\n }\n\n private async loadTreeBegin(root: NodeId): Promise<string | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.path, 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n const lines = text.split('\\n').filter((line) => line.length > 0)\n for (const line of lines) {\n const record = JSON.parse(line) as SpawnJournalRecord\n if (record.root === root && record.kind === 'begin') return record.at\n }\n return undefined\n }\n\n private async appendRecord(record: SpawnJournalRecord): Promise<void> {\n const fs = await import('node:fs/promises')\n const path = await import('node:path')\n await fs.mkdir(path.dirname(this.path), { recursive: true })\n const fh = await fs.open(this.path, 'a')\n try {\n await fh.write(`${JSON.stringify(record)}\\n`)\n await fh.sync()\n } finally {\n await fh.close()\n }\n }\n}\n\ntype SpawnJournalRecord =\n | { kind: 'begin'; root: NodeId; at: string }\n | { kind: 'event'; root: NodeId; event: SpawnEvent }\n\n/**\n * Two `seq` namespaces share the journal: a `spawned` event's `seq` is the spawn ordinal\n * (the order children were created), and a `settled`/`cancelled` event's `seq` is the\n * monotonic CURSOR order `scope.next()` yielded that settlement (B2). The uniqueness\n * replay rests on is the cursor namespace — two settlements cannot share the position\n * replay orders by — so the guard checks only settled/cancelled events. A `spawned`\n * ordinal legitimately equals a later `settled` cursor seq and is not a collision.\n */\nfunction assertSeqUnique(root: NodeId, events: SpawnEvent[], ev: SpawnEvent): void {\n // `spawned` (ordinal namespace) and `metered` (informational spend, no settlement order) live\n // outside the cursor-uniqueness namespace replay relies on.\n if (ev.kind === 'spawned' || ev.kind === 'metered') return\n if (events.some((e) => e.kind !== 'spawned' && e.kind !== 'metered' && e.seq === ev.seq)) {\n throw new Error(\n `spawn journal corrupted: duplicate cursor seq ${ev.seq} in tree '${root}'; ` +\n 'the cursor order replay relies on is not unique',\n )\n }\n}\n\n// ── Replay executor (build step 7) ───────────────────────────────────────────────\n\n/**\n * Re-feed a journaled spawn tree in strict `seq` order, rehydrating each settled\n * child's `out` from the blob store by `outRef`, and return the `Settled[]` exactly\n * as `scope.next()` originally delivered them.\n *\n * Determinism (B2): the events are sorted by `seq` BEFORE any blob `get`, so the\n * replay order is the recorded cursor order regardless of how fast each rehydration\n * resolves. `at` (wall-clock) is never a replay input. Fail loud on a tree that was\n * never begun, a settled-done event missing its `outRef`, or a blob the store can't\n * rehydrate — a silent gap would let `act` branch on the wrong evidence.\n */\nexport async function replaySpawnTree(\n journal: SpawnJournal,\n blobs: ResultBlobStore,\n root: NodeId,\n): Promise<Settled<unknown>[]> {\n const events = await journal.loadTree(root)\n if (events === undefined) {\n throw new Error(`replaySpawnTree: no journaled tree for root '${root}'`)\n }\n const ordered = [...events].sort((a, b) => a.seq - b.seq)\n const labels = new Map<NodeId, string>()\n for (const ev of ordered) {\n if (ev.kind === 'spawned') labels.set(ev.id, ev.label)\n }\n const settled: Settled<unknown>[] = []\n for (const ev of ordered) {\n if (ev.kind === 'spawned') continue\n if (ev.kind === 'metered') continue // a spend record, not a settlement — irrelevant to replay\n if (ev.kind === 'cancelled') {\n settled.push({\n kind: 'down',\n handle: replayHandle(ev.id, labels.get(ev.id) ?? ev.id, 'cancelled'),\n reason: ev.reason,\n infra: false,\n restartCount: 0,\n seq: ev.seq,\n })\n continue\n }\n if (ev.status === 'down') {\n settled.push({\n kind: 'down',\n handle: replayHandle(ev.id, labels.get(ev.id) ?? ev.id, 'failed'),\n reason: ev.verdict?.notes ?? 'child down',\n infra: ev.infra === true,\n restartCount: 0,\n seq: ev.seq,\n })\n continue\n }\n if (ev.outRef === undefined) {\n throw new Error(\n `replaySpawnTree: settled-done event for '${ev.id}' (seq ${ev.seq}) has no outRef; ` +\n 'cannot rehydrate the result the driver branched on',\n )\n }\n const out = await blobs.get(ev.outRef)\n if (out === undefined) {\n throw new Error(\n `replaySpawnTree: blob store has no artifact for outRef '${ev.outRef}' (node '${ev.id}', seq ${ev.seq})`,\n )\n }\n settled.push({\n kind: 'done',\n handle: replayHandle(ev.id, labels.get(ev.id) ?? ev.id, 'done'),\n out,\n outRef: ev.outRef,\n verdict: ev.verdict,\n spent: ev.spent,\n seq: ev.seq,\n })\n }\n return settled\n}\n\nfunction replayHandle(id: NodeId, label: string, status: NodeStatus) {\n return {\n id,\n label,\n status,\n abort() {\n throw new Error(`cannot abort node '${id}': replayed handles are terminal, not live`)\n },\n }\n}\n\n/**\n * Materialize the live tree (`TreeView`) from a journaled event list for resume. Folds\n * `spawned`/`settled`/`cancelled` into a per-node snapshot in `seq` order, then adds each\n * `metered` event's driver-inference spend onto its node in a separate additive pass — so the\n * resumed view matches what `scope.view` showed at the recorded cursor position.\n */\nexport function materializeTreeView(events: SpawnEvent[]): TreeView {\n const nodes = new Map<NodeId, MutableSnapshot>()\n let root: NodeId | undefined\n // `spawned` (ordinal namespace) and `settled`/`cancelled` (cursor namespace) carry\n // overlapping `seq` values, so create every node before any update — process spawns in\n // ordinal order, then settlements/cancellations in cursor order. A settle/cancel for an\n // un-spawned node is a corrupted log (fail loud via requireNode).\n const spawns = events\n .filter((ev): ev is Extract<SpawnEvent, { kind: 'spawned' }> => ev.kind === 'spawned')\n .sort((a, b) => a.seq - b.seq)\n const settlements = events\n .filter((ev) => ev.kind !== 'spawned' && ev.kind !== 'metered')\n .sort((a, b) => a.seq - b.seq)\n for (const ev of spawns) {\n if (ev.parent === undefined && root === undefined) root = ev.id\n nodes.set(ev.id, {\n id: ev.id,\n parent: ev.parent,\n label: ev.label,\n status: 'pending',\n runtime: ev.runtime,\n budget: ev.budget,\n spent: zeroSpend(),\n })\n }\n for (const ev of settlements) {\n if (ev.kind === 'settled') {\n const node = requireNode(nodes, ev.id)\n node.status = ev.status === 'done' ? 'done' : 'failed'\n node.spent = ev.spent\n node.outRef = ev.outRef\n } else {\n const node = requireNode(nodes, ev.id)\n node.status = 'cancelled'\n }\n }\n // Driver inference: a separate pass so it accumulates ONTO the settled child-work base (no\n // dependence on metered-vs-settled seq order) without touching node status.\n for (const ev of events) {\n if (ev.kind !== 'metered') continue\n const node = requireNode(nodes, ev.id)\n node.spent = addJournalSpend(node.spent, ev.spend)\n }\n const snapshots = [...nodes.values()].map(freezeSnapshot)\n return {\n root: root ?? snapshots[0]?.id ?? '',\n nodes: snapshots,\n inFlight: snapshots.filter((n) => n.status === 'running' || n.status === 'acquiring').length,\n }\n}\n\ninterface MutableSnapshot {\n id: NodeId\n parent?: NodeId\n label: string\n status: NodeStatus\n runtime: Runtime\n budget: NodeSnapshot['budget']\n spent: Spend\n outRef?: string\n}\n\nfunction zeroSpend(): Spend {\n return { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 }\n}\n\n/** Add a `metered` spend record onto a node's accumulated spend (per channel). */\nfunction addJournalSpend(a: Spend, b: Spend): Spend {\n return {\n iterations: a.iterations + b.iterations,\n tokens: { input: a.tokens.input + b.tokens.input, output: a.tokens.output + b.tokens.output },\n usd: a.usd + b.usd,\n ms: a.ms + b.ms,\n }\n}\n\nfunction requireNode(nodes: Map<NodeId, MutableSnapshot>, id: NodeId): MutableSnapshot {\n const node = nodes.get(id)\n if (!node) {\n throw new Error(`spawn journal corrupted: settle/cancel for node '${id}' with no prior spawn`)\n }\n return node\n}\n\nfunction freezeSnapshot(node: MutableSnapshot): NodeSnapshot {\n return {\n id: node.id,\n parent: node.parent,\n label: node.label,\n status: node.status,\n runtime: node.runtime,\n budget: node.budget,\n spent: node.spent,\n outRef: node.outRef,\n }\n}\n\nfunction isNoEntError(err: unknown): boolean {\n return (\n typeof err === 'object' &&\n err !== null &&\n 'code' in err &&\n (err as { code: unknown }).code === 'ENOENT'\n )\n}\n","/**\n * @experimental\n *\n * Runtime hook contracts. Hooks are execution-scoped observers, not part of an\n * `AgentProfile`: profiles stay portable agent recipes; hooks attach to the\n * loop or product harness that is running the profile.\n */\n\nexport type RuntimeHookPhase = 'before' | 'after' | 'error' | 'event'\n\nexport type RuntimeHookTarget =\n | 'agent.run'\n | 'agent.turn'\n | 'agent.tool_call'\n | 'agent.spawn'\n | 'agent.child'\n | 'agent.plan'\n | 'agent.decision'\n | (string & {})\n\nexport type RuntimeDecisionKind =\n | 'continue'\n | 'verify'\n | 'ask'\n | 'retry'\n | 'stop'\n | 'memory-write'\n | 'memory-read'\n | 'tool-select'\n | 'skill-select'\n | 'workflow-select'\n | 'surface-promote'\n | (string & {})\n\nexport interface RuntimeHookEvent<Payload = unknown> {\n id: string\n runId: string\n scenarioId?: string\n target: RuntimeHookTarget\n phase: RuntimeHookPhase\n timestamp: number\n stepIndex?: number\n parentId?: string\n payload?: Payload\n metadata?: Record<string, unknown>\n}\n\nexport interface RuntimeHookContext {\n signal?: AbortSignal\n}\n\nexport interface RuntimeDecisionEvidenceRef {\n source: string\n id: string\n detail?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface RuntimeDecisionPoint {\n id: string\n runId: string\n scenarioId?: string\n stepIndex: number\n kind: RuntimeDecisionKind\n candidateActions: string[]\n context?: string\n evidence: RuntimeDecisionEvidenceRef[]\n metadata?: Record<string, unknown>\n}\n\nexport interface RuntimeHookErrorContext {\n hook: 'onEvent' | 'onDecisionPoint'\n eventId?: string\n target?: RuntimeHookTarget\n phase?: RuntimeHookPhase\n decisionId?: string\n decisionKind?: RuntimeDecisionKind\n}\n\n/**\n * The observation seam attached to a running loop (never to the portable genome).\n * Implement the optional hooks to receive lifecycle events, semantic decision points,\n * and hook errors. Author with {@link defineRuntimeHooks} for inference, and attach N\n * observers at once with {@link composeRuntimeHooks} — there is ONE event stream, not a\n * callback-prop zoo.\n */\nexport interface RuntimeHooks {\n /**\n * General before/after/event hook. Use this for telemetry, memory capture,\n * policy wrapping, child lifecycle observers, or product-specific extension\n * points.\n */\n onEvent?: (event: RuntimeHookEvent, context: RuntimeHookContext) => void | Promise<void>\n /**\n * Semantic decision hook. Belief-state evaluation consumes this, but runtime\n * code should keep emitting ordinary lifecycle events as the base layer.\n */\n onDecisionPoint?: (\n point: RuntimeDecisionPoint,\n context: RuntimeHookContext,\n ) => void | Promise<void>\n onHookError?: (error: Error, context: RuntimeHookErrorContext) => void | Promise<void>\n}\n\n/** Identity helper that types a {@link RuntimeHooks} literal so the fields are inferred. */\nexport function defineRuntimeHooks(hooks: RuntimeHooks): RuntimeHooks {\n return hooks\n}\n\n/**\n * Merge several {@link RuntimeHooks} into one. Falsy entries are dropped (so you can\n * pass `flag && hooks`), and every observer's `onEvent`/`onDecisionPoint` fires for each\n * event. Use this to attach N observers to a loop instead of a second event bus.\n */\nexport function composeRuntimeHooks(\n ...entries: Array<RuntimeHooks | undefined | null | false>\n): RuntimeHooks {\n const hooks = entries.filter((entry): entry is RuntimeHooks => !!entry)\n return {\n onEvent: hooks.some((hook) => hook.onEvent)\n ? (event, context) => {\n const pending: Promise<unknown>[] = []\n for (const hook of hooks) {\n const result = hook.onEvent?.(event, context)\n if (isThenable(result)) pending.push(Promise.resolve(result))\n }\n if (pending.length > 0) return Promise.all(pending).then(() => undefined)\n return undefined\n }\n : undefined,\n onDecisionPoint: hooks.some((hook) => hook.onDecisionPoint)\n ? (point, context) => {\n const pending: Promise<unknown>[] = []\n for (const hook of hooks) {\n const result = hook.onDecisionPoint?.(point, context)\n if (isThenable(result)) pending.push(Promise.resolve(result))\n }\n if (pending.length > 0) return Promise.all(pending).then(() => undefined)\n return undefined\n }\n : undefined,\n onHookError: hooks.some((hook) => hook.onHookError)\n ? (error, context) => {\n const pending: Promise<unknown>[] = []\n for (const hook of hooks) {\n const result = hook.onHookError?.(error, context)\n if (isThenable(result)) pending.push(Promise.resolve(result))\n }\n if (pending.length > 0) return Promise.all(pending).then(() => undefined)\n return undefined\n }\n : undefined,\n }\n}\n\nexport function notifyRuntimeHookEvent(\n hooks: RuntimeHooks | undefined,\n event: RuntimeHookEvent,\n context: RuntimeHookContext = {},\n): void {\n const onEvent = hooks?.onEvent\n if (!onEvent) return\n\n try {\n const result = onEvent(event, context)\n if (isThenable(result)) {\n void result.catch((error) => {\n notifyRuntimeHookError(hooks, toError(error), {\n hook: 'onEvent',\n eventId: event.id,\n target: event.target,\n phase: event.phase,\n })\n })\n }\n } catch (error) {\n notifyRuntimeHookError(hooks, toError(error), {\n hook: 'onEvent',\n eventId: event.id,\n target: event.target,\n phase: event.phase,\n })\n }\n}\n\nexport function notifyRuntimeDecisionPoint(\n hooks: RuntimeHooks | undefined,\n point: RuntimeDecisionPoint,\n context: RuntimeHookContext = {},\n): void {\n const onDecisionPoint = hooks?.onDecisionPoint\n if (!onDecisionPoint) return\n\n try {\n const result = onDecisionPoint(point, context)\n if (isThenable(result)) {\n void result.catch((error) => {\n notifyRuntimeHookError(hooks, toError(error), {\n hook: 'onDecisionPoint',\n decisionId: point.id,\n decisionKind: point.kind,\n })\n })\n }\n } catch (error) {\n notifyRuntimeHookError(hooks, toError(error), {\n hook: 'onDecisionPoint',\n decisionId: point.id,\n decisionKind: point.kind,\n })\n }\n}\n\nfunction notifyRuntimeHookError(\n hooks: RuntimeHooks | undefined,\n error: Error,\n context: RuntimeHookErrorContext,\n): void {\n try {\n const result = hooks?.onHookError?.(error, context)\n if (isThenable(result)) void result.catch(() => undefined)\n } catch {\n // Hook errors must never become agent-loop errors.\n }\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'then' in value &&\n typeof (value as { then?: unknown }).then === 'function'\n )\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error))\n}\n","/**\n * @experimental\n *\n * `acquireSandbox` — cold-start-resilient sandbox acquisition. Eliminates the\n * \"create timed out at the proxy\" failure mode conceptually by DECOUPLING \"the\n * create HTTP call returned\" from \"the sandbox is ready\":\n *\n * - Create is initiated with a known `name`.\n * - Readiness is observed from the sandbox's own `status` (`refresh()` polls\n * true state), NOT from whether the create call returned in time.\n * - If the create call itself times out at a gateway (502/503/504/522/524 or\n * a transport timeout), provisioning is still running server-side — so we\n * find the named sandbox via `list()` and wait for it to reach `running`.\n *\n * Result: a scale-from-zero cold start (node boot + host-agent registration,\n * minutes) can no longer surface as a create failure behind a ~100s proxy\n * limit. The loop becomes indifferent to whether the host pool is warm or cold.\n *\n * Invariant: an instance reporting no `status` (the minimal test fakes) is\n * treated as ready; only an explicit `pending`/`provisioning` status triggers\n * waiting, and only a retryable THROW triggers the find-by-name path. Real\n * errors (auth, validation, budget) fail loud. A box that is created (or found)\n * but never reaches `running` (abort, terminal status, budget) is torn down\n * before the failure propagates, so an abort storm during cold start does not\n * leak live sandboxes.\n */\n\nimport type { CreateSandboxOptions, SandboxInstance } from '@tangle-network/sandbox'\nimport { ValidationError } from '../errors'\nimport type { SandboxClient } from './types'\nimport { sleep as abortableSleep, deleteBoxSafe, randomUuid, throwIfAborted } from './util'\n\n/**\n * HTTP statuses where create should be retried — gateway timeouts\n * (502/503/504/522/524) where provisioning may continue server-side, plus\n * request-level retryables (408/425/429).\n */\nconst RETRYABLE_HTTP = new Set([502, 503, 504, 522, 524, 408, 425, 429])\nconst TERMINAL_STATUS = new Set(['failed', 'expired', 'stopped'])\n\n/** @experimental */\nexport interface AcquireOptions {\n /**\n * Total budget for the sandbox to reach `running`, covering on-demand node\n * cold-start. Default 600_000ms — matches the orchestrator's pending-host\n * registration window so we never give up before the platform itself would.\n */\n readyTimeoutMs?: number\n /** Poll interval while waiting for `running` / for the named sandbox to appear. */\n pollIntervalMs?: number\n /** Cancellation (user abort). Distinct from create-call timeouts. */\n signal?: AbortSignal\n /** Stamp a name so a timed-out create is recoverable by lookup. Auto-generated if absent. */\n name?: string\n /** Clock override for deterministic tests. */\n now?: () => number\n /** Sleep override for deterministic tests. */\n sleep?: (ms: number) => Promise<void>\n}\n\n/** Minimal client surface acquire needs beyond `create` (the real SDK satisfies it). */\ninterface PollableClient extends SandboxClient {\n list?: (options?: unknown) => Promise<SandboxInstance[]>\n get?: (id: string) => Promise<SandboxInstance | null>\n}\n\n/** @experimental */\nexport async function acquireSandbox(\n client: SandboxClient,\n options: CreateSandboxOptions,\n acquire: AcquireOptions = {},\n): Promise<SandboxInstance> {\n if (!client || typeof client.create !== 'function') {\n throw new ValidationError('acquireSandbox: client.create is required')\n }\n const now = acquire.now ?? Date.now\n const sleep = acquire.sleep ?? ((ms: number) => abortableSleep(ms, acquire.signal))\n const pollMs = acquire.pollIntervalMs ?? 3000\n const deadline = now() + (acquire.readyTimeoutMs ?? 600_000)\n // After a retryable create error (commonly a gateway/request timeout on a cold\n // scale-from-zero), the orchestrator has usually ACCEPTED the request and is\n // still provisioning the NAMED box — which appears in list() a few seconds\n // AFTER the create call gave up. Scan list() this many windows for it to\n // appear before re-POSTing: re-creating immediately restarts a fresh cold\n // provision and hits the same wall — that thrash is why a cold acquire never\n // converges within the budget; attaching to the in-flight box does.\n const appearScans = 5\n // crypto.randomUUID is collision-resistant — find-by-name recovery scans\n // list() for this exact name, so two concurrent acquires must never collide.\n const name = options.name ?? acquire.name ?? `loop-sbx-${randomUuid()}`\n const createOpts: CreateSandboxOptions = { ...options, name }\n const c = client as PollableClient\n\n let lastErr: unknown\n let attempt = 0\n while (now() < deadline) {\n throwIfAborted(acquire.signal)\n try {\n const box = await client.create(createOpts)\n // Tear the just-created box down if it never reaches `running` (abort,\n // terminal status, budget) so a failed wait never leaks a live sandbox.\n return await waitReadyOrDestroy(box, deadline, pollMs, acquire.signal, now, sleep)\n } catch (err) {\n throwIfAborted(acquire.signal)\n // Non-retryable (auth/validation/budget) fails loud immediately.\n if (!isRetryable(err)) throw err\n lastErr = err\n // Recovery for a gateway-timed-out create, in order:\n // (a) the orchestrator usually ACCEPTED the create and is provisioning\n // the named box — it appears in list() a few seconds later, so poll\n // for it across `appearScans` windows and attach (this is the cold-\n // start fix: a single scan misses a row not yet written and the loop\n // would otherwise re-POST a fresh cold provision every backoff);\n // (b) only if it never appears did the create truly roll back — retry\n // create with backoff (lands once a warm host exists / autoscaler\n // caught up).\n if (typeof c.list === 'function') {\n for (let scan = 0; scan < appearScans && now() < deadline; scan += 1) {\n const found = (await c.list().catch(() => []))?.find((b) => b.name === name)\n if (found)\n return await waitReadyOrDestroy(found, deadline, pollMs, acquire.signal, now, sleep)\n if (scan < appearScans - 1) await sleep(pollMs)\n }\n }\n attempt += 1\n await sleep(Math.min(pollMs * attempt, 15_000))\n }\n }\n throw new ValidationError(\n `acquireSandbox: could not acquire a running sandbox \"${name}\" within budget`,\n { cause: lastErr instanceof Error ? lastErr : undefined },\n )\n}\n\n/** `waitUntilReady`, tearing the box down (best-effort) on any throw so a box\n * that never reaches `running` (abort, terminal status, budget) does not leak. */\nasync function waitReadyOrDestroy(\n box: SandboxInstance,\n deadline: number,\n pollMs: number,\n signal: AbortSignal | undefined,\n now: () => number,\n sleep: (ms: number) => Promise<void>,\n): Promise<SandboxInstance> {\n try {\n return await waitUntilReady(box, deadline, pollMs, signal, now, sleep)\n } catch (err) {\n await deleteBoxSafe(box)\n throw err\n }\n}\n\n/** Wait for `running`. No status (minimal fakes) = ready. Terminal status throws. */\nasync function waitUntilReady(\n box: SandboxInstance,\n deadline: number,\n pollMs: number,\n signal: AbortSignal | undefined,\n now: () => number,\n sleep: (ms: number) => Promise<void>,\n): Promise<SandboxInstance> {\n for (;;) {\n throwIfAborted(signal)\n const status = readStatus(box)\n if (status === undefined || status === 'running') return box\n if (TERMINAL_STATUS.has(status)) {\n throw new ValidationError(\n `acquireSandbox: sandbox ${box.id ?? '(unknown)'} is ${status}${box.error ? `: ${box.error}` : ''}`,\n )\n }\n if (now() >= deadline) {\n throw new ValidationError(\n `acquireSandbox: sandbox ${box.id ?? '(unknown)'} not running within budget (last status: ${status})`,\n )\n }\n await sleep(pollMs)\n if (typeof box.refresh === 'function') await box.refresh()\n }\n}\n\nfunction readStatus(box: SandboxInstance): string | undefined {\n const s = (box as { status?: unknown }).status\n return typeof s === 'string' ? s : undefined\n}\n\nfunction isRetryable(err: unknown): boolean {\n if (!err || typeof err !== 'object') return false\n const e = err as { status?: number; statusCode?: number; name?: string; message?: string }\n const status = e.status ?? e.statusCode\n if (typeof status === 'number' && RETRYABLE_HTTP.has(status)) return true\n const name = e.name ?? ''\n if (name === 'TimeoutError' || name === 'ServerError' || name === 'NetworkError') return true\n const msg = e.message ?? ''\n // Transient TRANSPORT failures.\n if (\n /\\b(timed out|timeout|gateway|temporarily unavailable|too many requests|ECONNRESET|ETIMEDOUT|EAI_AGAIN)\\b/i.test(\n msg,\n )\n ) {\n return true\n }\n // Transient PLATFORM provisioning failures thrown by `create` itself — edge data\n // plane unreachable, container-phase provision failure, or a rolled-back create.\n // Retry create onto a FRESH host rather than failing the whole rollout; the loop\n // stays bounded by the ready deadline. A box that booted and then reached a\n // terminal `failed` status with a real error is NOT retried here — that's a genuine\n // fault surfaced by `waitUntilReady`, not a host blip.\n return /provision failed|edge data plane|not reachable|failed to create sandbox/i.test(msg)\n}\n","/**\n * @experimental\n *\n * Capability probe for the loop kernel's backend-blind lineage seams. The\n * kernel must NEVER ask \"is this Docker or Firecracker?\"; it asks \"can this\n * platform fork a checkpoint?\" via `client.criuStatus()` and degrades to fresh\n * boxes when the answer is no. CRIU availability is a per-platform fact, so the\n * probe is memoized per client — one network round-trip, reused across every\n * fanout in the run.\n *\n * Invariant: a client with no `criuStatus` method (the loop's test fakes, the\n * raw SDK before it grew the probe) reports `canFork = false`. The seam is\n * fail-CLOSED — never assume forking works, only enable it on a positive probe.\n */\n\nimport type { SandboxClient } from './types'\n\n/**\n * What the loop kernel is allowed to know about a sandbox backend: a single\n * capability bit, never the backend's identity. `canFork` gates the\n * checkpoint+fork fanout path; everything else (session continuation) is a\n * universal SDK feature that needs no probe.\n *\n * @experimental\n */\nexport interface SandboxCapabilities {\n /**\n * True only when `client.criuStatus()` returned `{ available: true }`. When\n * false, a fork-enabled fanout degrades to independent fresh boxes — same\n * result, no shared context prefix.\n */\n canFork: boolean\n}\n\nconst probeCache = new WeakMap<object, Promise<SandboxCapabilities>>()\n\n/**\n * Probe (and memoize per client) what the loop may rely on. A client without a\n * `criuStatus` method, or whose probe rejects, yields `canFork = false` — a\n * failed probe must never claim a capability the platform may not have. The\n * promise is cached so concurrent fanout branches share one round-trip.\n *\n * @experimental\n */\nexport function probeSandboxCapabilities(client: SandboxClient): Promise<SandboxCapabilities> {\n const key = client as unknown as object\n const cached = probeCache.get(key)\n if (cached) return cached\n const probe = resolveCapabilities(client)\n probeCache.set(key, probe)\n return probe\n}\n\nasync function resolveCapabilities(client: SandboxClient): Promise<SandboxCapabilities> {\n const criuStatus = (client as CriuCapableClient).criuStatus\n if (typeof criuStatus !== 'function') return { canFork: false }\n try {\n const status = await criuStatus.call(client)\n return { canFork: status?.available === true }\n } catch {\n // A probe that throws (transport error, unsupported endpoint) is treated as\n // \"no fork\" — fail closed so a flaky probe degrades to fresh boxes rather\n // than attempting a checkpoint the platform can't honor.\n return { canFork: false }\n }\n}\n\n/**\n * Narrowed view of the optional CRIU probe. The loop-side `SandboxClient`\n * does not require `criuStatus`; this widens it optionally so the probe can be\n * read without importing sandbox-backend specifics. @experimental\n */\nexport interface CriuCapableClient {\n criuStatus?: () => Promise<{ available: boolean; criuVersion?: string; reason?: string }>\n}\n","/**\n * @experimental\n *\n * Backend-options assembly shared by the loop kernel's `createSandboxForSpec`\n * and the sandbox planner's box creation, so the worker box and the planner box\n * boot identically. Builds the options only — the acquire path (cold-start\n * recovery) lives in the kernel, the planner calls `client.create` directly.\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport type { CreateSandboxOptions } from '@tangle-network/sandbox'\n\ntype BackendType = NonNullable<CreateSandboxOptions['backend']>['type']\ntype BackendOverride = NonNullable<CreateSandboxOptions['backend']>\n\n/**\n * Resolve the backend `type`: an explicit override wins, then the profile's\n * `metadata.backendType` hint, else the SDK's profile-driven default\n * (`'opencode'` on the platform side). A profile with no hint falls through to\n * the default rather than asserting provenance the profile never declared.\n */\nfunction resolveBackendType(\n profile: AgentProfile,\n override: Partial<BackendOverride> | undefined,\n): BackendType {\n if (override?.type) return override.type\n const explicit = profile.metadata?.backendType\n if (typeof explicit === 'string') return explicit as BackendType\n return 'opencode' as BackendType\n}\n\n/**\n * Build `CreateSandboxOptions` for `profile`, merging `overrides` and setting\n * `backend.profile`. `model`/`server` from an override backend pass through.\n */\nexport function buildBackendOptions(\n profile: AgentProfile,\n overrides: Partial<CreateSandboxOptions> | undefined,\n): CreateSandboxOptions {\n const base = overrides ?? {}\n const overrideBackend = base.backend\n return {\n ...base,\n backend: {\n type: resolveBackendType(profile, overrideBackend),\n profile,\n ...(overrideBackend?.model ? { model: overrideBackend.model } : {}),\n ...(overrideBackend?.server ? { server: overrideBackend.server } : {}),\n },\n }\n}\n","/**\n * @experimental\n *\n * `SandboxLineage` — the backend-blind owner of box + session handles for a\n * single `runLoop` invocation. It exists so `run-loop.ts` never references a\n * backend (Docker / Firecracker): the lineage turns \"continue this session\" and\n * \"fork this branch\" into capability-gated sandbox-SDK calls and degrades to\n * fresh boxes when a capability is absent.\n *\n * Three operations, mirroring the kernel's per-iteration choices:\n * - `start(spec, prompt)` → a fresh box; the FIRST `streamPrompt` carries a\n * minted `sessionId` so later `continue` calls reuse the same server-side\n * conversation instead of re-injecting prior context as prompt text.\n * - `continue(handle, prompt)` → the SAME box, `streamPrompt({ sessionId })`.\n * The context lives in the sandbox; the prompt is only the new turn. Before\n * streaming it ASSERTS the session is still live server-side (via\n * `box.session(id).status()`): if the platform never honored the\n * client-minted id (or reaped it), `status()` is `null` and `continue`\n * fails loud rather than silently re-running the turn without prior context.\n * - `fork(handle, n, ...)` → when `canFork`, `checkpoint({ leaveRunning })` on\n * the parent then `fork(checkpointId)` × n so N branches inherit a shared\n * context prefix; otherwise N independent fresh boxes (same result, no\n * prefix). Either way each branch streams its own turn. Child-box creation\n * is bounded by the lineage's `maxConcurrency` — a 20-way fanout under a\n * concurrency cap of 2 provisions boxes in bounded waves, not all at once.\n *\n * Invariant: the lineage OWNS every box it starts or forks and tears them all\n * down on `teardown()` (or earlier via `prune`). It never tears down a box\n * mid-flight — the kernel decides when a handle is done. Streaming itself stays\n * in `run-loop.ts`; the lineage only hands back the live `streamPrompt` iterable\n * so the kernel keeps ownership of event collection, cost accounting, and trace\n * emission.\n */\n\nimport type { CreateSandboxOptions, SandboxEvent, SandboxInstance } from '@tangle-network/sandbox'\nimport { ValidationError } from '../errors'\nimport { acquireSandbox } from './sandbox-acquire'\nimport { buildBackendOptions } from './sandbox-backend'\nimport type { SandboxCapabilities } from './sandbox-capabilities'\nimport type { AgentRunSpec, MountRecorder, SandboxClient } from './types'\nimport {\n deleteBoxSafe,\n mapWithConcurrency,\n randomUuid,\n throwAbort,\n throwIfAborted,\n withTimeout,\n} from './util'\n\nconst TEARDOWN_TIMEOUT_MS = 15_000\nconst DEFAULT_FORK_CONCURRENCY = 4\n\n/**\n * One turn's event stream, in the lineage's chosen streaming mode.\n *\n * - `'sse'` (default): live `streamPrompt` — low latency, full per-token trace.\n * Best for interactive chat.\n * - `'poll'`: fire-and-detach via `dispatchPrompt`, await the terminal result by\n * status-polling (NOT a held SSE), then yield the answer as one synthesized\n * event. A long, quiet in-box turn (clone + build + test) never holds a live\n * stream a proxy idle-timeout can drop mid-execution — the failure mode that\n * made batch eval runs lose their stream on both prod and staging. Lower trace\n * fidelity (one terminal event, not per-token), so it is opt-in for batch.\n *\n * Both yield the same `SandboxEvent` vocabulary, so callers are agnostic.\n */\nasync function* pollPromptEvents(\n box: SandboxInstance,\n prompt: string,\n sessionId: string,\n signal: AbortSignal,\n): AsyncIterable<SandboxEvent> {\n if (signal.aborted) throwAbort()\n // dispatchPrompt returns the session id the platform actually assigned, which\n // may be one it MINTED rather than the supplied `sessionId`. Polling the\n // supplied id when the platform minted a different one 404s the session-events\n // endpoint (\"Resource not found\"). Always follow the assigned id.\n const dispatched = await box.dispatchPrompt(prompt, { sessionId, signal })\n const activeSessionId = dispatched.sessionId\n const result = await box.session(activeSessionId).result()\n if (signal.aborted) throwAbort()\n yield {\n type: 'result',\n id: activeSessionId,\n data: {\n finalText: result.response ?? '',\n success: result.success,\n ...(result.error ? { error: result.error } : {}),\n ...(result.usage ? { usage: result.usage } : {}),\n },\n }\n}\n\nexport function promptEvents(\n streaming: 'sse' | 'poll',\n box: SandboxInstance,\n prompt: string,\n sessionId: string,\n signal: AbortSignal,\n): AsyncIterable<SandboxEvent> {\n return streaming === 'poll'\n ? pollPromptEvents(box, prompt, sessionId, signal)\n : box.streamPrompt(prompt, { sessionId, signal })\n}\n\n/**\n * A live box plus the session that threads its iterations together. Handed back\n * by `start`/`fork`, passed into `continue`/`fork` to descend from. Opaque to\n * the kernel beyond `box` (for placement/teardown) and `sessionId` (trace).\n *\n * @experimental\n */\nexport interface SandboxLineageHandle {\n /** The owned, running sandbox this handle drives. */\n box: SandboxInstance\n /**\n * Stable session id threaded through this box's `streamPrompt` calls. Minted\n * by the lineage on `start`; reused on `continue` so the server continues the\n * same conversation. A forked handle starts a fresh session on its new box —\n * the shared context comes from the checkpoint, not a shared session id.\n */\n sessionId: string\n}\n\n/**\n * Owns box + session handles for one loop run and offers the three\n * capability-gated lifecycle moves. Construct via `createSandboxLineage`.\n *\n * @experimental\n */\nexport interface SandboxLineage {\n /**\n * Acquire a fresh box and begin a new session on it. Returns the handle and\n * the live `streamPrompt` iterable for the first turn (caller drains it).\n */\n start(\n spec: AgentRunSpec<unknown>,\n prompt: string,\n signal: AbortSignal,\n ): Promise<{ handle: SandboxLineageHandle; events: AsyncIterable<SandboxEvent> }>\n /**\n * Continue an existing handle's session with one more turn on the SAME box.\n * The prior context is server-side; `prompt` is only the new turn. Asserts the\n * session is still known to the sandbox first (fail-loud) so a platform that\n * silently dropped the client-minted session id surfaces as an error instead\n * of a contextless turn the caller mistakes for a real continuation.\n */\n continue(\n handle: SandboxLineageHandle,\n prompt: string,\n signal: AbortSignal,\n ): Promise<AsyncIterable<SandboxEvent>>\n /**\n * Branch `count` children from `parent`. When the platform can fork, each\n * child inherits `parent`'s checkpoint — and therefore the parent's IMAGE and\n * PROFILE: under a real fork `specs[i]` does NOT re-select a per-branch\n * profile (the SDK forks the running box, it can't swap the image). `specs[i]`\n * picks the per-branch profile ONLY on the degraded fresh-box path (no CRIU).\n * A heterogeneous-profile fanout therefore homogenizes to the parent's profile\n * when fork is available — pass a single shared spec for forked fanouts, or\n * use `random@k` (no fork) when branches must differ. Each child's first turn\n * streams `prompts[i]`. Child-box creation is bounded by `maxConcurrency`.\n */\n fork(\n parent: SandboxLineageHandle,\n prompts: string[],\n specs: AgentRunSpec<unknown>[],\n signal: AbortSignal,\n ): Promise<{ handle: SandboxLineageHandle; events: AsyncIterable<SandboxEvent> }[]>\n /**\n * Destroy every owned box whose handle is NOT in `keep`, freeing it before\n * loop end. The kernel calls this after a round when it can prove no future\n * round will descend from the pruned boxes (deterministic, monotonic branch\n * selection); boxes still reachable as a future branch source are retained.\n * Best-effort, bounded, parallel — a failed delete never throws.\n */\n prune(keep: Iterable<SandboxLineageHandle>): Promise<void>\n /** Destroy every box this lineage owns. Best-effort, bounded, parallel. */\n teardown(): Promise<void>\n}\n\n/**\n * Build a lineage bound to one client + its probed capabilities. The\n * capabilities are passed in (not re-probed) so the kernel probes once per run\n * and the lineage stays a pure function of \"what this platform can do\".\n *\n * @experimental\n */\nexport function createSandboxLineage(\n client: SandboxClient,\n capabilities: SandboxCapabilities,\n options: {\n maxConcurrency?: number\n streaming?: 'sse' | 'poll'\n /** Run provenance recorder forwarded to every `prepareBox` the lineage runs\n * (fresh start, continue, and fork branches). Absent ⇒ mounts go unrecorded\n * (a no-op recorder stands in so the ctx shape is always satisfied). */\n recordMount?: MountRecorder\n } = {},\n): SandboxLineage {\n if (!client || typeof client.create !== 'function') {\n throw new ValidationError('createSandboxLineage: client.create is required')\n }\n // 'sse' (default) preserves the byte-identical live-stream behavior; 'poll' is\n // the drop-resilient fire-and-detach path for long, quiet batch turns.\n const streaming = options.streaming ?? 'sse'\n const recordMount: MountRecorder = options.recordMount ?? (() => {})\n // Bounds the burst of box creation inside `fork` so an N-way fanout doesn't\n // provision N boxes simultaneously regardless of the loop's concurrency cap.\n const forkConcurrency = Math.max(\n 1,\n Math.floor(options.maxConcurrency ?? DEFAULT_FORK_CONCURRENCY),\n )\n const owned: SandboxInstance[] = []\n\n const acquireFresh = async (\n spec: AgentRunSpec<unknown>,\n signal: AbortSignal,\n ): Promise<SandboxInstance> => {\n if (signal.aborted) throwAbort()\n const opts: CreateSandboxOptions = buildBackendOptions(spec.profile, spec.sandboxOverrides)\n const box = await acquireSandbox(client, opts, { signal })\n await spec.prepareBox?.(box, { signal, recordMount })\n owned.push(box)\n return box\n }\n\n return {\n async start(spec, prompt, signal) {\n const box = await acquireFresh(spec, signal)\n const sessionId = mintSessionId()\n const events = promptEvents(streaming, box, prompt, sessionId, signal)\n return { handle: { box, sessionId }, events }\n },\n\n async continue(handle, prompt, signal) {\n if (signal.aborted) throwAbort()\n // Fail loud if the platform did not preserve the client-minted session:\n // continuing a dead/unknown session would silently lose all prior context.\n await assertSessionLive(handle.box, handle.sessionId)\n // Same box, same session id — the server continues the conversation; we do\n // NOT re-acquire and do NOT re-inject prior context as prompt text.\n return promptEvents(streaming, handle.box, prompt, handle.sessionId, signal)\n },\n\n async fork(parent, prompts, specs, signal) {\n if (prompts.length === 0) {\n throw new ValidationError('SandboxLineage.fork: prompts must be non-empty')\n }\n if (signal.aborted) throwAbort()\n const checkpointId = capabilities.canFork\n ? await checkpointForFork(parent.box, signal)\n : undefined\n // checkpointId === undefined ⇒ either the platform can't fork or the\n // checkpoint call yielded nothing usable: degrade to independent fresh\n // boxes. Never silently reuse the parent box for a branch.\n //\n // Bounded by `forkConcurrency`: an N-way fanout creates child boxes in\n // waves of at most `forkConcurrency`, not all N at once. Abort is checked\n // per branch (between waves), since the SDK's `fork`/`create` calls take no\n // signal and cannot be interrupted once in flight.\n return mapWithConcurrency(prompts, forkConcurrency, async (prompt, i) => {\n throwIfAborted(signal)\n const spec = specs[i % specs.length]\n if (!spec) throw new ValidationError('SandboxLineage.fork: no AgentRunSpec for branch')\n if (checkpointId !== undefined) {\n const box = await forkFromCheckpoint(parent.box, checkpointId, signal)\n owned.push(box)\n await spec.prepareBox?.(box, { signal, recordMount })\n const sessionId = mintSessionId()\n return {\n handle: { box, sessionId },\n events: promptEvents(streaming, box, prompt, sessionId, signal),\n }\n }\n const box = await acquireFresh(spec, signal)\n const sessionId = mintSessionId()\n return {\n handle: { box, sessionId },\n events: promptEvents(streaming, box, prompt, sessionId, signal),\n }\n })\n },\n\n async prune(keep) {\n const keepBoxes = new Set<SandboxInstance>()\n for (const handle of keep) keepBoxes.add(handle.box)\n const survivors: SandboxInstance[] = []\n const doomed: SandboxInstance[] = []\n for (const box of owned) (keepBoxes.has(box) ? survivors : doomed).push(box)\n if (doomed.length === 0) return\n owned.length = 0\n owned.push(...survivors)\n await Promise.allSettled(doomed.map((box) => destroyBounded(box)))\n },\n\n async teardown() {\n const boxes = owned.splice(0, owned.length)\n await Promise.allSettled(boxes.map((box) => destroyBounded(box)))\n },\n }\n}\n\n/** Stable, collision-resistant session id minted per box (the caller owns the id). */\nfunction mintSessionId(): string {\n return `loop-sess-${randomUuid()}`\n}\n\n/**\n * Checkpoint the parent leaving it running, returning the checkpoint id to fork\n * from, or `undefined` when the box exposes no `checkpoint` (the loop's fakes)\n * or the call produced no id. `undefined` makes the caller degrade to fresh\n * boxes — a fork that can't checkpoint must not pretend to share context.\n */\nasync function checkpointForFork(\n box: SandboxInstance,\n signal: AbortSignal,\n): Promise<string | undefined> {\n const checkpoint = (box as CheckpointCapableBox).checkpoint\n if (typeof checkpoint !== 'function') return undefined\n if (signal.aborted) throwAbort()\n const result = await checkpoint.call(box, { leaveRunning: true })\n const id = result?.checkpointId\n return typeof id === 'string' && id.length > 0 ? id : undefined\n}\n\n/**\n * Fork a child box from `checkpointId`. The box exposes `fork` whenever the\n * platform advertised `canFork`; a missing `fork` here is a contract violation\n * (probe said yes, box says no) and fails loud rather than silently degrading.\n *\n * `signal` gates entry only: the SDK's `fork(checkpointId, options)` takes no\n * abort signal (`ForkOptions` is name/env/resources/metadata), so an in-flight\n * fork cannot be interrupted. The caller (`fork`) checks abort per branch, so\n * cancellation is responsive at branch boundaries, not mid-fork.\n */\nasync function forkFromCheckpoint(\n box: SandboxInstance,\n checkpointId: string,\n signal: AbortSignal,\n): Promise<SandboxInstance> {\n const fork = (box as ForkCapableBox).fork\n if (typeof fork !== 'function') {\n throw new ValidationError(\n 'SandboxLineage.fork: capabilities report canFork but the box has no fork() method',\n )\n }\n if (signal.aborted) throwAbort()\n return fork.call(box, checkpointId)\n}\n\n/**\n * Fail loud when a handle's session is no longer known to the sandbox. The real\n * SDK box exposes `session(id).status()` which resolves `null` for an unknown /\n * reaped id; a `null` here means a `continue` would run WITHOUT the prior\n * context the caller believes is threaded — so refuse it. Boxes that expose no\n * `session` method (the loop's test fakes, or an SDK without the session API)\n * cannot be verified and are allowed through unchecked.\n */\nasync function assertSessionLive(box: SandboxInstance, sessionId: string): Promise<void> {\n const session = (box as SessionCapableBox).session\n if (typeof session !== 'function') return\n const info = await session.call(box, sessionId).status()\n if (info === null) {\n throw new ValidationError(\n `SandboxLineage.continue: session ${sessionId} is not known to the sandbox — the platform ` +\n 'did not preserve the client-minted session id (or it was reaped). Continuing would run ' +\n 'without prior context; refusing to silently lose conversation continuity.',\n )\n }\n}\n\nasync function destroyBounded(box: SandboxInstance): Promise<void> {\n await withTimeout(deleteBoxSafe(box), TEARDOWN_TIMEOUT_MS)\n}\n\n/**\n * Loop-side widening of the box's optional checkpoint method. The\n * `SandboxClient`/`SandboxInstance` surface the kernel relies on does not\n * require checkpointing; this reads it optionally so the lineage can probe-gate\n * without importing sandbox-backend specifics. @experimental\n */\nexport interface CheckpointCapableBox {\n checkpoint?: (options?: { leaveRunning?: boolean; tags?: string[] }) => Promise<{\n checkpointId: string\n }>\n}\n\n/** Loop-side widening of the box's optional fork method. @experimental */\nexport interface ForkCapableBox {\n fork?: (checkpointId: string, options?: { name?: string }) => Promise<SandboxInstance>\n}\n\n/**\n * Loop-side widening of the box's optional session accessor. The real\n * `SandboxInstance` exposes `session(id).status()`; the loop reads it optionally\n * so `continue` can assert session liveness without requiring it of the test\n * fakes. `status()` resolves `null` when the id is unknown to the sandbox.\n * @experimental\n */\nexport interface SessionCapableBox {\n session?: (id: string) => { status: () => Promise<unknown | null> }\n}\n","/**\n * @experimental\n *\n * `runLoop` — the topology-agnostic kernel built atop the sandbox SDK.\n *\n * Each iteration:\n * 1. `driver.plan(task, history)` → N tasks (1 = refine, N = fanout, 0 = stop)\n * 2. For each task (parallel, bounded by `maxConcurrency`):\n * a. round-robin an `AgentRunSpec` from `agentRuns`\n * b. `sandboxClient.create({ backend: { profile }, ...overrides })`\n * c. emit `loop.iteration.dispatch` with the placement\n * (`{ sibling, sandboxId }` or `{ fleet, fleetId, machineId, sandboxId }`)\n * d. iterate `box.streamPrompt(taskToPrompt(task))` and collect events\n * 3. `output.parse(events)` → typed `Output`\n * 4. `validator?.validate(output)` → `DefaultVerdict`\n * 5. Append `Iteration` to history; emit `loop.iteration.ended`\n * 6. `driver.decide(history)` → if terminal, return result + winner\n *\n * The kernel owns: iteration accounting, per-iteration timing, error\n * capture, abort propagation, concurrency cap, cost aggregation, and trace\n * emission. The kernel does NOT own: what the agent runs (sandbox SDK +\n * profile), how outputs are decoded (output adapter), how outputs are\n * scored (validator), or topology (driver).\n */\n\nimport type { SandboxEvent, SandboxInstance } from '@tangle-network/sandbox'\nimport { ValidationError } from '../errors'\nimport { notifyRuntimeHookEvent } from '../runtime-hooks'\nimport { acquireSandbox } from './sandbox-acquire'\nimport { buildBackendOptions } from './sandbox-backend'\nimport { probeSandboxCapabilities } from './sandbox-capabilities'\nimport { extractLlmCallEvent } from './sandbox-events'\nimport {\n createSandboxLineage,\n promptEvents,\n type SandboxLineage,\n type SandboxLineageHandle,\n} from './sandbox-lineage'\nimport type {\n AgentRunSpec,\n Driver,\n ExecCtx,\n Iteration,\n LoopLineageOptions,\n LoopResult,\n LoopSandboxPlacement,\n LoopTokenUsage,\n LoopTraceEmitter,\n LoopTraceEvent,\n LoopWinner,\n MountManifestEntry,\n MountRecorder,\n OutputAdapter,\n SandboxClient,\n SelectionReceipt,\n Validator,\n} from './types'\nimport {\n addTokenUsage,\n deleteBoxSafe,\n randomSuffix,\n stringifySafe,\n throwAbort,\n withTimeout,\n zeroTokenUsage,\n} from './util'\n\nconst DEFAULT_MAX_ITERATIONS = 10\nconst DEFAULT_MAX_CONCURRENCY = 4\n\n/** @experimental */\nexport interface RunLoopOptions<Task, Output, Decision> {\n driver: Driver<Task, Output, Decision>\n /**\n * Single agent spec — every iteration uses this profile. Mutually\n * exclusive with `agentRuns`.\n */\n agentRun?: AgentRunSpec<Task>\n /**\n * Multiple specs for heterogeneous fanout. The kernel round-robins\n * through them when the driver plans N tasks. Mutually exclusive with\n * `agentRun`.\n */\n agentRuns?: AgentRunSpec<Task>[]\n output: OutputAdapter<Output>\n validator?: Validator<Output>\n task: Task\n ctx: ExecCtx\n /** Default 10. Hard cap on total iterations across all `plan()` rounds. */\n maxIterations?: number\n /** Default 4. In-flight worker cap within a single `plan()` batch. */\n maxConcurrency?: number\n /**\n * Pre-allocated id for trace correlation. Default = `loop-${random}`.\n * Surfaces as `runId` on every emitted `LoopTraceEvent`.\n */\n runId?: string\n /**\n * Clock override; default `Date.now`. Deterministic tests pass a\n * monotonic counter to stabilize iteration timing fields.\n */\n now?: () => number\n /**\n * Override the default winner selector (highest-valid-score, ties broken\n * by earliest iteration).\n */\n selectWinner?: (iterations: Iteration<Task, Output>[]) => LoopWinner<Task, Output> | undefined\n /**\n * Same-sandbox driver mode — a kernel→caller out-channel, not a value handed\n * in. When set, the kernel keeps each finished worker box alive across the\n * `plan()` boundary and hands it here, so a same-sandbox planner\n * (one that reuses the worker's box) can stream its move INTO the\n * worker's live box — steering from the worker's real filesystem and state,\n * not just a history summary. The kernel owns teardown: every box kept alive\n * this way is destroyed at loop end (and the callback is invoked with\n * `undefined` then as a teardown sentinel). Without it, worker boxes are torn\n * down per-iteration (default) and a same-sandbox planner has nothing to\n * reuse. Intended for single-worker (refine) loops: under fanout every box is\n * still kept for teardown, but only the last-finishing box is handed here, so\n * a planner sees an arbitrary branch's filesystem — pair it with refine.\n */\n onWorkerBox?: (box: SandboxInstance | undefined) => void\n /**\n * Opt-in box-lineage controls. Default OFF — unset means every iteration\n * acquires a fresh box, streams once, and tears it down (today's behavior,\n * byte-identical). With `sessionContinuity` on, a refine round continues the\n * parent iteration's session on its live box; with `forkFanout` on (and a\n * fork-capable platform), a fanout round forks the parent's checkpoint so the\n * branches share a context prefix. The lineage owns every box it starts or\n * forks and tears them all down at loop end — so these paths are mutually\n * exclusive with `onWorkerBox`, which claims the same box-ownership channel.\n * @experimental\n */\n lineage?: LoopLineageOptions\n}\n\n/** @experimental */\nexport async function runLoop<Task, Output, Decision>(\n options: RunLoopOptions<Task, Output, Decision>,\n): Promise<LoopResult<Task, Output, Decision>> {\n const specs = resolveAgentRuns(options)\n const maxIterations = options.maxIterations ?? DEFAULT_MAX_ITERATIONS\n if (!Number.isFinite(maxIterations) || maxIterations <= 0) {\n throw new ValidationError('runLoop: maxIterations must be > 0')\n }\n const maxConcurrency = options.maxConcurrency ?? DEFAULT_MAX_CONCURRENCY\n if (!Number.isFinite(maxConcurrency) || maxConcurrency <= 0) {\n throw new ValidationError('runLoop: maxConcurrency must be > 0')\n }\n // Default fresh-box path streaming mode (read regardless of lineage activation,\n // which gates on sessionContinuity/forkFanout — the bench uses neither).\n const sandboxStreaming = options.lineage?.streaming ?? 'sse'\n if (!options.ctx?.sandboxClient || typeof options.ctx.sandboxClient.create !== 'function') {\n throw new ValidationError('runLoop: ctx.sandboxClient.create is required')\n }\n const now = options.now ?? Date.now\n const runId = options.runId ?? `loop-${randomSuffix()}`\n const loopStart = now()\n const driverName = options.driver.name ?? 'driver'\n const iterations: Iteration<Task, Output>[] = []\n // Per-run provenance manifest. `recordMount` is threaded into every box\n // preparation path (fresh + lineage) so a `prepareBox` declares what it\n // mounted. The kernel never inspects box contents — it only collects what the\n // caller records.\n const mounts: MountManifestEntry[] = []\n const recordMount: MountRecorder = (entry) => {\n mounts.push(entry)\n }\n let round = 0\n // Same-sandbox mode: worker boxes are kept alive (not torn down per-iteration)\n // so the planner can stream into the latest; the kernel destroys them at loop end.\n const ownedBoxes: SandboxInstance[] = []\n const collectBox = options.onWorkerBox\n ? (box: SandboxInstance) => {\n ownedBoxes.push(box)\n options.onWorkerBox?.(box)\n }\n : undefined\n\n // Opt-in box lineage: when either flag is set, a backend-blind lineage owns\n // box+session handles so a refine continues the parent session and a fanout\n // forks the parent checkpoint. Both flags off ⇒ lineage stays undefined and\n // the per-iteration acquire/stream/teardown path is byte-identical to today.\n const lineageState = await setUpLineage(options, maxConcurrency, recordMount)\n\n emitRunLoopHook(options, {\n target: 'agent.run',\n phase: 'before',\n runId,\n timestamp: now(),\n payload: {\n driver: driverName,\n agentRunNames: specs.map((spec) => spec.name ?? spec.profile.name ?? 'agent'),\n maxIterations,\n maxConcurrency,\n },\n })\n\n await emitTrace(options.ctx.traceEmitter, {\n kind: 'loop.started',\n runId,\n timestamp: now(),\n payload: {\n driver: driverName,\n agentRunNames: specs.map((spec) => spec.name ?? spec.profile.name ?? 'agent'),\n maxIterations,\n maxConcurrency,\n },\n })\n\n const controller = new AbortController()\n const onOuterAbort = () => controller.abort()\n if (options.ctx.signal) {\n if (options.ctx.signal.aborted) controller.abort()\n else options.ctx.signal.addEventListener('abort', onOuterAbort, { once: true })\n }\n\n try {\n while (iterations.length < maxIterations) {\n if (controller.signal.aborted) throwAbort()\n emitRunLoopHook(options, {\n target: 'agent.plan',\n phase: 'before',\n runId,\n timestamp: now(),\n stepIndex: round,\n payload: { roundIndex: round, historyLength: iterations.length },\n })\n const planned = await options.driver.plan(options.task, iterations)\n // plan() may be a long LLM call (sandbox planner); an abort during it must\n // not launch a fresh batch of workers on an already-cancelled loop.\n if (controller.signal.aborted) throwAbort()\n const planDesc = options.driver.describePlan?.()\n const roundIndex = round\n const baseIndex = iterations.length\n const remaining = maxIterations - iterations.length\n const slice = planned.slice(0, remaining)\n // Edge lineage: a driver may DECLARE the branch source (planner-authored\n // topology); otherwise the kernel infers it — round 0 branches from root\n // (undefined), later rounds from the best-valid (else latest) iteration so\n // far. Either way it's emitted, not guessed by the viewer.\n const parentIndex =\n planDesc?.parentIndex ?? (roundIndex === 0 ? undefined : branchPoint(iterations))\n const childIndices = slice.map((_, i) => baseIndex + i)\n const moveKind =\n planDesc?.kind ??\n (planned.length === 0 ? 'stop' : planned.length === 1 ? 'refine' : 'fanout')\n emitRunLoopHook(options, {\n target: 'agent.plan',\n phase: 'after',\n runId,\n timestamp: now(),\n stepIndex: roundIndex,\n payload: {\n roundIndex,\n plannedCount: planned.length,\n moveKind,\n parentIndex,\n childIndices,\n },\n })\n await emitTrace(options.ctx.traceEmitter, {\n kind: 'loop.plan',\n runId,\n timestamp: now(),\n payload: {\n roundIndex,\n plannedCount: planned.length,\n moveKind,\n rationale: planDesc?.rationale,\n parentIndex,\n childIndices,\n },\n })\n round += 1\n if (planned.length === 0) break\n\n // Reserve slots up front so concurrent workers may mutate by index.\n for (let i = 0; i < slice.length; i += 1) {\n const spec = specs[(baseIndex + i) % specs.length]!\n iterations.push({\n index: baseIndex + i,\n task: slice[i] as Task,\n agentRunName: spec.name ?? spec.profile.name ?? 'agent',\n events: [],\n startedAt: now(),\n endedAt: 0,\n costUsd: 0,\n tokenUsage: zeroTokenUsage(),\n })\n }\n\n // Decide how this round acquires its sandbox streams. Without lineage it's\n // a fresh box per iteration (today's path). With lineage it may continue\n // the parent session (refine) or fork the parent checkpoint (fanout).\n const lineagePlan = lineageState\n ? planLineageRound(lineageState, specs, slice, parentIndex, controller.signal)\n : undefined\n\n await runBatch({\n slice,\n baseIndex,\n iterations,\n specs,\n output: options.output,\n validator: options.validator,\n maxConcurrency,\n streaming: sandboxStreaming,\n signal: controller.signal,\n ctx: options.ctx,\n runId,\n now,\n roundIndex,\n parentIndex,\n collectBox,\n lineagePlan,\n lineageState,\n recordMount,\n })\n\n if (controller.signal.aborted) throwAbort()\n\n emitRunLoopHook(options, {\n target: 'agent.decision',\n phase: 'before',\n runId,\n timestamp: now(),\n stepIndex: roundIndex,\n payload: { historyLength: iterations.length },\n })\n const decision = await options.driver.decide(iterations)\n emitRunLoopHook(options, {\n target: 'agent.decision',\n phase: 'after',\n runId,\n timestamp: now(),\n stepIndex: roundIndex,\n payload: { decision: stringifySafe(decision), historyLength: iterations.length },\n })\n await emitTrace(options.ctx.traceEmitter, {\n kind: 'loop.decision',\n runId,\n timestamp: now(),\n payload: { decision: stringifySafe(decision), historyLength: iterations.length },\n })\n // Terminal decision ends the loop; a non-terminal one falls through to the\n // next plan() round, so this must return rather than continue.\n if (isTerminalDecision(decision)) {\n return await finalizeAndEmitEnded(\n options,\n decision,\n iterations,\n loopStart,\n now,\n runId,\n mounts,\n )\n }\n // The loop continues: free any lineage boxes no future round can descend\n // from, so the live-box set tracks the active frontier instead of growing\n // with every round. No-op unless pruning is provably safe (see canPrune).\n if (lineageState) await pruneLineage(lineageState, iterations)\n }\n\n // Either the cap was reached without a terminal decision, or plan() returned\n // [] first — both ask the driver for its final state and close out identically.\n return await decideAndFinalize(options, iterations, loopStart, now, runId, mounts)\n } finally {\n if (options.ctx.signal) options.ctx.signal.removeEventListener('abort', onOuterAbort)\n // Same-sandbox mode kept worker boxes alive across plan() so the planner could\n // stream into them — the kernel owns their teardown. Destroy in parallel so a\n // large fanout's deletes don't serialize, and bound each so a hung platform\n // delete cannot wedge loop return after the caller aborted.\n await Promise.allSettled(\n ownedBoxes.map((b) => destroySandboxSafe(b, options.ctx.traceEmitter, runId, now)),\n )\n if (options.onWorkerBox) options.onWorkerBox(undefined)\n // The lineage owns every box it started or forked across all rounds; it tears\n // them down at loop end (kept alive between rounds so a later round can\n // continue/fork them).\n if (lineageState) await lineageState.lineage.teardown()\n }\n}\n\n/**\n * Per-loop lineage state: the backend-blind lineage, the caller's opt-in flags,\n * and the live handle for each completed iteration so a later round can continue\n * or fork from it. `undefined` ⇒ no lineage; the kernel uses the fresh-box path.\n */\ninterface LineageState {\n lineage: SandboxLineage\n options: LoopLineageOptions\n /** iteration index → its live box+session handle (kept alive across rounds). */\n handles: Map<number, SandboxLineageHandle>\n /**\n * Whether the kernel may free non-frontier boxes after each round. Safe only\n * when the driver never authors its own branch point (`describePlan` absent),\n * so the kernel-inferred `branchPoint` — which moves monotonically toward\n * higher-scoring iterations — is the only descent source. A driver that\n * declares `parentIndex` may descend from any prior iteration, so no box can\n * be freed before loop end.\n */\n canPrune: boolean\n}\n\n/**\n * Build the lineage when either lineage flag is set. Probes the platform's fork\n * capability once per run (the lineage degrades gracefully when it's absent).\n * Rejects the lineage + `onWorkerBox` combination: both claim the same\n * box-ownership channel, and silently honoring one would leak or double-free.\n */\nasync function setUpLineage<Task, Output, Decision>(\n options: RunLoopOptions<Task, Output, Decision>,\n maxConcurrency: number,\n recordMount: MountRecorder,\n): Promise<LineageState | undefined> {\n const lineageOpts = options.lineage\n if (!lineageOpts || (!lineageOpts.sessionContinuity && !lineageOpts.forkFanout)) return undefined\n if (options.onWorkerBox) {\n throw new ValidationError(\n 'runLoop: `lineage` and `onWorkerBox` both own worker boxes — pass only one',\n )\n }\n const capabilities = await probeSandboxCapabilities(options.ctx.sandboxClient)\n return {\n lineage: createSandboxLineage(options.ctx.sandboxClient, capabilities, {\n maxConcurrency,\n streaming: lineageOpts.streaming,\n recordMount,\n }),\n options: lineageOpts,\n handles: new Map(),\n canPrune: typeof options.driver.describePlan !== 'function',\n }\n}\n\n/**\n * One iteration's sandbox-stream source for a lineage round. The kernel awaits\n * `acquire()` inside the concurrency-bounded batch (so a fork's per-branch\n * `streamPrompt` and a continue's same-box stream are both rate-limited and\n * abort-checked like a fresh create). Returns the live event stream plus the\n * handle to record for the NEXT round to descend from.\n */\ninterface LineageStreamSource {\n acquire(): Promise<{ events: AsyncIterable<SandboxEvent>; handle: SandboxLineageHandle }>\n}\n\n/** The per-round lineage plan: a stream source per slice offset, or `undefined`\n * for offsets with no lineage source (defensive — never expected). */\ntype LineageRoundPlan = (LineageStreamSource | undefined)[]\n\n/**\n * Decide, for one round, how each iteration acquires its sandbox stream:\n * - refine (1 task) + `sessionContinuity` + a live parent handle ⇒ continue\n * the parent session on its box.\n * - fanout (N tasks) + `forkFanout` + a live parent handle ⇒ fork the parent\n * checkpoint once and stream each branch from a child box (degrades to fresh\n * boxes inside the lineage when the platform can't fork).\n * - otherwise (round 0, no parent, the off flag) ⇒ start a fresh box per\n * iteration THROUGH the lineage so it's owned + a handle is recorded for a\n * later round to descend from.\n * Round 0 (parentIndex undefined) always starts fresh — the independence of the\n * first batch is preserved.\n */\nfunction planLineageRound<Task>(\n state: LineageState,\n specs: AgentRunSpec<Task>[],\n slice: Task[],\n parentIndex: number | undefined,\n signal: AbortSignal,\n): LineageRoundPlan {\n const lineage = state.lineage\n const parent = parentIndex !== undefined ? state.handles.get(parentIndex) : undefined\n const promptFor = (offset: number): string => {\n const spec = specs[offset % specs.length]\n if (!spec) throw new ValidationError('runLoop: no AgentRunSpec available for lineage iteration')\n return spec.taskToPrompt(slice[offset] as Task)\n }\n const specAt = (offset: number): AgentRunSpec<unknown> => {\n const spec = specs[offset % specs.length]\n if (!spec) throw new ValidationError('runLoop: no AgentRunSpec available for lineage iteration')\n return spec as AgentRunSpec<unknown>\n }\n\n // Continue the parent session: a single-task round descending from a live\n // handle, with the flag on. Reuses the parent's box + session id.\n if (slice.length === 1 && parent && state.options.sessionContinuity) {\n return [\n {\n async acquire() {\n const events = await lineage.continue(parent, promptFor(0), signal)\n // Continuation threads the SAME handle forward — later rounds keep\n // descending from this box's evolving session.\n return { events, handle: parent }\n },\n },\n ]\n }\n\n // Fork the parent checkpoint: a multi-task round descending from a live handle,\n // with the flag on. One checkpoint, N child streams — lazily awaited once and\n // shared across the offsets so the batch checkpoints exactly once.\n if (slice.length > 1 && parent && state.options.forkFanout) {\n const prompts = slice.map((_, offset) => promptFor(offset))\n const childSpecs = slice.map((_, offset) => specAt(offset))\n let forked: Promise<{ handle: SandboxLineageHandle; events: AsyncIterable<SandboxEvent> }[]>\n const ensureForked = () => {\n forked ??= lineage.fork(parent, prompts, childSpecs, signal)\n return forked\n }\n return slice.map((_, offset) => ({\n async acquire() {\n const branches = await ensureForked()\n const branch = branches[offset]\n if (!branch)\n throw new ValidationError('runLoop: lineage fork produced no branch for offset')\n return branch\n },\n }))\n }\n\n // Fresh through the lineage (round 0, no parent, or the relevant flag off):\n // start an owned box per iteration and record a handle for later descent.\n return slice.map((_, offset) => ({\n async acquire() {\n return lineage.start(specAt(offset), promptFor(offset), signal)\n },\n }))\n}\n\n/**\n * After a round, free lineage boxes no future round can descend from. The only\n * descent source for a kernel-inferred topology is `branchPoint`, which moves\n * monotonically toward higher-scoring iterations and never returns to one it has\n * passed — so every box except the current branch point's is unreachable and can\n * be torn down now instead of at loop end. Skipped entirely when the driver\n * authors its own branch point (`canPrune` false): it may descend from any prior\n * iteration. Also skipped when the branch point has no recorded handle (its\n * acquire failed) — that conservative case keeps every box.\n */\nasync function pruneLineage<Task, Output>(\n state: LineageState,\n iterations: ReadonlyArray<Iteration<Task, Output>>,\n): Promise<void> {\n if (!state.canPrune) return\n const keepIndex = branchPoint(iterations)\n if (keepIndex === undefined) return\n const keep = state.handles.get(keepIndex)\n if (!keep) return\n await state.lineage.prune([keep])\n // Drop handle entries pointing at the now-freed boxes so the map never hands a\n // later round a deleted box. Entries sharing the kept box (a refine chain)\n // stay.\n const stale: number[] = []\n for (const [index, handle] of state.handles) {\n if (handle.box !== keep.box) stale.push(index)\n }\n for (const index of stale) state.handles.delete(index)\n}\n\ninterface RunBatchArgs<Task, Output> {\n slice: Task[]\n baseIndex: number\n iterations: Iteration<Task, Output>[]\n specs: AgentRunSpec<Task>[]\n output: OutputAdapter<Output>\n validator: Validator<Output> | undefined\n maxConcurrency: number\n signal: AbortSignal\n ctx: ExecCtx\n runId: string\n now: () => number\n /** Plan round these iterations belong to — stamped as `groupId`. */\n roundIndex: number\n /** Iteration this round branched from — stamped as `parentIndex`. */\n parentIndex?: number\n /**\n * Same-sandbox mode: when set, a finished iteration's box is handed here\n * (kept alive for the planner) instead of being torn down. `undefined` =\n * default per-iteration teardown.\n */\n collectBox?: (box: SandboxInstance) => void\n /**\n * Lineage mode: per-offset stream sources for this round. When set, an\n * iteration acquires its sandbox stream through the lineage (continue / fork /\n * fresh) instead of `createSandboxForSpec`, and the lineage — not the\n * iteration — owns box teardown (deferred to loop end).\n */\n lineagePlan?: LineageRoundPlan\n /** The loop's lineage state; iterations record their handle here for the next\n * round to descend from. Set iff `lineagePlan` is. */\n lineageState?: LineageState\n /** Sandbox streaming mode for the default fresh-box path. 'poll' fire-and-\n * detaches + status-polls the terminal result (drop-resilient for long batch\n * turns); 'sse' streams live (default). */\n streaming: 'sse' | 'poll'\n /** The run's provenance recorder, forwarded to `prepareBox` on the default\n * fresh-box path so a mount declares itself into the manifest. (The lineage\n * path carries its own recorder from `createSandboxLineage`.) */\n recordMount: MountRecorder\n}\n\nasync function runBatch<Task, Output>(args: RunBatchArgs<Task, Output>) {\n const queue = args.slice.map((task, offset) => ({ task, index: args.baseIndex + offset }))\n const inflight = new Set<Promise<void>>()\n // Every started worker, so a rejecting iteration (abort short-circuit, or a\n // throwing trace emitter) cannot orphan its still-running siblings: we always\n // drain ALL of them before propagating the first error.\n const started: Promise<void>[] = []\n let firstError: unknown\n try {\n while (queue.length > 0 || inflight.size > 0) {\n while (inflight.size < args.maxConcurrency && queue.length > 0) {\n const item = queue.shift()!\n const p = executeIteration({ ...args, item }).finally(() => inflight.delete(p))\n started.push(p)\n inflight.add(p)\n }\n if (inflight.size === 0) break\n try {\n await Promise.race(inflight)\n } catch (err) {\n if (firstError === undefined) firstError = err\n // Stop scheduling new work; drain the rest in the finally below.\n queue.length = 0\n break\n }\n }\n } finally {\n const settled = await Promise.allSettled(started)\n if (firstError === undefined) {\n const rejected = settled.find((s) => s.status === 'rejected')\n if (rejected && rejected.status === 'rejected') firstError = rejected.reason\n }\n }\n if (firstError !== undefined) throw firstError\n}\n\ninterface ExecuteIterationArgs<Task, Output> extends RunBatchArgs<Task, Output> {\n item: { task: Task; index: number }\n}\n\nasync function executeIteration<Task, Output>(args: ExecuteIterationArgs<Task, Output>) {\n const slot = args.iterations[args.item.index]\n if (!slot)\n throw new ValidationError(`runLoop: missing iteration slot at index ${args.item.index}`)\n const spec = args.specs[args.item.index % args.specs.length]\n if (!spec) throw new ValidationError('runLoop: no AgentRunSpec available for iteration')\n slot.startedAt = args.now()\n slot.agentRunName = spec.name ?? spec.profile.name ?? 'agent'\n\n await emitTrace(args.ctx.traceEmitter, {\n kind: 'loop.iteration.started',\n runId: args.runId,\n timestamp: args.now(),\n payload: {\n iterationIndex: args.item.index,\n agentRunName: slot.agentRunName,\n taskHash: hashJson(args.item.task),\n groupId: args.roundIndex,\n parentIndex: args.parentIndex,\n },\n })\n\n let box: SandboxInstance | undefined\n // Lineage-owned boxes are torn down by the lineage at loop end, not here. The\n // flag tracks whether THIS iteration's box came from the lineage so the\n // teardown branch below skips it.\n let lineageOwned = false\n try {\n // Stream source: the lineage (continue / fork / fresh) when this round runs\n // under lineage, else a fresh box + a single `streamPrompt` (today's path,\n // byte-identical when no lineage). The lineage path supplies a session id on\n // the stream; the fresh path passes none — preserving N-independent-boxes.\n let stream: AsyncIterable<SandboxEvent>\n const source = args.lineagePlan?.[args.item.index - args.baseIndex]\n if (source) {\n const acquired = await source.acquire()\n box = acquired.handle.box\n lineageOwned = true\n args.lineageState?.handles.set(args.item.index, acquired.handle)\n stream = acquired.events\n } else {\n box = await createSandboxForSpec(args.ctx.sandboxClient, spec, args.signal, args.recordMount)\n const prompt = spec.taskToPrompt(args.item.task)\n // 'poll' (opt-in) fire-and-detaches + status-polls the terminal result so a\n // long, quiet turn never holds a drop-prone live SSE; 'sse' (default)\n // streams live — byte-identical to the prior path.\n stream =\n args.streaming === 'poll'\n ? promptEvents('poll', box, prompt, `${args.runId}-i${args.item.index}`, args.signal)\n : box.streamPrompt(prompt, { signal: args.signal })\n }\n const placement = describeSandboxPlacement(args.ctx.sandboxClient, box)\n await emitTrace(args.ctx.traceEmitter, {\n kind: 'loop.iteration.dispatch',\n runId: args.runId,\n timestamp: args.now(),\n payload: {\n iterationIndex: args.item.index,\n agentRunName: slot.agentRunName,\n placement: placement.kind,\n sandboxId: placement.sandboxId,\n fleetId: placement.fleetId,\n machineId: placement.machineId,\n groupId: args.roundIndex,\n parentIndex: args.parentIndex,\n },\n })\n const events: SandboxEvent[] = []\n for await (const event of stream) {\n events.push(event)\n // Tee each raw event to an optional host observer so a caller can stream\n // the agent's live output. Best-effort + isolated: the observer gets a\n // defensive copy (mutating it cannot corrupt the event the run itself\n // consumes for cost accounting + output parsing below), and a sync throw\n // or a rejected async result is swallowed — it can never break the run.\n if (args.ctx.onSandboxEvent) {\n try {\n // Hand the observer its own defensive copy so it cannot mutate the\n // event the run consumes below (output.parse reads event.data.*; cost\n // accounting reads event.data.usage.* + event.data.tokenUsage.*). The\n // copy is built inside this try so even a malformed event (a throwing\n // getter / hostile proxy that defeats the fallback copy) cannot break\n // the run — the observer is simply skipped for that event.\n const observerEvent = cloneEventForObserver(event)\n const result = args.ctx.onSandboxEvent(observerEvent, {\n iterationIndex: args.item.index,\n agentRunName: slot.agentRunName,\n })\n // An async observer's rejection escapes this try/catch (the promise is\n // not awaited), so attach a catch to uphold the isolation guarantee.\n if (result && typeof (result as PromiseLike<void>).then === 'function') {\n void (result as PromiseLike<void>).then(undefined, () => {})\n }\n } catch {\n // Non-critical telemetry — never let it interrupt the stream.\n }\n }\n const llmCall = extractLlmCallEvent(event, slot.agentRunName)\n if (llmCall) {\n slot.costUsd += llmCall.costUsd ?? 0\n addTokenUsage(slot.tokenUsage, { input: llmCall.tokensIn, output: llmCall.tokensOut })\n args.ctx.runHandle?.observe(llmCall)\n }\n }\n slot.events = events\n slot.output = args.output.parse(events)\n if (args.validator) {\n slot.verdict = await args.validator.validate(slot.output, {\n iteration: args.item.index,\n ...(box ? { box } : {}),\n signal: args.signal,\n traceEmitter: args.ctx.traceEmitter,\n })\n }\n } catch (err) {\n slot.error = err instanceof Error ? err : new Error(String(err))\n } finally {\n slot.endedAt = args.now()\n await emitTrace(args.ctx.traceEmitter, {\n kind: 'loop.iteration.ended',\n runId: args.runId,\n timestamp: args.now(),\n payload: {\n iterationIndex: args.item.index,\n agentRunName: slot.agentRunName,\n outputHash: slot.output !== undefined ? hashJson(slot.output) : undefined,\n verdict: slot.verdict,\n error: slot.error?.message,\n costUsd: slot.costUsd,\n durationMs: slot.endedAt - slot.startedAt,\n tokenUsage:\n slot.tokenUsage.input || slot.tokenUsage.output ? { ...slot.tokenUsage } : undefined,\n groupId: args.roundIndex,\n parentIndex: args.parentIndex,\n outputPreview:\n slot.output !== undefined ? stringifySafe(slot.output, { max: 280 }) : undefined,\n },\n })\n // The loop owns the per-shot box lifecycle. Default: tear it down now so\n // sandboxes don't leak. Same-sandbox mode: hand it to the kernel to keep\n // alive for the planner. Lineage mode: the lineage owns the box and keeps it\n // alive across rounds (a later round may continue/fork it), tearing it down\n // at loop end — so skip per-iteration teardown here.\n if (lineageOwned) {\n // no-op: lineage.teardown() reaps this box at loop end\n } else if (args.collectBox && box) {\n args.collectBox(box)\n } else {\n await destroySandboxSafe(box, args.ctx.traceEmitter, args.runId, args.now)\n }\n }\n // An abort caught above is NOT a soft per-iteration failure — it must\n // short-circuit the batch, not degrade to a recorded empty iteration. The\n // trace was already emitted in the finally, so re-throw it now.\n if (isAbortError(slot.error) || args.signal.aborted) {\n if (slot.error) throw slot.error\n throwAbort()\n }\n // A structural lineage error (a dropped session, a fork-capability contract\n // violation, a missing spec) is likewise not a soft worker failure: it\n // invalidates the run's continuity/branching guarantee, so propagate it\n // instead of degrading to a recorded empty iteration the driver might ignore.\n if (slot.error instanceof ValidationError) throw slot.error\n}\n\nfunction isAbortError(err: unknown): boolean {\n return err instanceof Error && err.name === 'AbortError'\n}\n\nconst TEARDOWN_TIMEOUT_MS = 15_000\n\n/**\n * Best-effort sandbox teardown. A failed delete must never surface as a loop\n * error, and instances without a `delete` (the loop's test fakes) are skipped.\n * A delete that throws or hangs (bounded by `TEARDOWN_TIMEOUT_MS`) is recorded\n * as a `loop.teardown.failed` trace so a silently-leaking box is observable —\n * distinct from a fake with no `delete`, which is expected and stays silent.\n */\nasync function destroySandboxSafe(\n box: SandboxInstance | undefined,\n trace?: LoopTraceEmitter,\n runId?: string,\n now?: () => number,\n): Promise<void> {\n if (!box || typeof (box as { delete?: unknown }).delete !== 'function') return\n const emitFailed = async (reason: string) => {\n if (!trace || !runId) return\n await emitTrace(trace, {\n kind: 'loop.teardown.failed',\n runId,\n timestamp: (now ?? Date.now)(),\n payload: { sandboxId: readSandboxId(box), reason },\n })\n }\n // Bound the delete so a hung platform delete can't wedge loop return after an\n // abort. `undefined` = timed out; `false` = delete threw; `true` = deleted.\n const outcome = await withTimeout(deleteBoxSafe(box), TEARDOWN_TIMEOUT_MS)\n if (outcome === undefined) await emitFailed('timeout')\n else if (outcome === false) await emitFailed('delete threw')\n}\n\n/**\n * Branch point for a new round — the iteration a later round descends from.\n * Highest-valid-score iteration so far; ties + no-valid fall back to the latest\n * index. Inferred (not driver-declared), so refine renders as a chain and\n * fanout→refine chains off the fanout winner.\n */\nfunction branchPoint<Task, Output>(\n iterations: ReadonlyArray<Iteration<Task, Output>>,\n): number | undefined {\n if (iterations.length === 0) return undefined\n let best = iterations.length - 1\n let bestScore = -Infinity\n for (const iter of iterations) {\n if (iter.verdict?.valid !== true) continue\n const score = iter.verdict.score ?? 0\n if (score > bestScore) {\n bestScore = score\n best = iter.index\n }\n }\n return best\n}\n\nexport function describeSandboxPlacement(\n client: SandboxClient,\n box: SandboxInstance,\n): LoopSandboxPlacement {\n if (typeof client.describePlacement === 'function') {\n try {\n const result = client.describePlacement(box)\n if (\n result &&\n typeof result === 'object' &&\n (result.kind === 'sibling' || result.kind === 'fleet')\n ) {\n return {\n kind: result.kind,\n sandboxId: result.sandboxId ?? readSandboxId(box),\n fleetId: result.fleetId,\n machineId: result.machineId,\n }\n }\n } catch {\n // Adapter bug must not corrupt the iteration; fall through to default.\n }\n }\n return { kind: 'sibling', sandboxId: readSandboxId(box) }\n}\n\nfunction readSandboxId(box: SandboxInstance): string | undefined {\n const raw = (box as unknown as { id?: unknown }).id\n return typeof raw === 'string' && raw.length > 0 ? raw : undefined\n}\n\n/**\n * Instantiate a sandbox for an `AgentRunSpec`: sets `backend.profile` to the\n * spec's profile (inferring the backend type when the spec doesn't override\n * it) and merges `sandboxOverrides`. Shared by the loop kernel and the\n * `AgentRuntime.act` sandbox bridge so both boot the sandbox identically.\n *\n * `recordMount`, when supplied, is forwarded to `prepareBox` so the caller can\n * declare what it mounted into the box for the run's provenance manifest. The\n * loop kernel passes its per-run recorder; other callers (which have no\n * `LoopResult` to attach to) omit it and the prepareBox recorder is a no-op.\n */\nexport async function createSandboxForSpec<Task>(\n client: SandboxClient,\n spec: AgentRunSpec<Task>,\n signal: AbortSignal,\n recordMount?: MountRecorder,\n): Promise<SandboxInstance> {\n const opts = buildBackendOptions(spec.profile, spec.sandboxOverrides)\n // Cold-start-resilient acquire: a slow scale-from-zero create (node boot +\n // host-agent registration) can't surface as a failure — readiness is observed\n // from sandbox status, and a gateway-timed-out create is recovered by lookup.\n if (signal.aborted) throwAbort()\n const box = await acquireSandbox(client, opts, { signal })\n await invokePrepareBox(spec, box, signal, recordMount)\n return box\n}\n\n/**\n * Invoke a spec's `prepareBox` with a complete ctx. `recordMount` is the run's\n * provenance recorder when one is threaded down; absent, a no-op stands in so\n * the ctx shape is always satisfied and a caller that records mounts on a path\n * with no manifest (e.g. the `AgentRuntime.act` bridge) silently drops nothing\n * it cares about — it simply has nowhere to surface a manifest.\n */\nasync function invokePrepareBox<Task>(\n spec: AgentRunSpec<Task>,\n box: SandboxInstance,\n signal: AbortSignal,\n recordMount?: MountRecorder,\n): Promise<void> {\n if (!spec.prepareBox) return\n await spec.prepareBox(box, { signal, recordMount: recordMount ?? noopMountRecorder })\n}\n\n/** Shared no-op recorder for box-preparation paths that have no run manifest. */\nconst noopMountRecorder: MountRecorder = () => {}\n\ninterface FinalizeArgs<Task, Output, Decision> {\n options: RunLoopOptions<Task, Output, Decision>\n decision: Decision\n iterations: Iteration<Task, Output>[]\n startMs: number\n now: () => number\n runId: string\n /** Provenance mounts recorded across the run's box preparations. */\n mounts: MountManifestEntry[]\n}\n\nfunction finalize<Task, Output, Decision>(\n args: FinalizeArgs<Task, Output, Decision>,\n): LoopResult<Task, Output, Decision> {\n // Precedence: an explicit caller `selectWinner` wins; else a driver-AUTHORED\n // winner (a `select` topology move); else the default argmax. A driver that\n // declares nothing returns undefined and falls through — existing behavior.\n // Track which selector produced the winner so the receipts attribute it.\n let selector: SelectionReceipt['selector']\n let winner: LoopWinner<Task, Output> | undefined\n if (args.options.selectWinner) {\n selector = 'caller'\n winner = args.options.selectWinner(args.iterations)\n } else {\n const authored = args.options.driver.selectWinner?.(args.iterations)\n if (authored) {\n selector = 'driver'\n winner = authored\n } else {\n selector = 'default'\n winner = defaultSelectWinner(args.iterations)\n }\n }\n const costUsd = args.iterations.reduce((sum, iter) => sum + (iter.costUsd || 0), 0)\n const tokenUsage = args.iterations.reduce((acc: LoopTokenUsage, iter) => {\n addTokenUsage(acc, iter.tokenUsage)\n return acc\n }, zeroTokenUsage())\n const result: LoopResult<Task, Output, Decision> = {\n decision: args.decision,\n iterations: args.iterations,\n winner,\n durationMs: args.now() - args.startMs,\n costUsd,\n tokenUsage,\n provenance: {\n mounts: args.mounts,\n selectionReceipts: buildSelectionReceipts(args.iterations, winner, selector),\n },\n }\n return result\n}\n\n/**\n * One receipt per scored candidate — a candidate being an iteration that\n * produced an output without erroring (an errored or output-less iteration was\n * never selectable, so it gets no receipt). The receipt records the candidate's\n * score and whether the selector chose it as the winner, attributed to the\n * selector identity that ran. Domain-free: it states WHAT was selected and its\n * score, never anything about the task or output content.\n */\nfunction buildSelectionReceipts<Task, Output>(\n iterations: Iteration<Task, Output>[],\n winner: LoopWinner<Task, Output> | undefined,\n selector: SelectionReceipt['selector'],\n): SelectionReceipt[] {\n const receipts: SelectionReceipt[] = []\n for (const iter of iterations) {\n if (iter.output === undefined || iter.error) continue\n const selected = winner?.iterationIndex === iter.index\n const receipt: SelectionReceipt = {\n candidateIndex: iter.index,\n selected,\n selector,\n }\n if (iter.verdict?.score !== undefined) receipt.score = iter.verdict.score\n // The kernel can only speak to its OWN selection logic. A caller- or\n // driver-authored winner runs by its own rationale, so the kernel leaves\n // `reason` unset rather than inventing one.\n if (selector === 'default') receipt.reason = defaultSelectorReason(iter, selected)\n receipts.push(receipt)\n }\n return receipts\n}\n\n/** Plain-language reason for the default selector's decision (best-valid-score,\n * earliest-index tiebreak, falling back to best non-errored when none valid). */\nfunction defaultSelectorReason<Task, Output>(\n iter: Iteration<Task, Output>,\n selected: boolean,\n): string {\n const valid = iter.verdict?.valid === true\n if (selected) return valid ? 'best valid score' : 'best non-errored score (no valid candidate)'\n return valid ? 'valid but not top score' : 'not selected'\n}\n\n/**\n * Run `decide`, emit the `loop.decision` trace, then finalize and emit\n * `loop.ended`. The two post-while exits (cap reached / `plan()` returned `[]`)\n * share this exact sequence.\n */\nasync function decideAndFinalize<Task, Output, Decision>(\n options: RunLoopOptions<Task, Output, Decision>,\n iterations: Iteration<Task, Output>[],\n startMs: number,\n now: () => number,\n runId: string,\n mounts: MountManifestEntry[],\n): Promise<LoopResult<Task, Output, Decision>> {\n emitRunLoopHook(options, {\n target: 'agent.decision',\n phase: 'before',\n runId,\n timestamp: now(),\n payload: { historyLength: iterations.length },\n })\n const decision = await options.driver.decide(iterations)\n emitRunLoopHook(options, {\n target: 'agent.decision',\n phase: 'after',\n runId,\n timestamp: now(),\n payload: { decision: stringifySafe(decision), historyLength: iterations.length },\n })\n await emitTrace(options.ctx.traceEmitter, {\n kind: 'loop.decision',\n runId,\n timestamp: now(),\n payload: { decision: stringifySafe(decision), historyLength: iterations.length },\n })\n return finalizeAndEmitEnded(options, decision, iterations, startMs, now, runId, mounts)\n}\n\n/** Finalize the loop and emit the terminal `loop.ended` span. Used by the\n * in-loop terminal path (decision trace already emitted) and decideAndFinalize. */\nasync function finalizeAndEmitEnded<Task, Output, Decision>(\n options: RunLoopOptions<Task, Output, Decision>,\n decision: Decision,\n iterations: Iteration<Task, Output>[],\n startMs: number,\n now: () => number,\n runId: string,\n mounts: MountManifestEntry[],\n): Promise<LoopResult<Task, Output, Decision>> {\n const result = finalize({ options, decision, iterations, startMs, now, runId, mounts })\n emitRunLoopHook(options, {\n target: 'agent.run',\n phase: 'after',\n runId,\n timestamp: now(),\n payload: {\n decision: stringifySafe(decision),\n winnerIterationIndex: result.winner?.iterationIndex,\n totalCostUsd: result.costUsd,\n durationMs: result.durationMs,\n iterations: iterations.length,\n },\n })\n // Await the terminal span (unlike a fire-and-forget) so a process exiting\n // right after runLoop resolves (MCP subprocess / CLI dispatch) can't drop it.\n await emitTrace(options.ctx.traceEmitter, {\n kind: 'loop.ended',\n runId,\n timestamp: now(),\n payload: {\n winnerIterationIndex: result.winner?.iterationIndex,\n totalCostUsd: result.costUsd,\n durationMs: result.durationMs,\n iterations: iterations.length,\n },\n })\n return result\n}\n\n/**\n * The kernel's winner argmax — best-valid-score, ties broken by earliest index,\n * falling back to the best-scoring non-errored output when none is valid. Exported\n * so the `runProgram` tree executor selects across merged sub-loop iterations with\n * the SAME semantics the kernel uses at a single loop's finalize (one selector, not\n * a forked copy).\n */\nexport function defaultSelectWinner<Task, Output>(\n iterations: Iteration<Task, Output>[],\n): LoopWinner<Task, Output> | undefined {\n const candidates = iterations.filter((iter) => iter.output !== undefined && !iter.error)\n if (candidates.length === 0) return undefined\n const valid = candidates.filter((iter) => iter.verdict?.valid === true)\n const pool = valid.length > 0 ? valid : candidates\n const sorted = [...pool].sort(\n (a, b) => (b.verdict?.score ?? 0) - (a.verdict?.score ?? 0) || a.index - b.index,\n )\n const top = sorted[0]\n if (!top || top.output === undefined) return undefined\n return {\n task: top.task,\n output: top.output,\n verdict: top.verdict,\n iterationIndex: top.index,\n agentRunName: top.agentRunName,\n }\n}\n\nfunction resolveAgentRuns<Task, Output, Decision>(\n options: RunLoopOptions<Task, Output, Decision>,\n): AgentRunSpec<Task>[] {\n if (options.agentRun && options.agentRuns) {\n throw new ValidationError('runLoop: pass exactly one of `agentRun` or `agentRuns`')\n }\n if (options.agentRun) return [options.agentRun]\n if (options.agentRuns && options.agentRuns.length > 0) return options.agentRuns\n throw new ValidationError('runLoop: `agentRun` or non-empty `agentRuns` is required')\n}\n\nfunction isTerminalDecision(decision: unknown): boolean {\n return (\n decision === 'stop' || decision === 'pick-winner' || decision === 'fail' || decision === 'done'\n )\n}\n\nfunction emitRunLoopHook<Task, Output, Decision>(\n options: RunLoopOptions<Task, Output, Decision>,\n event: {\n target: 'agent.run' | 'agent.plan' | 'agent.decision'\n phase: 'before' | 'after' | 'error' | 'event'\n runId: string\n timestamp: number\n stepIndex?: number\n payload?: Record<string, unknown>\n },\n): void {\n notifyRuntimeHookEvent(\n options.ctx.hooks,\n {\n id: `${event.runId}:${event.target}:${event.phase}${\n event.stepIndex === undefined ? '' : `:${event.stepIndex}`\n }`,\n runId: event.runId,\n target: event.target,\n phase: event.phase,\n timestamp: event.timestamp,\n stepIndex: event.stepIndex,\n payload: event.payload,\n metadata: { producer: 'run-loop' },\n },\n { signal: options.ctx.signal },\n )\n}\n\nasync function emitTrace(\n emitter: LoopTraceEmitter | undefined,\n event: LoopTraceEvent,\n): Promise<void> {\n if (!emitter) return\n await emitter.emit(event)\n}\n\n/**\n * Defensive copy of a sandbox event for the per-event observer tee. Prefers\n * `structuredClone` for full deep isolation. `event.data` is\n * `Record<string, unknown>`, so it may carry a non-cloneable leaf (a function\n * or stream) that makes `structuredClone` throw; in that case fall back to a\n * recursive copy of the plain-object/array spine. That still isolates every\n * field the run reads (output.parse reads `event.data.*`; cost accounting reads\n * `event.data.usage.*` and `event.data.tokenUsage.*`). Function leaves are\n * shared by reference (the run never reads them) and non-plain containers are\n * replaced by inert placeholders, so the observer shares no mutable object the\n * run consumes.\n */\nfunction cloneEventForObserver(event: SandboxEvent): SandboxEvent {\n try {\n return structuredClone(event)\n } catch {\n return copyPlainSpine(event, new WeakMap()) as SandboxEvent\n }\n}\n\n/**\n * Recursively copy the plain-object/array spine of `value`, sharing only\n * primitives and functions (which the run never reads) by reference. `seen`\n * maps each original object to its copy and is populated before recursing into\n * children, so a cycle or a repeated reference resolves to the copy — never the\n * original. A non-plain object (a Map, class instance, etc. — the kind of value\n * that made `structuredClone` throw and that can't be generically deep-copied)\n * is replaced by an inert empty object rather than shared by reference, so the\n * observer can never reach a mutable container the run reads.\n */\nfunction copyPlainSpine(value: unknown, seen: WeakMap<object, unknown>): unknown {\n if (value === null || typeof value !== 'object') return value\n const existing = seen.get(value)\n if (existing !== undefined) return existing\n if (Array.isArray(value)) {\n const copy: unknown[] = []\n seen.set(value, copy)\n for (const item of value) copy.push(copyPlainSpine(item, seen))\n return copy\n }\n const proto = Object.getPrototypeOf(value)\n if (proto !== Object.prototype && proto !== null) return {}\n const copy: Record<string, unknown> = {}\n seen.set(value, copy)\n for (const [key, v] of Object.entries(value)) copy[key] = copyPlainSpine(v, seen)\n return copy\n}\n\n/**\n * Stable hash for the trace payload. Not cryptographic — only used so\n * downstream eval pipelines can group iterations whose task / output is the\n * same. Bare structural hash; non-JSON values stringify via their `toString`.\n */\nfunction hashJson(value: unknown): string {\n let str: string\n try {\n str = JSON.stringify(value) ?? String(value)\n } catch {\n str = String(value)\n }\n // FNV-1a 32-bit — branch-free, dependency-free, good enough for grouping.\n let h = 0x811c9dc5\n for (let i = 0; i < str.length; i += 1) {\n h ^= str.charCodeAt(i)\n h = Math.imul(h, 0x01000193)\n }\n return (h >>> 0).toString(16).padStart(8, '0')\n}\n","/**\n * @experimental\n *\n * The reactive `Scope` impl (KEYSTONE, build step 4 + the step-8 adapter).\n *\n * An `Agent.act` runs inside a `Scope`. It `spawn`s children dynamically and reacts to\n * them via `next()`. The scope owns ONE in-memory nursery — the authoritative live set —\n * and is the single place that drives a child's lifecycle: reserve budget atomically,\n * resolve a `Executor` through the open registry, run it (one-shot OR streaming),\n * fold its normalized `UsageEvent`s into a conserved `Spend`, reconcile the reservation\n * (refunding the unspent remainder), persist the result blob + journal records, and\n * deliver the `Settled` through the `next()` cursor.\n *\n * Three invariants this impl enforces by construction:\n * - `next()` is a ray.wait n=1 cursor over THIS scope's live set; it assigns the\n * monotonic `seq` (the recorded cursor order) at the moment it yields a settlement, so\n * replay re-delivers in the identical order — `seq` is never wall-clock.\n * - Budget is reserved at spawn and reconciled at settle through the shared `BudgetPool`,\n * so `spawn` fails CLOSED on an exhausted pool and total ≡ free + reserved + committed.\n * - `view` reads the in-memory nursery, never the journal — O(live), synchronous.\n *\n * The settle path is the only writer of journal `settled` events; the spawn path the only\n * writer of `spawned` events. The result blob is `put` BEFORE the journal `settled` record\n * references its `outRef`, so a crash can never leave a journaled ref with no blob.\n */\n\nimport { contentAddress } from '../../durable/spawn-journal'\nimport { ValidationError } from '../../errors'\nimport { notifyRuntimeHookEvent, type RuntimeHooks } from '../../runtime-hooks'\nimport type { Iteration } from '../types'\nimport type { BudgetPool, ReservationTicket } from './budget'\nimport type {\n Agent,\n AgentSpec,\n Budget,\n DefaultVerdict,\n Executor,\n ExecutorContext,\n ExecutorRegistry,\n ExecutorResult,\n Handle,\n NodeId,\n NodeSnapshot,\n NodeStatus,\n ResultBlobStore,\n Scope,\n Settled,\n SpawnJournal,\n SpawnOpts,\n Spend,\n TreeView,\n UsageEvent,\n} from './types'\n\n/** Construction args for `createScope`. The supervisor threads the shared pool, journal,\n * blob store, and executor registry through; `depth`/`maxDepth` pair the runtime\n * recursion ceiling with the conserved pool (R3). */\nexport interface ScopeArgs {\n /** This scope's owning node id — children get `${parentId}:s${seq}` ids. */\n readonly parentId: NodeId\n /** Journal/blob root key the supervisor `beginTree`'d. */\n readonly root: NodeId\n /** The shared conserved reservation pool (one per supervised run). */\n readonly pool: BudgetPool\n /** Append-only spawn journal; this scope writes `spawned` + `settled` records. */\n readonly journal: SpawnJournal\n /** Content-addressed result store backing `outRef` rehydration. */\n readonly blobs: ResultBlobStore\n /** The open executor resolver (BYO → router/inline → registered harness factory). */\n readonly executors: ExecutorRegistry\n /** Per-spawn executor-construction seams (sandbox client, router config, cli bin). */\n readonly seams: Readonly<Record<string, unknown>>\n /** This scope's recursion depth (root = 0). */\n readonly depth: number\n /** Runtime recursion-depth ceiling — a spawn past it fails closed `depth-exceeded`. */\n readonly maxDepth?: number\n /** Abort signal for this scope; an abort cascades into every live child's executor. */\n readonly signal: AbortSignal\n /** Injected clock — keeps the journal `at` timestamp deterministic in tests. */\n readonly now?: () => number\n /** Lifecycle stream sink. `spawn` emits `agent.spawn`, `next` emits `agent.child` — the\n * SAME stream `runLoop`/`tool-loop` feed, so the recursive tree is ONE observable stream\n * (the topology viewer reads it). Undefined ⇒ the journal stays the only record. */\n readonly hooks?: RuntimeHooks\n}\n\n/**\n * Internal live-set entry. `settled` resolves once the child's executor has fully drained,\n * its reservation reconciled, and its result blob persisted; `next()` awaits these to drive\n * the cursor. `resolved` mirrors that terminal value synchronously so a concurrent `next()`\n * can pick the next undelivered settlement without re-racing. `delivered` guards exactly-once\n * delivery; `seq` is stamped by `next()`, never here.\n */\ninterface LiveChild {\n readonly id: NodeId\n status: NodeStatus\n runtime: NodeSnapshot['runtime']\n readonly budget: Budget\n readonly label: string\n spent: Spend\n outRef?: string\n /** Resolves with the terminal settlement WITHOUT a `seq` — `next()` stamps the seq. */\n readonly settled: Promise<PreSeqSettled>\n /** Synchronous mirror of `settled`'s value once it has resolved (else `undefined`). */\n resolved?: PreSeqSettled\n /** True once `next()` has yielded this child's settlement. */\n delivered: boolean\n /** The executor's out-of-band inbox, captured at spawn — backs `scope.send`. */\n readonly deliver?: (msg: unknown) => void\n}\n\n/** A child's terminal settlement before the cursor stamps the monotonic `seq`. */\ntype PreSeqSettled =\n | {\n kind: 'done'\n out: unknown\n outRef: string\n verdict?: DefaultVerdict\n spent: Spend\n /** A driver child's OWN-inference subtree total (from `Executor.metered()`) — journaled as a\n * `metered` event for this node, NOT reconciled (already debited live via `observe`). */\n metered?: Spend\n }\n | {\n kind: 'down'\n reason: string\n infra: boolean\n restartCount: number\n /** A CRASHED driver child's partial OWN-inference subtree total — re-homed on the down path\n * too, so the journal matches the pool (which already debited it via `observe`). */\n metered?: Spend\n }\n\n/**\n * The recursion seam key. A `Scope` seeds a value of this on each child's\n * `ExecutorContext.seams` so a child whose executor is a DRIVER can mount a NESTED `Scope`\n * over the SAME conserved pool at `depth+1`. A leaf executor never reads it. Single-sourced\n * here so the scope and the driver-executor agree on the seam without a circular import.\n */\nexport const nestedScopeSeamKey = 'nested-scope'\n\n/**\n * The recursion seam value: mount a nested `Scope` for a driver child. `parentId` is the\n * driver child's own node id (so its children get `${nodeId}:s${ordinal}` ids and its\n * nested journal tree is namespaced under it); `root` is the journal tree key for the\n * nested tree (distinct from the parent's so cursor seqs never collide in the per-tree\n * guard). `depth` is `parent.depth + 1`. The nested scope shares the parent's `pool`\n * (conserved budget across depth), `journal`/`blobs` (one record), and `executors` (a\n * nested child resolves to leaf-or-driver through the same open registry).\n */\nexport interface NestedScopeSeam {\n /** This scope's recursion depth — a nested scope runs at `depth + 1`. */\n readonly depth: number\n /** The runtime recursion-depth ceiling, paired with the conserved pool (R3). */\n readonly maxDepth?: number\n /** The journal tree key the parent scope writes to (used to namespace nested trees). */\n readonly journalRoot: NodeId\n /** Mount a nested scope rooted at `nestedRoot`, parented at this driver child's node id. */\n mount(nestedRoot: NodeId, signal: AbortSignal): Scope<unknown>\n}\n\nfunction makeNestedScopeSeam(args: ScopeArgs, childNodeId: NodeId): NestedScopeSeam {\n return {\n depth: args.depth,\n ...(args.maxDepth !== undefined ? { maxDepth: args.maxDepth } : {}),\n journalRoot: args.root,\n mount(nestedRoot: NodeId, signal: AbortSignal): Scope<unknown> {\n return createScope<unknown>({\n parentId: childNodeId,\n root: nestedRoot,\n pool: args.pool,\n journal: args.journal,\n blobs: args.blobs,\n executors: args.executors,\n // Re-seed the parent's NON-recursion seams (sandbox/router for leaf grandchildren);\n // the nested scope adds its OWN nested-scope seam per child in `spawn`.\n seams: args.seams,\n depth: args.depth + 1,\n ...(args.maxDepth !== undefined ? { maxDepth: args.maxDepth } : {}),\n signal,\n ...(args.now ? { now: args.now } : {}),\n ...(args.hooks ? { hooks: args.hooks } : {}),\n })\n },\n }\n}\n\nexport function createScope<Out>(args: ScopeArgs): Scope<Out> {\n const children = new Map<NodeId, LiveChild>()\n // Two distinct monotonic counters in two namespaces:\n // - `spawnOrdinal` is the spawn order (0,1,2,…); it mints the deterministic node id\n // `${parent}:s${ordinal}` and stamps the `spawned` event's `seq`. Known at spawn.\n // - `cursorSeq` is the order `next()` yields settlements (B2); it stamps the\n // `settled`/`cancelled` event's `seq` and the `Settled.seq` the driver branches on.\n // They are separate so a `spawned` event never collides with a `settled` event in the\n // journal's per-tree uniqueness guard (which is scoped to the cursor namespace).\n let spawnOrdinal = 0\n let cursorSeq = 0\n let meterSeq = 0\n const now = args.now ?? Date.now\n\n function spawn<C extends Out>(\n agent: Agent<unknown, C>,\n task: unknown,\n opts: SpawnOpts,\n ):\n | { ok: true; handle: Handle<C> }\n | { ok: false; reason: 'budget-exhausted' | 'depth-exceeded' } {\n if (args.maxDepth !== undefined && args.depth >= args.maxDepth) {\n return { ok: false, reason: 'depth-exceeded' }\n }\n\n // Resolve the leaf executor through the OPEN registry FIRST (no reservation to unwind\n // if the agent is misconfigured). An agent carries its executor mapping as the\n // `executorSpec` (an `AgentSpec`); resolution precedence (BYO → router/inline → harness\n // factory) lives in the registry, not in a call-site switch.\n const spec = (agent as unknown as { executorSpec?: unknown }).executorSpec\n if (!isAgentSpec(spec)) {\n throw new ValidationError(\n `scope.spawn: agent \"${agent.name}\" exposes no \\`executorSpec\\` (AgentSpec) to resolve a Executor`,\n )\n }\n const resolved = args.executors.resolve<C>(spec)\n if (!resolved.succeeded) throw new ValidationError(`scope.spawn: ${resolved.error}`)\n\n // Reserve the child's whole ceiling atomically; fail CLOSED when the pool can't cover\n // it (never read-then-spawn overcommit, so Σk is conserved by construction).\n const reservation = args.pool.reserve(opts.budget)\n if (!reservation.ok) return { ok: false, reason: reservation.reason }\n\n // Everything between reserve and runChild's hand-off owns the reservation. A SYNCHRONOUS\n // throw here (most likely the executor factory `resolved.value(spec, ctx)`) would otherwise\n // leak the reservation — runChild, which reconciles the ticket, is never reached. Release it\n // with zero spend on throw, then rethrow, so `total ≡ free + reserved + committed` holds.\n // (runChild is the last statement and never sync-throws, so there is no double-reconcile.)\n try {\n const ordinal = spawnOrdinal++\n const id: NodeId = `${args.parentId}:s${ordinal}`\n\n // The child's abort chains off this scope's signal (a scope abort reaps every child)\n // AND off its own handle.abort(). Aborting mid-acquire cascades through the executor's\n // signal into its acquireSandbox find-by-name reap, so an acquiring node never leaks.\n const childAbort = new AbortController()\n const cascadeAbort = () => childAbort.abort()\n if (args.signal.aborted) childAbort.abort()\n else args.signal.addEventListener('abort', cascadeAbort, { once: true })\n\n // Seed THIS scope's own keystone deps into the child's `ExecutorContext.seams`, so a\n // child whose executor is a DRIVER can mount a nested `Scope` at `depth+1` over the\n // SAME conserved pool + shared journal/blobs/registry (the recursion seam). A leaf\n // executor ignores it; the parent's sandbox/router seams still pass through for leaves.\n // The mounted nested scope re-seeds the SAME bag for ITS children, so the recursion\n // composes — a driver child of a driver child mounts one level deeper still.\n const ctx: ExecutorContext = {\n signal: childAbort.signal,\n seams: { ...args.seams, [nestedScopeSeamKey]: makeNestedScopeSeam(args, id) },\n }\n const executor = resolved.value(spec, ctx) as Executor<C>\n\n const handle: Handle<C> = {\n id,\n label: opts.label,\n get status(): NodeStatus {\n return children.get(id)?.status ?? 'cancelled'\n },\n abort(reason?: string): void {\n childAbort.abort(reason)\n },\n }\n\n const live: LiveChild = {\n id,\n status: 'acquiring',\n runtime: executor.runtime,\n budget: opts.budget,\n label: opts.label,\n spent: zeroSpend(),\n settled: undefined as unknown as Promise<PreSeqSettled>,\n delivered: false,\n ...(executor.deliver ? { deliver: executor.deliver.bind(executor) } : {}),\n }\n children.set(id, live)\n\n void args.journal.appendEvent(args.root, {\n kind: 'spawned',\n id,\n parent: args.parentId,\n label: opts.label,\n budget: opts.budget,\n runtime: executor.runtime,\n seq: ordinal,\n at: new Date(now()).toISOString(),\n })\n\n notifyRuntimeHookEvent(\n args.hooks,\n {\n id: `${id}:spawn`,\n runId: args.root,\n target: 'agent.spawn',\n phase: 'after',\n timestamp: now(),\n stepIndex: ordinal,\n parentId: args.parentId,\n payload: {\n childId: id,\n label: opts.label,\n runtime: executor.runtime,\n budget: opts.budget,\n depth: args.depth,\n },\n },\n { signal: args.signal },\n )\n\n // Drive the executor to settlement off to the side; `next()` awaits the resulting\n // promise. A thrown executor (or a real abort) is TYPED into a `down` record by\n // `runChild` (never re-thrown) so a single failing child never rejects the cursor.\n const settled = runChild(\n live,\n executor,\n childAbort,\n task,\n opts,\n args.pool,\n reservation.ticket,\n args.blobs,\n )\n .then((s) => {\n live.resolved = s\n return s\n })\n .finally(() => {\n args.signal.removeEventListener('abort', cascadeAbort)\n })\n ;(live as { settled: Promise<PreSeqSettled> }).settled = settled\n\n return { ok: true, handle }\n } catch (err) {\n args.pool.reconcile(reservation.ticket, zeroSpend())\n throw err\n }\n }\n\n async function next(): Promise<Settled<Out> | null> {\n const undelivered = () => [...children.values()].filter((c) => !c.delivered)\n if (undelivered().length === 0) return null\n\n // ray.wait n=1: await the FIRST not-yet-delivered child to settle. Loop because a\n // concurrent `next()` may take the race winner between the await and the pick.\n for (;;) {\n const pending = undelivered()\n if (pending.length === 0) return null\n // Prefer an already-resolved-but-undelivered child (no await needed).\n const ready = pending.find((c) => c.resolved !== undefined)\n const chosen = ready ?? (await raceFirstSettled(pending))\n if (chosen.delivered) continue\n chosen.delivered = true\n\n const seq = cursorSeq++\n const settlement = chosen.resolved\n if (!settlement) {\n throw new ValidationError(\n `scope.next: child '${chosen.id}' won the settle race without a resolved value`,\n )\n }\n return finalizeSettlement<Out>(chosen, settlement, seq, args, now)\n }\n }\n\n function send(nodeId: NodeId, msg: unknown): boolean {\n const child = children.get(nodeId)\n // Deliver only to a child that is still LIVE (not yet yielded by the cursor) and whose executor\n // accepts an inbox. A settled/unknown child, or a leaf with no `deliver`, cannot be steered.\n if (!child || child.delivered || !child.deliver) return false\n child.deliver(msg)\n return true\n }\n\n async function meter(spend: Spend, detail?: Record<string, unknown>): Promise<void> {\n const seq = meterSeq++\n // Debit the driver's own inference against the shared conserved pool (free → committed), so\n // equal-k counts it live and `budget.tokensLeft` reflects it for the in-loop guard.\n args.pool.observe(spend)\n // Journal it as a `metered` event — the durable TWIN of the pool debit (as `settled` is the\n // twin of `reconcile`), so every journal-based cost reader sums driver inference automatically.\n // Awaited like the settled append (cost-critical), so it has landed before the supervisor's\n // join-barrier cost roll-up.\n await args.journal.appendEvent(args.root, {\n kind: 'metered',\n id: args.parentId,\n spend,\n seq,\n at: new Date(now()).toISOString(),\n })\n // Emit it as an `agent.turn` event so the trace/topology view sees per-turn driver inference\n // (the same stream `spawn`/`next` feed — one observable tree).\n notifyRuntimeHookEvent(\n args.hooks,\n {\n id: `${args.parentId}:meter:${seq}`,\n runId: args.root,\n target: 'agent.turn',\n phase: 'after',\n timestamp: now(),\n parentId: args.parentId,\n payload: { spend, ...(detail ?? {}) },\n },\n { signal: args.signal },\n )\n }\n\n return {\n spawn,\n next,\n send,\n signal: args.signal,\n meter,\n get view(): TreeView {\n return makeTreeView(args.parentId, children)\n },\n get budget() {\n return args.pool.readout()\n },\n }\n}\n\n/** Await whichever pending child settles first, returning the child (its `resolved` is set\n * by the time this resolves because `runChild`'s `.then` sets it before the promise\n * resolves downstream). */\nasync function raceFirstSettled(pending: LiveChild[]): Promise<LiveChild> {\n return Promise.race(pending.map((c) => c.settled.then(() => c)))\n}\n\n/** Stamp the cursor `seq`, write the `settled` journal record, and project the\n * `PreSeqSettled` into the frozen `Settled` the driver branches on. */\nasync function finalizeSettlement<Out>(\n child: LiveChild,\n settlement: PreSeqSettled,\n seq: number,\n args: ScopeArgs,\n now: () => number,\n): Promise<Settled<Out>> {\n const handle = frozenHandle<Out>(child)\n if (settlement.kind === 'down') {\n child.status = 'failed'\n await args.journal.appendEvent(args.root, {\n kind: 'settled',\n id: child.id,\n status: 'down',\n spent: child.spent,\n infra: settlement.infra,\n seq,\n at: new Date(now()).toISOString(),\n })\n // Re-home a crashed driver child's partial inference too (the pool already debited it via\n // `observe`) — so spentTotal/trajectory never undercount a sub-driver that died mid-run.\n if (settlement.metered) {\n await args.journal.appendEvent(args.root, {\n kind: 'metered',\n id: child.id,\n spend: settlement.metered,\n seq,\n at: new Date(now()).toISOString(),\n })\n }\n notifyRuntimeHookEvent(\n args.hooks,\n {\n id: `${child.id}:settled`,\n runId: args.root,\n target: 'agent.child',\n phase: 'after',\n timestamp: now(),\n stepIndex: seq,\n parentId: args.parentId,\n payload: {\n childId: child.id,\n status: 'down',\n reason: settlement.reason,\n infra: settlement.infra,\n spent: child.spent,\n },\n },\n { signal: args.signal },\n )\n return {\n kind: 'down',\n handle,\n reason: settlement.reason,\n infra: settlement.infra,\n restartCount: settlement.restartCount,\n seq,\n }\n }\n\n child.status = 'done'\n child.outRef = settlement.outRef\n child.spent = settlement.spent\n await args.journal.appendEvent(args.root, {\n kind: 'settled',\n id: child.id,\n status: 'done',\n outRef: settlement.outRef,\n ...(settlement.verdict ? { verdict: settlement.verdict } : {}),\n spent: settlement.spent,\n seq,\n at: new Date(now()).toISOString(),\n })\n // Re-home a driver child's OWN-inference subtree total up to THIS (parent) tree as a `metered`\n // event for the child node — mirroring how `settled.spent` rolls child WORK up. So summing any\n // sub-tree root yields its true driver-inference cost, NOT reconciled (already pool-debited).\n if (settlement.metered) {\n await args.journal.appendEvent(args.root, {\n kind: 'metered',\n id: child.id,\n spend: settlement.metered,\n seq,\n at: new Date(now()).toISOString(),\n })\n }\n notifyRuntimeHookEvent(\n args.hooks,\n {\n id: `${child.id}:settled`,\n runId: args.root,\n target: 'agent.child',\n phase: 'after',\n timestamp: now(),\n stepIndex: seq,\n parentId: args.parentId,\n payload: {\n childId: child.id,\n status: 'done',\n outRef: settlement.outRef,\n score: settlement.verdict?.score,\n valid: settlement.verdict?.valid,\n spent: settlement.spent,\n },\n },\n { signal: args.signal },\n )\n return {\n kind: 'done',\n handle,\n out: settlement.out as Out,\n outRef: settlement.outRef,\n ...(settlement.verdict ? { verdict: settlement.verdict } : {}),\n spent: settlement.spent,\n seq,\n }\n}\n\n/**\n * Drive one child's `Executor` to a terminal `PreSeqSettled`, folding usage into the\n * conserved `Spend`, reconciling the reservation, and persisting the result blob. Both\n * executor shapes are handled here: a one-shot `Promise<ExecutorResult>` and a streaming\n * `AsyncIterable<UsageEvent>` whose terminal artifact is read from `resultArtifact()`.\n *\n * A thrown executor (or a real abort) becomes a TYPED `down` — never re-thrown — so a\n * single failing child cannot reject the `next()` cursor (the M2 typed-result discipline,\n * applied per child). The reservation is reconciled on EVERY path (success, abort, throw)\n * so the conserved pool can never leak a reservation.\n */\nasync function runChild<C>(\n live: LiveChild,\n executor: Executor<C>,\n childAbort: AbortController,\n task: unknown,\n opts: SpawnOpts,\n pool: BudgetPool,\n ticket: ReservationTicket,\n blobs: ResultBlobStore,\n): Promise<PreSeqSettled> {\n let reconciled = false\n const reconcileOnce = (spend: Spend) => {\n if (reconciled) return\n reconciled = true\n // A budgetExempt executor reports zero spend by contract; the reconcile refunds its\n // whole reservation, keeping it out of the conserved Σk by construction.\n pool.reconcile(ticket, clampSpend(spend, opts.budget))\n }\n try {\n live.status = 'running'\n const ran = executor.execute(task, childAbort.signal)\n let artifact: ExecutorResult<C>\n if (isAsyncIterable(ran)) {\n // Streaming: fold the incremental usage events as they arrive (the conserved-pool\n // authority), then read the terminal artifact after the stream drains.\n const spend = await foldStream(ran)\n live.spent = spend\n artifact = executor.resultArtifact() as ExecutorResult<C>\n reconcileOnce(spend)\n } else {\n const terminal = await ran\n live.spent = terminal.spent\n artifact = terminal\n reconcileOnce(terminal.spent)\n }\n\n // A driver child's OWN-inference subtree total — re-homed by the parent on EVERY settle exit\n // (done, aborted, crash) so the journal always matches what the pool already debited.\n const ownMetered = executor.metered?.()\n\n if (childAbort.signal.aborted) {\n await teardownSafe(executor, opts.shutdown ?? 'brutalKill')\n return downRecord('aborted before settle', true, ownMetered)\n }\n\n // The durable record is keyed by the canonical content address of the output — the\n // single addressing scheme the blob store enforces and the supervisor's winner path\n // uses. An executor's self-minted `resultArtifact().outRef` is its own internal dedup\n // hint; the journal/blob `outRef` is re-derived here so replay rehydrates by one\n // scheme. Persist the blob BEFORE the journal `settled` record references its `outRef`,\n // so a crash never leaves a journaled ref pointing at a missing blob.\n const outRef = contentAddress(artifact.out)\n await blobs.put(outRef, artifact.out)\n await teardownSafe(executor, opts.shutdown ?? 'infinity')\n return {\n kind: 'done',\n out: artifact.out,\n outRef,\n ...(artifact.verdict ? { verdict: artifact.verdict } : {}),\n spent: live.spent,\n ...(ownMetered ? { metered: ownMetered } : {}),\n }\n } catch (err) {\n // Reconcile the (likely partial) spend so the reservation is refunded even on a throw.\n reconcileOnce(live.spent)\n await teardownSafe(executor, 'brutalKill')\n const aborted = childAbort.signal.aborted || isAbortError(err)\n // A crashed driver child still re-homes the partial inference it durably metered.\n return downRecord(errMessage(err), aborted || isInfraError(err), executor.metered?.())\n }\n}\n\n/**\n * The step-8 merge-boundary adapter (M4): rehydrate a `Settled.done` into the kernel's\n * `Iteration` shape so `defaultSelectWinner` stays single-sourced — the supervisor selects\n * across settled children with the SAME argmax the loop kernel uses, not a forked copy.\n *\n * `index` is the cursor `seq` (the recorded, replay-stable order); `output`/`verdict`/\n * `tokenUsage`/`costUsd` are read straight off the settlement (already rehydrated from the\n * `outRef` blob by `next()`). Events are empty — a settled child is an opaque leaf result,\n * not a sandbox event stream — and the timing/cost fields project its conserved `Spend`.\n * Fail loud on a `down` settlement: only a `done` child is an iteration.\n */\nexport function settledToIteration<Out>(settled: Settled<Out>): Iteration<unknown, Out> {\n if (settled.kind === 'down') {\n throw new ValidationError(\n `settledToIteration: cannot adapt a 'down' settlement (node '${settled.handle.id}', seq ${settled.seq}) to an Iteration`,\n )\n }\n return {\n index: settled.seq,\n task: undefined,\n agentRunName: settled.handle.label,\n output: settled.out,\n ...(settled.verdict ? { verdict: settled.verdict } : {}),\n events: [],\n startedAt: 0,\n endedAt: settled.spent.ms,\n costUsd: settled.spent.usd,\n tokenUsage: { input: settled.spent.tokens.input, output: settled.spent.tokens.output },\n }\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────────────────\n\nfunction makeTreeView(root: NodeId, children: Map<NodeId, LiveChild>): TreeView {\n const nodes: NodeSnapshot[] = [...children.values()].map((c) => ({\n id: c.id,\n parent: root,\n label: c.label,\n status: c.status,\n runtime: c.runtime,\n budget: c.budget,\n spent: c.spent,\n ...(c.outRef ? { outRef: c.outRef } : {}),\n }))\n return {\n root,\n nodes,\n inFlight: nodes.filter((n) => n.status === 'running' || n.status === 'acquiring').length,\n }\n}\n\nfunction frozenHandle<C>(child: LiveChild): Handle<C> {\n return {\n id: child.id,\n label: child.label,\n status: child.status,\n abort(): void {\n // A settled child is terminal; abort is a no-op (its executor already tore down).\n },\n }\n}\n\nasync function foldStream(stream: AsyncIterable<UsageEvent>): Promise<Spend> {\n const tokens = { input: 0, output: 0 }\n let usd = 0\n let iterations = 0\n for await (const ev of stream) {\n if (ev.kind === 'tokens') {\n tokens.input += ev.input\n tokens.output += ev.output\n } else if (ev.kind === 'cost') {\n usd += ev.usd\n } else {\n iterations += 1\n }\n }\n return { iterations, tokens, usd, ms: 0 }\n}\n\n/** Clamp a child's reported spend to its reservation so the pool's fail-loud over-spend\n * guard never trips on a benign overshoot from an external usage report; the difference\n * refunds to the pool as if the child stopped at its ceiling. */\nfunction clampSpend(spend: Spend, budget: Budget): Spend {\n const totalTokens = spend.tokens.input + spend.tokens.output\n const tokensOk = totalTokens <= budget.maxTokens\n const itersOk = spend.iterations <= budget.maxIterations\n const usdOk = budget.maxUsd === undefined || spend.usd <= budget.maxUsd\n if (tokensOk && itersOk && usdOk) return spend\n const ratio = !tokensOk && totalTokens > 0 ? budget.maxTokens / totalTokens : 1\n return {\n iterations: Math.min(spend.iterations, budget.maxIterations),\n tokens:\n ratio < 1\n ? {\n input: Math.floor(spend.tokens.input * ratio),\n output: Math.floor(spend.tokens.output * ratio),\n }\n : spend.tokens,\n usd: budget.maxUsd === undefined ? spend.usd : Math.min(spend.usd, budget.maxUsd),\n ms: spend.ms,\n }\n}\n\nasync function teardownSafe<C>(\n executor: Executor<C>,\n grace: number | 'brutalKill' | 'infinity',\n): Promise<void> {\n try {\n await executor.teardown(grace)\n } catch {\n // Teardown failure is observable through the node staying live; swallow so it never\n // masks the settlement itself. The supervisor's join barrier reaps on its own grace.\n }\n}\n\nfunction downRecord(reason: string, infra: boolean, metered?: Spend): PreSeqSettled {\n return { kind: 'down', reason, infra, restartCount: 0, ...(metered ? { metered } : {}) }\n}\n\nfunction zeroSpend(): Spend {\n return { iterations: 0, tokens: { input: 0, output: 0 }, usd: 0, ms: 0 }\n}\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterable<UsageEvent> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as AsyncIterable<UsageEvent>)[Symbol.asyncIterator] === 'function'\n )\n}\n\n/** An `AgentSpec` is identified structurally — it carries a `profile` and a `harness`\n * field (`null` or a `BackendType`) and optionally an `executor`. */\nfunction isAgentSpec(value: unknown): value is AgentSpec {\n if (typeof value !== 'object' || value === null) return false\n const v = value as Record<string, unknown>\n return 'profile' in v && 'harness' in v\n}\n\nfunction isAbortError(err: unknown): boolean {\n return (\n typeof err === 'object' &&\n err !== null &&\n 'name' in err &&\n (err as { name: unknown }).name === 'AbortError'\n )\n}\n\n/** External-boundary failures (network/FS/subprocess) are infra — excluded from the merge\n * `n` and the equal-k assertion. A `ValidationError` from a built-in executor wraps a\n * config/transport failure, so it counts as infra; other throws are a real bad result. */\nfunction isInfraError(err: unknown): boolean {\n return err instanceof ValidationError\n}\n\nfunction errMessage(err: unknown): string {\n if (err instanceof Error) return err.message\n return String(err)\n}\n","/**\n * The one router chat client: direct OpenAI-compatible completions through the\n * Tangle router — the cheapest dial, no sandbox. Three layers: `routerChatWithUsage`\n * (chat-only), `routerChatWithTools` (one completion with function tools), and\n * `routerToolLoop` (the off-box agentic loop over tool-calling). Shared by the\n * built-in executors and the bench/lab harnesses.\n *\n * Reports REAL token usage so the backend-integrity guard sees a real backend.\n * Returns `undefined` usage when the provider omitted it — never a fabricated 0\n * (a phantom 0 reads as a free call downstream, which the gate would act on).\n */\n\nimport { estimateCost, isModelPriced } from '@tangle-network/agent-eval'\nimport { runBrainLoop, type ToolLoopChat } from './tool-loop'\n\nexport interface RouterConfig {\n routerBaseUrl: string\n routerKey: string\n model: string\n /**\n * Optional completion transport. When set, `routerChatWithUsage` / `routerChatWithTools` call it\n * with the OpenAI-shape request body and use the parsed `/chat/completions` JSON it returns,\n * INSTEAD of `fetch(routerBaseUrl + '/chat/completions')`. When absent the fetch path runs\n * unchanged — the live router stays the default. The injection seam an offline benchmark uses to\n * drive the worker with no network: a deterministic in-process responder satisfies it, no server.\n */\n complete?: (body: Record<string, unknown>) => Promise<unknown>\n}\n\nexport interface RouterChatResult {\n content: string\n /** REAL usage, or undefined when the provider reported none. */\n usage?: { input: number; output: number }\n /** Derived from usage via `estimateCost` when the model is priced; else undefined. */\n costUsd?: number\n}\n\nexport async function routerChatWithUsage(\n cfg: RouterConfig,\n messages: Array<{ role: string; content: string }>,\n opts?: { temperature?: number; signal?: AbortSignal; maxTokens?: number },\n): Promise<RouterChatResult> {\n const url = `${cfg.routerBaseUrl.replace(/\\/$/, '')}/chat/completions`\n const headers = { 'content-type': 'application/json', authorization: `Bearer ${cfg.routerKey}` }\n let temperature = opts?.temperature ?? 0.2\n // max_tokens default is generous: THINKING models (kimi-k2.6) spend the budget on\n // reasoning_content first — a small router default yields EMPTY content.\n const body = (): Record<string, unknown> => ({\n model: cfg.model,\n messages,\n temperature,\n max_tokens: opts?.maxTokens ?? 8192,\n })\n // Injected transport short-circuits the network: the offline benchmark seam. It owns its own\n // determinism, so the fetch-specific transient-retry/temperature-handling below does not apply.\n if (cfg.complete) return parseChatResult(await cfg.complete(body()), cfg.model)\n // Retry TRANSIENT upstream failures (429/5xx) with backoff so a single capacity\n // hiccup doesn't kill a whole multi-model benchmark run; and auto-handle the\n // \"only temperature 1 is allowed\" 400 some thinking models (e.g. kimi-k2.6) return.\n let lastErr = ''\n for (let attempt = 0; attempt < 5; attempt += 1) {\n const res = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body()),\n ...(opts?.signal ? { signal: opts.signal } : {}),\n })\n if (res.ok) return parseChatResult(await res.json(), cfg.model)\n const status = res.status\n const text = (await res.text()).slice(0, 200)\n lastErr = `router ${status}: ${text}`\n if (status === 400 && /temperature/i.test(text) && temperature !== 1) {\n temperature = 1 // model requires temperature 1 — retry once with it\n continue\n }\n // Non-retryable (auth/quota/malformed) fails loud immediately; retryable\n // statuses back off and continue until the loop's attempt bound, then the\n // post-loop throw is the honest \"exhausted retries\" terminal. 408/425 + the\n // Cloudflare-origin family (520/522/524) are transient under heavy parallel\n // load — a fleet of concurrent gate runs hits 524 (\"origin timeout\") and must\n // retry, not crash the whole run.\n if (![408, 425, 429, 500, 502, 503, 504, 520, 522, 524].includes(status))\n throw new Error(lastErr)\n if (attempt < 4) await new Promise((r) => setTimeout(r, 800 * 2 ** attempt))\n }\n throw new Error(`${lastErr} (exhausted retries)`)\n}\n\nfunction parseChatResult(json: unknown, model: string): RouterChatResult {\n const data = json as {\n choices?: Array<{ message?: { content?: string } }>\n usage?: { prompt_tokens?: number; completion_tokens?: number }\n }\n const u = data.usage\n const usage =\n u && typeof u.prompt_tokens === 'number' && typeof u.completion_tokens === 'number'\n ? { input: u.prompt_tokens, output: u.completion_tokens }\n : undefined\n const costUsd =\n usage && isModelPriced(model) ? estimateCost(usage.input, usage.output, model) : undefined\n return {\n content: data.choices?.[0]?.message?.content ?? '',\n ...(usage ? { usage } : {}),\n ...(costUsd !== undefined ? { costUsd } : {}),\n }\n}\n\n/** A tool-call the model emitted (provider-neutral; mirrors the runtime's ToolCallRequest). */\nexport interface RouterToolCall {\n id: string\n name: string\n /** Raw JSON arguments string as emitted by the model. */\n arguments: string\n}\n\nexport interface RouterChatToolsResult {\n content: string | null\n toolCalls: RouterToolCall[]\n usage?: { input: number; output: number }\n costUsd?: number\n}\n\n/**\n * A router completion WITH tool-calling — the operator driver's LLM seam. Passes OpenAI-shape\n * `messages` (system/user/assistant-with-tool_calls/tool roles) + function `tools`, and returns the\n * assistant text plus the tool calls the model wants run. Same fail-loud + real-usage discipline as\n * `routerChatWithUsage`. `tool_choice: 'auto'` lets the model decide; the driver loops on the result.\n */\nexport async function routerChatWithTools(\n cfg: RouterConfig,\n messages: ReadonlyArray<Record<string, unknown>>,\n tools: ReadonlyArray<{\n type: 'function'\n function: { name: string; description?: string; parameters: unknown }\n }>,\n opts?: {\n temperature?: number\n signal?: AbortSignal\n toolChoice?: 'auto' | 'required' | 'none'\n maxTokens?: number\n },\n): Promise<RouterChatToolsResult> {\n const body: Record<string, unknown> = {\n model: cfg.model,\n messages,\n tools,\n tool_choice: opts?.toolChoice ?? 'auto',\n temperature: opts?.temperature ?? 0.3,\n ...(opts?.maxTokens ? { max_tokens: opts.maxTokens } : {}),\n }\n // Injected transport short-circuits the network — the offline benchmark seam (see RouterConfig.complete).\n const raw = cfg.complete\n ? await cfg.complete(body)\n : await (async () => {\n const res = await fetch(`${cfg.routerBaseUrl.replace(/\\/$/, '')}/chat/completions`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${cfg.routerKey}` },\n body: JSON.stringify(body),\n ...(opts?.signal ? { signal: opts.signal } : {}),\n })\n if (!res.ok) throw new Error(`router ${res.status}: ${(await res.text()).slice(0, 200)}`)\n return res.json()\n })()\n const data = raw as {\n choices?: Array<{\n message?: {\n content?: string | null\n tool_calls?: Array<{ id?: string; function?: { name?: string; arguments?: string } }>\n }\n }>\n usage?: { prompt_tokens?: number; completion_tokens?: number }\n }\n const msg = data.choices?.[0]?.message\n const toolCalls: RouterToolCall[] = (msg?.tool_calls ?? []).map((tc, i) => ({\n id: tc.id ?? `call_${i}`,\n name: tc.function?.name ?? '',\n arguments: tc.function?.arguments ?? '{}',\n }))\n const u = data.usage\n const usage =\n u && typeof u.prompt_tokens === 'number' && typeof u.completion_tokens === 'number'\n ? { input: u.prompt_tokens, output: u.completion_tokens }\n : undefined\n const costUsd =\n usage && isModelPriced(cfg.model)\n ? estimateCost(usage.input, usage.output, cfg.model)\n : undefined\n return {\n content: msg?.content ?? null,\n toolCalls,\n ...(usage ? { usage } : {}),\n ...(costUsd !== undefined ? { costUsd } : {}),\n }\n}\n\nexport interface ToolSpec {\n type: 'function'\n function: { name: string; description?: string; parameters: unknown }\n}\n\nexport interface RouterToolLoopResult {\n /** The model's final assistant text (the turn where it stopped calling tools, or the budget turn). */\n final: string\n /** Inference turns spent (≤ maxTurns) — the equal-budget unit vs random@k. */\n turns: number\n toolCalls: number\n /** The behavior trace: each tool call + its result, in order. What a trace-analyst\n * steerer reads (behavior, never the verdict) to diagnose + redirect the next shot. */\n toolTrace: Array<{ name: string; args: string; result: string }>\n usage: { input: number; output: number }\n /** The full conversation after the loop (seed + every assistant/tool turn). Lets a caller\n * CARRY the messages into the next shot (depth continuation) and read the trajectory. */\n messages: Array<Record<string, unknown>>\n}\n\n/**\n * The tool-using router backend: a real agentic loop OVER the Tangle router (which\n * supports tool-calling), off-box — no sandbox. Each turn is one router completion\n * with `tools`; if the model emits tool_calls, `execute` runs them on the host and\n * their results are folded back as `tool` messages; the loop repeats until the\n * model answers without a tool call or the turn budget is hit. One turn = one\n * inference call, so `maxTurns` is the equal-compute unit against random@k.\n *\n * This is the depth substrate for agentic gates (the worker ACTS, observes the real\n * result, and continues) that the chat-only `routerChatWithUsage` cannot express.\n */\nexport async function routerToolLoop(\n cfg: RouterConfig,\n system: string,\n user: string,\n tools: ReadonlyArray<ToolSpec>,\n execute: (name: string, args: Record<string, unknown>) => Promise<string>,\n opts?: {\n maxTurns?: number\n temperature?: number\n signal?: AbortSignal\n maxTokens?: number\n /** Seed the loop with an existing conversation (depth continuation) instead of\n * `[system, user]`. When set, `system`/`user` are ignored. The array is copied. */\n initialMessages?: ReadonlyArray<Record<string, unknown>>\n },\n): Promise<RouterToolLoopResult> {\n // The router adapter over the canonical `runBrainLoop`: bind the inference to the router\n // (`routerChatWithTools`), seed the conversation, and let the one shared skeleton drive.\n const initialMessages = opts?.initialMessages ?? [\n { role: 'system', content: system },\n { role: 'user', content: user },\n ]\n return runBrainLoop({\n chat: (messages, toolSpecs) =>\n routerChatWithTools(cfg, messages, toolSpecs, {\n ...(opts?.temperature !== undefined ? { temperature: opts.temperature } : {}),\n ...(opts?.maxTokens ? { maxTokens: opts.maxTokens } : {}),\n ...(opts?.signal ? { signal: opts.signal } : {}),\n }),\n tools,\n execute,\n initialMessages,\n maxTurns: opts?.maxTurns ?? 4,\n })\n}\n\n/**\n * The router as a supervisor BRAIN: the canonical `ToolLoopChat` seam backed by the router's\n * tool-calling. The driver's spawn/observe/steer/await/stop turns become real router tool-calls.\n * The turnkey production brain — tests script a mock `ToolLoopChat`; production passes\n * `routerBrain(cfg)`. No message translation: the loop already speaks the router's OpenAI shape.\n */\nexport function routerBrain(cfg: RouterConfig, opts: { temperature?: number } = {}): ToolLoopChat {\n const temperature = opts.temperature ?? 0.4\n return (messages, tools) =>\n routerChatWithTools(cfg, messages, tools, { temperature, toolChoice: 'auto' })\n}\n","/**\n * THE canonical agentic tool-loop. One inference turn → run any requested tools → fold the\n * results back as `tool` messages → repeat, until the model answers without a tool call or the\n * turn budget is hit. One turn = one inference call (the equal-compute unit vs random@k).\n *\n * The inference is an INJECTABLE seam (`ToolLoopChat`): a router model, a sandboxed CLI\n * harness, or a scripted mock all satisfy it — so the loop is backend-agnostic. The metered /\n * steerable concerns the call sites add (a driver's conserved-pool + deadline bound; an inline\n * executor's inbox flush + abort) attach via optional `hooks`; the skeleton stays one copy.\n */\nimport type { RouterToolCall, ToolSpec } from './router-client'\n\ntype Msg = Record<string, unknown>\n\n/** One inference turn over the running conversation + the tool specs → the model's text, any\n * tool calls, and token usage. The seam every brain satisfies. */\nexport type ToolLoopChat = (\n messages: ReadonlyArray<Msg>,\n tools: ReadonlyArray<ToolSpec>,\n) => Promise<{\n content?: string | null\n toolCalls: RouterToolCall[]\n usage?: { input: number; output: number }\n /** The turn's inference cost (usd) when the provider priced it — for callers that meter usd\n * into a conserved pool (the supervisor brain). `runBrainLoop` itself ignores it. */\n costUsd?: number\n}>\n\n/** Optional per-loop concerns the metered/steerable call sites attach. The loop is one copy;\n * the budget/deadline bound, the inbox flush, and the metering hook in HERE — not as forks. */\nexport interface ToolLoopHooks {\n /** Run before each inference turn (e.g. flush queued steers into `messages`). */\n beforeTurn?(turn: number, messages: Msg[]): void | Promise<void>\n /** Return true to stop before the next turn (e.g. pool starved / deadline passed / aborted). */\n stopBefore?(turn: number): boolean\n /** Each turn's usage, for metering into a conserved budget pool. */\n onUsage?(usage: { input: number; output: number }): void\n}\n\nexport interface ToolLoopResult {\n /** The model's final assistant text (where it stopped calling tools, or the budget turn). */\n final: string\n /** Inference turns spent (≤ maxTurns) — the equal-compute unit. */\n turns: number\n toolCalls: number\n /** The behavior trace: each call + its result, in order — what a trace-analyst steerer reads. */\n toolTrace: Array<{ name: string; args: string; result: string }>\n usage: { input: number; output: number }\n /** The full conversation after the loop — lets a caller CARRY the messages into the next shot. */\n messages: Msg[]\n}\n\nexport async function runBrainLoop(opts: {\n chat: ToolLoopChat\n tools: ReadonlyArray<ToolSpec>\n execute: (name: string, args: Record<string, unknown>) => Promise<string>\n /** Seed the conversation (a fresh `[system,user]` or a depth continuation). The array is copied. */\n initialMessages: ReadonlyArray<Msg>\n maxTurns?: number\n hooks?: ToolLoopHooks\n}): Promise<ToolLoopResult> {\n const maxTurns = opts.maxTurns ?? 4\n const messages: Msg[] = [...opts.initialMessages]\n let toolCalls = 0\n let lastText = ''\n const usage = { input: 0, output: 0 }\n const toolTrace: Array<{ name: string; args: string; result: string }> = []\n\n for (let turn = 1; turn <= maxTurns; turn += 1) {\n if (opts.hooks?.stopBefore?.(turn)) break\n await opts.hooks?.beforeTurn?.(turn, messages)\n const r = await opts.chat(messages, opts.tools)\n if (r.usage) {\n usage.input += r.usage.input\n usage.output += r.usage.output\n opts.hooks?.onUsage?.(r.usage)\n }\n if (r.content) lastText = r.content\n if (r.toolCalls.length === 0)\n return { final: lastText, turns: turn, toolCalls, toolTrace, usage, messages }\n\n // Record the assistant turn verbatim (content + the tool_calls it requested), then run each\n // call and fold the result back as a `tool` message.\n messages.push({\n role: 'assistant',\n content: r.content ?? '',\n tool_calls: r.toolCalls.map((tc) => ({\n id: tc.id,\n type: 'function',\n function: { name: tc.name, arguments: tc.arguments },\n })),\n })\n for (const tc of r.toolCalls) {\n toolCalls += 1\n let args: Record<string, unknown> = {}\n try {\n args = JSON.parse(tc.arguments) as Record<string, unknown>\n } catch {\n // Malformed args from the model are a real outcome, not an infra fault — feed the error\n // back so it can correct, rather than throwing the whole loop.\n messages.push({\n role: 'tool',\n tool_call_id: tc.id,\n content: `error: arguments were not valid JSON: ${tc.arguments.slice(0, 200)}`,\n })\n continue\n }\n const out = await opts.execute(tc.name, args)\n messages.push({ role: 'tool', tool_call_id: tc.id, content: out })\n toolTrace.push({ name: tc.name, args: tc.arguments, result: out })\n }\n }\n return { final: lastText, turns: maxTurns, toolCalls, toolTrace, usage, messages }\n}\n","/**\n * @experimental\n *\n * The worker-side receive end of the down-leg: a per-worker inbox an executor exposes as\n * `Executor.deliver`. The driver's `steer_agent` / `answer_question` land here,\n * and the worker's agent loop drains them at two points (Drew's two delivery modes):\n *\n * - QUEUED (default): the message accumulates and is FLUSHED at the next step boundary — folded\n * into the conversation before the next think. A worker is also forced to flush BEFORE it may\n * settle, so it can never finish while a steer/answer it never read is still pending.\n * - FORCEFUL (`interrupt: true`): trips `freshInterrupt()`'s signal so the loop can abort its\n * in-flight turn immediately, then re-plan with the message folded in — breaking the worker out\n * of a wrong path mid-task instead of waiting for it to finish the step.\n *\n * `deliver` never throws — a malformed message is ignored, per the `Executor.deliver` contract.\n */\n\nexport interface InboxMessage {\n readonly kind: 'steer' | 'answer'\n readonly text: string\n /** Forceful messages abort the in-flight turn; queued ones wait for the boundary flush. */\n readonly interrupt: boolean\n /** Present for an `answer` — the question id it resolves. */\n readonly questionId?: string\n}\n\nexport interface Inbox {\n /** The `Executor.deliver` implementation — accept a raw down-message from `Scope.send`. */\n deliver(msg: unknown): void\n /** Remove and return all pending messages (the flush). */\n drain(): InboxMessage[]\n pending(): number\n /** Open a fresh per-turn interrupt signal; a later forceful `deliver` aborts it. The loop links\n * this into the signal it passes to its inference call, then re-plans when it fires. */\n freshInterrupt(): AbortSignal\n /** Render drained messages as ONE operator turn to fold into the worker's conversation. */\n fold(messages: ReadonlyArray<InboxMessage>): string\n}\n\nfunction parseDown(msg: unknown): InboxMessage | undefined {\n if (!msg || typeof msg !== 'object') return undefined\n const m = msg as Record<string, unknown>\n const interrupt = m.interrupt === true\n if (typeof m.steer === 'string') return { kind: 'steer', text: m.steer, interrupt }\n if (typeof m.answer === 'string')\n return {\n kind: 'answer',\n text: m.answer,\n interrupt,\n ...(typeof m.questionId === 'string' ? { questionId: m.questionId } : {}),\n }\n return undefined\n}\n\nexport function createInbox(): Inbox {\n const pending: InboxMessage[] = []\n let live: AbortController | null = null\n return {\n deliver(msg) {\n const m = parseDown(msg)\n if (!m) return\n pending.push(m)\n // A forceful message aborts the turn currently in flight (if any).\n if (m.interrupt && live && !live.signal.aborted) live.abort()\n },\n drain() {\n return pending.splice(0, pending.length)\n },\n pending: () => pending.length,\n freshInterrupt() {\n live = new AbortController()\n return live.signal\n },\n fold(messages) {\n const lines = messages.map((m) => {\n if (m.kind === 'answer')\n return `- Answer to your question${m.questionId ? ` (${m.questionId})` : ''}: ${m.text}`\n return `- New instruction from your supervisor: ${m.text}`\n })\n return `[SUPERVISOR] Out-of-band message(s) — address these before continuing:\\n${lines.join('\\n')}`\n },\n }\n}\n","/**\n * @experimental\n *\n * Git worktree helpers for the in-process delegation executor. Each\n * delegation runs in its own worktree so multiple parallel harness\n * subprocesses (claude / codex / opencode in a 3-way fanout) don't clobber\n * each other's edits on the shared workspace.\n *\n * Worktrees live under `<repoRoot>/.agent-worktrees/<runId>/`. After the\n * harness exits + the diff is captured, the worktree is removed.\n *\n * All operations spawn `git` via `child_process.spawn` synchronously\n * (via a `runGit` helper). Stays narrow on purpose: no commits, no rebases.\n * Diff capture stages all changes (`git add -A`) into the ephemeral worktree's\n * index so created (untracked) files appear in the `--cached` diff.\n */\n\nimport { spawn } from 'node:child_process'\n\n/** @experimental */\nexport interface WorktreeHandle {\n /** Absolute path to the worktree directory. */\n path: string\n /** SHA the worktree was created at. */\n baseSha: string\n /** Branch name created for this worktree (typically `delegate/<runId>`). */\n branch: string\n}\n\n/** @experimental */\nexport interface CreateWorktreeOptions {\n /** Absolute path to the main git checkout. */\n repoRoot: string\n /** Unique id for the worktree path + branch. Use the delegation run id. */\n runId: string\n /** Parent directory the worktree lives under. Defaults to `.agent-worktrees`. */\n variantsDir?: string\n /** Override the base ref (default `HEAD`). */\n baseRef?: string\n /** Test seam — inject a custom git runner. */\n runGit?: GitRunner\n}\n\n/** @experimental */\nexport interface DiffOptions {\n /** Worktree to diff. */\n worktree: WorktreeHandle\n /** What to compare against. Default `worktree.baseSha`. */\n baseRef?: string\n /** Test seam. */\n runGit?: GitRunner\n}\n\n/** @experimental */\nexport interface DiffResult {\n patch: string\n stats: {\n filesChanged: number\n insertions: number\n deletions: number\n }\n}\n\n/** @experimental */\nexport interface RemoveWorktreeOptions {\n worktree: WorktreeHandle\n repoRoot: string\n /** Force removal even if dirty (default true; the loser of a fanout has uncommitted changes). */\n force?: boolean\n /** Test seam. */\n runGit?: GitRunner\n}\n\n/** Pluggable git runner (sync) — replaceable in tests. */\nexport type GitRunner = (\n args: ReadonlyArray<string>,\n opts: { cwd: string },\n) => { stdout: string; stderr: string; exitCode: number }\n\nasync function runGitAsync(\n args: ReadonlyArray<string>,\n cwd: string,\n runner?: GitRunner,\n): Promise<{ stdout: string; stderr: string; exitCode: number }> {\n if (runner) return runner(args, { cwd })\n return new Promise((resolve, reject) => {\n const proc = spawn('git', args, { cwd, stdio: 'pipe' })\n let stdout = ''\n let stderr = ''\n proc.stdout?.on('data', (c) => {\n stdout += String(c)\n })\n proc.stderr?.on('data', (c) => {\n stderr += String(c)\n })\n proc.on('error', reject)\n proc.on('close', (code) => resolve({ stdout, stderr, exitCode: code ?? -1 }))\n })\n}\n\nfunction ensureGitOk(\n step: string,\n result: { stdout: string; stderr: string; exitCode: number },\n): void {\n if (result.exitCode !== 0) {\n throw new Error(\n `worktree: git ${step} failed (exit ${result.exitCode}): ${result.stderr.slice(0, 400)}`,\n )\n }\n}\n\n/** @experimental */\nexport async function createWorktree(options: CreateWorktreeOptions): Promise<WorktreeHandle> {\n const variants = options.variantsDir ?? '.agent-worktrees'\n const baseRef = options.baseRef ?? 'HEAD'\n const branch = `delegate/${options.runId}`\n const path = `${options.repoRoot.replace(/\\/+$/, '')}/${variants}/${options.runId}`\n\n const headSha = await runGitAsync(['rev-parse', baseRef], options.repoRoot, options.runGit)\n ensureGitOk(`rev-parse ${baseRef}`, headSha)\n\n const add = await runGitAsync(\n ['worktree', 'add', '-b', branch, path, baseRef],\n options.repoRoot,\n options.runGit,\n )\n ensureGitOk(`worktree add ${path}`, add)\n\n return { path, baseSha: headSha.stdout.trim(), branch }\n}\n\n/** @experimental */\nexport async function captureWorktreeDiff(options: DiffOptions): Promise<DiffResult> {\n const baseRef = options.baseRef ?? options.worktree.baseSha\n // Stage everything (incl. NEW/untracked files) before diffing: a plain `git diff <ref>`\n // omits untracked files, so a worker that delivers by CREATING a file (a fresh dossier,\n // a new module) would produce an empty diff and silently fail to compound. Staging into\n // the index and diffing `--cached` captures created files. The worktree is ephemeral, so\n // mutating its index has no observable side effect.\n await runGitAsync(['add', '-A'], options.worktree.path, options.runGit)\n const patch = await runGitAsync(\n ['diff', '--cached', baseRef],\n options.worktree.path,\n options.runGit,\n )\n // No `ensureGitOk` here — diff returns 0 even when there are no changes.\n\n // Stats: `git diff --shortstat` produces e.g. \" 3 files changed, 42 insertions(+), 10 deletions(-)\".\n const shortstat = await runGitAsync(\n ['diff', '--cached', '--shortstat', baseRef],\n options.worktree.path,\n options.runGit,\n )\n const stats = parseShortstat(shortstat.stdout)\n return { patch: patch.stdout, stats }\n}\n\nfunction parseShortstat(text: string): DiffResult['stats'] {\n // `text` is the raw stdout of `git diff --shortstat`. Empty when no\n // changes. Parse defensively — the format is stable but we don't trust\n // it for type-safety.\n const out = { filesChanged: 0, insertions: 0, deletions: 0 }\n const filesMatch = text.match(/(\\d+)\\s+files?\\s+changed/)\n if (filesMatch?.[1]) out.filesChanged = Number(filesMatch[1])\n const insertMatch = text.match(/(\\d+)\\s+insertions?/)\n if (insertMatch?.[1]) out.insertions = Number(insertMatch[1])\n const deleteMatch = text.match(/(\\d+)\\s+deletions?/)\n if (deleteMatch?.[1]) out.deletions = Number(deleteMatch[1])\n return out\n}\n\n/** @experimental */\nexport async function removeWorktree(options: RemoveWorktreeOptions): Promise<void> {\n const force = options.force ?? true\n const args = ['worktree', 'remove']\n if (force) args.push('--force')\n args.push(options.worktree.path)\n const result = await runGitAsync(args, options.repoRoot, options.runGit)\n // Don't ensureGitOk — partial-removal scenarios are tolerable; the\n // worktree dir may already be gone (caller deleted it manually).\n if (result.exitCode !== 0 && !/not a working tree/.test(result.stderr)) {\n // Best-effort branch cleanup so the next run can reuse the runId.\n await runGitAsync(\n ['branch', '-D', options.worktree.branch],\n options.repoRoot,\n options.runGit,\n ).catch(() => undefined)\n }\n // Always attempt branch removal — the worktree-remove sometimes leaves\n // the branch behind even when the directory is gone.\n await runGitAsync(\n ['branch', '-D', options.worktree.branch],\n options.repoRoot,\n options.runGit,\n ).catch(() => undefined)\n}\n","/**\n * @experimental\n *\n * The worktree-CLI leaf executor — a supervisor-authored `AgentProfile` driving a local\n * coding-harness CLI (claude / codex / opencode) on its OWN git worktree, surfaced as the open\n * `Executor<Out>` port (`./types`). It is a LEAF executor: it plugs straight into the\n * `Scope`/`Supervisor` recursion and `gateOnDeliverable`, so it IS the canonical recursive path\n * (no `runLoop`/virtual-SandboxInstance shim in between).\n *\n * This is a THIN adapter: the physical act (worktree → profile-aware harness invocation → diff →\n * checks → cleanup) lives ONCE in `runWorktreeHarness` (`../../mcp/worktree-harness`), shared with\n * the `runLoop`/coder-delegate `createInProcessExecutor`. This executor only projects that core's\n * result onto the `Executor` port (artifact + spend) and owns the teardown point. The §1.5 payload\n * (authored systemPrompt + model) reaches the harness inside the core, not here.\n *\n * Token accounting: a harness CLI does not surface usage, so this executor defaults to\n * `budgetExempt: true` — its spend is NOT metered against the conserved pool and its iterations are\n * EXCLUDED from the equal-k arms by construction (mirrors `cliExecutor`). The exemption is an\n * explicit, documented `budgetExempt` option rather than a buried hardcode: set it `false` ONLY for\n * a harness that genuinely surfaces real token/usd usage to meter into the pool — otherwise the\n * executor would meter a fabricated zero, which the no-silent-zeros rule forbids.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { contentAddress } from '../../durable/spawn-journal'\nimport { ValidationError } from '../../errors'\nimport type { LocalHarness, runLocalHarness } from '../../mcp/local-harness'\nimport type { GitRunner } from '../../mcp/worktree'\nimport {\n runWorktreeHarness,\n type WorktreeCheckRunner,\n type WorktreeCommandResult,\n type WorktreeHarnessResult,\n type WorktreeHarnessRun,\n} from '../../mcp/worktree-harness'\nimport { zeroTokenUsage } from '../util'\nimport type { Executor, ExecutorResult, Spend } from './types'\n\nexport type { WorktreeCommandResult }\n/** Terminal artifact of one worktree-CLI run — the canonical worktree-harness result (the captured\n * diff + the harness's run record + the derived checks). */\nexport type WorktreePatchArtifact = WorktreeHarnessResult\n\n/** @experimental */\nexport interface WorktreeCliExecutorOptions {\n /** Absolute path to the git checkout the worktree is cut from. */\n repoRoot: string\n /** The SUPERVISOR-AUTHORED profile (the §1.5 payload: systemPrompt + model). */\n profile: AgentProfile\n /** Which local harness CLI drives this leaf (`claude` | `codex` | `opencode`). */\n harness: LocalHarness\n /** The per-task instruction handed to the harness (composed under the system prompt). */\n taskPrompt: string\n /** Unique id for the worktree path + branch. Defaults to a fresh UUID. */\n runId?: string\n /** Override the base ref the worktree is cut from (default `HEAD`). */\n baseRef?: string\n /** Wall-clock cap per harness subprocess (ms). Default 5 min (the `runLocalHarness` default). */\n harnessTimeoutMs?: number\n /**\n * Shell command run in the live worktree to derive the tests-PASS signal (e.g. `pnpm test`).\n * Its exit code becomes `artifact.checks.tests.passed`. Omit to skip (no signal derived).\n */\n testCmd?: string\n /** Shell command run in the live worktree to derive the typecheck-PASS signal (e.g. `pnpm typecheck`). */\n typecheckCmd?: string\n /** Wall-clock cap per verification command (ms). Default = `harnessTimeoutMs` or 5 min. */\n checkTimeoutMs?: number\n /** Test seam — inject a git runner so unit tests drive the worktree helpers without git. */\n runGit?: GitRunner\n /** Test seam — inject the harness runner so unit tests script a `LocalHarnessResult`. */\n runHarness?: typeof runLocalHarness\n /** Test seam — inject the verification-command runner so unit tests script test/typecheck\n * outcomes without spawning a real shell. Defaults to a `/bin/sh -c` spawn in the worktree. */\n runCommand?: WorktreeCheckRunner\n /**\n * Exclude this leaf's spend from the conserved pool + equal-k arms. Defaults to `true` because a\n * coding-harness CLI does not surface token usage, so metering it would record a fabricated zero\n * (the no-silent-zeros rule forbids that). Set `false` ONLY for a harness that surfaces real\n * token/usd usage worth metering — the executor would then debit the (real) spend it captures.\n */\n budgetExempt?: boolean\n}\n\n/**\n * Build a worktree-CLI leaf `Executor`. Per-spawn (a fresh worktree + abort + teardown each), so a\n * fanout of N profiles = N parallel worktrees that never clobber each other.\n *\n * Fail-loud: an empty `repoRoot`/`harness`/`taskPrompt` throws at construction. `resultArtifact()`\n * before `execute()` resolves throws.\n *\n * @experimental\n */\nexport function createWorktreeCliExecutor(\n options: WorktreeCliExecutorOptions,\n): Executor<WorktreePatchArtifact> {\n if (!options.repoRoot) {\n throw new ValidationError('createWorktreeCliExecutor: repoRoot required')\n }\n if (!options.harness) {\n throw new ValidationError('createWorktreeCliExecutor: harness required')\n }\n if (typeof options.taskPrompt !== 'string' || options.taskPrompt.length === 0) {\n throw new ValidationError('createWorktreeCliExecutor: taskPrompt required')\n }\n\n const runId = options.runId ?? randomUUID()\n const controller = new AbortController()\n // Default true: a harness CLI cannot account tokens, so the honest value is \"exclude from the\n // pool + equal-k\" rather than meter a fabricated zero. An explicit `false` opts a real-usage\n // harness into metering the spend it captures.\n const budgetExempt = options.budgetExempt ?? true\n\n let run: WorktreeHarnessRun | undefined\n let artifact: ExecutorResult<WorktreePatchArtifact> | undefined\n\n return {\n runtime: 'cli',\n budgetExempt,\n async execute(_task, signal): Promise<ExecutorResult<WorktreePatchArtifact>> {\n const linked = linkSignals(signal, controller.signal)\n const started = Date.now()\n\n run = await runWorktreeHarness({\n repoRoot: options.repoRoot,\n profile: options.profile,\n harness: options.harness,\n taskPrompt: options.taskPrompt,\n runId,\n ...(options.baseRef ? { baseRef: options.baseRef } : {}),\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.harnessTimeoutMs !== undefined\n ? { harnessTimeoutMs: options.harnessTimeoutMs }\n : {}),\n ...(options.checkTimeoutMs !== undefined ? { checkTimeoutMs: options.checkTimeoutMs } : {}),\n ...(linked ? { signal: linked } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n\n const spent: Spend = {\n iterations: 1,\n // The worktree-harness core surfaces no token/usd usage, so tokens/usd are a genuine zero\n // (NOT a fabricated cost). When budgetExempt is true the pool ignores this spend entirely;\n // when explicitly false the scope debits exactly this captured spend — the real iteration.\n tokens: zeroTokenUsage(),\n usd: 0,\n ms: Date.now() - started,\n }\n artifact = { outRef: contentAddress(run.result), out: run.result, spent }\n return artifact\n },\n async teardown(_grace): Promise<{ destroyed: boolean }> {\n controller.abort()\n // The loser of a fanout (or any settled run) is dirty — remove its worktree. A run that\n // THREW already cleaned itself up in the core, so `run` stays undefined and this is a no-op.\n if (run) {\n const r = run\n run = undefined\n await r.cleanup()\n }\n return { destroyed: true }\n },\n resultArtifact() {\n if (!artifact) {\n throw new ValidationError(\n 'createWorktreeCliExecutor: resultArtifact() read before execute() resolved',\n )\n }\n return artifact\n },\n }\n}\n\n/** Link two abort signals into one that fires when either does. Returns `undefined` when neither\n * is present so the harness runner gets no signal at all. */\nfunction linkSignals(a: AbortSignal, b: AbortSignal): AbortSignal | undefined {\n if (a.aborted || b.aborted) {\n const c = new AbortController()\n c.abort()\n return c.signal\n }\n const c = new AbortController()\n const onAbort = () => c.abort()\n a.addEventListener('abort', onAbort, { once: true })\n b.addEventListener('abort', onAbort, { once: true })\n return c.signal\n}\n","/**\n * @experimental\n *\n * The ONE worktree-harness execution core. The physical act — run a supervisor-authored\n * `AgentProfile` on a local coding-harness CLI (claude / codex / opencode) against a fresh git\n * worktree off `repoRoot`, capture the diff, derive the test/typecheck PASS signals, then clean\n * up — lives here ONCE. Two executors adapt it to two ports without re-implementing it:\n * - `createWorktreeCliExecutor` — the `Scope`/`Supervisor` leaf `Executor`.\n * - `createInProcessExecutor` — the `runLoop` `SandboxClient` / coder-delegate path.\n *\n * §1.5 by construction: the authored `profile.prompt.systemPrompt` + `profile.model.default`\n * reach the harness through `harnessInvocation` HERE, so neither port can drop them — the exact\n * bug that existed while the in-process path called `runLocalHarness` with only the task prompt.\n *\n * Lifecycle: `createWorktree` → `harnessInvocation` + `runLocalHarness` → `captureWorktreeDiff`\n * (BEFORE checks, so the patch is the harness's output, not polluted by files a test run writes)\n * → the configured test/typecheck commands in the live worktree → return the result + a `cleanup`\n * the caller invokes at its own teardown point. A throw cleans up before propagating, so a failed\n * run never leaks a worktree.\n */\n\nimport { spawn } from 'node:child_process'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport {\n harnessInvocation,\n type LocalHarness,\n type LocalHarnessResult,\n runLocalHarness,\n} from './local-harness'\nimport {\n captureWorktreeDiff,\n createWorktree,\n type GitRunner,\n removeWorktree,\n type WorktreeHandle,\n} from './worktree'\n\n/** Outcome of one verification command run in the worktree (test or typecheck). */\nexport interface WorktreeCommandResult {\n /** The shell command line that was run. */\n command: string\n /** Did the command exit 0? The PASS signal a deliverable gate / coder output reads. */\n passed: boolean\n /** OS exit code, or `null` when killed before exit. */\n exitCode: number | null\n /** Combined stdout+stderr (capped) — surfaced in traces for diagnosis. */\n output: string\n}\n\n/** The canonical result of one worktree-harness run, projected by each port to its own shape. */\nexport interface WorktreeHarnessResult {\n /** The branch the worktree was cut on (`delegate/<runId>`). */\n branch: string\n /** `git diff` of the worktree against its base — the unified patch the harness produced. */\n patch: string\n /** Shortstat-derived change counts. */\n stats: { filesChanged: number; insertions: number; deletions: number }\n /** The harness subprocess outcome. */\n harness: {\n name: LocalHarness\n exitCode: number | null\n timedOut: boolean\n killedBySignal: NodeJS.Signals | null\n durationMs: number\n stdout: string\n stderr: string\n }\n /** Verification signals derived in the live worktree (present only when commands were given). */\n checks?: {\n tests?: WorktreeCommandResult\n typecheck?: WorktreeCommandResult\n }\n}\n\n/** The single shell-command-in-worktree runner seam (replaces the per-executor copies). */\nexport type WorktreeCheckRunner = (opts: {\n command: string\n cwd: string\n timeoutMs: number\n signal?: AbortSignal\n}) => Promise<{ exitCode: number | null; output: string }>\n\n/** @experimental */\nexport interface RunWorktreeHarnessOptions {\n /** Absolute path to the git checkout the worktree is cut from. */\n repoRoot: string\n /** The SUPERVISOR-AUTHORED profile — its systemPrompt + model reach the harness (§1.5). */\n profile: AgentProfile\n /** Which local harness CLI drives this run. */\n harness: LocalHarness\n /** The per-task instruction handed to the harness (composed under the system prompt). */\n taskPrompt: string\n /** Unique id for the worktree path + branch. */\n runId: string\n /** Override the base ref the worktree is cut from (default `HEAD`). */\n baseRef?: string\n /** Shell command run in the live worktree to derive the tests-PASS signal. Omit to skip. */\n testCmd?: string\n /** Shell command run in the live worktree to derive the typecheck-PASS signal. Omit to skip. */\n typecheckCmd?: string\n /** Wall-clock cap per harness subprocess (ms). */\n harnessTimeoutMs?: number\n /** Wall-clock cap per verification command (ms). Default = `harnessTimeoutMs` or 5 min. */\n checkTimeoutMs?: number\n /** Cap on each check's captured output. Default 16k. */\n checkOutputCap?: number\n /** Abort signal — linked into the harness subprocess and the check commands. */\n signal?: AbortSignal\n /** Test seam — inject a git runner so unit tests drive the worktree helpers without git. */\n runGit?: GitRunner\n /** Test seam — inject the harness runner so unit tests script a `LocalHarnessResult`. */\n runHarness?: typeof runLocalHarness\n /** Test seam — inject the verification-command runner. Defaults to a `/bin/sh -c` spawn. */\n runCommand?: WorktreeCheckRunner\n}\n\n/** One worktree-harness run: the result + the worktree handle + a single-use `cleanup`. */\nexport interface WorktreeHarnessRun {\n worktree: WorktreeHandle\n result: WorktreeHarnessResult\n /** Remove the worktree. The caller invokes this at its own teardown point (the leaf in its\n * `Executor.teardown`, the SandboxClient in its `streamPrompt` finally). On a thrown run the\n * core already cleaned up, so the caller never double-removes. */\n cleanup: () => Promise<void>\n}\n\nconst defaultCheckOutputCap = 16_000\n\n/**\n * Run the one worktree-harness operation. Fail-loud cleanup: any throw removes the worktree\n * before propagating, so a failed run never leaks one (the caller cleans up the success path).\n */\nexport async function runWorktreeHarness(\n opts: RunWorktreeHarnessOptions,\n): Promise<WorktreeHarnessRun> {\n const runHarness = opts.runHarness ?? runLocalHarness\n const runCommand = opts.runCommand ?? defaultRunCommand\n const checkTimeoutMs = opts.checkTimeoutMs ?? opts.harnessTimeoutMs ?? 5 * 60 * 1000\n const cap = opts.checkOutputCap ?? defaultCheckOutputCap\n\n const worktree = await createWorktree({\n repoRoot: opts.repoRoot,\n runId: opts.runId,\n ...(opts.baseRef ? { baseRef: opts.baseRef } : {}),\n ...(opts.runGit ? { runGit: opts.runGit } : {}),\n })\n\n const cleanup = (): Promise<void> =>\n removeWorktree({\n worktree,\n repoRoot: opts.repoRoot,\n ...(opts.runGit ? { runGit: opts.runGit } : {}),\n }).catch(() => undefined)\n\n try {\n // §1.5: the authored systemPrompt + model reach the harness (NOT the prompt-only path).\n const { command, args } = harnessInvocation(opts.harness, opts.profile, opts.taskPrompt)\n const harnessResult: LocalHarnessResult = await runHarness({\n harness: opts.harness,\n cwd: worktree.path,\n taskPrompt: opts.taskPrompt,\n invocation: { command, args },\n ...(opts.harnessTimeoutMs !== undefined ? { timeoutMs: opts.harnessTimeoutMs } : {}),\n ...(opts.signal ? { signal: opts.signal } : {}),\n })\n\n // Diff BEFORE checks — the patch is the harness's output, not whatever a test run left behind.\n const diff = await captureWorktreeDiff({\n worktree,\n ...(opts.runGit ? { runGit: opts.runGit } : {}),\n })\n\n const checks = await runChecks({\n worktreePath: worktree.path,\n ...(opts.testCmd !== undefined ? { testCmd: opts.testCmd } : {}),\n ...(opts.typecheckCmd !== undefined ? { typecheckCmd: opts.typecheckCmd } : {}),\n timeoutMs: checkTimeoutMs,\n cap,\n runCommand,\n ...(opts.signal ? { signal: opts.signal } : {}),\n })\n\n const result: WorktreeHarnessResult = {\n branch: worktree.branch,\n patch: diff.patch,\n stats: diff.stats,\n harness: {\n name: opts.harness,\n exitCode: harnessResult.exitCode,\n timedOut: harnessResult.timedOut,\n killedBySignal: harnessResult.killedBySignal,\n durationMs: harnessResult.durationMs,\n stdout: harnessResult.stdout,\n stderr: harnessResult.stderr,\n },\n ...(checks ? { checks } : {}),\n }\n return { worktree, result, cleanup }\n } catch (err) {\n await cleanup()\n throw err\n }\n}\n\n/** Run the configured test + typecheck commands in the live worktree, projecting exit codes into\n * `checks`. Returns `undefined` when neither was configured (so the result omits `checks`). */\nasync function runChecks(opts: {\n worktreePath: string\n testCmd?: string\n typecheckCmd?: string\n timeoutMs: number\n cap: number\n runCommand: WorktreeCheckRunner\n signal?: AbortSignal\n}): Promise<WorktreeHarnessResult['checks'] | undefined> {\n if (opts.testCmd === undefined && opts.typecheckCmd === undefined) return undefined\n const run = async (command: string): Promise<WorktreeCommandResult> => {\n const res = await opts.runCommand({\n command,\n cwd: opts.worktreePath,\n timeoutMs: opts.timeoutMs,\n ...(opts.signal ? { signal: opts.signal } : {}),\n })\n return {\n command,\n passed: res.exitCode === 0,\n exitCode: res.exitCode,\n output: res.output.length > opts.cap ? res.output.slice(-opts.cap) : res.output,\n }\n }\n const checks: NonNullable<WorktreeHarnessResult['checks']> = {}\n if (opts.testCmd !== undefined) checks.tests = await run(opts.testCmd)\n if (opts.typecheckCmd !== undefined) checks.typecheck = await run(opts.typecheckCmd)\n return checks\n}\n\n/** Default verification-command runner — `/bin/sh -c <command>` in the worktree, capturing\n * combined stdout+stderr. Never throws on a non-zero exit (that IS the fail signal); only a\n * spawn failure (ENOENT shell) rejects. */\nfunction defaultRunCommand(opts: {\n command: string\n cwd: string\n timeoutMs: number\n signal?: AbortSignal\n}): Promise<{ exitCode: number | null; output: string }> {\n return new Promise((resolve, reject) => {\n const child = spawn('/bin/sh', ['-c', opts.command], {\n cwd: opts.cwd,\n stdio: ['ignore', 'pipe', 'pipe'],\n })\n const chunks: string[] = []\n let settled = false\n const timer = setTimeout(() => child.kill('SIGTERM'), opts.timeoutMs)\n const onAbort = () => child.kill('SIGTERM')\n opts.signal?.addEventListener('abort', onAbort, { once: true })\n child.stdout?.on('data', (d) => chunks.push(String(d)))\n child.stderr?.on('data', (d) => chunks.push(String(d)))\n const finish = (fn: () => void) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n opts.signal?.removeEventListener('abort', onAbort)\n fn()\n }\n child.on('error', (err) => finish(() => reject(err)))\n child.on('close', (code) => finish(() => resolve({ exitCode: code, output: chunks.join('') })))\n })\n}\n","/**\n * @experimental\n *\n * The leaf runtime — the built-in `Executor` IMPLEMENTATIONS behind the ONE\n * open interface frozen in `./types`, plus the open resolver/registry that maps\n * an `AgentSpec` to one of them OR accepts a bring-your-own executor verbatim.\n *\n * The interface is the extension point, not a closed `inline|sandbox|cli` union:\n * - router/inline : a direct OpenAI-compatible Router call, no box (one-shot).\n * - sandbox : COMPOSES the existing `runLoop` kernel as a single-task\n * leaf and surfaces its token/cost usage as `UsageEvent`s;\n * forwards PR #150's optional `lineage` passthrough WITHOUT\n * reinventing checkpoint/fork (streaming).\n * - cli : a Halo/RLM subprocess; `budgetExempt` (no token accounting),\n * excluded from the equal-k arms by construction (streaming).\n * Every metered runtime reports through the SAME normalized `UsageEvent` channel\n * so the conserved budget pool meters them identically. A user's own agent is\n * first-class the moment it implements `Executor` — register it by name or\n * pass it as `AgentSpec.executor`.\n *\n * Layering: `estimateCost`/`isModelPriced` are substrate primitives from\n * `@tangle-network/agent-eval`; `runLoop`/`acquireSandbox` are runtime kernels\n * from this package. No per-vendor adapters live here.\n */\n\nimport { spawn } from 'node:child_process'\nimport { randomUUID } from 'node:crypto'\nimport { estimateCost, isModelPriced } from '@tangle-network/agent-eval'\nimport type { BackendType, SandboxEvent } from '@tangle-network/sandbox'\nimport { ValidationError } from '../../errors'\nimport type { LocalHarness } from '../../mcp/local-harness'\nimport {\n type AgentEnvironmentProvider,\n type AgentEnvironmentProviderRegistry,\n type ProviderExecutorOptions,\n providerAsExecutor,\n resolveAgentEnvironmentProvider,\n} from '../environment-provider'\nimport { routerChatWithUsage, type ToolSpec } from '../router-client'\nimport type { RunLoopOptions } from '../run-loop'\nimport { runLoop } from '../run-loop'\nimport type {\n AgentRunSpec,\n Driver,\n ExecCtx,\n Iteration,\n OutputAdapter,\n SandboxClient,\n} from '../types'\nimport { zeroTokenUsage } from '../util'\nimport { createInbox, type Inbox } from './inbox'\nimport type {\n AgentSpec,\n DefaultVerdict,\n Executor,\n ExecutorContext,\n ExecutorFactory,\n ExecutorRegistry,\n ExecutorResult,\n Runtime,\n Spend,\n UsageEvent,\n} from './types'\nimport { createWorktreeCliExecutor } from './worktree-cli-executor'\n\n// ── Seam contracts (read off ExecutorContext.seams, narrowed per built-in) ─────\n\n/**\n * Router/inline connection seam. A direct OpenAI-compatible Router endpoint —\n * the cheapest leaf, no box, no tools. `model` overrides the profile's model\n * hint when present; otherwise the profile's `model.default` is required.\n */\nexport interface RouterSeam {\n routerBaseUrl: string\n routerKey: string\n model?: string\n}\n\n/**\n * Sandbox executor seam. The `sandboxClient` the composed `runLoop` creates\n * boxes through, plus the optional trace/run/lineage wiring forwarded into the\n * loop. `lineage` is opaque here (PR #150's `RunLoopOptions.lineage`): forwarded\n * forward-compatibly, never inspected — this executor does NOT reinvent\n * checkpoint/fork.\n */\nexport interface SandboxSeam {\n sandboxClient: SandboxClient\n /** Forwarded into the composed `runLoop`'s `ctx` (trace emitter, run handle, etc.). */\n loopCtx?: Partial<Omit<ExecCtx, 'sandboxClient' | 'signal'>>\n /** PR #150 `RunLoopOptions.lineage` passthrough — opaque; forwarded, not parsed. */\n lineage?: unknown\n /** Hard cap on the composed loop's iterations. The budget pool reserves against\n * the spawn `Budget.maxIterations`; this is the leaf's own ceiling. Default 1. */\n maxIterations?: number\n}\n\n/** CLI subprocess seam. `bin` + `args` describe the Halo/RLM process to spawn. */\nexport interface CliSeam {\n bin: string\n args?: string[]\n /** Extra environment for the subprocess (merged over `process.env`). */\n env?: Record<string, string>\n /** Working directory for the subprocess. */\n cwd?: string\n}\n\n/**\n * cli-worktree seam. A supervisor-authored `AgentProfile` driving a local coding-harness CLI\n * (claude / codex / opencode) on its own git worktree — the leaf `createWorktreeCliExecutor`\n * named as data. `harness` + `repoRoot` + `taskPrompt` are required; the authored\n * `profile.prompt.systemPrompt` + `profile.model.default` reach the harness via the §1.5\n * `harnessInvocation` mapper. Everything else mirrors `WorktreeCliExecutorOptions`.\n */\nexport interface CliWorktreeSeam {\n repoRoot: string\n harness: LocalHarness\n taskPrompt: string\n runId?: string\n baseRef?: string\n harnessTimeoutMs?: number\n}\n\n/**\n * cli-bridge seam. A local OpenAI-compatible bridge that fronts harness CLIs\n * (claude-code / opencode / kimi / pi) behind one HTTP surface; `model` doubles\n * as the harness selector (e.g. `claude-code/sonnet`, `opencode/<provider>/<model>`).\n * `agentProfile` is the bridge-dialect profile (metadata.disallowedTools, mcp)\n * forwarded verbatim per request — how an arm disables native tools or injects\n * a provider search MCP.\n *\n * The executor opens a RESUMABLE cli-bridge session — structurally identical to the\n * sandbox executor's persistent box, just local. `sessionId` is the stable\n * caller-owned id cli-bridge maps to the harness's internal conversation id; a\n * follow-up steer/resume on the SAME id continues the SAME harness session (opencode\n * `-s`, claude `--resume`, …). Omit it and the executor mints a stable one per spawn.\n */\nexport interface BridgeSeam {\n bridgeUrl: string\n bridgeBearer: string\n model: string\n agentProfile?: Record<string, unknown>\n timeoutMs?: number\n /** Stable, caller-owned cli-bridge session id for harness-side resume. Defaults\n * to a freshly minted per-spawn id so each worker is its own resumable session. */\n sessionId?: string\n /** Per-resume-turn inference cap before the worker settles on its last output.\n * Mirrors `routerToolsInlineExecutor.maxTurns`; default 200 (runaway backstop). */\n maxTurns?: number\n}\n\n/** Generic environment provider executor config. External packages implement\n * `AgentEnvironmentProvider`; this built-in wrapper lets `createExecutor`\n * consume them as backend data while preserving the existing usage channel. */\nexport interface ProviderSeam extends ProviderExecutorOptions {\n provider: AgentEnvironmentProvider | string\n registry?: AgentEnvironmentProviderRegistry\n}\n\nconst routerSeamKey = 'router'\nconst sandboxSeamKey = 'sandbox'\nconst cliSeamKey = 'cli'\nconst bridgeSeamKey = 'bridge'\nconst cliWorktreeSeamKey = 'cli-worktree'\nconst providerSeamKey = 'provider'\n\n// ── Content-addressed result pointers (the B1 replay source) ───────────────────\n\n/** Deterministic content hash for an `outRef`. FNV-1a 32-bit over the canonical\n * JSON of the result — not cryptographic, sufficient for content-addressing the\n * replay blob so two identical outputs collapse to one pointer. */\nfunction contentRef(prefix: string, value: unknown): string {\n let str: string\n try {\n str = JSON.stringify(value) ?? String(value)\n } catch {\n str = String(value)\n }\n let h = 0x811c9dc5\n for (let i = 0; i < str.length; i += 1) {\n h ^= str.charCodeAt(i)\n h = Math.imul(h, 0x01000193)\n }\n return `${prefix}:${(h >>> 0).toString(16).padStart(8, '0')}`\n}\n\nfunction zeroSpend(): Spend {\n return { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 }\n}\n\n// ── router/inline executor (harness === null) ──────────────────────────────────\n\n/**\n * A direct OpenAI-compatible Router chat-completion. One-shot: resolves a\n * `ExecutorResult` and reports its terminal usage as `UsageEvent`s through the\n * conserved pool. Reports REAL token usage — when the provider omits `usage`,\n * the spend records zero tokens but the call still counts one iteration (a\n * phantom fabricated 0 is never emitted as a priced cost).\n *\n * Transport = `routerChatWithUsage` (`../router-client`): transient router\n * failures (429/5xx/Cloudflare-origin) retry with backoff before the executor\n * fails the task.\n */\nexport const routerInlineExecutor: ExecutorFactory<unknown> = (spec, ctx) => {\n const seam = readSeam<RouterSeam>(ctx, routerSeamKey, 'router/inline')\n const model = seam.model ?? spec.profile.model?.default\n if (!model) {\n throw new ValidationError(\n 'routerInlineExecutor: no model — set RouterSeam.model or AgentProfile.model.default',\n )\n }\n if (!seam.routerBaseUrl || !seam.routerKey) {\n throw new ValidationError('routerInlineExecutor: RouterSeam.routerBaseUrl + routerKey required')\n }\n\n const controller = new AbortController()\n const abortIfSignalled = () => {\n if (ctx.signal.aborted) controller.abort()\n }\n abortIfSignalled()\n if (!ctx.signal.aborted) ctx.signal.addEventListener('abort', abortIfSignalled, { once: true })\n\n let artifact: ExecutorResult<unknown> | undefined\n\n return {\n runtime: 'router' as Runtime,\n async execute(task, signal): Promise<ExecutorResult<unknown>> {\n const messages = taskToMessages(task, spec)\n const started = Date.now()\n const linked = linkSignals(signal, controller.signal)\n const r = await routerChatWithUsage(\n { routerBaseUrl: seam.routerBaseUrl, routerKey: seam.routerKey, model },\n messages,\n linked ? { signal: linked } : {},\n )\n const spent: Spend = {\n iterations: 1,\n tokens: r.usage ? { input: r.usage.input, output: r.usage.output } : zeroTokenUsage(),\n usd: r.costUsd ?? 0,\n ms: Date.now() - started,\n }\n const out = { content: r.content } as unknown\n artifact = { outRef: contentRef('router', { model, content: r.content }), out, spent }\n return artifact\n },\n teardown(_grace): Promise<{ destroyed: boolean }> {\n controller.abort()\n return Promise.resolve({ destroyed: true })\n },\n resultArtifact() {\n if (!artifact) {\n throw new ValidationError('routerInlineExecutor: resultArtifact() read before execute()')\n }\n return { ...artifact, spent: artifact.spent }\n },\n }\n}\n\nexport type { ToolSpec }\n\n/**\n * Router seam WITH tool use — the tool-using router backend. Same direct\n * OpenAI-compatible endpoint as `RouterSeam`, but each turn passes `tools`; when\n * the model emits tool_calls they run via `executeToolCall` ON THIS HOST and the\n * results fold back as `tool` messages, repeating until the model answers without\n * a tool or `maxTurns` is hit. A real agentic loop, OFF-BOX — no sandbox, so it\n * is unaffected by a box's egress allowlist. One turn = one completion = the\n * equal-compute unit. `executeToolCall` receives the task so per-task tool\n * surfaces (e.g. a gym keyed by task) can dispatch correctly.\n */\nexport interface RouterToolsSeam {\n routerBaseUrl: string\n routerKey: string\n model?: string\n tools: ReadonlyArray<ToolSpec>\n executeToolCall: (name: string, args: Record<string, unknown>, task: unknown) => Promise<string>\n /** Online observer of each tool step — the seam a `DetectorMonitor` taps to watch the live pipe\n * (raise a `finding` when the worker loops/errors). Called after every tool call resolves, with\n * real per-call wall-clock (`startedAt`/`endedAt`/`durationMs`) so a push `TraceSource` can carry\n * non-zero span durations onto the unified timeline. */\n onToolStep?: (step: {\n toolName: string\n args: Record<string, unknown>\n status: 'ok' | 'error'\n // Real per-call wall-clock — the owned-loop executor always supplies these. Optional so an\n // external `RouterToolsSeam` that omits timing still satisfies the type (the span then collapses\n // to order + counts, per `toToolSpan`), keeping this an additive, non-breaking field set.\n startedAt?: number\n endedAt?: number\n durationMs?: number\n }) => void\n /** Max inference turns. Default 200 (runaway backstop — set far above any\n * legitimate workflow). For tighter per-workflow limits use a cost budget\n * or wall-clock deadline at the call site. */\n maxTurns?: number\n}\nconst routerToolsSeamKey = 'router-tools'\n\ninterface RouterToolsResponse {\n choices?: Array<{\n message?: {\n content?: string | null\n tool_calls?: Array<{ id?: string; function?: { name?: string; arguments?: string } }>\n }\n }>\n usage?: { prompt_tokens?: number; completion_tokens?: number }\n}\n\n/**\n * The tool-using router executor. Drives the multi-turn tool loop the single-shot\n * `routerInlineExecutor` cannot express; same fail-loud + real-usage discipline.\n */\nexport const routerToolsInlineExecutor: ExecutorFactory<unknown> = (spec, ctx) => {\n const seam = readSeam<RouterToolsSeam>(ctx, routerToolsSeamKey, 'router-tools')\n const model = seam.model ?? spec.profile.model?.default\n if (!model) {\n throw new ValidationError(\n 'routerToolsInlineExecutor: no model — set RouterToolsSeam.model or AgentProfile.model.default',\n )\n }\n if (!seam.routerBaseUrl || !seam.routerKey) {\n throw new ValidationError(\n 'routerToolsInlineExecutor: RouterToolsSeam.routerBaseUrl + routerKey required',\n )\n }\n const maxTurns = seam.maxTurns ?? 200\n\n const controller = new AbortController()\n const abortIfSignalled = () => {\n if (ctx.signal.aborted) controller.abort()\n }\n abortIfSignalled()\n if (!ctx.signal.aborted) ctx.signal.addEventListener('abort', abortIfSignalled, { once: true })\n\n // The down-leg receive end: the driver's steer/answer/resume land here via `Scope.send`.\n const inbox = createInbox()\n\n let artifact: ExecutorResult<unknown> | undefined\n\n return {\n runtime: 'router' as Runtime,\n deliver: (m) => inbox.deliver(m),\n async execute(task, signal): Promise<ExecutorResult<unknown>> {\n const started = Date.now()\n const messages: Array<Record<string, unknown>> = [\n ...(taskToMessages(task, spec) as Array<Record<string, unknown>>),\n ]\n const tokens = zeroTokenUsage()\n let turns = 0\n let lastText = ''\n // Fold any queued down-messages into the conversation as one operator turn (the boundary flush).\n const flush = () => {\n const pending = inbox.drain()\n if (pending.length) messages.push({ role: 'user', content: inbox.fold(pending) })\n return pending.length > 0\n }\n\n // The external abort sources (caller signal + executor teardown), merged ONCE — so we don't\n // re-register listeners on these long-lived signals every turn.\n const external = mergeAbortSignals(signal, controller.signal)\n\n for (let t = 0; t < maxTurns; t += 1) {\n // QUEUED messages flush at the step boundary, before this turn's inference.\n flush()\n // A forceful (interrupt) message aborts THIS turn so the worker re-plans immediately. The\n // per-turn controller fires on `external` OR a fresh interrupt; its listener on `external` is\n // removed after the turn (`cleanup`) so nothing accumulates across turns.\n const interruptSig = inbox.freshInterrupt()\n const turnController = new AbortController()\n const abortTurn = () => turnController.abort()\n if (external.aborted) turnController.abort()\n else external.addEventListener('abort', abortTurn)\n interruptSig.addEventListener('abort', abortTurn, { once: true })\n const cleanup = () => external.removeEventListener('abort', abortTurn)\n let res: Response\n try {\n res = await fetch(`${seam.routerBaseUrl.replace(/\\/$/, '')}/chat/completions`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${seam.routerKey}`,\n },\n body: JSON.stringify({\n model,\n messages,\n tools: seam.tools,\n tool_choice: 'auto',\n temperature: 0.2,\n }),\n signal: turnController.signal,\n })\n } catch (e) {\n cleanup()\n // Re-plan ONLY when a forceful inbox message aborted this turn (a real AbortError, with the\n // interrupt — not the external teardown/budget signal). The re-planned turn still consumes a\n // loop slot (so interrupt spam is bounded by maxTurns, not a hang) but does not bill a turn.\n // Any other error — incl. a network fault coincident with an interrupt — is fatal: rethrow.\n const interruptAbort =\n e instanceof DOMException &&\n e.name === 'AbortError' &&\n interruptSig.aborted &&\n !signal.aborted &&\n !controller.signal.aborted\n if (interruptAbort) continue\n throw e\n }\n cleanup()\n // The inference completed — count the turn now (an interrupted, re-planned turn doesn't bill).\n turns += 1\n if (!res.ok) {\n throw new ValidationError(\n `routerToolsInlineExecutor: router ${res.status}: ${(await res.text()).slice(0, 200)}`,\n )\n }\n const data = (await res.json()) as RouterToolsResponse\n const u = data.usage\n if (u && typeof u.prompt_tokens === 'number' && typeof u.completion_tokens === 'number') {\n tokens.input += u.prompt_tokens\n tokens.output += u.completion_tokens\n }\n const msg = data.choices?.[0]?.message\n if (msg?.content) lastText = msg.content\n const toolCalls = msg?.tool_calls ?? []\n if (toolCalls.length === 0) {\n // Before settling, flush once more — a worker may not finish while a steer/answer it never\n // read is still pending. If anything flushed, keep going; otherwise it is truly done.\n if (flush()) continue\n break\n }\n\n // Record the assistant turn verbatim, then run each call on the host and\n // fold the result back as a `tool` message for the next turn.\n messages.push({\n role: 'assistant',\n content: msg?.content ?? '',\n tool_calls: toolCalls.map((tc, i) => ({\n id: tc.id ?? `call_${i}`,\n type: 'function',\n function: { name: tc.function?.name ?? '', arguments: tc.function?.arguments ?? '{}' },\n })),\n })\n for (let i = 0; i < toolCalls.length; i += 1) {\n const tc = toolCalls[i]\n const id = tc?.id ?? `call_${i}`\n let args: Record<string, unknown> = {}\n try {\n args = JSON.parse(tc?.function?.arguments ?? '{}') as Record<string, unknown>\n } catch {\n // Malformed args are a real outcome, not an infra fault — feed the error\n // back so the model can correct, rather than aborting the whole loop.\n messages.push({\n role: 'tool',\n tool_call_id: id,\n content: 'error: tool arguments were not valid JSON',\n })\n continue\n }\n const toolName = tc?.function?.name ?? ''\n let result: string\n let status: 'ok' | 'error' = 'ok'\n const toolStartedAt = Date.now()\n try {\n result = await seam.executeToolCall(toolName, args, task)\n } catch (e) {\n status = 'error'\n result = `error: ${e instanceof Error ? e.message : String(e)}`\n }\n const toolEndedAt = Date.now()\n messages.push({ role: 'tool', tool_call_id: id, content: result })\n // Feed the online detector pipe (stuck-loop / error-streak) — a worker repeating the same\n // call or hammering errors is caught mid-run, not only at settle. This is an observability\n // side-channel: a throwing monitor must never crash the production inference loop.\n try {\n seam.onToolStep?.({\n toolName,\n args,\n status,\n startedAt: toolStartedAt,\n endedAt: toolEndedAt,\n durationMs: toolEndedAt - toolStartedAt,\n })\n } catch {\n // ignore — monitoring must not break the worker\n }\n }\n }\n\n const usd = isModelPriced(model) ? estimateCost(tokens.input, tokens.output, model) : 0\n const spent: Spend = { iterations: turns, tokens, usd, ms: Date.now() - started }\n const out = { content: lastText } as unknown\n artifact = { outRef: contentRef('router-tools', { model, content: lastText }), out, spent }\n return artifact\n },\n teardown(_grace): Promise<{ destroyed: boolean }> {\n controller.abort()\n return Promise.resolve({ destroyed: true })\n },\n resultArtifact() {\n if (!artifact) {\n throw new ValidationError(\n 'routerToolsInlineExecutor: resultArtifact() read before execute()',\n )\n }\n return { ...artifact, spent: artifact.spent }\n },\n }\n}\n\n// ── sandbox executor (harness is a BackendType) ────────────────────────────────\n\n/**\n * COMPOSES `runLoop` as a single-task leaf: one box, a refine driver bounded to\n * the seam's `maxIterations` (default 1), the spec's profile as the agent run.\n * Surfaces the loop's aggregated `tokenUsage` + `costUsd` as `UsageEvent`s after\n * it drains, and yields one `iteration` event per loop iteration. Forwards the\n * optional `lineage` passthrough WITHOUT importing sandbox-lineage / reinventing\n * checkpoint/fork.\n *\n * Streaming shape: the loop runs to completion inside the first `next()`, then\n * the recorded usage events are yielded; the terminal artifact is read from\n * `resultArtifact()` after the stream drains.\n */\nexport const sandboxExecutor: ExecutorFactory<unknown> = (spec, ctx) => {\n if (spec.harness === null) {\n throw new ValidationError('sandboxExecutor: harness is null (router/inline) — wrong executor')\n }\n const harness = spec.harness as BackendType\n const seam = readSeam<SandboxSeam>(ctx, sandboxSeamKey, 'sandbox')\n if (!seam.sandboxClient || typeof seam.sandboxClient.create !== 'function') {\n throw new ValidationError('sandboxExecutor: SandboxSeam.sandboxClient.create required')\n }\n const maxIterations = seam.maxIterations ?? 1\n if (!Number.isFinite(maxIterations) || maxIterations <= 0) {\n throw new ValidationError('sandboxExecutor: maxIterations must be > 0')\n }\n\n const controller = new AbortController()\n const abortIfSignalled = () => {\n if (ctx.signal.aborted) controller.abort()\n }\n abortIfSignalled()\n if (!ctx.signal.aborted) ctx.signal.addEventListener('abort', abortIfSignalled, { once: true })\n\n let artifact: ExecutorResult<unknown> | undefined\n\n // The leaf runs an opaque, self-parallelizing coding harness; the loop just\n // refines once over it. Output is the raw event stream parsed to its tail text.\n const output: OutputAdapter<SandboxLeafOut> = {\n parse(events: SandboxEvent[]): SandboxLeafOut {\n return { events }\n },\n }\n const driver = singleShotDriver<SandboxLeafOut>(maxIterations)\n\n return {\n runtime: 'sandbox' as Runtime,\n execute(task, signal): AsyncIterable<UsageEvent> {\n return streamSandboxLeaf({\n task,\n signal,\n harness,\n spec,\n seam,\n output,\n driver,\n maxIterations,\n controller,\n loopCtx: seam.loopCtx,\n onArtifact: (a) => {\n artifact = a\n },\n })\n },\n teardown(_grace): Promise<{ destroyed: boolean }> {\n // The composed runLoop owns its box teardown (finally{allSettled(destroy)});\n // aborting the loop's signal cascades into that barrier.\n controller.abort()\n return Promise.resolve({ destroyed: true })\n },\n resultArtifact() {\n if (!artifact) {\n throw new ValidationError('sandboxExecutor: resultArtifact() read before stream drained')\n }\n return artifact\n },\n }\n}\n\ninterface SandboxLeafOut {\n events: SandboxEvent[]\n}\n\ninterface StreamSandboxArgs {\n task: unknown\n signal: AbortSignal\n harness: BackendType\n spec: AgentSpec\n seam: SandboxSeam\n output: OutputAdapter<SandboxLeafOut>\n driver: Driver<unknown, SandboxLeafOut, string>\n maxIterations: number\n controller: AbortController\n loopCtx?: Partial<Omit<ExecCtx, 'sandboxClient' | 'signal'>>\n onArtifact: (a: ExecutorResult<unknown>) => void\n}\n\nasync function* streamSandboxLeaf(args: StreamSandboxArgs): AsyncIterable<UsageEvent> {\n const linked = new AbortController()\n const cascade = () => linked.abort()\n if (args.signal.aborted || args.controller.signal.aborted) linked.abort()\n else {\n args.signal.addEventListener('abort', cascade, { once: true })\n args.controller.signal.addEventListener('abort', cascade, { once: true })\n }\n\n const agentRun: AgentRunSpec<unknown> = {\n profile: args.spec.profile,\n taskToPrompt: (t) => taskToPrompt(t),\n name: args.spec.profile.name ?? args.harness,\n sandboxOverrides: { backend: { type: args.harness } },\n }\n const started = Date.now()\n\n // `lineage` is a PR #150 RunLoopOptions field absent on this branch — forwarded\n // forward-compatibly without coupling to its (not-yet-present) static type.\n const loopOptions = {\n driver: args.driver,\n agentRun,\n output: args.output,\n task: args.task,\n maxIterations: args.maxIterations,\n maxConcurrency: 1,\n ctx: {\n ...(args.loopCtx ?? {}),\n sandboxClient: args.seam.sandboxClient,\n signal: linked.signal,\n } as ExecCtx,\n ...(args.seam.lineage !== undefined ? { lineage: args.seam.lineage } : {}),\n } as RunLoopOptions<unknown, SandboxLeafOut, string>\n\n try {\n const result = await runLoop(loopOptions)\n const out = result.winner?.output ?? { events: [] }\n const verdict = result.winner?.verdict\n const spent: Spend = {\n iterations: result.iterations.length,\n tokens: { input: result.tokenUsage.input, output: result.tokenUsage.output },\n usd: result.costUsd,\n ms: Date.now() - started,\n }\n args.onArtifact({\n outRef: contentRef('sandbox', { harness: args.harness, out }),\n out,\n ...(verdict ? { verdict } : {}),\n spent,\n })\n for (let i = 0; i < result.iterations.length; i += 1) yield { kind: 'iteration' }\n if (result.tokenUsage.input || result.tokenUsage.output) {\n yield { kind: 'tokens', input: result.tokenUsage.input, output: result.tokenUsage.output }\n }\n if (result.costUsd) yield { kind: 'cost', usd: result.costUsd }\n } finally {\n args.signal.removeEventListener('abort', cascade)\n args.controller.signal.removeEventListener('abort', cascade)\n }\n}\n\n// ── cli executor (Halo / external RLM subprocess) ──────────────────────────────\n\n/**\n * Spawns a subprocess (`bin` + `args`). It cannot account tokens, so it is\n * `budgetExempt: true`: its spend is NOT metered against the conserved pool and\n * its iterations are EXCLUDED from the equal-k arms by construction (the\n * resolver/equal-k path checks `budgetExempt`). teardown is SIGTERM → SIGKILL\n * with a grace window. Streaming: yields one `iteration` event on clean exit.\n */\nexport const cliExecutor: ExecutorFactory<unknown> = (_spec, ctx) => {\n const seam = readSeam<CliSeam>(ctx, cliSeamKey, 'cli')\n if (!seam.bin) throw new ValidationError('cliExecutor: CliSeam.bin required')\n\n const controller = new AbortController()\n const abortIfSignalled = () => {\n if (ctx.signal.aborted) controller.abort()\n }\n abortIfSignalled()\n if (!ctx.signal.aborted) ctx.signal.addEventListener('abort', abortIfSignalled, { once: true })\n\n let proc: ReturnType<typeof spawn> | undefined\n let artifact: ExecutorResult<unknown> | undefined\n\n return {\n runtime: 'cli' as Runtime,\n budgetExempt: true,\n execute(task, signal): AsyncIterable<UsageEvent> {\n return streamCliLeaf({\n task,\n signal,\n seam,\n controller,\n onProc: (p) => {\n proc = p\n },\n onArtifact: (a) => {\n artifact = a\n },\n })\n },\n async teardown(grace): Promise<{ destroyed: boolean }> {\n controller.abort()\n if (!proc || proc.exitCode !== null || proc.killed) return { destroyed: true }\n return killWithGrace(proc, grace)\n },\n resultArtifact() {\n if (!artifact) {\n throw new ValidationError('cliExecutor: resultArtifact() read before stream drained')\n }\n return artifact\n },\n }\n}\n\ninterface StreamCliArgs {\n task: unknown\n signal: AbortSignal\n seam: CliSeam\n controller: AbortController\n onProc: (p: ReturnType<typeof spawn>) => void\n onArtifact: (a: ExecutorResult<unknown>) => void\n}\n\nasync function* streamCliLeaf(args: StreamCliArgs): AsyncIterable<UsageEvent> {\n const prompt = taskToPrompt(args.task)\n const proc = spawn(args.seam.bin, args.seam.args ?? [], {\n ...(args.seam.cwd ? { cwd: args.seam.cwd } : {}),\n env: { ...process.env, ...(args.seam.env ?? {}) },\n stdio: ['pipe', 'pipe', 'pipe'],\n })\n args.onProc(proc)\n\n const onAbort = () => killWithGrace(proc, 'brutalKill')\n if (args.signal.aborted || args.controller.signal.aborted) onAbort()\n else {\n args.signal.addEventListener('abort', onAbort, { once: true })\n args.controller.signal.addEventListener('abort', onAbort, { once: true })\n }\n\n // Feed the task on stdin; the subprocess owns its own tool/agent loop.\n if (proc.stdin) {\n proc.stdin.write(prompt)\n proc.stdin.end()\n }\n const chunks: string[] = []\n const errChunks: string[] = []\n if (proc.stdout) proc.stdout.on('data', (d: Buffer) => chunks.push(d.toString('utf8')))\n if (proc.stderr) proc.stderr.on('data', (d: Buffer) => errChunks.push(d.toString('utf8')))\n\n const exit = await new Promise<{ code: number | null; error?: Error }>((resolve) => {\n proc.once('error', (err) => resolve({ code: null, error: err }))\n proc.once('close', (code) => resolve({ code }))\n })\n args.signal.removeEventListener('abort', onAbort)\n args.controller.signal.removeEventListener('abort', onAbort)\n\n if (exit.error) {\n throw new ValidationError(`cliExecutor: spawn failed: ${exit.error.message}`, {\n cause: exit.error,\n })\n }\n if (exit.code !== 0) {\n throw new ValidationError(\n `cliExecutor: ${args.seam.bin} exited ${exit.code}: ${errChunks.join('').slice(0, 200)}`,\n )\n }\n const out = { content: chunks.join('') } as unknown\n // budgetExempt: spend is recorded zero (not metered) — never a fabricated cost.\n args.onArtifact({ outRef: contentRef('cli', out), out, spent: zeroSpend() })\n yield { kind: 'iteration' }\n}\n\n/** SIGTERM, then SIGKILL after `grace` ms (`'brutalKill'` = immediate SIGKILL,\n * `'infinity'` = await clean exit, never escalate). */\nfunction killWithGrace(\n proc: ReturnType<typeof spawn>,\n grace: number | 'brutalKill' | 'infinity',\n): Promise<{ destroyed: boolean }> {\n if (proc.exitCode !== null || proc.killed) return Promise.resolve({ destroyed: true })\n return new Promise((resolve) => {\n let timer: ReturnType<typeof setTimeout> | undefined\n proc.once('close', () => {\n if (timer) clearTimeout(timer)\n resolve({ destroyed: true })\n })\n if (grace === 'brutalKill') {\n proc.kill('SIGKILL')\n return\n }\n proc.kill('SIGTERM')\n if (grace === 'infinity') return\n timer = setTimeout(() => {\n if (proc.exitCode === null && !proc.killed) proc.kill('SIGKILL')\n }, grace)\n })\n}\n\n// ── bridge executor (harness CLIs behind the local cli-bridge) ──────────────────\n\n/**\n * A worker as a RESUMABLE cli-bridge harness session — the local twin of the\n * sandbox executor. Both are a persistent, streamed agent session the driver\n * spawns, watches stream `UsageEvent`s, then STEERS/RESUMES out-of-band; the only\n * difference is where the harness runs (local cli-bridge vs a cloud box).\n *\n * Structure mirrors `streamSandboxLeaf` + `routerToolsInlineExecutor`:\n * - STREAMED: `execute` returns an `AsyncIterable<UsageEvent>`; the SSE chunks\n * cli-bridge emits (`stream:true`) are parsed into incremental usage + a tail\n * artifact read via `resultArtifact()` after the stream drains.\n * - RESUMABLE: every turn carries a stable `session_id`. cli-bridge maps it to the\n * harness's internal conversation id (SQLite `SessionStore`), so a steer delivered\n * via `deliver` re-calls the SAME session id — opencode `-s <id>`, claude\n * `--resume`, … — continuing the SAME harness session, not a fresh one.\n * - STEERABLE: the down-leg `inbox` is drained at each turn boundary; a queued\n * steer becomes the next turn's prompt on the same session, and the worker can't\n * settle while a steer it never read is pending (the sandbox/router contract).\n * - ABORT: the caller signal + teardown fold into the per-turn fetch signal; a\n * forceful (`interrupt`) steer aborts the in-flight turn so the worker re-plans.\n *\n * Reports REAL usage when the bridge surfaces it, never a fabricated cost.\n */\nexport const bridgeExecutor: ExecutorFactory<unknown> = (spec, ctx) => {\n const seam = readSeam<BridgeSeam>(ctx, bridgeSeamKey, 'bridge')\n if (!seam.bridgeUrl || !seam.bridgeBearer || !seam.model) {\n throw new ValidationError(\n 'bridgeExecutor: BridgeSeam.bridgeUrl + bridgeBearer + model required',\n )\n }\n const maxTurns = seam.maxTurns ?? 200\n // A stable per-spawn session id (caller can pin one) — cli-bridge keys harness\n // resume off this exactly as a box id keys a sandbox session.\n const sessionId = seam.sessionId ?? `bridge-${spec.profile.name ?? 'worker'}-${randomUUID()}`\n\n const controller = new AbortController()\n const abortIfSignalled = () => {\n if (ctx.signal.aborted) controller.abort()\n }\n abortIfSignalled()\n if (!ctx.signal.aborted) ctx.signal.addEventListener('abort', abortIfSignalled, { once: true })\n\n // The down-leg receive end: the driver's steer/answer/resume land here via `Scope.send`.\n const inbox = createInbox()\n let artifact: ExecutorResult<unknown> | undefined\n\n return {\n runtime: 'cli' as Runtime,\n deliver: (m) => inbox.deliver(m),\n execute(task, signal): AsyncIterable<UsageEvent> {\n return streamBridgeSession({\n task,\n signal,\n spec,\n seam,\n sessionId,\n maxTurns,\n inbox,\n controller,\n onArtifact: (a) => {\n artifact = a\n },\n })\n },\n teardown(_grace): Promise<{ destroyed: boolean }> {\n controller.abort()\n return Promise.resolve({ destroyed: true })\n },\n resultArtifact() {\n if (!artifact) {\n throw new ValidationError('bridgeExecutor: resultArtifact() read before stream drained')\n }\n return { ...artifact, spent: artifact.spent }\n },\n }\n}\n\ninterface StreamBridgeArgs {\n task: unknown\n signal: AbortSignal\n spec: AgentSpec\n seam: BridgeSeam\n sessionId: string\n maxTurns: number\n inbox: Inbox\n controller: AbortController\n onArtifact: (a: ExecutorResult<unknown>) => void\n}\n\n/**\n * One resumable cli-bridge session, run as a streamed turn loop. Turn 0 sends the\n * task; each subsequent turn fires ONLY when the inbox has a steer/answer to fold —\n * re-calling the SAME `session_id` so cli-bridge resumes the harness conversation.\n * Mirrors `routerToolsInlineExecutor`'s drain→turn→settle loop, but each turn is a\n * full streamed harness session call rather than a single chat round.\n */\nasync function* streamBridgeSession(args: StreamBridgeArgs): AsyncIterable<UsageEvent> {\n const { seam, inbox } = args\n const started = Date.now()\n const url = `${seam.bridgeUrl.replace(/\\/$/, '')}/v1/chat/completions`\n const external = mergeAbortSignals(args.signal, args.controller.signal)\n const tokens = zeroTokenUsage()\n let usd = 0\n let turns = 0\n let lastText = ''\n const toolCalls: string[] = []\n\n // Turn 0 is the task; later turns carry the folded steer/answer as the next prompt\n // on the SAME session. `nextPrompt` is undefined once there's nothing pending.\n let nextPrompt: string | undefined = taskToPrompt(args.task)\n const system = args.spec.profile.prompt?.systemPrompt\n\n for (let t = 0; t < args.maxTurns; t += 1) {\n // Drain queued down-messages; on turns > 0 they ARE the prompt (resume content).\n const pending = inbox.drain()\n if (pending.length) {\n const folded = inbox.fold(pending)\n nextPrompt = t === 0 && nextPrompt ? `${nextPrompt}\\n\\n${folded}` : folded\n }\n if (nextPrompt === undefined) break\n\n // Each turn sends ONLY the new prompt — cli-bridge's session resume replays the\n // harness's own history server-side (opencode `-s`), so re-sending it would\n // double the conversation. Turn 0 may include the system preamble.\n const messages: Array<{ role: string; content: string }> = []\n if (t === 0 && typeof system === 'string' && system.length > 0) {\n messages.push({ role: 'system', content: system })\n }\n messages.push({ role: 'user', content: nextPrompt })\n nextPrompt = undefined\n\n // Per-turn signal: external teardown/abort OR a forceful interrupt steer.\n const interruptSig = inbox.freshInterrupt()\n const turnController = new AbortController()\n const abortTurn = () => turnController.abort()\n if (external.aborted) turnController.abort()\n else external.addEventListener('abort', abortTurn)\n interruptSig.addEventListener('abort', abortTurn, { once: true })\n const timer = seam.timeoutMs ? setTimeout(abortTurn, seam.timeoutMs) : undefined\n const cleanup = () => {\n external.removeEventListener('abort', abortTurn)\n if (timer) clearTimeout(timer)\n }\n\n let res: Response\n try {\n res = await fetch(url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${seam.bridgeBearer}`,\n 'x-session-id': args.sessionId,\n },\n body: JSON.stringify({\n model: seam.model,\n stream: true,\n session_id: args.sessionId,\n ...(seam.agentProfile ? { agent_profile: seam.agentProfile } : {}),\n messages,\n }),\n signal: turnController.signal,\n })\n } catch (e) {\n cleanup()\n // Re-plan ONLY when a forceful steer (not external teardown) aborted the turn —\n // the steer is already queued, so loop back and fold it. Anything else is fatal.\n const interruptAbort =\n e instanceof DOMException &&\n e.name === 'AbortError' &&\n interruptSig.aborted &&\n !args.signal.aborted &&\n !args.controller.signal.aborted\n if (interruptAbort) continue\n throw e\n }\n if (!res.ok) {\n cleanup()\n throw new ValidationError(\n `bridgeExecutor: bridge ${res.status}: ${(await res.text()).slice(0, 300)}`,\n )\n }\n if (!res.body) {\n cleanup()\n throw new ValidationError('bridgeExecutor: bridge response had no body to stream')\n }\n\n let turnText = ''\n try {\n for await (const chunk of parseSseChatStream(res.body)) {\n if (chunk.content) {\n turnText += chunk.content\n yield { kind: 'iteration' }\n }\n if (chunk.toolCall) toolCalls.push(chunk.toolCall)\n if (chunk.usage) {\n tokens.input += chunk.usage.input\n tokens.output += chunk.usage.output\n yield { kind: 'tokens', input: chunk.usage.input, output: chunk.usage.output }\n }\n if (typeof chunk.cost === 'number' && chunk.cost > 0) {\n usd += chunk.cost\n yield { kind: 'cost', usd: chunk.cost }\n }\n }\n } finally {\n cleanup()\n }\n turns += 1\n if (turnText) lastText = turnText\n\n // Before settling, drain once more — the worker can't finish while a steer it\n // never read is pending (the sandbox/router settle contract). A pending steer\n // becomes the next resume turn; otherwise the session is truly done.\n if (inbox.pending() === 0) break\n }\n\n const spent: Spend = {\n iterations: turns,\n tokens,\n usd,\n ms: Date.now() - started,\n }\n const out = { content: lastText, toolCalls } as unknown\n args.onArtifact({\n outRef: contentRef('bridge', { model: seam.model, session: args.sessionId, content: lastText }),\n out,\n spent,\n })\n}\n\ninterface BridgeStreamChunk {\n content?: string\n toolCall?: string\n usage?: { input: number; output: number }\n cost?: number\n}\n\n/**\n * Parse cli-bridge's OpenAI-compatible SSE stream into normalized chunks. Each\n * `data:` line is an OpenAI chat-completion chunk (`choices[].delta`); `[DONE]`\n * and SSE comments (`:` keepalives) terminate/skip. Mirrors how `streamSandboxLeaf`\n * folds a box's event stream — same `UsageEvent` currency, different wire shape.\n */\nasync function* parseSseChatStream(\n body: ReadableStream<Uint8Array>,\n): AsyncIterable<BridgeStreamChunk> {\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let buf = ''\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n buf += decoder.decode(value, { stream: true })\n // SSE frames are separated by a blank line; split on it and keep the tail.\n let sep = buf.indexOf('\\n\\n')\n while (sep !== -1) {\n const frame = buf.slice(0, sep)\n buf = buf.slice(sep + 2)\n const chunk = parseSseFrame(frame)\n if (chunk === 'done') return\n if (chunk) yield chunk\n sep = buf.indexOf('\\n\\n')\n }\n }\n } finally {\n reader.releaseLock()\n }\n}\n\n/** Parse one SSE frame (possibly multi-line `data:`/comment) into a chunk, `'done'`,\n * or undefined (comment/keepalive/empty). */\nfunction parseSseFrame(frame: string): BridgeStreamChunk | 'done' | undefined {\n const dataLines: string[] = []\n for (const rawLine of frame.split('\\n')) {\n const line = rawLine.replace(/\\r$/, '')\n if (!line || line.startsWith(':')) continue // comment / keepalive\n if (line.startsWith('data:')) dataLines.push(line.slice('data:'.length).trimStart())\n }\n if (dataLines.length === 0) return undefined\n const data = dataLines.join('\\n')\n if (data === '[DONE]') return 'done'\n let parsed: {\n choices?: Array<{\n delta?: {\n content?: string | null\n tool_calls?: Array<{ function?: { name?: string } }>\n }\n message?: { content?: string | null }\n }>\n error?: { message?: string }\n usage?: { prompt_tokens?: number; completion_tokens?: number; cost?: number }\n }\n try {\n parsed = JSON.parse(data)\n } catch {\n return undefined\n }\n if (parsed.error) {\n throw new ValidationError(\n `bridgeExecutor: bridge stream error: ${parsed.error.message ?? 'unknown'}`,\n )\n }\n const out: BridgeStreamChunk = {}\n const choice = parsed.choices?.[0]\n const content = choice?.delta?.content ?? choice?.message?.content\n if (typeof content === 'string' && content.length > 0) out.content = content\n const toolName = choice?.delta?.tool_calls?.[0]?.function?.name\n if (typeof toolName === 'string' && toolName.length > 0) out.toolCall = toolName\n const u = parsed.usage\n if (u && (typeof u.prompt_tokens === 'number' || typeof u.completion_tokens === 'number')) {\n out.usage = { input: u.prompt_tokens ?? 0, output: u.completion_tokens ?? 0 }\n }\n if (typeof u?.cost === 'number') out.cost = u.cost\n return Object.keys(out).length > 0 ? out : undefined\n}\n\n// ── cli-worktree executor (authored profile → harness CLI on a git worktree) ────\n\n/**\n * The leaf `createWorktreeCliExecutor` as a backend-as-data factory: a supervisor-authored\n * `AgentProfile` driving claude / codex / opencode on its own worktree. `budgetExempt` like\n * the other CLI leaves; the authored systemPrompt + model reach the harness via §1.5.\n */\nexport const cliWorktreeExecutor: ExecutorFactory<unknown> = (spec, ctx) => {\n const seam = readSeam<CliWorktreeSeam>(ctx, cliWorktreeSeamKey, 'cli-worktree')\n if (!seam.repoRoot || !seam.harness || !seam.taskPrompt) {\n throw new ValidationError(\n 'cliWorktreeExecutor: CliWorktreeSeam.repoRoot + harness + taskPrompt required',\n )\n }\n return createWorktreeCliExecutor({\n repoRoot: seam.repoRoot,\n profile: spec.profile,\n harness: seam.harness,\n taskPrompt: seam.taskPrompt,\n ...(seam.runId ? { runId: seam.runId } : {}),\n ...(seam.baseRef ? { baseRef: seam.baseRef } : {}),\n ...(seam.harnessTimeoutMs !== undefined ? { harnessTimeoutMs: seam.harnessTimeoutMs } : {}),\n }) as Executor<unknown>\n}\n\n// ── createExecutor: the ONE built-in factory (backend as data) ──────────────────\n\n/**\n * Config for {@link createExecutor}: the backend is DATA — the cost dial a profile,\n * an experiment config, or a replay journal can name — not an import choice. Each\n * variant carries its backend's seam (router/router-tools/bridge/cli/cli-worktree/sandbox).\n */\nexport type ExecutorConfig =\n | ({ backend: 'router' } & RouterSeam)\n | ({ backend: 'router-tools' } & RouterToolsSeam)\n | ({ backend: 'bridge' } & BridgeSeam)\n | ({ backend: 'cli' } & CliSeam)\n | ({ backend: 'cli-worktree' } & CliWorktreeSeam)\n | ({ backend: 'provider' } & ProviderSeam)\n | ({ backend: 'sandbox'; harness?: BackendType } & SandboxSeam)\n\n/**\n * The single built-in executor factory. Picks a leaf backend by data (`config.backend`),\n * injects the matching seam, and delegates to that backend's built-in implementation.\n * The `Executor` port stays OPEN: bring-your-own agents implement `Executor` directly\n * and never pass through here. Use this (or `createExecutorRegistry`) instead of a\n * per-vendor adapter or a closed `inline|sandbox|cli` switch — those bypass the\n * `UsageEvent` reporting channel.\n */\nexport function createExecutor(config: ExecutorConfig): ExecutorFactory<unknown> {\n return (spec, ctx) => {\n const { backend, ...seam } = config as ExecutorConfig & Record<string, unknown>\n const seamed: ExecutorContext = { ...ctx, seams: { ...ctx.seams, [backend]: seam } }\n switch (config.backend) {\n case 'router':\n return routerInlineExecutor(spec, seamed)\n case 'router-tools':\n return routerToolsInlineExecutor(spec, seamed)\n case 'bridge':\n return bridgeExecutor(spec, seamed)\n case 'cli':\n return cliExecutor(spec, seamed)\n case 'cli-worktree':\n return cliWorktreeExecutor(spec, seamed)\n case 'provider': {\n const providerSeam = readSeam<ProviderSeam>(seamed, providerSeamKey, 'provider')\n const provider = resolveAgentEnvironmentProvider(\n providerSeam.provider,\n providerSeam.registry,\n )\n return providerAsExecutor(provider, providerSeam)(spec, seamed)\n }\n case 'sandbox': {\n // The sandbox executor requires a concrete harness; a spec-level harness\n // wins, else the config names it (fail-loud inside if both are absent).\n const harness = spec.harness ?? config.harness ?? null\n return sandboxExecutor({ ...spec, harness }, seamed)\n }\n }\n }\n}\n\n// ── The open registry ──────────────────────────────────────────────────────────\n\n/**\n * The open resolver/registry. Pre-registers the three built-ins under their\n * runtime tags (`'router'`, `'sandbox'`, `'cli'`) and accepts `register(name,\n * factory)` for any additional runtime — and a BYO `AgentSpec.executor` resolves\n * without touching the registry at all. NOT a closed switch; registration + BYO\n * ARE the extension points.\n *\n * `resolve` precedence (frozen in `ExecutorRegistry`): a BYO `spec.executor` →\n * `harness === null` → the `'router'` factory; else a registered factory for the\n * harness-derived runtime (`'sandbox'` for any `BackendType`); else fail loud.\n */\nexport function createExecutorRegistry(): ExecutorRegistry {\n const factories = new Map<Runtime, ExecutorFactory<unknown>>()\n factories.set('router', routerInlineExecutor)\n factories.set('inline', routerInlineExecutor)\n factories.set('sandbox', sandboxExecutor)\n factories.set('cli', cliExecutor)\n\n return {\n register<Out>(runtime: Runtime, factory: ExecutorFactory<Out>): void {\n if (factories.has(runtime)) {\n throw new ValidationError(`executor registry: runtime \"${runtime}\" already registered`)\n }\n factories.set(runtime, factory as ExecutorFactory<unknown>)\n },\n resolve<Out>(\n spec: AgentSpec,\n ): { succeeded: true; value: ExecutorFactory<Out> } | { succeeded: false; error: string } {\n // BYO: a caller-supplied executor wins, wrapped in a trivial per-spawn factory.\n if (spec.executor) {\n const byo = spec.executor\n return { succeeded: true, value: (() => byo) as ExecutorFactory<Out> }\n }\n // router/inline: an agent with no harness is a direct Router call.\n if (spec.harness === null) {\n const f = factories.get('router')\n if (!f) return { succeeded: false, error: 'executor registry: no \"router\" factory' }\n return { succeeded: true, value: f as ExecutorFactory<Out> }\n }\n // sandbox: any BackendType maps to the sandbox-composing-runLoop executor.\n const runtimeTag: Runtime = 'sandbox'\n const f = factories.get(runtimeTag)\n if (!f) {\n return {\n succeeded: false,\n error: `executor registry: no factory for runtime \"${runtimeTag}\" (harness \"${spec.harness}\") and no BYO executor`,\n }\n }\n return { succeeded: true, value: f as ExecutorFactory<Out> }\n },\n }\n}\n\n// ── Shared helpers ──────────────────────────────────────────────────────────────\n\n/** Narrow a named seam off the `ExecutorContext`, failing loud when absent — no\n * silent default for a required external-boundary seam. */\nfunction readSeam<T>(ctx: ExecutorContext, key: string, who: string): T {\n const seam = ctx.seams[key]\n if (seam === undefined || seam === null) {\n throw new ValidationError(`${who} executor: missing required seam \"${key}\" on ExecutorContext`)\n }\n return seam as T\n}\n\n/** A leaf task is opaque (`unknown`). A string is the prompt verbatim; an object\n * with a `prompt`/`content`/`task` string field uses it; otherwise it serializes. */\nfunction taskToPrompt(task: unknown): string {\n if (typeof task === 'string') return task\n if (task && typeof task === 'object') {\n const obj = task as Record<string, unknown>\n for (const k of ['prompt', 'content', 'task', 'message']) {\n if (typeof obj[k] === 'string') return obj[k] as string\n }\n }\n return JSON.stringify(task)\n}\n\n/** Router messages from the opaque task + the profile's system prompt, when set. */\nfunction taskToMessages(task: unknown, spec: AgentSpec): Array<{ role: string; content: string }> {\n const messages: Array<{ role: string; content: string }> = []\n const system = spec.profile.prompt?.systemPrompt\n if (typeof system === 'string' && system.length > 0) {\n messages.push({ role: 'system', content: system })\n }\n messages.push({ role: 'user', content: taskToPrompt(task) })\n return messages\n}\n\n/** A driver that refines a single task up to `maxIterations` times then stops —\n * the minimal policy that lets the sandbox executor run `runLoop` as one leaf. */\nfunction singleShotDriver<Out>(maxIterations: number): Driver<unknown, Out, string> {\n return {\n name: 'leaf',\n plan(task, history): Promise<unknown[]> {\n return Promise.resolve(history.length >= maxIterations ? [] : [task])\n },\n decide(history: ReadonlyArray<Iteration<unknown, Out>>): string {\n return history.length >= maxIterations ? 'stop' : 'continue'\n },\n }\n}\n\n/** Link two abort signals into one that fires when either does. Returns\n * `undefined` when neither is present so `fetch` gets no signal at all. */\nfunction linkSignals(a: AbortSignal, b: AbortSignal): AbortSignal | undefined {\n if (a.aborted || b.aborted) {\n const c = new AbortController()\n c.abort()\n return c.signal\n }\n const c = new AbortController()\n const onAbort = () => c.abort()\n a.addEventListener('abort', onAbort, { once: true })\n b.addEventListener('abort', onAbort, { once: true })\n return c.signal\n}\n\n/** Combine N abort signals into one that fires when ANY does. Node-portable (no `AbortSignal.any`,\n * which needs >=20.3 — the package floor is >=20). */\nfunction mergeAbortSignals(...signals: AbortSignal[]): AbortSignal {\n const c = new AbortController()\n const onAbort = () => c.abort()\n for (const s of signals) {\n if (s.aborted) {\n c.abort()\n break\n }\n s.addEventListener('abort', onAbort, { once: true })\n }\n return c.signal\n}\n\n// Re-export the verdict + spend surface so a consumer importing the runtime\n// built-ins gets the budget vocabulary from one place.\nexport type { DefaultVerdict, Executor, ExecutorResult, Spend, UsageEvent }\n","/**\n * @experimental\n *\n * The conserved budget reservation pool — the invariant the whole instrument\n * rests on (critique M5/B3). One root `Budget` becomes a conserved pool of three\n * quantities (tokens, usd, iterations) plus an absolute deadline. Children reserve\n * atomically at spawn and reconcile at settle:\n *\n * total ≡ free + reserved + committed (invariant, always)\n *\n * `reserve` moves a child's whole ceiling from `free` → `reserved` and fails closed\n * when `free` can't cover it (never read-then-spawn overcommit, so `Σk(treatment) ≡\n * Σk(blind)` by construction). `reconcile` releases the reservation, commits ACTUAL\n * spend, and refunds the unspent remainder to `free`. Tokens and usd are separate\n * channels (`LoopTokenUsage` has no `usd`); iterations are conserved alongside them.\n *\n * Pure and deterministic: `now()` is injected, there is no I/O, and no wall-clock or\n * RNG read. A `reserve`/`reconcile` ticket is single-use (fail-loud on double or\n * unknown reconcile) so a child can never refund twice.\n */\n\nimport { addTokenUsage, zeroTokenUsage } from '../util'\nimport type { Budget, LoopTokenUsage, Spend, UsageEvent } from './types'\n\nexport type { Budget, Spend, UsageEvent }\n\n/** Opaque, single-use reservation handle returned by `reserve` and consumed by\n * `reconcile`. Carries the reserved ceilings so reconciliation needs no lookup. */\nexport interface ReservationTicket {\n readonly id: number\n readonly reserved: {\n readonly tokens: number\n readonly usd: number\n readonly iterations: number\n }\n}\n\n/** Post-reservation pool readout — the shape `Scope.budget` exposes. `tokensLeft`,\n * `usdLeft`, and `reservedTokens` reflect committed-but-unsettled reservations;\n * `deadlineMs` is the ABSOLUTE wall-clock deadline (0 when the root set none).\n * `usdCapped` distinguishes a real `usdLeft <= 0` exhaustion from an uncapped pool (which always\n * reads `usdLeft: 0`) — the in-loop guard needs it to bound a usd-capped driver. */\nexport type BudgetReadout = Readonly<{\n tokensLeft: number\n usdLeft: number\n usdCapped: boolean\n deadlineMs: number\n reservedTokens: number\n}>\n\nexport interface BudgetPool {\n /**\n * Atomically reserve a child's full ceiling from the free balance. Fails closed\n * ({ ok: false }) when the pool can't cover tokens, usd, or iterations — the\n * caller inspects `ok` before `ticket`.\n */\n reserve(\n b: Budget,\n ): { ok: true; ticket: ReservationTicket } | { ok: false; reason: 'budget-exhausted' }\n /**\n * Release a reservation: commit the actual `spent`, refund the unspent remainder\n * to the free pool. Throws on an unknown or already-reconciled ticket (fail loud —\n * a double refund would silently break conservation).\n */\n reconcile(ticket: ReservationTicket, spent: Spend): void\n /** Fold a normalized `UsageEvent` stream (or array) into a `Spend`. Tokens via\n * `addTokenUsage`, usd on its own channel, iterations from `'iteration'` events.\n * `ms` is left zero — wall-clock duration is the caller's to record, not the pool's. */\n spendFrom(events: AsyncIterable<UsageEvent> | UsageEvent[]): Promise<Spend>\n /** The current readout, reflecting all outstanding reservations. */\n readout(): BudgetReadout\n /**\n * Record OBSERVED spend that did NOT go through reserve/reconcile — the driver's OWN inference\n * (its chat turns), which is real compute but not a spawned child. A direct `free → committed`\n * debit, so `total ≡ free + reserved + committed` is preserved: equal-k counts the driver's\n * tokens and the in-loop budget guard (`readout().tokensLeft`) sees them. `free` may go negative\n * when a run overspends — that is honest (the readout then signals exhaustion). It never throws:\n * the spend already happened, so accounting records reality; the in-loop guard prevents MORE.\n * The DURABLE record is the journal's `metered` event (written by `Scope.meter`); this debit\n * only makes the live `readout()` reflect driver inference for the in-loop guard.\n */\n observe(spend: Spend): void\n /** Fail loud if any reservation is still open — the conserved-pool leak detector. Called at the\n * supervisor's join barrier: once every child has settled, no ticket may remain (a leaked\n * reservation would silently break `total ≡ free + reserved + committed`). */\n assertNoOpenTickets(): void\n}\n\n/** Fold a normalized `UsageEvent` array into a `Spend`. Tokens and usd are separate\n * channels; iterations come from `'iteration'` events. Pure; `ms` stays zero (the\n * pool does not read wall-clock). */\nexport function spendFromUsageEvents(events: UsageEvent[]): Spend {\n const tokens = zeroTokenUsage()\n let usd = 0\n let iterations = 0\n for (const ev of events) {\n if (ev.kind === 'tokens') {\n addTokenUsage(tokens, { input: ev.input, output: ev.output })\n } else if (ev.kind === 'cost') {\n usd += ev.usd\n } else {\n iterations += 1\n }\n }\n return { iterations, tokens, usd, ms: 0 }\n}\n\nasync function foldUsage(events: AsyncIterable<UsageEvent> | UsageEvent[]): Promise<Spend> {\n if (Array.isArray(events)) return spendFromUsageEvents(events)\n const tokens = zeroTokenUsage()\n let usd = 0\n let iterations = 0\n for await (const ev of events) {\n if (ev.kind === 'tokens') {\n addTokenUsage(tokens, { input: ev.input, output: ev.output })\n } else if (ev.kind === 'cost') {\n usd += ev.usd\n } else {\n iterations += 1\n }\n }\n return { iterations, tokens, usd, ms: 0 }\n}\n\nfunction totalTokens(usage: LoopTokenUsage): number {\n return usage.input + usage.output\n}\n\n/**\n * Create a conserved reservation pool from a root `Budget`. `now()` is injected so the\n * deadline readout is deterministic; defaults to `Date.now` for non-test callers. The\n * absolute deadline is fixed at construction (`now() + budget.deadlineMs`) so the\n * readout's `deadlineMs` is a stable wall-clock instant, not a shrinking remainder.\n */\nexport function createBudgetPool(root: Budget, now: () => number = Date.now): BudgetPool {\n // free + reserved + committed ≡ root totals, per channel, always.\n let freeTokens = root.maxTokens\n let reservedTokens = 0\n let committedTokens = 0\n\n const usdCapped = root.maxUsd !== undefined\n let freeUsd = root.maxUsd ?? 0\n let reservedUsd = 0\n let committedUsd = 0\n\n let freeIterations = root.maxIterations\n let reservedIterations = 0\n let committedIterations = 0\n\n const absoluteDeadlineMs = root.deadlineMs !== undefined ? now() + root.deadlineMs : 0\n\n let nextTicketId = 0\n const open = new Set<number>()\n\n function reserve(\n b: Budget,\n ): { ok: true; ticket: ReservationTicket } | { ok: false; reason: 'budget-exhausted' } {\n const wantTokens = b.maxTokens\n const wantUsd = b.maxUsd ?? 0\n const wantIterations = b.maxIterations\n // Fail-closed admission: every requested channel must fit the free balance. A\n // usd request against an uncapped root is unsatisfiable (the root declared no $).\n if (wantTokens > freeTokens) return { ok: false, reason: 'budget-exhausted' }\n if (wantIterations > freeIterations) return { ok: false, reason: 'budget-exhausted' }\n if (wantUsd > 0 && (!usdCapped || wantUsd > freeUsd)) {\n return { ok: false, reason: 'budget-exhausted' }\n }\n\n freeTokens -= wantTokens\n reservedTokens += wantTokens\n freeIterations -= wantIterations\n reservedIterations += wantIterations\n if (wantUsd > 0) {\n freeUsd -= wantUsd\n reservedUsd += wantUsd\n }\n\n const id = nextTicketId++\n open.add(id)\n return {\n ok: true,\n ticket: { id, reserved: { tokens: wantTokens, usd: wantUsd, iterations: wantIterations } },\n }\n }\n\n function reconcile(ticket: ReservationTicket, spent: Spend): void {\n if (!open.has(ticket.id)) {\n throw new Error(`budget pool: reconcile of unknown or already-settled ticket ${ticket.id}`)\n }\n open.delete(ticket.id)\n\n const { tokens: rTokens, usd: rUsd, iterations: rIterations } = ticket.reserved\n\n // Clamp actual spend to the reservation: a child must never commit more than it\n // reserved (that would overdraw the conserved pool). Over-spend is a fail-loud bug.\n const spentTokens = totalTokens(spent.tokens)\n if (spentTokens > rTokens) {\n throw new Error(\n `budget pool: ticket ${ticket.id} spent ${spentTokens} tokens > reserved ${rTokens}`,\n )\n }\n if (spent.iterations > rIterations) {\n throw new Error(\n `budget pool: ticket ${ticket.id} spent ${spent.iterations} iterations > reserved ${rIterations}`,\n )\n }\n // USD is conserved ONLY when the root declared a ceiling. `maxUsd` is optional: when no\n // root ceiling exists, usd is an OBSERVED quantity (committed for accounting), never a\n // budgeted constraint — so an unset ceiling must not behave as a hard $0 limit that\n // fail-closes a real priced spend. The over-spend clamp applies only to a capped pool.\n if (usdCapped && spent.usd > rUsd) {\n throw new Error(`budget pool: ticket ${ticket.id} spent $${spent.usd} > reserved $${rUsd}`)\n }\n\n // Release the whole reservation, then commit actual spend; the difference is the\n // refund that flows back to `free`.\n reservedTokens -= rTokens\n committedTokens += spentTokens\n freeTokens += rTokens - spentTokens\n\n reservedIterations -= rIterations\n committedIterations += spent.iterations\n freeIterations += rIterations - spent.iterations\n\n if (usdCapped && rUsd > 0) {\n reservedUsd -= rUsd\n committedUsd += spent.usd\n freeUsd += rUsd - spent.usd\n } else {\n // Uncapped (or a zero-ceiling child under a capped root): record the observed spend\n // without touching the reservation channel — usd is accounted, not conserved here.\n committedUsd += spent.usd\n }\n }\n\n function observe(spend: Spend): void {\n const tokens = totalTokens(spend.tokens)\n // Direct free → committed debit (no reservation ticket). `free` may go negative on overspend —\n // that is honest; the readout then reports exhaustion and the in-loop guard halts the driver.\n // The DURABLE record of this spend is the journal's `metered` event (the twin written by\n // `Scope.meter`); this debit exists only to make the live `readout()` reflect driver inference.\n freeTokens -= tokens\n committedTokens += tokens\n freeIterations -= spend.iterations\n committedIterations += spend.iterations\n committedUsd += spend.usd\n if (usdCapped) freeUsd -= spend.usd\n }\n\n function readout(): BudgetReadout {\n return {\n tokensLeft: freeTokens,\n usdLeft: usdCapped ? freeUsd : 0,\n usdCapped,\n deadlineMs: absoluteDeadlineMs,\n reservedTokens,\n }\n }\n\n function assertNoOpenTickets(): void {\n if (open.size > 0) {\n throw new Error(\n `budget pool: ${open.size} reservation(s) still open at join barrier (leaked ticket ids: ${[...open].join(', ')}) — conserved-pool invariant violated`,\n )\n }\n }\n\n return {\n reserve,\n reconcile,\n spendFrom: foldUsage,\n readout,\n observe,\n assertNoOpenTickets,\n }\n}\n","/**\n * @experimental\n *\n * The `Supervisor` impl (KEYSTONE, build step 5).\n *\n * Owns the four things a free-running recursive `act` cannot own itself: the GLOBAL\n * conserved budget pool, the event-sourced spawn log, the abort cascade over the whole\n * live tree, and the OTP intensity breaker. `run` builds the root `Scope` over those,\n * runs the root `Agent.act`, and returns a TYPED `SupervisedResult` — a no-winner is\n * never coerced into a best-effort `Out`.\n *\n * Three lifecycle invariants this impl enforces by construction:\n * - Join barrier: when `act()` settles (resolve OR reject), every still-live child is\n * torn down before `run` returns — the generalization of the kernel's\n * `finally{ Promise.allSettled(destroy) }` barrier (run-loop.ts) from boxes to the\n * whole sub-tree. A teardown failure is `allSettled`'d and journaled as a\n * `cancelled` event; it NEVER masks act()'s own outcome. act()'s rejection is the\n * PRIMARY error (the kernel's firstError precedence), so a teardown throw during the\n * barrier can never overwrite the real failure.\n * - Abort cascade: a root abort (caller signal, `RootHandle.abort`, a tripped breaker,\n * or pool exhaustion) aborts ONE internal controller whose signal is the root scope's\n * signal. The scope cascades that into every live child's executor abort — which, for\n * an `acquiring` child, chains into the `acquireSandbox` signal and reaps the\n * find-by-name orphan box (M1). The supervisor never reaps children directly.\n * - The supervisor NEVER re-enters a child (m3): the kernel/`acquireSandbox` already\n * retried at the leaf, and a driver re-spawns through `scope.spawn`. The breaker only\n * COUNTS `down` settlements within the intensity window and trips to a typed\n * no-winner; it does not restart anything.\n *\n * Selection lives in the driver, not here (selector≠judge): `act` returns the synthesized\n * winner `Out`. The supervisor content-addresses that `Out` for its replay `outRef`, reads\n * `spentTotal` off the journal (`settled` child work + `metered` driver inference), and wraps\n * it as a typed `winner` — it does not re-rank children behind the driver's back.\n */\n\nimport { contentAddress } from '../../durable/spawn-journal'\nimport { RuntimeRunStateError } from '../../errors'\nimport { type BudgetPool, createBudgetPool } from './budget'\nimport { createScope } from './scope'\nimport type {\n Agent,\n RootHandle,\n RootSignal,\n Scope,\n SpawnEvent,\n SpawnJournal,\n Spend,\n SupervisedResult,\n Supervisor,\n SupervisorOpts,\n TreeView,\n} from './types'\n\n/** The default runtime recursion-depth ceiling, paired with the conserved pool so a\n * runaway recursion hits budget-exhaustion first and depth-exceeded second (R3). */\nconst defaultMaxDepth = 4\n\n/** A no-winner reason the supervisor can prove from its OWN lifecycle state — pinned to\n * the frozen `SupervisedResult` reason union. A driver rejecting for a domain reason\n * (not budget/abort) is classed `all-children-down`, the only typed bucket for \"the tree\n * produced no usable result\". */\ntype NoWinnerReason = (SupervisedResult<unknown> & { kind: 'no-winner' })['reason']\n\nexport function createSupervisor<Task, Out>(): Supervisor<Task, Out> {\n let attached: RootControl | undefined\n\n async function run(\n root: Agent<Task, Out>,\n task: Task,\n opts: SupervisorOpts,\n ): Promise<SupervisedResult<Out>> {\n const now = opts.now ?? Date.now\n const pool = createBudgetPool(opts.budget, now)\n await opts.journal.beginTree(opts.runId, new Date(now()).toISOString())\n\n // Journal the root as its own `spawned` node (parent-less, the spawn-ordinal-0 marker), so a\n // journal-based reader — `trajectoryReport`, `replaySpawnTree`, `materializeTreeView` — can\n // reconstruct the WHOLE realized tree from a real run, not only hand-built journals. The root\n // is never `scope.spawn`ed (the supervisor runs `act` directly), so without this the root node\n // is absent and `trajectoryReport` fails its `nodes.has(root)` invariant. The uniqueness guard\n // skips `spawned` events (only the cursor namespace must be unique), so sharing ordinal 0 with\n // the first child's spawn is not a collision; replay ignores `spawned` events for settlement\n // reconstruction, so the replayed `Settled[]` is unchanged.\n await opts.journal.appendEvent(opts.runId, {\n kind: 'spawned',\n id: opts.runId,\n label: 'root',\n budget: opts.budget,\n runtime: 'inline',\n seq: 0,\n at: new Date(now()).toISOString(),\n })\n\n // ONE internal controller is the root scope's abort source. Every cascade path\n // (caller signal, RootHandle.abort, breaker trip, deadline) aborts it; the scope\n // fans it out to each live child's executor (acquire-aware reap included).\n const controller = new AbortController()\n const cascadeAbort = (reason?: string) => {\n if (controller.signal.aborted) return\n // Carry the reason on the signal so it chains down to each child's abort signal\n // (`childAbort.signal.reason`) — the diagnostic the scope's executors observe.\n controller.abort(reason)\n }\n\n const onCallerAbort = () => cascadeAbort('caller signal aborted')\n if (opts.signal) {\n if (opts.signal.aborted) cascadeAbort('caller signal aborted')\n else opts.signal.addEventListener('abort', onCallerAbort, { once: true })\n }\n\n // The breaker watches `down` settlements via a counting journal decorator, so it\n // observes every child failure without intercepting `scope.next()` (the driver's\n // private channel). Tripping aborts the same controller; the trip is recorded so the\n // final result can name it.\n const breaker = createIntensityBreaker(opts, () => cascadeAbort('intensity breaker tripped'))\n const journal = wrapJournalForBreaker(opts.journal, breaker)\n\n const scope = createScope<Out>({\n parentId: opts.runId,\n root: opts.runId,\n pool,\n journal,\n blobs: opts.blobs,\n executors: opts.executors,\n seams: {},\n depth: 0,\n maxDepth: opts.maxDepth ?? defaultMaxDepth,\n signal: controller.signal,\n now,\n hooks: opts.hooks,\n })\n\n // `view`/drain read the scope opaquely (`Out` erased) — the supervisor never `spawn`s\n // on it, so the live-tree readout and the join barrier are `Out`-agnostic.\n const openScope = scope as unknown as Scope<unknown>\n\n // Bind any attached RootHandle to THIS live run so view()/signal()/abort() reach the\n // live scope + the one cascade controller. Detached again in the finally barrier.\n if (attached) {\n attached.bind({ scope: openScope, cascadeAbort, signal: pushRootSignal(cascadeAbort) })\n }\n\n let actOutcome: { ok: true; out: Out } | { ok: false; error: unknown }\n try {\n const out = await root.act(task, scope)\n actOutcome = { ok: true, out }\n } catch (error) {\n // act()'s rejection is the PRIMARY error; capture it before the join barrier so a\n // teardown failure in the barrier can never overwrite it (firstError precedence).\n actOutcome = { ok: false, error }\n } finally {\n // Join barrier: tear down every still-live child. Generalizes the kernel's\n // `finally{ Promise.allSettled(destroy) }` — a teardown throw is allSettled'd and\n // journaled, never re-thrown.\n await drainLiveChildren(openScope, controller)\n if (opts.signal) opts.signal.removeEventListener('abort', onCallerAbort)\n if (attached) attached.unbind()\n }\n\n const tree = scope.view\n if (actOutcome.ok) {\n // Every child has settled (join barrier above); no reservation may remain. A leaked ticket\n // would silently corrupt the conserved spend total, so fail loud here — on the success path\n // only, where the act() error precedence does not apply.\n pool.assertNoOpenTickets()\n const out = actOutcome.out\n // Completion-oracle at the root: a `winner` MUST carry a real `Out`. A driver that ran to\n // completion but selected nothing (its keep-best finalize found no DELIVERED child) returns\n // `undefined` — that is a no-winner, never a winner wrapping `undefined`. The supervisor's\n // contract is to refuse coercing a non-result into a best-effort Out (Foreman's 0/18 lesson).\n if (out !== undefined) {\n // The driver synthesized a winner. Content-address it for the replay `outRef`, put it\n // once, and sum the conserved spend off every journaled settlement. No re-ranking — the\n // driver already selected.\n const outRef = contentAddress(out)\n await opts.blobs.put(outRef, out)\n // ONE ledger: the journal. `settled` events carry spawned-child WORK; `metered` events carry\n // the drivers' OWN inference (the twin of `pool.observe`). `spentTotal` is their sum and the\n // breakdown keeps the two separable — the A++ view of where the tokens went. No pool bridge.\n const { childWork, driverInference } = await spentFromJournal(journal, opts.runId)\n return {\n kind: 'winner',\n out,\n outRef,\n tree,\n spentTotal: addSpend(childWork, driverInference),\n ...(isNonEmptySpend(driverInference)\n ? { spentBreakdown: { driverInference, childWork } }\n : {}),\n }\n }\n return noWinner()\n }\n\n // act() rejected. The reason is proven from lifecycle state, in precedence order:\n // a tripped breaker outranks any abort (it is the most specific cause) outranks\n // budget-exhaustion outranks the residual \"the tree produced nothing usable\" bucket.\n // A no-winner is TYPED — never a best-effort coercion of a partial child (M2).\n return noWinner()\n\n // A no-winner still incurred real conserved spend before failing, so it carries `spentTotal`\n // summed off the SAME journal the winner path reads — the caller always learns the cost.\n async function noWinner(): Promise<SupervisedResult<Out>> {\n const { childWork, driverInference } = await spentFromJournal(journal, opts.runId)\n return {\n kind: 'no-winner',\n reason: classifyNoWinner(controller, pool, opts, breaker),\n tree,\n downCount: breaker.downCount(),\n spentTotal: addSpend(childWork, driverInference),\n }\n }\n }\n\n function attach(h: RootHandle<Out>): void {\n const control = rootControls.get(h as RootHandle<unknown>)\n if (!control) {\n throw new RuntimeRunStateError(\n 'supervisor.attach: handle was not minted by createRootHandle (no control channel)',\n )\n }\n attached = control\n }\n\n return { run, attach }\n}\n\n// ── Root handle ───────────────────────────────────────────────────────────────\n\n/** The live binding the supervisor populates while a run is in flight. `view` reads the\n * live scope; `cascadeAbort`/`signal` reach the one cascade controller. */\ninterface RunBinding {\n readonly scope: Scope<unknown>\n readonly cascadeAbort: (reason?: string) => void\n readonly signal: (msg: RootSignal) => void\n}\n\n/** The supervisor-private control behind a `RootHandle`. `createRootHandle` mints it and\n * registers it in `rootControls`; `attach` looks it up and `bind`s it to the live run. */\ninterface RootControl {\n bind(binding: RunBinding): void\n unbind(): void\n}\n\n/** Module-private channel from a minted `RootHandle` to its `RootControl`, so `attach`\n * can prove a handle is ours and reach its binding without leaking the control onto the\n * frozen `RootHandle` shape. */\nconst rootControls = new WeakMap<RootHandle<unknown>, RootControl>()\n\n/**\n * Mint a `RootHandle` plus its supervisor-private control. The handle is the substrate a\n * chat/pi-viz client attaches to (Q2): `view()` reads the live tree, `signal()` delivers\n * an out-of-band message, `abort()` cascades. Before `run` binds it (and after `run`\n * unbinds it) the handle is fail-loud: a client that talks to a handle that is not\n * driving a live run gets a typed error, never a silent no-op.\n */\nexport function createRootHandle<Out>(): RootHandle<Out> {\n let binding: RunBinding | undefined\n const handle: RootHandle<Out> = {\n view(): TreeView {\n if (!binding) {\n throw new RuntimeRunStateError(\n 'RootHandle.view: handle is not bound to a live run (attach it before run, read after run starts)',\n )\n }\n return binding.scope.view\n },\n signal(msg: RootSignal): void {\n if (!binding) {\n throw new RuntimeRunStateError('RootHandle.signal: handle is not bound to a live run')\n }\n binding.signal(msg)\n },\n abort(reason?: string): void {\n if (!binding) {\n throw new RuntimeRunStateError('RootHandle.abort: handle is not bound to a live run')\n }\n binding.cascadeAbort(reason ?? 'root handle aborted')\n },\n }\n rootControls.set(handle as RootHandle<unknown>, {\n bind(b: RunBinding): void {\n binding = b\n },\n unbind(): void {\n binding = undefined\n },\n })\n return handle\n}\n\n/** A `RootSignal` sink: `cancel` cascades an abort; pause/resume/ask are observability\n * signals the substrate accepts but does not act on here (the chat/pi-viz client owns\n * pause semantics — building them now would be mechanism ahead of the gate). */\nfunction pushRootSignal(cascadeAbort: (reason?: string) => void): (msg: RootSignal) => void {\n return (msg: RootSignal): void => {\n if (msg.kind === 'cancel') cascadeAbort(msg.reason ?? 'root signal: cancel')\n }\n}\n\n// ── OTP intensity breaker ───────────────────────────────────────────────────────\n\n/**\n * Counts `down` settlements inside a sliding window. More than `maxRestarts` of them\n * within `withinMs` trips the supervisor (aborting the cascade) rather than letting a\n * driver re-spawn a doomed child forever. With either bound unset the breaker is inert\n * (it still counts `down`s for `downCount`). The breaker NEVER restarts a child — it is a\n * circuit breaker over the driver's own re-spawn decisions (m3).\n */\ninterface IntensityBreaker {\n recordDown(at: number): void\n tripped(): boolean\n downCount(): number\n}\n\nfunction createIntensityBreaker(opts: SupervisorOpts, trip: () => void): IntensityBreaker {\n const max = opts.maxRestarts\n const within = opts.withinMs\n const armed = max !== undefined && within !== undefined\n const recent: number[] = []\n let total = 0\n let isTripped = false\n return {\n recordDown(at: number): void {\n total += 1\n if (!armed || isTripped) return\n recent.push(at)\n const cutoff = at - within\n while (recent.length > 0 && recent[0]! < cutoff) recent.shift()\n if (recent.length > max) {\n isTripped = true\n trip()\n }\n },\n tripped(): boolean {\n return isTripped\n },\n downCount(): number {\n return total\n },\n }\n}\n\n/** Decorate the journal so the breaker observes every `settled`-`down` event the scope\n * appends, without the supervisor intercepting `scope.next()`. The decorator is\n * transparent — it forwards every method verbatim and only reads the down events. */\nfunction wrapJournalForBreaker(journal: SpawnJournal, breaker: IntensityBreaker): SpawnJournal {\n return {\n loadTree: (root) => journal.loadTree(root),\n beginTree: (root, at) => journal.beginTree(root, at),\n appendEvent: (root, ev: SpawnEvent) => {\n if (ev.kind === 'settled' && ev.status === 'down') breaker.recordDown(Date.parse(ev.at))\n return journal.appendEvent(root, ev)\n },\n }\n}\n\n// ── Join barrier + result classification ─────────────────────────────────────────\n\n/**\n * Drain the root scope's live set so every still-running/acquiring child is torn down\n * before `run` returns — the join barrier. Abort the cascade controller first (so each\n * child's executor stops cleanly), then pull `next()` to completion so every aborted\n * child's teardown + reconcile runs and its `settled` event is journaled by the scope.\n * A child's own teardown failure is already swallowed inside `runChild`, and the cursor\n * itself never rejects (a failing child is typed into a `down`), so the whole barrier is\n * `allSettled`'d — a stray throw here is NOT the primary error (firstError precedence).\n */\nasync function drainLiveChildren(\n scope: Scope<unknown>,\n controller: AbortController,\n): Promise<void> {\n const hasLive = scope.view.inFlight > 0\n if (!hasLive) return\n // Cascade the abort into every live child's executor before draining.\n if (!controller.signal.aborted) controller.abort()\n await Promise.allSettled([drainCursor(scope)])\n}\n\nasync function drainCursor(scope: Scope<unknown>): Promise<void> {\n for (;;) {\n const settled = await scope.next()\n if (settled === null) return\n }\n}\n\nfunction classifyNoWinner(\n controller: AbortController,\n pool: BudgetPool,\n opts: SupervisorOpts,\n breaker: IntensityBreaker,\n): NoWinnerReason {\n // A tripped breaker is the most specific cause (children kept dying), so it outranks\n // the generic abort it raised. Then a caller/handle abort. Then the pool. The residual\n // bucket is \"ran to completion under budget but produced nothing usable\".\n if (breaker.tripped()) return 'all-children-down'\n if (controller.signal.aborted) return 'aborted'\n if (poolExhausted(pool, opts)) return 'budget-exhausted'\n return 'all-children-down'\n}\n\nfunction poolExhausted(pool: BudgetPool, opts: SupervisorOpts): boolean {\n const r = pool.readout()\n if (r.tokensLeft <= 0) return true\n if (opts.budget.maxUsd !== undefined && r.usdLeft <= 0) return true\n if (\n opts.budget.deadlineMs !== undefined &&\n r.deadlineMs > 0 &&\n (opts.now ?? Date.now)() >= r.deadlineMs\n ) {\n return true\n }\n return false\n}\n\n/**\n * Sum the conserved spend over every journaled `settled` event — the honest per-channel\n * total (input/output/usd/iterations all preserved), read off the same evidence replay\n * reads. Computed AFTER the join barrier so every child's settlement is recorded. Fails\n * loud if the tree was never journaled (the supervisor always `beginTree`s, so a missing\n * tree is a corrupted journal, not a normal path).\n */\nasync function spentFromJournal(\n journal: SpawnJournal,\n root: string,\n): Promise<{ childWork: Spend; driverInference: Spend }> {\n const events = await journal.loadTree(root)\n if (events === undefined) {\n throw new RuntimeRunStateError(\n `supervisor: spawn tree '${root}' is missing from the journal after run (corrupted log)`,\n )\n }\n const childWork: Spend = { iterations: 0, tokens: { input: 0, output: 0 }, usd: 0, ms: 0 }\n const driverInference: Spend = { iterations: 0, tokens: { input: 0, output: 0 }, usd: 0, ms: 0 }\n for (const ev of events) {\n // `settled` = spawned-child work (reconciled); `metered` = driver inference (re-homed up the\n // tree, so this single root-tree pass already includes every nested driver's inference).\n if (ev.kind === 'settled') accumulate(childWork, ev.spent)\n else if (ev.kind === 'metered') accumulate(driverInference, ev.spend)\n }\n return { childWork, driverInference }\n}\n\n/** Add `b` into `a` in place, per channel. */\nfunction accumulate(a: Spend, b: Spend): void {\n a.iterations += b.iterations\n a.tokens.input += b.tokens.input\n a.tokens.output += b.tokens.output\n a.usd += b.usd\n a.ms += b.ms\n}\n\n/** Sum two conserved-spend tallies per channel — the child-work journal sum + the drivers' own\n * metered inference, so `spentTotal` is the true cost of the run. */\nfunction addSpend(a: Spend, b: Spend): Spend {\n return {\n iterations: a.iterations + b.iterations,\n tokens: { input: a.tokens.input + b.tokens.input, output: a.tokens.output + b.tokens.output },\n usd: a.usd + b.usd,\n ms: a.ms + b.ms,\n }\n}\n\n/** True when any driver metered inference this run (so the winner carries a `spentBreakdown`).\n * Checks every channel `addSpend` sums — including `ms` — so the gate stays consistent with the\n * total even though the coordination driver currently stamps `ms: 0`. */\nfunction isNonEmptySpend(s: Spend): boolean {\n return s.iterations > 0 || s.tokens.input > 0 || s.tokens.output > 0 || s.usd > 0 || s.ms > 0\n}\n","/**\n * @experimental\n *\n * The completion-oracle: **settled ⟺ DELIVERED.**\n *\n * Foreman's one hard lesson (0/18 self-improvement deliverables) — \"done\" must mean a check\n * PASSED, not the agent's say-so. `gateOnDeliverable` wraps an `Executor` so its settlement\n * is `valid` ONLY when the deliverable check passes. The child still RUNS and settles (its\n * spend is conserved into the pool either way), but a child that ran WITHOUT delivering\n * settles `valid:false` — so a keep-best driver never counts it as done, and a gate never\n * inflates with self-judged wins.\n *\n * Dual-purpose by construction:\n * - product: the agent fleet only advances on real, checked deliverables.\n * - proof: the gate's `valid` is the honest settle — equal-k comparisons can't be gamed by an\n * arm that \"ran\" without producing the artifact.\n *\n * The check is a DEPLOYABLE oracle — a test command, a state verifier, the commit0 judge —\n * read off the child's output, never the model judging itself. A throwing check is\n * fail-closed (not delivered), never a crash.\n */\n\nimport type { DefaultVerdict, Executor, ExecutorResult, UsageEvent } from './types'\n\n/**\n * The deployable completion oracle passed to {@link gateOnDeliverable}: a `check` that\n * decides DELIVERED (settles `valid` ⟺ it resolves true) plus an optional `describe` of\n * what the spawn was supposed to produce. The check reads the child's output — never the\n * model judging itself.\n */\nexport interface DeliverableSpec<Out = unknown> {\n /** The deployable check that decides DELIVERED. `settled.valid ⟺ this resolves true`. */\n check: (out: Out) => boolean | Promise<boolean>\n /** What the spawn was supposed to produce — surfaced in traces/reports. */\n describe?: string\n}\n\n/**\n * Wrap an `Executor` so its settlement `valid` reflects the deliverable check, not the\n * inner verdict. Handles both `execute` shapes (one-shot `Promise<ExecutorResult>` and\n * streaming `AsyncIterable<UsageEvent>` + `resultArtifact()`); the check runs once the inner\n * executor has produced its output. The inner `score` is preserved; only `valid` is gated.\n */\nexport function gateOnDeliverable<Out>(\n inner: Executor<Out>,\n deliverable: DeliverableSpec<Out>,\n): Executor<Out> {\n let gated: DefaultVerdict | undefined\n\n const check = async (out: Out, baseScore?: number): Promise<DefaultVerdict> => {\n let delivered: boolean\n try {\n delivered = (await deliverable.check(out)) === true\n } catch {\n delivered = false // fail-closed: a throwing check is NOT a delivery\n }\n return { valid: delivered, score: baseScore ?? (delivered ? 1 : 0) }\n }\n\n return {\n runtime: inner.runtime,\n ...(inner.budgetExempt !== undefined ? { budgetExempt: inner.budgetExempt } : {}),\n ...(inner.deliver ? { deliver: (m: unknown) => inner.deliver?.(m) } : {}),\n execute(task, signal) {\n const r = inner.execute(task, signal)\n if (isAsyncIterable(r)) {\n // Streaming: pass the usage events through (the conserved-pool fold consumes them),\n // then gate the verdict from the settled artifact.\n return (async function* () {\n for await (const ev of r) yield ev\n const art = inner.resultArtifact()\n gated = await check(art.out, art.verdict?.score)\n })()\n }\n // One-shot: gate the resolved result's verdict in place.\n return (async () => {\n const res = await r\n gated = await check(res.out, res.verdict?.score)\n return { ...res, verdict: gated } satisfies ExecutorResult<Out>\n })()\n },\n teardown: (grace) => inner.teardown(grace),\n resultArtifact() {\n const art = inner.resultArtifact()\n return { ...art, verdict: gated ?? art.verdict }\n },\n }\n}\n\nfunction isAsyncIterable(v: unknown): v is AsyncIterable<UsageEvent> {\n return (\n v != null &&\n typeof (v as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function'\n )\n}\n","/**\n * @experimental\n *\n * The supervisor's intelligence is AUTHORING the agents it spawns — not pressing buttons.\n *\n * Every agent here is three things: instructions (system prompt), tools, and a model — its\n * `AgentProfile`. The supervisor's job is to WRITE those profiles: read the task, decompose it,\n * and for each sub-task author a tailored worker recipe. `supervisorInstructions` is the how-to the\n * supervisor reads (its system prompt); `authoredWorker` builds a worker AGENT from a profile the\n * supervisor authored — the authored systemPrompt + model shape the worker's call.\n *\n * The skill is the single OPTIMIZABLE surface: edit it → the supervisor designs better agents.\n * That is the self-improvement lever (the prompt/skill lever), not the execution plumbing.\n */\n\nimport { type AnalystFinding, computeFindingId, makeFinding } from '@tangle-network/agent-eval'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { contentAddress } from '../../durable/spawn-journal'\nimport { type RouterConfig, routerChatWithUsage } from '../router-client'\nimport { type DeliverableSpec, gateOnDeliverable } from './completion-gate'\nimport type { Agent, AgentSpec, Executor, ExecutorResult } from './types'\n\n/** What the supervisor AUTHORS per sub-task — a worker recipe (a partial `AgentProfile`). */\nexport interface AuthoredProfile {\n name: string\n /** The rich, task-specific instructions the supervisor wrote for THIS worker. */\n systemPrompt: string\n /** The model the supervisor chose for this sub-task (falls back to the run default). */\n model?: string\n}\n\n/** Narrow an untyped `spawn_agent` profile argument to an `AuthoredProfile`, or null if the\n * supervisor failed to author one (empty/placeholder profile — a skill violation worth catching). */\nexport function asAuthoredProfile(raw: unknown): AuthoredProfile | null {\n const p = raw as Partial<AuthoredProfile> | undefined\n if (!p || typeof p.systemPrompt !== 'string' || p.systemPrompt.trim().length === 0) return null\n return {\n name: typeof p.name === 'string' && p.name.length > 0 ? p.name : 'worker',\n systemPrompt: p.systemPrompt,\n ...(typeof p.model === 'string' ? { model: p.model } : {}),\n }\n}\n\n/** The supervisor SKILL — the how-to the supervisor reads (its system prompt). THE optimizable\n * surface: editing this changes how the supervisor designs every agent it spawns. */\nexport function supervisorInstructions(opts?: { goal?: string }): string {\n return [\n 'You are a SUPERVISOR. You do NOT do the work yourself — your job is to DESIGN and DRIVE specialist worker agents.',\n '',\n 'For the task you are given:',\n '1. DECOMPOSE it into the smallest set of sub-tasks a single focused worker can each deliver.',\n '2. For EACH sub-task, AUTHOR a worker by calling spawn_agent with a COMPLETE `profile`:',\n ' • name: a short id for the worker.',\n ' • systemPrompt: rich, specific instructions for THIS sub-task — tell the worker exactly what to produce, how to use its tools fully, and what \"done\" means. Never a one-liner; write the prompt a power-user would write.',\n ' • model: the model best suited to this sub-task (omit to use the default).',\n ' NEVER spawn a worker with an empty profile. The quality of the worker IS the quality of the profile you write.',\n \"3. await_event (kinds:['settled']) to collect each worker. Its result says valid:true only if the deployable check passed.\",\n '4. If a worker did NOT deliver, AUTHOR A NEW worker whose systemPrompt names the SPECIFIC failure and how to fix it — never just retry the same prompt.',\n '5. Stop (reply with no tool call) once the work is delivered. You cannot declare done yourself — only a delivered (valid:true) worker counts.',\n ...(opts?.goal ? ['', `The goal: ${opts.goal}`] : []),\n ].join('\\n')\n}\n\n/** Build a worker AGENT from a profile the supervisor authored: the authored `systemPrompt` +\n * `model` shape the worker's one model call; the deliverable gates settlement (valid ⟺ delivered). */\nexport function authoredWorker(\n profile: AuthoredProfile,\n opts: {\n cfg: RouterConfig\n taskPrompt: string\n deliverable: DeliverableSpec\n temperature?: number\n },\n): Agent<unknown, unknown> {\n let artifact: ExecutorResult<unknown> | undefined\n const model = profile.model ?? opts.cfg.model\n const inner: Executor<unknown> = {\n runtime: 'router',\n async execute(_t, signal) {\n const res = await routerChatWithUsage(\n { ...opts.cfg, model },\n [\n { role: 'system', content: profile.systemPrompt },\n { role: 'user', content: opts.taskPrompt },\n ],\n { temperature: opts.temperature ?? 0.4, ...(signal ? { signal } : {}) },\n )\n artifact = {\n outRef: contentAddress(res.content),\n out: res.content,\n spent: {\n iterations: 1,\n tokens: res.usage ?? { input: 0, output: 0 },\n usd: res.costUsd ?? 0,\n ms: 0,\n },\n }\n return artifact\n },\n teardown: () => Promise.resolve({ destroyed: true }),\n resultArtifact: () => {\n if (!artifact) throw new Error('authoredWorker: resultArtifact read before execute')\n return artifact\n },\n }\n const gated = gateOnDeliverable(inner, opts.deliverable)\n const spec: AgentSpec = {\n profile: { name: profile.name } as AgentProfile,\n harness: null,\n executor: gated,\n }\n return { name: profile.name, act: async () => '', executorSpec: spec } as Agent<\n unknown,\n unknown\n > & {\n executorSpec: AgentSpec\n }\n}\n\n// ── Profile-richness gate ────────────────────────────────────────────────────\n//\n// The supervisor's product is the worker PROFILE it authors. The failure mode the existing\n// gates miss: `asAuthoredProfile` / `local-harness` only reject a FULLY EMPTY system prompt —\n// a two-sentence stub passes. `assessAuthoredProfile` OBSERVES the authored artifact (it reads\n// no judge verdict, so it steers cleanly past `assertTraceDerivedFindings`) and flags THIN:\n// a short/few-line system prompt, OR no tools, OR no skills, OR no MCP when the task needs one.\n// It emits a real `AnalystFinding` so it rides the SAME coordination bus the driver pulls via\n// `await_event({kinds:['finding']})` — the supervisor can self-correct and re-author richer.\n\n/** Thresholds below which a system prompt is treated as a thin stub. Tunable per call. */\nexport interface ProfileRichnessThresholds {\n /** A prompt shorter than this many characters is thin (default 600). */\n readonly minSystemPromptChars: number\n /** A prompt with fewer than this many non-blank lines is thin (default 6). */\n readonly minSystemPromptLines: number\n}\n\nexport const defaultProfileRichnessThresholds: ProfileRichnessThresholds = {\n minSystemPromptChars: 600,\n minSystemPromptLines: 6,\n}\n\n/** Per-field verdict on one authored profile — the raw material the bench renders + scores. */\nexport interface ProfileRichness {\n readonly name: string\n /** The resolved system prompt (canonical `prompt.systemPrompt`, the sandbox `prompt.system`\n * convention, or a bare-string prompt — whichever the author used). */\n readonly systemPrompt: string\n readonly systemPromptChars: number\n readonly systemPromptLines: number\n readonly sentenceCount: number\n readonly hasDescription: boolean\n readonly hasTools: boolean\n readonly hasSkills: boolean\n readonly hasMcp: boolean\n readonly hasSubagents: boolean\n /** 0..1 — fraction of richness signals present (prompt-depth + the four levers). */\n readonly richness: number\n /** True when the supervisor authored a stub instead of a real profile. */\n readonly thin: boolean\n /** The specific reasons it is thin (empty when rich) — used in the finding's action. */\n readonly reasons: string[]\n}\n\n/** Read the system prompt from any authored shape: canonical `prompt.systemPrompt`, the sandbox\n * `prompt.system` convention, or a bare-string `prompt`. */\nfunction resolveSystemPrompt(profile: AgentProfile): string {\n const pr = (profile as { prompt?: unknown }).prompt\n if (typeof pr === 'string') return pr\n if (pr && typeof pr === 'object') {\n const o = pr as { systemPrompt?: unknown; system?: unknown }\n if (typeof o.systemPrompt === 'string') return o.systemPrompt\n if (typeof o.system === 'string') return o.system\n }\n return ''\n}\n\n/** OBSERVE one authored `AgentProfile` and score its richness (no judge verdict is read). The task\n * context (`needsMcp`) lets a domain say \"this work needs a data/tool MCP\" so a missing MCP counts. */\nexport function assessAuthoredProfile(\n profile: AgentProfile,\n opts?: { needsMcp?: boolean; thresholds?: Partial<ProfileRichnessThresholds> },\n): ProfileRichness {\n const th = { ...defaultProfileRichnessThresholds, ...(opts?.thresholds ?? {}) }\n const systemPrompt = resolveSystemPrompt(profile)\n const trimmed = systemPrompt.trim()\n const systemPromptChars = trimmed.length\n const systemPromptLines = trimmed\n ? trimmed.split('\\n').filter((l) => l.trim().length > 0).length\n : 0\n const sentenceCount = trimmed\n ? (trimmed.match(/[.!?](\\s|$)/g) ?? []).length || (trimmed ? 1 : 0)\n : 0\n const hasDescription =\n typeof profile.description === 'string' && profile.description.trim().length > 0\n const tools = (profile as { tools?: Record<string, unknown> }).tools\n const hasTools = !!tools && Object.keys(tools).length > 0\n const skills = (profile.resources as { skills?: unknown[] } | undefined)?.skills\n const hasSkills = Array.isArray(skills) && skills.length > 0\n const mcp = (profile as { mcp?: Record<string, unknown> }).mcp\n const hasMcp = !!mcp && Object.keys(mcp).length > 0\n const subagents = (profile as { subagents?: Record<string, unknown> }).subagents\n const hasSubagents = !!subagents && Object.keys(subagents).length > 0\n\n const reasons: string[] = []\n const promptThin =\n systemPromptChars < th.minSystemPromptChars || systemPromptLines < th.minSystemPromptLines\n if (promptThin)\n reasons.push(\n `system prompt is thin (${systemPromptChars} chars, ${systemPromptLines} lines; need ≥${th.minSystemPromptChars} chars and ≥${th.minSystemPromptLines} lines)`,\n )\n if (!hasTools)\n reasons.push('no tools granted (a worker can only act through the tools you grant it)')\n if (!hasSkills) reasons.push('no skills attached (no reusable how-to notes injected)')\n if (opts?.needsMcp && !hasMcp) reasons.push('no MCP server, but the task needs data/tool access')\n\n // Richness = fraction of signals present. Prompt-depth is one signal; the four levers are the rest.\n const signals = [!promptThin, hasTools, hasSkills, hasDescription, opts?.needsMcp ? hasMcp : true]\n const richness = signals.filter(Boolean).length / signals.length\n // THIN ⟺ the prompt is a stub OR the worker has no levers at all (no tools AND no skills AND no mcp).\n const thin = promptThin || (!hasTools && !hasSkills && !hasMcp)\n\n return {\n name: profile.name ?? 'worker',\n systemPrompt,\n systemPromptChars,\n systemPromptLines,\n sentenceCount,\n hasDescription,\n hasTools,\n hasSkills,\n hasMcp,\n hasSubagents,\n richness,\n thin,\n reasons,\n }\n}\n\n/** Turn a {@link ProfileRichness} verdict into a bus-routable `AnalystFinding` (area `profile-quality`).\n * Severity scales with thinness; the recommended action names the MISSING lever so the supervisor can\n * re-author. `subject` = the worker name so per-worker findings diff cleanly across re-authors. */\nexport function profileRichnessFinding(\n richness: ProfileRichness,\n opts?: { analystId?: string; runId?: string },\n): AnalystFinding {\n const analyst_id = opts?.analystId ?? 'profile-richness'\n const subject = richness.name\n const claim = richness.thin\n ? `Worker \"${richness.name}\" was authored as a THIN profile: ${richness.reasons.join('; ')}.`\n : `Worker \"${richness.name}\" was authored as a rich profile (richness ${(richness.richness * 100).toFixed(0)}%).`\n const severity: AnalystFinding['severity'] = richness.thin\n ? richness.richness < 0.25\n ? 'high'\n : 'medium'\n : 'info'\n return makeFinding({\n analyst_id,\n severity,\n area: 'profile-quality',\n claim,\n subject,\n confidence: 0.9,\n evidence_refs: [\n {\n kind: 'metric',\n uri: `profile:${subject}`,\n excerpt: `chars=${richness.systemPromptChars} lines=${richness.systemPromptLines} tools=${richness.hasTools} skills=${richness.hasSkills} mcp=${richness.hasMcp} richness=${richness.richness.toFixed(2)}`,\n },\n ],\n ...(richness.thin\n ? { recommended_action: `Re-author \"${richness.name}\" with: ${richness.reasons.join('; ')}.` }\n : {}),\n id_basis: computeFindingId({\n analyst_id,\n area: 'profile-quality',\n subject,\n claim: `richness:${richness.thin ? 'thin' : 'rich'}`,\n }),\n })\n}\n","/**\n * @experimental\n *\n * The child→parent message bus: the ONE pipe carrying every message a worker, sub-driver, or\n * analyst sends up to the driver — settled outputs, questions, and trace-analyst findings. It\n * unifies channels that were ad-hoc before (the settled-worker cursor, the ask-parent question\n * channel, and analyst results) into a single typed primitive with two lanes:\n *\n * - PASS-THROUGH (`subscribe`): every published event reaches subscribers immediately — the\n * express lane for online steering and live observation (a UI, a hook, the parent's box).\n * - STANDBY (`pull`): events also queue so the driver consumes them on its own cadence. The queue\n * is PRIORITY-ordered: a higher-`priority` event (a blocking question) is bumped ahead of\n * queued settles/findings so the driver sees it first; ties resolve FIFO by publish order.\n *\n * Observability is first-class (A++): every event is stamped with a monotonic `seq` and wall-clock\n * `at`, the full ordered `history()` is retained as an audit/replay trail, and `stats()` exposes\n * published/pulled counts by kind. Subscribers receive the stamped record, not a bare event.\n *\n * The interface is transport-agnostic on purpose. Same box → this in-process queue. Cross box →\n * the SAME publish/pull/subscribe surface backed by a durable mailbox on the parent's box (children\n * POST events with at-least-once retry; payloads are blob refs so the event stays small). Consumers\n * depend only on this interface, so distribution is a transport swap, never an architecture change.\n */\n\n/** Every bus event is a discriminated union member keyed by `type`. */\nexport interface BusEvent {\n readonly type: string\n}\n\n/** A published event stamped for ordering and observability. `seq` is the monotonic publish index;\n * `priority` drives pull order (higher = bumped ahead); `at` is the wall-clock publish time (ms). */\nexport interface BusRecord<E extends BusEvent> {\n readonly seq: number\n readonly at: number\n readonly priority: number\n readonly event: E\n}\n\nexport interface PublishOptions {\n /** Higher = pulled ahead of lower-priority queued events (default 0). A blocking question sets\n * this so it bumps to the front of the driver's inbox. */\n readonly priority?: number\n /** Whether the event enters the pull queue (default true). Set `false` for record-only events —\n * the parent→child down-leg (steer / answer / resume): they belong in `history()` and reach\n * `subscribe` observers, but the parent must never `pull` its own outbound message back. */\n readonly queue?: boolean\n}\n\nexport interface BusStats {\n readonly published: number\n readonly pulled: number\n /** Count published per event `type`. */\n readonly byKind: Readonly<Record<string, number>>\n}\n\nexport interface EventBus<E extends BusEvent> {\n /** Stamp + queue the event, then deliver the stamped record to every subscriber in order.\n * Returns the stamped record. */\n publish(event: E, opts?: PublishOptions): Promise<BusRecord<E>>\n /** Remove and return the highest-priority QUEUED event whose type is in `kinds` (any if omitted),\n * ties broken FIFO by `seq`; `undefined` when nothing matches. */\n pull(kinds?: ReadonlyArray<E['type']>): E | undefined\n /** Register a pass-through handler; it receives the stamped record of every event published after\n * registration. Returns an unsubscribe fn. */\n subscribe(handler: (record: BusRecord<E>) => void | Promise<void>): () => void\n /** Count of queued, not-yet-pulled events (filtered by `kinds` when given). */\n pending(kinds?: ReadonlyArray<E['type']>): number\n /** The full ordered log of every event ever published (the audit/replay trail). */\n history(): ReadonlyArray<BusRecord<E>>\n /** Throughput counters for observability dashboards. */\n stats(): BusStats\n}\n\nexport function createEventBus<E extends BusEvent>(now: () => number = Date.now): EventBus<E> {\n const queue: BusRecord<E>[] = []\n const log: BusRecord<E>[] = []\n const subscribers: Array<(record: BusRecord<E>) => void | Promise<void>> = []\n const byKind: Record<string, number> = {}\n let seq = 0\n let pulled = 0\n\n const matches = (r: BusRecord<E>, kinds?: ReadonlyArray<E['type']>) =>\n !kinds || kinds.includes(r.event.type)\n\n // Index of the highest-priority matching record; ties resolve to the earliest `seq` (the queue is\n // maintained in publish order, so the first scan hit at the max priority is the oldest).\n const bestIndex = (kinds?: ReadonlyArray<E['type']>): number => {\n let best = -1\n let bestPriority = Number.NEGATIVE_INFINITY\n for (let i = 0; i < queue.length; i++) {\n const r = queue[i]\n if (!r || !matches(r, kinds)) continue\n if (r.priority > bestPriority) {\n best = i\n bestPriority = r.priority\n }\n }\n return best\n }\n\n return {\n async publish(event, opts) {\n const record: BusRecord<E> = { seq: seq++, at: now(), priority: opts?.priority ?? 0, event }\n // Record-only events (the down-leg) skip the pull queue but still hit the log + subscribers.\n if (opts?.queue !== false) queue.push(record)\n log.push(record)\n byKind[event.type] = (byKind[event.type] ?? 0) + 1\n // Sequential, not Promise.all: a subscriber that steers off this event must observe a\n // consistent order, and a throwing subscriber must not silently drop siblings' delivery.\n for (const handler of subscribers) await handler(record)\n return record\n },\n pull(kinds) {\n const i = bestIndex(kinds)\n if (i < 0) return undefined\n pulled++\n return queue.splice(i, 1)[0]?.event\n },\n subscribe(handler) {\n subscribers.push(handler)\n return () => {\n const i = subscribers.indexOf(handler)\n if (i >= 0) subscribers.splice(i, 1)\n }\n },\n pending(kinds) {\n return kinds ? queue.filter((r) => matches(r, kinds)).length : queue.length\n },\n history() {\n return log\n },\n stats() {\n return { published: seq, pulled, byKind: { ...byKind } }\n },\n }\n}\n","/**\n * @experimental\n *\n * MCP binding for a live `Scope`. A sandbox driver gets the same small verbs\n * the in-process driver has: spawn, observe, await, steer, ask/answer, analyze,\n * and stop. Settled outputs remain Scope artifacts; product code can project\n * them into any UI/report envelope it needs.\n */\n\nimport type {\n Budget,\n ResultBlobStore,\n Scope,\n Settled,\n Agent as SuperviseAgent,\n} from '../../runtime'\nimport { type BusRecord, type BusStats, createEventBus } from '../../runtime/supervise/event-bus'\nimport type { McpToolDescriptor } from '../server'\n\n/** A worker the driver has drained via `await_event`. */\nexport interface SettledWorker {\n readonly id: string\n readonly status: 'done' | 'down'\n readonly score?: number\n readonly valid?: boolean\n readonly outRef?: string\n readonly reason?: string\n}\n\nexport type QuestionLevel = 'worker' | 'driver' | 'loop'\nexport type QuestionUrgency = 'continue-without' | 'blocks-step' | 'blocks-run'\n\nexport interface QuestionOption {\n readonly label: string\n readonly tradeoff: string\n}\n\nexport interface Question {\n readonly id: string\n readonly from: string\n readonly level: QuestionLevel\n readonly question: string\n readonly reason: string\n readonly urgency: QuestionUrgency\n readonly options?: ReadonlyArray<QuestionOption>\n}\n\nexport type QuestionDecision =\n | { readonly kind: 'answer'; readonly answer: string; readonly by: string }\n | { readonly kind: 'defer'; readonly reason: string }\n | { readonly kind: 'escalate'; readonly to: 'parent' | 'user' | string; readonly reason: string }\n\nexport interface QuestionRecord extends Question {\n readonly status: 'open' | 'answered' | 'deferred' | 'escalated'\n readonly decision?: QuestionDecision\n readonly openedAt: number\n}\n\ntype QuestionInput = Omit<Question, 'id'> & { readonly id?: string }\nexport type QuestionPolicy = 'auto' | 'mustDecide' | 'bubble' | 'failClosed'\n\nexport interface AnalystRegistry {\n readonly kinds: ReadonlyArray<{ id: string; description: string; area: string }>\n readonly run: (kindId: string, trace: unknown) => Promise<unknown>\n}\n\n/** A trace-analyst result re-entered as a message on the bus (the `finding` event kind). */\nexport interface AnalystFindingEvent {\n readonly fromWorker: string\n readonly analyst: string\n readonly findings: unknown\n}\n\n/** A parent→child message (the down-leg): recorded for observability, delivered via the child inbox,\n * never pulled back by the parent. `delivered` mirrors whether the live child accepted it. */\nexport interface DownMessageEvent {\n readonly toWorker: string\n readonly instruction: string\n readonly delivered: boolean\n}\n\n/** Every message on the one typed pipe. UP (child→parent): question / settled / finding — queued for\n * the driver to `pull`. DOWN (parent→child): steer / answer — record-only (history + subscribers),\n * routed to the child inbox. New kinds are additive. */\nexport type CoordinationEvent =\n | { readonly type: 'question'; readonly question: QuestionRecord }\n | { readonly type: 'settled'; readonly worker: SettledWorker }\n | { readonly type: 'finding'; readonly finding: AnalystFindingEvent }\n | { readonly type: 'steer'; readonly down: DownMessageEvent }\n | { readonly type: 'answer'; readonly down: DownMessageEvent; readonly questionId: string }\n\nexport type MakeWorkerAgent = (profile: unknown) => SuperviseAgent<unknown, unknown>\n\nexport interface CoordinationToolsOptions {\n readonly scope: Scope<unknown>\n readonly blobs: ResultBlobStore\n readonly makeWorkerAgent: MakeWorkerAgent\n readonly perWorker: Budget\n readonly analysts?: AnalystRegistry\n readonly onEvent?: (event: CoordinationEvent) => void | Promise<void>\n readonly questionPolicy?: QuestionPolicy\n /** Analyst kind ids to run AUTOMATICALLY when a worker settles `done` (the analyst-on-settle\n * hook). Each result is published as a `finding` event on the bus — pass-through to subscribers\n * and queued for the driver to pull via `await_event`. Omit/empty = no auto-analysis (default;\n * the driver can still run lenses on demand via `run_analyst`). Requires `analysts`. */\n readonly analyzeOnSettle?: ReadonlyArray<string>\n /** Hard cap on how many workers may be LIVE (spawned but not yet settled) at once. `spawn_agent`\n * counts the scope's non-terminal nodes and fails closed (`error: 'max-live-workers'`) BEFORE\n * reserving from the pool when the cap is already met — a concurrency fence on top of the\n * conserved-budget fence (the pool bounds total work; this bounds simultaneous work, e.g. live\n * sandboxes/boxes). Omit or `<= 0` = no cap (the prior behavior; the pool stays the only fence). */\n readonly maxLiveWorkers?: number\n}\n\n/**\n * The supervisor-side toolbox returned by {@link createCoordinationTools}: the MCP tool\n * descriptors a driver `AgentProfile` calls to spawn, steer, observe, and settle workers\n * over a live `Scope`, plus the typed accessors (`settled`/`questions`/`history`/`stats`/\n * `raiseFinding`) for the bidirectional coordination bus. This is the live, backend-of-your-\n * choice, steerable counterpart to the one-shot own-sandbox delegation MCP.\n */\nexport interface CoordinationTools {\n readonly tools: McpToolDescriptor[]\n isStopped(): boolean\n stopReason(): string | undefined\n settled(): ReadonlyArray<SettledWorker>\n questions(): ReadonlyArray<QuestionRecord>\n /** The full ordered log of every bus event — UP (settled / question / finding) and DOWN\n * (steer / answer) — the observability audit + replay trail. Each record carries seq,\n * timestamp, and priority. */\n history(): ReadonlyArray<BusRecord<CoordinationEvent>>\n /** Bus throughput counters (published / pulled / by-kind) for live dashboards. */\n stats(): BusStats\n /** Raise a `finding` on the bus from outside the settle hook — the seam an ONLINE detector\n * (mid-run, on the worker pipe) uses to tell the driver \"this worker is looping/erroring\" the\n * moment it happens, instead of only at settle. Queued for `await_event` + pass-through. */\n raiseFinding(finding: AnalystFindingEvent): Promise<void>\n}\n\n/** The reserved coordination verb names — the complete set `createCoordinationTools` can emit\n * (the analyst pair is conditional but still reserved). A driver's extra WORK tools must not\n * collide with any of these, or it could no longer coordinate; callers validate eagerly against\n * this set so the conflict fails loud at construction, not buried in a swallowed `act()` throw. */\nexport const coordinationVerbNames = [\n 'spawn_agent',\n 'observe_agent',\n 'steer_agent',\n 'await_event',\n 'list_questions',\n 'answer_question',\n 'ask_parent',\n 'stop',\n 'list_analysts',\n 'run_analyst',\n] as const\n\nconst idArg = { type: 'string', description: 'The workerId returned by spawn_agent.' } as const\n\n/** Build the driver's MCP tools over a live scope. */\nexport function createCoordinationTools(opts: CoordinationToolsOptions): CoordinationTools {\n let stopped = false\n let reason: string | undefined\n let questionSeq = 0\n const ledger: SettledWorker[] = []\n const questions: QuestionRecord[] = []\n const questionPolicy = opts.questionPolicy ?? 'auto'\n\n // The one child→parent pipe. `onEvent` (back-compat) becomes a pass-through subscriber receiving\n // the bare event, so every kind — question, settled, finding — reaches it immediately, and the\n // driver pulls queued findings / questions via `await_event`.\n const bus = createEventBus<CoordinationEvent>()\n if (opts.onEvent) {\n const cb = opts.onEvent\n bus.subscribe((rec) => cb(rec.event))\n }\n\n // Urgency → bus priority: a blocking question is bumped ahead of queued settles/findings so the\n // driver sees it FIRST when it drains the inbox (and pass-through already delivered it the instant\n // it was raised). Non-blocking messages share priority 0 and resolve FIFO.\n const urgencyPriority = (u: QuestionUrgency): number =>\n u === 'blocks-run' ? 20 : u === 'blocks-step' ? 10 : 0\n\n const str = (v: unknown, field: string): string => {\n if (typeof v !== 'string' || v.length === 0)\n throw new Error(`coordination tools: \"${field}\" must be a non-empty string`)\n return v\n }\n const obj = (raw: unknown): Record<string, unknown> => {\n if (!raw || typeof raw !== 'object')\n throw new Error('coordination tools: arguments must be an object')\n return raw as Record<string, unknown>\n }\n // Parse a per-spawn `budget` override and merge it over the per-worker default (per field).\n // Fails loud on a non-object or a non-finite numeric field — a malformed budget must never\n // silently fall back to the default and run a sub-task on a ceiling nobody chose.\n const mergeBudget = (base: Budget, raw: unknown): Budget => {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw))\n throw new Error('coordination tools: \"budget\" must be an object')\n const o = raw as Record<string, unknown>\n const field = (name: keyof Budget): number | undefined => {\n const v = o[name]\n if (v === undefined) return undefined\n if (typeof v !== 'number' || !Number.isFinite(v))\n throw new Error(`coordination tools: \"budget.${name}\" must be a finite number`)\n return v\n }\n const maxIterations = field('maxIterations')\n const maxTokens = field('maxTokens')\n const maxUsd = field('maxUsd')\n const deadlineMs = field('deadlineMs')\n return {\n maxIterations: maxIterations ?? base.maxIterations,\n maxTokens: maxTokens ?? base.maxTokens,\n ...((maxUsd ?? base.maxUsd) === undefined ? {} : { maxUsd: maxUsd ?? base.maxUsd }),\n ...((deadlineMs ?? base.deadlineMs) === undefined\n ? {}\n : { deadlineMs: deadlineMs ?? base.deadlineMs }),\n }\n }\n const level = (v: unknown): Question['level'] => {\n if (v === 'worker' || v === 'driver' || v === 'loop') return v\n throw new Error('coordination tools: \"level\" must be worker, driver, or loop')\n }\n const urgency = (v: unknown): Question['urgency'] => {\n if (v === 'continue-without' || v === 'blocks-step' || v === 'blocks-run') return v\n throw new Error(\n 'coordination tools: \"urgency\" must be continue-without, blocks-step, or blocks-run',\n )\n }\n\n const recordSettled = (s: Settled<unknown>): SettledWorker => {\n const w: SettledWorker =\n s.kind === 'done'\n ? {\n id: s.handle.id,\n status: 'done',\n score: s.verdict?.score ?? 0,\n valid: s.verdict?.valid ?? false,\n outRef: s.outRef,\n }\n : { id: s.handle.id, status: 'down', reason: s.reason }\n ledger.push(w)\n return w\n }\n\n // Producer: drain exactly one settlement from the scope cursor onto the bus (a `settled` event),\n // then fire the analyst-on-settle hook — auto-run each configured lens over the worker's trace and\n // publish its result as a `finding`. Returns false when the cursor is idle (no live workers). The\n // cursor is a once-per-child source, so a settlement is produced at most once.\n const drainSettlement = async (): Promise<boolean> => {\n const s = await opts.scope.next()\n if (!s) return false\n const w = recordSettled(s)\n await bus.publish({ type: 'settled', worker: w })\n if (w.status === 'done' && w.outRef && opts.analysts && opts.analyzeOnSettle?.length) {\n const trace = await opts.blobs.get(w.outRef)\n for (const analyst of opts.analyzeOnSettle) {\n const findings = await opts.analysts.run(analyst, trace)\n await bus.publish({ type: 'finding', finding: { fromWorker: w.id, analyst, findings } })\n }\n }\n return true\n }\n\n // The down-leg: record a parent→child message on the bus for the audit trail (history +\n // subscribers) WITHOUT enqueuing it — the parent must never pull its own outbound message back.\n // Overloaded so the `answer` kind REQUIRES a questionId (no silent `?? ''` fallback to mask a bug).\n function sendDown(type: 'steer', down: DownMessageEvent): Promise<void>\n function sendDown(type: 'answer', down: DownMessageEvent, questionId: string): Promise<void>\n async function sendDown(\n type: 'steer' | 'answer',\n down: DownMessageEvent,\n questionId?: string,\n ): Promise<void> {\n await bus.publish(\n type === 'answer'\n ? { type, down, questionId: str(questionId, 'questionId') }\n : { type, down },\n { queue: false },\n )\n }\n\n // Consumer projection: the wire shape the driver sees for a pulled bus event.\n const projectEvent = (ev: CoordinationEvent): Record<string, unknown> => {\n if (ev.type === 'settled') {\n const w = ev.worker\n return w.status === 'done'\n ? {\n type: 'settled',\n settled: w.id,\n status: 'done',\n score: w.score,\n valid: w.valid,\n outRef: w.outRef,\n }\n : { type: 'settled', settled: w.id, status: 'down', reason: w.reason }\n }\n if (ev.type === 'question') return { type: 'question', question: ev.question }\n if (ev.type === 'finding') return { type: 'finding', ...ev.finding }\n if (ev.type === 'answer') return { type: 'answer', ...ev.down, questionId: ev.questionId }\n // Down-leg `steer` is record-only (never queued), so the driver never pulls it; project\n // defensively for completeness.\n return { type: ev.type, ...ev.down }\n }\n\n const nextQuestionId = (from: string): string => `${from}:q${questionSeq++}`\n const normalizeQuestion = (q: QuestionInput, fallbackFrom: string): Question => {\n const from = str(q.from ?? fallbackFrom, 'from')\n return {\n id: typeof q.id === 'string' && q.id.length > 0 ? q.id : nextQuestionId(from),\n from,\n level: level(q.level),\n question: str(q.question, 'question'),\n reason: str(q.reason, 'reason'),\n ...(q.options ? { options: q.options } : {}),\n urgency: urgency(q.urgency),\n }\n }\n const addQuestion = (\n raw: QuestionInput,\n fallbackFrom: string,\n decision?: QuestionDecision,\n ): { question: QuestionRecord; added: boolean } => {\n const q = normalizeQuestion(raw, fallbackFrom)\n const existing = questions.find((x) => x.id === q.id)\n if (existing) return { question: existing, added: false }\n const effectiveDecision =\n decision ??\n (questionPolicy === 'bubble'\n ? ({\n kind: 'escalate',\n to: 'parent',\n reason: 'question policy bubbled to parent',\n } as const)\n : undefined)\n const status: QuestionRecord['status'] =\n effectiveDecision?.kind === 'answer'\n ? 'answered'\n : effectiveDecision?.kind === 'defer'\n ? 'deferred'\n : effectiveDecision?.kind === 'escalate'\n ? 'escalated'\n : 'open'\n const record: QuestionRecord = {\n ...q,\n status,\n openedAt: Date.now(),\n ...(effectiveDecision ? { decision: effectiveDecision } : {}),\n }\n questions.push(record)\n return { question: record, added: true }\n }\n const emitNewQuestion = async (record: {\n question: QuestionRecord\n added: boolean\n }): Promise<QuestionRecord> => {\n if (record.added)\n await bus.publish(\n { type: 'question', question: record.question },\n { priority: urgencyPriority(record.question.urgency) },\n )\n return record.question\n }\n const decideQuestion = (questionId: string, decision: QuestionDecision): QuestionRecord => {\n const idx = questions.findIndex((q) => q.id === questionId)\n if (idx < 0) throw new Error(`unknown questionId ${JSON.stringify(questionId)}`)\n const prior = questions[idx] as QuestionRecord\n const status: QuestionRecord['status'] =\n decision.kind === 'answer' ? 'answered' : decision.kind === 'defer' ? 'deferred' : 'escalated'\n const next: QuestionRecord = { ...prior, status, decision }\n questions[idx] = next\n return next\n }\n const blockingQuestionsForStop = (): QuestionRecord[] => {\n if (questionPolicy === 'auto' || questionPolicy === 'bubble') return []\n return questions.filter((q) => {\n const blocking = q.urgency === 'blocks-step' || q.urgency === 'blocks-run'\n if (!blocking) return false\n if (questionPolicy === 'mustDecide') return q.status === 'open'\n return q.status !== 'answered' && q.status !== 'deferred'\n })\n }\n\n // Count workers that are LIVE — spawned but not yet settled — off the scope's in-memory live set\n // (O(live), synchronous). The terminal statuses are done/failed/cancelled; everything else\n // (pending/acquiring/running) is still in flight. This is the concurrency fence's input.\n const maxLiveWorkers = opts.maxLiveWorkers\n const liveWorkerCount = (): number =>\n opts.scope.view.nodes.filter(\n (n) => n.status !== 'done' && n.status !== 'failed' && n.status !== 'cancelled',\n ).length\n\n const tools: McpToolDescriptor[] = [\n {\n name: 'spawn_agent',\n description:\n 'Start a worker the driver will drive. `profile` is the worker or another driver; ' +\n '`task` is what it should do. Reserves budget from the conserved pool and fails closed. ' +\n 'Pass an optional `budget` (per-field) to give a hard sub-task more than the default — it ' +\n 'merges over the per-worker default; the conserved pool is still the hard fence. When a ' +\n 'max-live-workers cap is set it also fails closed (`error: \"max-live-workers\"`) while that ' +\n 'many workers are still in flight — settle or steer one before spawning another.',\n inputSchema: {\n type: 'object',\n properties: {\n profile: { description: 'The worker/driver profile to run.' },\n task: { description: 'The task the worker should perform.' },\n label: { type: 'string', description: 'Optional trace label.' },\n budget: {\n type: 'object',\n description:\n 'Optional per-spawn budget that merges over the per-worker default (per field). ' +\n 'Only set the ceilings this sub-task needs raised; the conserved pool still fences.',\n properties: {\n maxIterations: { type: 'number' },\n maxTokens: { type: 'number' },\n maxUsd: { type: 'number' },\n deadlineMs: { type: 'number' },\n },\n },\n },\n required: ['profile', 'task'],\n },\n handler: (raw) => {\n const a = obj(raw)\n // Concurrency fence FIRST — fail closed before reserving budget, so a rejected spawn never\n // touches the pool. The conserved pool bounds TOTAL work; this bounds SIMULTANEOUS work.\n if (\n maxLiveWorkers !== undefined &&\n maxLiveWorkers > 0 &&\n liveWorkerCount() >= maxLiveWorkers\n )\n return Promise.resolve({ error: 'max-live-workers' as const })\n const agent = opts.makeWorkerAgent(a.profile)\n const budget =\n a.budget === undefined ? opts.perWorker : mergeBudget(opts.perWorker, a.budget)\n const res = opts.scope.spawn(agent, a.task, {\n budget,\n label: typeof a.label === 'string' ? a.label : 'worker',\n })\n return Promise.resolve(res.ok ? { workerId: res.handle.id } : { error: res.reason })\n },\n },\n {\n name: 'observe_agent',\n description: 'Inspect a worker status, spend, and settled output artifact when available.',\n inputSchema: { type: 'object', properties: { workerId: idArg }, required: ['workerId'] },\n handler: async (raw) => {\n const id = str(obj(raw).workerId, 'workerId')\n const node = opts.scope.view.nodes.find((n) => n.id === id)\n if (!node) return { error: `unknown workerId ${JSON.stringify(id)}` }\n const output = node.outRef ? await opts.blobs.get(node.outRef) : undefined\n return {\n status: node.status,\n spent: node.spent,\n outRef: node.outRef ?? null,\n output: output ?? null,\n }\n },\n },\n {\n name: 'steer_agent',\n description:\n 'Send a message DOWN to a still-LIVE worker (parent→child): a new instruction, a course ' +\n 'correction, or a continuation. The worker drains it at its next step boundary — and before ' +\n 'it may settle, so it cannot finish while a message it never read is pending. A worker that ' +\n 'already settled is gone (returns delivered:false) — spawn a fresh one instead.',\n inputSchema: {\n type: 'object',\n properties: {\n workerId: idArg,\n instruction: { type: 'string', description: 'What the worker should do next.' },\n interrupt: {\n type: 'boolean',\n description:\n 'true = forceful: abort the worker’s in-flight inference so it re-plans on the NEXT ' +\n 'turn (a tool already mid-execution finishes first; only the owned tool-loop honors this). ' +\n 'false/omitted = queued: it flushes at the next step boundary (and before it may settle).',\n },\n },\n required: ['workerId', 'instruction'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const workerId = str(a.workerId, 'workerId')\n const instruction = str(a.instruction, 'instruction')\n const interrupt = a.interrupt === true\n const delivered = opts.scope.send(workerId, { steer: instruction, interrupt })\n await sendDown('steer', { toWorker: workerId, instruction, delivered })\n return { delivered }\n },\n },\n {\n name: 'await_event',\n description:\n 'Wait for and pull the next message a worker, sub-driver, or analyst sent up — the unified ' +\n \"inbox. An event is one of: a settled worker output ('settled'), a question needing your \" +\n \"answer ('question', from ask_parent / the worker's ask-user), or a trace-analyst finding \" +\n \"('finding', from analyze-on-settle). Pass kinds:['settled'] for just the next finished \" +\n 'worker; omit `kinds` to also receive questions and findings. Returns { idle: true } when ' +\n 'nothing is queued and no workers are live.',\n inputSchema: {\n type: 'object',\n properties: {\n kinds: {\n type: 'array',\n items: { type: 'string', enum: ['settled', 'question', 'finding'] },\n description: 'Restrict to these event kinds (any if omitted).',\n },\n },\n },\n handler: async (raw) => {\n const k = obj(raw).kinds\n const kinds = Array.isArray(k)\n ? (k.filter((x) => x === 'settled' || x === 'question' || x === 'finding') as Array<\n CoordinationEvent['type']\n >)\n : undefined\n // Already-queued async messages (findings, questions) first; else drive the cursor to\n // produce the next settlement (and its findings), then re-pull.\n let ev = bus.pull(kinds)\n if (!ev) {\n const drained = await drainSettlement()\n ev = bus.pull(kinds)\n if (!ev) return { idle: !drained }\n }\n return projectEvent(ev)\n },\n },\n {\n name: 'list_questions',\n description:\n 'List questions raised by workers, drivers, or analysts. Blocking stop behavior follows questionPolicy.',\n inputSchema: { type: 'object', properties: {} },\n handler: () => Promise.resolve({ questions }),\n },\n {\n name: 'answer_question',\n description: 'Record an answer, deferral, or escalation for a loop question.',\n inputSchema: {\n type: 'object',\n properties: {\n questionId: { type: 'string' },\n answer: { type: 'string' },\n by: { type: 'string', description: 'Node id or \"user\".' },\n deferReason: { type: 'string' },\n escalateTo: { type: 'string', enum: ['parent', 'user'] },\n escalateReason: { type: 'string' },\n },\n required: ['questionId'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const questionId = str(a.questionId, 'questionId')\n if (typeof a.answer === 'string' && a.answer.length > 0) {\n const answer = a.answer\n const question = decideQuestion(questionId, {\n kind: 'answer',\n answer,\n by: typeof a.by === 'string' && a.by.length > 0 ? a.by : 'user',\n })\n // Route the answer DOWN to the worker that asked, unparking it, and record the down-leg.\n // A blocking question parked the worker, so deliver forcefully — it should resume on the\n // answer immediately, not wait for its next step boundary.\n const interrupt = question.urgency === 'blocks-run' || question.urgency === 'blocks-step'\n const delivered = opts.scope.send(question.from, { answer, questionId, interrupt })\n await sendDown(\n 'answer',\n { toWorker: question.from, instruction: answer, delivered },\n questionId,\n )\n // Surface `delivered` like steer_agent — the caller must see whether the answer actually\n // reached a live worker (false when it already settled or has no inbox).\n return { question, delivered }\n }\n if (typeof a.deferReason === 'string' && a.deferReason.length > 0) {\n return Promise.resolve({\n question: decideQuestion(questionId, {\n kind: 'defer',\n reason: a.deferReason,\n }),\n })\n }\n if (a.escalateTo === 'parent' || a.escalateTo === 'user') {\n const escalateReason =\n typeof a.escalateReason === 'string' && a.escalateReason.length > 0\n ? a.escalateReason\n : 'driver escalated'\n return Promise.resolve({\n question: decideQuestion(questionId, {\n kind: 'escalate',\n to: a.escalateTo,\n reason: escalateReason,\n }),\n })\n }\n throw new Error('answer_question: provide answer, deferReason, or escalateTo')\n },\n },\n {\n name: 'ask_parent',\n description: 'Raise a question to the parent driver/Pi/user when this driver cannot decide.',\n inputSchema: {\n type: 'object',\n properties: {\n from: { type: 'string' },\n level: { type: 'string', enum: ['worker', 'driver', 'loop'] },\n question: { type: 'string' },\n reason: { type: 'string' },\n urgency: { type: 'string', enum: ['continue-without', 'blocks-step', 'blocks-run'] },\n },\n required: ['from', 'level', 'question', 'reason', 'urgency'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const from = str(a.from, 'from')\n const q = await emitNewQuestion(\n addQuestion(\n {\n from,\n level: level(a.level),\n question: str(a.question, 'question'),\n reason: str(a.reason, 'reason'),\n urgency: urgency(a.urgency),\n },\n from,\n { kind: 'escalate', to: 'parent', reason: 'asked parent' },\n ),\n )\n return { question: q }\n },\n },\n {\n name: 'stop',\n description: 'Declare the run complete.',\n inputSchema: {\n type: 'object',\n properties: { reason: { type: 'string', description: 'Why you are stopping.' } },\n },\n handler: (raw) => {\n const blocking = blockingQuestionsForStop()\n if (blocking.length) {\n return Promise.resolve({\n stopped: false,\n error: 'unresolved-blocking-questions',\n questions: blocking,\n })\n }\n stopped = true\n const r = obj(raw).reason\n reason = typeof r === 'string' ? r : undefined\n return Promise.resolve({ stopped: true })\n },\n },\n ]\n\n if (opts.analysts) {\n tools.push({\n name: 'list_analysts',\n description: 'List trace-analyst lenses available to run over a settled worker.',\n inputSchema: { type: 'object', properties: {} },\n handler: () => Promise.resolve({ analysts: opts.analysts?.kinds }),\n })\n tools.push({\n name: 'run_analyst',\n description: 'Apply an analyst lens to a settled worker trace.',\n inputSchema: {\n type: 'object',\n properties: {\n kind: { type: 'string', description: 'The analyst kind id.' },\n workerId: idArg,\n },\n required: ['kind', 'workerId'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const id = str(a.workerId, 'workerId')\n const node = opts.scope.view.nodes.find((n) => n.id === id)\n if (!node) return { error: `unknown workerId ${JSON.stringify(id)}` }\n if (!node.outRef)\n return { error: `worker ${JSON.stringify(id)} has not settled — no trace to analyze yet` }\n const trace = await opts.blobs.get(node.outRef)\n return { findings: await opts.analysts?.run(str(a.kind, 'kind'), trace) }\n },\n })\n }\n\n return {\n tools,\n history: () => bus.history(),\n raiseFinding: (finding) => bus.publish({ type: 'finding', finding }).then(() => undefined),\n stats: () => bus.stats(),\n isStopped: () => stopped,\n stopReason: () => reason,\n settled: () => ledger,\n questions: () => questions,\n }\n}\n","/**\n * @experimental\n *\n * `driverAgent` — the driver's BRAIN.\n *\n * The recursive driver-executor (`driver-executor.ts`) runs a driver `Agent.act` inside a\n * nested `Scope`; this is the intelligent `act`: it mounts the coordination MCP verbs\n * (`createCoordinationTools`) over that scope and runs an LLM tool-loop, so the driver\n * REASONS — spawn / observe / steer / await / stop — about how to drive its children,\n * instead of running a fixed script. Each turn: ask the driver LLM for tool calls, run them\n * against the live scope, fold the results back, repeat until the driver stops (no tool\n * calls) or the turn cap forces a keep-best finalize.\n *\n * Recursion composes through `makeWorkerAgent`: `spawn_agent` resolves a `profile` to a\n * worker LEAF or — when the profile is a driver — a `driverChild` wrapping ANOTHER\n * `driverAgent` over its own nested scope (see `driver-executor.ts`). So an agent\n * drives an agent that drives an agent, each an LLM tool-loop, all on one conserved-budget\n * tree.\n *\n * Two seams are INJECTED so the loop runs offline with no creds and stays decoupled:\n * - `brain` (`ToolLoopChat`) — one driver-LLM turn over the canonical tool-loop seam; a test\n * drives a scripted mock, production passes the router's tool-calling (`routerBrain`), a\n * sandboxed harness drives the verbs as MCP tools. The same seam every tool-loop uses.\n * - `systemPrompt` — the driver's stance (the agent-eval worker-driver prompt / the prompt\n * generator). Injected, never hardcoded — the prompt is a pluggable role.\n */\n\nimport { ValidationError } from '../../errors'\nimport type { McpToolDescriptor } from '../../mcp/server'\nimport {\n coordinationVerbNames,\n createCoordinationTools,\n type MakeWorkerAgent,\n} from '../../mcp/tools/coordination'\nimport type { ToolSpec } from '../router-client'\nimport { runBrainLoop, type ToolLoopChat } from '../tool-loop'\nimport type { Agent, Budget, ResultBlobStore, Scope, Spend } from './types'\n\nexport interface DriverAgentOptions {\n readonly name: string\n /** The driver-LLM seam — ONE inference turn over the conversation + the coordination tool specs\n * (the canonical `ToolLoopChat`): a scripted mock offline, the router's tool-calling in\n * production, or a sandboxed harness. The same seam every tool-loop uses; no bespoke shape. */\n readonly brain: ToolLoopChat\n /** Shared blob store — `observe_agent` reads settled outputs through it. */\n readonly blobs: ResultBlobStore\n /** Resolve a spawned `profile` to a worker LEAF or a driver child (the recursion seam). */\n readonly makeWorkerAgent: MakeWorkerAgent\n /** Per-child budget reserved from the conserved pool on each spawn. */\n readonly perWorker: Budget\n /** Hard cap on simultaneously-LIVE workers — `spawn_agent` fails closed once this many are in\n * flight (a concurrency fence on top of the conserved-pool fence). Omit/`<= 0` = no cap. */\n readonly maxLiveWorkers?: number\n /** The driver's stance — a string, or built from the task (the worker-driver prompt /\n * the generator). INJECTED so the prompt is a pluggable, optimizable role. */\n readonly systemPrompt: string | ((task: unknown) => string)\n /** WORK tools the driver may call DIRECTLY (alongside the coordination verbs) — so the driver is\n * not a pure manager but a full agent that can ACT (do simple work itself) OR SPAWN (delegate).\n * Each is a router tool spec; their names must not collide with the coordination verbs. Pair with\n * `executeExtraTool`. Unset → coordination-only (the prior behavior). */\n readonly extraTools?: ReadonlyArray<{\n readonly name: string\n readonly description?: string\n readonly parameters: Record<string, unknown>\n }>\n /** Runs an `extraTools` call. Returns a string result, or null/undefined to signal \"not handled\"\n * so the call falls through to the coordination dispatch. Required iff `extraTools` is set. */\n readonly executeExtraTool?: (\n name: string,\n args: Record<string, unknown>,\n ) => Promise<string | null | undefined>\n /** Max driver turns before the loop force-finalizes on the best settled child. Default 16.\n * `0` lifts the turn-COUNT cap: the loop is bounded instead by the conserved budget pool,\n * an absolute deadline, the driver's own stop, and abort (checked in-loop). A finite\n * anti-runaway tripwire still guards a degenerate driver that loops on a no-spawn tool. */\n readonly maxTurns?: number\n /** Injected clock for the in-loop absolute-deadline guard — keeps the deadline check\n * deterministic in tests. Defaults to `Date.now`. */\n readonly now?: () => number\n}\n\n/** maxTurns=0 anti-runaway tripwire: a finite ceiling for the ONE case the conserved pool can't\n * bound — a driver whose chat seam reports NO usage (so `scope.meter`/`pool.observe` is never\n * called and its turns don't drain the pool). With a usage-reporting seam, driver inference now\n * meters into the pool and `poolStarved` halts it; the pool + deadline + abort are the real bounds\n * and no healthy run approaches this. */\nconst runawayTripwireTurns = 2000\n\n/** Spawn-progress is impossible: the pool can't afford another worker AND nothing is in flight to\n * await. A long-horizon driver bounded by the conserved pool stops here instead of spinning (the\n * in-loop budget guard the turn cap alone never provided). Checks BOTH conserved channels: tokens\n * (can't afford a worker) and usd (a usd-capped pool whose ceiling the driver's own metered\n * inference has drained — `meter` debits usd, so without this a huge-token/small-usd pool would\n * overspend usd up to the turn tripwire). */\nfunction poolStarved(scope: Scope<unknown>, perWorker: Budget): boolean {\n const b = scope.budget\n if (b.reservedTokens > 0) return false // a child is in flight — await it, don't finalize early\n const tokenStarved = b.tokensLeft < perWorker.maxTokens\n const usdStarved = b.usdCapped && b.usdLeft <= 0\n return tokenStarved || usdStarved\n}\n\n/** The absolute wall-clock deadline (when the root set one) has passed. */\nfunction deadlinePassed(scope: Scope<unknown>, now: () => number): boolean {\n const b = scope.budget\n return b.deadlineMs > 0 && now() >= b.deadlineMs\n}\n\n/**\n * Build the intelligent recursive driver. Its `act` is the LLM tool-loop; spawn it as a\n * `driverChild` (`driver-executor.ts`) to run it inside a nested scope, recursively.\n */\nexport function driverAgent(opts: DriverAgentOptions): Agent<unknown, unknown> {\n if (typeof opts.brain !== 'function') {\n throw new ValidationError('driverAgent: opts.brain must be a function')\n }\n // Fail loud on a half-wired work-tool seam: extra tool specs with no executor (or an executor\n // with no specs the model can see) is a silent no-op the house rules forbid.\n if ((opts.extraTools?.length ?? 0) > 0 && typeof opts.executeExtraTool !== 'function') {\n throw new ValidationError(\n 'driverAgent: extraTools requires executeExtraTool (how to run a work-tool call)',\n )\n }\n // A work tool that shadows a coordination verb would leave the driver unable to coordinate.\n // Validate against the reserved verb set HERE (construction), so the conflict fails loud — not\n // buried inside act() where the supervisor would swallow the throw into a quiet no-winner.\n const reserved = new Set<string>(coordinationVerbNames)\n for (const t of opts.extraTools ?? []) {\n if (reserved.has(t.name)) {\n throw new ValidationError(\n `driverAgent: extra work tool \"${t.name}\" collides with a coordination verb`,\n )\n }\n }\n // Fail loud on a nonsensical cap: a negative maxTurns would silently run zero turns and\n // finalize an empty no-winner — a silent zero the house rules forbid.\n if (opts.maxTurns !== undefined && opts.maxTurns < 0) {\n throw new ValidationError(\n 'driverAgent: maxTurns must be >= 0 (0 lifts the turn cap; bounds become the conserved pool + deadline + abort)',\n )\n }\n // maxTurns=0 lifts the turn-COUNT cap: a long-horizon decomposition must not die on an\n // arbitrary number of turns. It is bounded instead by the conserved budget pool, an absolute\n // deadline, the driver's own stop, and abort — all checked in-loop below. The tripwire is a\n // pure anti-runaway guard, NOT the intended limit.\n const maxTurns = opts.maxTurns === 0 ? runawayTripwireTurns : (opts.maxTurns ?? 16)\n const now = opts.now ?? Date.now\n\n return {\n name: opts.name,\n async act(task, scope: Scope<unknown>): Promise<unknown> {\n const coord = createCoordinationTools({\n scope,\n blobs: opts.blobs,\n makeWorkerAgent: opts.makeWorkerAgent,\n perWorker: opts.perWorker,\n ...(opts.maxLiveWorkers !== undefined ? { maxLiveWorkers: opts.maxLiveWorkers } : {}),\n })\n const byName = new Map<string, McpToolDescriptor>(coord.tools.map((t) => [t.name, t]))\n const toolSpecs: ToolSpec[] = [\n ...coord.tools.map((t) => ({\n type: 'function' as const,\n function: { name: t.name, description: t.description, parameters: t.inputSchema },\n })),\n // Work tools the driver calls DIRECTLY — so it can ACT, not only delegate.\n ...(opts.extraTools ?? []).map((t) => ({\n type: 'function' as const,\n function: { name: t.name, description: t.description, parameters: t.parameters },\n })),\n ]\n const system =\n typeof opts.systemPrompt === 'function' ? opts.systemPrompt(task) : opts.systemPrompt\n\n // Meter the driver's OWN inference each turn into the conserved pool — the largest single\n // token consumer in the loop, and what makes maxTurns=0 genuinely bounded (a thinking driver\n // drains the pool → poolStarved). Wrapping the brain keeps the debit exactly where it was; a\n // scripted/mock turn reports no usage and meters nothing, so offline equal-k stays exact.\n // iterations:0 — the conserved iteration channel budgets CHILD rounds, not driver turns.\n let turn = 0\n const chat: ToolLoopChat = async (messages, tools) => {\n const res = await opts.brain(messages, tools)\n if (res.usage || res.costUsd !== undefined) {\n const turnSpend: Spend = {\n iterations: 0,\n tokens: { input: res.usage?.input ?? 0, output: res.usage?.output ?? 0 },\n usd: res.costUsd ?? 0,\n ms: 0,\n }\n await scope.meter(turnSpend, {\n kind: 'driver-inference',\n driver: opts.name,\n turn,\n toolCalls: (res.toolCalls ?? []).map((c) => c.name),\n })\n }\n turn += 1\n return res\n }\n\n await runBrainLoop({\n chat,\n tools: toolSpecs,\n execute: async (name, args) => {\n // WORK FIRST: a work tool the driver runs itself (act). A non-null return is handled here;\n // null/undefined means \"not mine\" → fall through to the coordination dispatch (spawn/await/…).\n if (opts.executeExtraTool) {\n const worked = await runExtraTool(opts.executeExtraTool, name, args)\n if (worked !== null && worked !== undefined) return worked\n }\n const tool = byName.get(name)\n const result = tool ? await runTool(tool, args) : { error: `unknown tool: ${name}` }\n return safeJson(result)\n },\n initialMessages: [\n { role: 'system', content: system },\n { role: 'user', content: stringifyTask(task) },\n ],\n maxTurns,\n // The conserved-pool + deadline + external-stop bound (what maxTurns=0 relies on): a driver\n // that can no longer spawn (pool starved) or has run past the deadline stops here instead of\n // burning turns. Checked before each inference turn.\n hooks: {\n stopBefore: () =>\n coord.isStopped() ||\n scope.signal.aborted ||\n poolStarved(scope, opts.perWorker) ||\n deadlinePassed(scope, now),\n },\n })\n // The driver's deliverable is the best DELIVERED child (the completion-oracle), never its own\n // prose — a driver cannot self-declare done (Foreman 0/18). No delivered child → undefined.\n return finalize(coord, opts.blobs)\n },\n }\n}\n\n/** Run a work tool. A throw is data to the driver (it can recover next turn), not a crash — fold\n * the error back as a string result. null/undefined passes through (the caller treats it as \"not\n * handled\" and falls to the coordination dispatch). */\nasync function runExtraTool(\n execute: (name: string, args: Record<string, unknown>) => Promise<string | null | undefined>,\n name: string,\n args: Record<string, unknown>,\n): Promise<string | null | undefined> {\n try {\n return await execute(name, args)\n } catch (e) {\n return `error: ${e instanceof Error ? e.message : String(e)}`\n }\n}\n\nasync function runTool(tool: McpToolDescriptor, args: Record<string, unknown>): Promise<unknown> {\n try {\n return await tool.handler(args)\n } catch (e) {\n // A tool throw is data to the driver (it can recover), not a crash — fold it back.\n return { error: e instanceof Error ? e.message : String(e) }\n }\n}\n\n/** Keep-best finalize under the completion-oracle: return the highest-scoring DELIVERED child's\n * output (settled `done` AND `valid` — its deliverable check passed). Returns undefined when no\n * child delivered — an honest \"the driver produced nothing\", never a high-scoring result that\n * ran without passing its check (Foreman's 0/18 lesson). `valid` is the single delivery signal,\n * matching `defaultSelectWinner`'s valid-first rule; the oracle just doesn't fall back to an\n * unchecked best-effort. */\nexport async function finalizeBestDelivered(\n settled: ReadonlyArray<{ status: string; score?: number; valid?: boolean; outRef?: string }>,\n blobs: ResultBlobStore,\n): Promise<unknown> {\n const delivered = settled.filter((w) => w.status === 'done' && w.valid === true)\n if (delivered.length === 0) return undefined\n let best = delivered[0]!\n for (const w of delivered) if ((w.score ?? 0) > (best.score ?? 0)) best = w\n return best.outRef ? await blobs.get(best.outRef) : undefined\n}\n\nasync function finalize(\n coord: {\n settled(): ReadonlyArray<{ status: string; score?: number; valid?: boolean; outRef?: string }>\n },\n blobs: ResultBlobStore,\n): Promise<unknown> {\n return finalizeBestDelivered(coord.settled(), blobs)\n}\n\nfunction stringifyTask(task: unknown): string {\n return typeof task === 'string' ? task : safeJson(task)\n}\n\nfunction safeJson(v: unknown): string {\n try {\n return JSON.stringify(v) ?? String(v)\n } catch {\n return String(v)\n }\n}\n","/**\n * @experimental\n *\n * Feedback persistence surface for the MCP layer.\n *\n * The substrate cannot import `@tangle-network/agent-knowledge` (it would\n * induce a dependency cycle), so the store is an abstract interface. The\n * default implementation is in-memory; consumers wire their own adapter\n * (a real KbStore-backed sink, an HTTP relay to gtm-agent's knowledge\n * service, etc.) via `createMcpServer({ feedbackStore })`.\n *\n * Feedback events are append-only: every rating is a new event with a\n * fresh id, even when the same delegation is rated multiple times. The\n * caller decides how to roll up scores downstream.\n */\n\nimport type { DelegateFeedbackArgs, DelegationFeedbackSnapshot } from './types'\n\n/** @experimental */\nexport interface FeedbackEvent {\n id: string\n refersTo: DelegateFeedbackArgs['refersTo']\n rating: DelegateFeedbackArgs['rating']\n by: DelegateFeedbackArgs['by']\n capturedAt: string\n namespace?: string\n}\n\n/** @experimental */\nexport interface FeedbackStore {\n /** Append a new event. Never dedupes — every rating is its own event. */\n put(event: FeedbackEvent): Promise<void>\n /**\n * List events filtered by `namespace`. When `namespace` is omitted, list\n * across all namespaces. Returns events in insertion order.\n */\n list(filter?: { namespace?: string; refersToRef?: string }): Promise<FeedbackEvent[]>\n}\n\n/** @experimental */\nexport class InMemoryFeedbackStore implements FeedbackStore {\n private readonly events: FeedbackEvent[] = []\n\n async put(event: FeedbackEvent): Promise<void> {\n this.events.push({ ...event })\n }\n\n async list(filter: { namespace?: string; refersToRef?: string } = {}): Promise<FeedbackEvent[]> {\n let out = this.events\n if (filter.namespace !== undefined) {\n out = out.filter((event) => event.namespace === filter.namespace)\n }\n if (filter.refersToRef !== undefined) {\n out = out.filter((event) => event.refersTo.ref === filter.refersToRef)\n }\n return out.map((event) => ({ ...event }))\n }\n}\n\n/**\n * Project a `FeedbackEvent` down to the snapshot shape carried on\n * `delegation_history` entries.\n *\n * @experimental\n */\nexport function eventToSnapshot(event: FeedbackEvent): DelegationFeedbackSnapshot {\n const snap: DelegationFeedbackSnapshot = {\n id: event.id,\n score: event.rating.score,\n by: event.by,\n notes: event.rating.notes,\n capturedAt: event.capturedAt,\n }\n if (event.rating.label) snap.label = event.rating.label\n return snap\n}\n","/**\n * @experimental\n *\n * Persistence port for the MCP delegation queue.\n *\n * `DelegationTaskQueue` keeps its working set in memory (status/history\n * reads stay synchronous) and journals every record mutation through a\n * `DelegationStore`. `DelegationTaskQueue.restore({ store })` is the load\n * path: it reads the full record set once at construction and rehydrates\n * the queue from it. After that the store only sees writes.\n *\n * Records MUST be JSON-safe — `FileDelegationStore` round-trips them\n * through `JSON.stringify`/`JSON.parse`, so a `Date`, `Map`, or function\n * smuggled into `args`/`result` would corrupt the journal.\n */\n\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\nimport { AgentEvalError } from '../errors'\nimport type { DelegationRecord } from './task-queue'\n\n/** @experimental */\nexport interface DelegationStore {\n /**\n * Read every persisted record. Called once, by\n * `DelegationTaskQueue.restore`, before any write. A missing backing\n * file is an empty store; an unparseable one throws\n * `DelegationStateCorruptError`.\n */\n loadAll(): Promise<DelegationRecord[]>\n /** Insert or replace the record keyed by `record.taskId`. */\n upsert(record: DelegationRecord): Promise<void>\n /**\n * Resolve an idempotency key to the taskId that claimed it, if any.\n * The queue serves submit-time dedupe from its rehydrated in-memory\n * index; this read exists for consumers that share a store across\n * processes without holding the full record set.\n */\n lookupIdempotencyKey(key: string): Promise<string | undefined>\n /** Delete the named records — the retention-cap eviction path. */\n remove(taskIds: readonly string[]): Promise<void>\n}\n\n/**\n * The persisted delegation state exists but cannot be parsed into\n * records. Fail loud: silently starting empty over a corrupt journal\n * would erase delegation history and re-run idempotent work. Opt into\n * recovery explicitly via `FileDelegationStoreOptions.recoverCorrupt`\n * (the bin maps `AGENT_RUNTIME_DELEGATION_STATE_RECOVER=1` onto it),\n * which archives the corrupt file and starts fresh.\n *\n * @experimental\n */\nexport class DelegationStateCorruptError extends AgentEvalError {\n constructor(message: string, options?: { cause?: unknown }) {\n super('validation', message, options)\n }\n}\n\n/**\n * A delegation-store read or write failed (filesystem error, store\n * called before `loadAll`, ...). Once the queue observes one, it stops\n * accepting new submissions — accepting work it cannot journal would\n * silently demote durable mode to in-memory mode.\n *\n * @experimental\n */\nexport class DelegationPersistenceError extends AgentEvalError {\n constructor(message: string, options?: { cause?: unknown }) {\n super('config', message, options)\n }\n}\n\n/** @experimental */\nexport class InMemoryDelegationStore implements DelegationStore {\n private readonly records = new Map<string, DelegationRecord>()\n\n async loadAll(): Promise<DelegationRecord[]> {\n return [...this.records.values()].map(cloneRecord)\n }\n\n async upsert(record: DelegationRecord): Promise<void> {\n this.records.set(record.taskId, cloneRecord(record))\n }\n\n async lookupIdempotencyKey(key: string): Promise<string | undefined> {\n for (const record of this.records.values()) {\n if (record.idempotencyKey === key) return record.taskId\n }\n return undefined\n }\n\n async remove(taskIds: readonly string[]): Promise<void> {\n for (const taskId of taskIds) this.records.delete(taskId)\n }\n}\n\n/** @experimental */\nexport interface FileDelegationStoreOptions {\n /** Absolute path of the JSON state file. Parent directories are created on first write. */\n filePath: string\n /**\n * When the state file exists but cannot be parsed, archive it to\n * `<filePath>.corrupt-<timestamp>` and start empty instead of\n * throwing `DelegationStateCorruptError`. Default false.\n */\n recoverCorrupt?: boolean\n}\n\ninterface PersistedDelegationState {\n version: 1\n records: DelegationRecord[]\n}\n\nconst STATE_FORMAT_VERSION = 1\n\n/**\n * JSON-file persistence for the delegation queue. Each write serializes\n * the full record set and lands it atomically (write to a sibling tmp\n * file, then `rename`), so readers never observe a torn file — a crash\n * mid-write leaves the previous snapshot intact. Writes are serialized\n * internally; concurrent `upsert`/`remove` calls cannot interleave.\n *\n * Built for the MCP server's scale (one stdio process, hundreds of\n * records): full-snapshot writes keep the format trivially inspectable\n * and corruption-detectable without a database dependency.\n *\n * @experimental\n */\nexport class FileDelegationStore implements DelegationStore {\n private readonly filePath: string\n private readonly recoverCorrupt: boolean\n private readonly records = new Map<string, DelegationRecord>()\n private loaded = false\n private writeTail: Promise<void> = Promise.resolve()\n private tmpSeq = 0\n\n constructor(options: FileDelegationStoreOptions) {\n this.filePath = options.filePath\n this.recoverCorrupt = options.recoverCorrupt ?? false\n }\n\n async loadAll(): Promise<DelegationRecord[]> {\n let raw: string\n try {\n raw = await readFile(this.filePath, 'utf8')\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n this.loaded = true\n return []\n }\n throw new DelegationPersistenceError(\n `FileDelegationStore: failed to read ${this.filePath}: ${errorMessage(err)}`,\n { cause: err },\n )\n }\n let state: PersistedDelegationState\n try {\n state = parsePersistedState(raw)\n } catch (err) {\n if (!this.recoverCorrupt) {\n throw new DelegationStateCorruptError(\n `FileDelegationStore: state file ${this.filePath} is corrupt (${errorMessage(err)}). ` +\n 'Repair or archive the file, or opt into automatic recovery ' +\n '(recoverCorrupt / AGENT_RUNTIME_DELEGATION_STATE_RECOVER=1) to archive it and start empty.',\n { cause: err },\n )\n }\n const archivePath = `${this.filePath}.corrupt-${Date.now()}`\n await rename(this.filePath, archivePath)\n this.loaded = true\n return []\n }\n this.records.clear()\n for (const record of state.records) this.records.set(record.taskId, record)\n this.loaded = true\n return [...this.records.values()].map(cloneRecord)\n }\n\n async upsert(record: DelegationRecord): Promise<void> {\n this.assertLoaded('upsert')\n this.records.set(record.taskId, cloneRecord(record))\n await this.enqueueWrite()\n }\n\n async lookupIdempotencyKey(key: string): Promise<string | undefined> {\n this.assertLoaded('lookupIdempotencyKey')\n for (const record of this.records.values()) {\n if (record.idempotencyKey === key) return record.taskId\n }\n return undefined\n }\n\n async remove(taskIds: readonly string[]): Promise<void> {\n this.assertLoaded('remove')\n let changed = false\n for (const taskId of taskIds) {\n if (this.records.delete(taskId)) changed = true\n }\n if (changed) await this.enqueueWrite()\n }\n\n private assertLoaded(op: string): void {\n if (this.loaded) return\n // Writing before load would snapshot only the new records and clobber\n // whatever the file already holds.\n throw new DelegationPersistenceError(\n `FileDelegationStore: ${op} called before loadAll() — the on-disk state has not been read yet`,\n )\n }\n\n private enqueueWrite(): Promise<void> {\n const write = this.writeTail.then(() => this.writeSnapshot())\n this.writeTail = write.catch(() => {})\n return write\n }\n\n private async writeSnapshot(): Promise<void> {\n const state: PersistedDelegationState = {\n version: STATE_FORMAT_VERSION,\n records: [...this.records.values()],\n }\n const payload = `${JSON.stringify(state)}\\n`\n this.tmpSeq += 1\n const tmpPath = `${this.filePath}.tmp-${process.pid}-${this.tmpSeq}`\n try {\n await mkdir(dirname(this.filePath), { recursive: true })\n await writeFile(tmpPath, payload, 'utf8')\n await rename(tmpPath, this.filePath)\n } catch (err) {\n throw new DelegationPersistenceError(\n `FileDelegationStore: failed to write ${this.filePath}: ${errorMessage(err)}`,\n { cause: err },\n )\n }\n }\n}\n\nfunction parsePersistedState(raw: string): PersistedDelegationState {\n const parsed: unknown = JSON.parse(raw)\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('top-level value is not an object')\n }\n const state = parsed as Record<string, unknown>\n if (state.version !== STATE_FORMAT_VERSION) {\n throw new Error(`unsupported state version ${JSON.stringify(state.version)}`)\n }\n if (!Array.isArray(state.records)) {\n throw new Error('`records` is not an array')\n }\n for (const record of state.records) {\n if (record === null || typeof record !== 'object') {\n throw new Error('a record entry is not an object')\n }\n const candidate = record as Record<string, unknown>\n if (typeof candidate.taskId !== 'string' || typeof candidate.status !== 'string') {\n throw new Error('a record entry is missing `taskId`/`status`')\n }\n }\n return { version: STATE_FORMAT_VERSION, records: state.records as DelegationRecord[] }\n}\n\nfunction cloneRecord(record: DelegationRecord): DelegationRecord {\n return structuredClone(record)\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * @experimental\n *\n * Compact loop-trace tee for the delegation journal.\n *\n * The OTEL exporter ({@link createPropagatingTraceEmitter}) is a no-op\n * without `OTEL_EXPORTER_OTLP_ENDPOINT`, which leaves delegated work streams\n * dark in practice. This module derives the same loop → round → branch span\n * tree (via the shared {@link buildLoopSpanNodes} builder) into a small,\n * JSON-safe shape persisted directly on the `DelegationRecord` — observable\n * through `delegation_status` with no collector infrastructure. Both sinks\n * coexist: the OTEL export path is unchanged.\n *\n * Payload discipline: a record's trace is hard-capped (spans + serialized\n * bytes). Past the cap the OLDEST spans are dropped and the record carries a\n * `traceTruncated: true` marker — truncation is never silent.\n */\n\nimport { buildLoopSpanNodes } from '../otel-export'\nimport type { LoopTraceEmitter, LoopTraceEvent } from '../runtime/types'\n\n/**\n * One span of a delegation's compact trace. Flat (parent linkage by id), all\n * values JSON-safe scalars — `FileDelegationStore` round-trips records\n * through `JSON.stringify`. `meta` carries the span's attributes (GenAI\n * semconv keys + `tangle.loop.*` extensions) exactly as the OTEL sink emits\n * them, so a consumer can re-export journal traces losslessly.\n *\n * @experimental\n */\nexport interface DelegationTraceSpan {\n spanId: string\n /** Absent on the tree root. */\n parentSpanId?: string\n /** `'loop'` | `'loop.round'` | `'loop.iteration'` (or a sink-specific name). */\n name: string\n /** Topology level: loop root, plan round, or iteration branch. */\n kind: 'loop' | 'round' | 'branch'\n startMs: number\n endMs: number\n meta?: Record<string, string | number | boolean>\n}\n\n/** Default cap on spans retained per delegation record. @experimental */\nexport const DELEGATION_TRACE_MAX_SPANS = 512\n\n/** Default cap on the serialized trace payload per record, in bytes. @experimental */\nexport const DELEGATION_TRACE_MAX_BYTES = 256 * 1024\n\n/** @experimental */\nexport interface DelegationTraceCaps {\n /** Default {@link DELEGATION_TRACE_MAX_SPANS}. */\n maxSpans?: number\n /** Default {@link DELEGATION_TRACE_MAX_BYTES}. Approximate — measured as the\n * sum of per-span `JSON.stringify` lengths. */\n maxBytes?: number\n}\n\n/** @experimental */\nexport interface CappedDelegationTrace {\n trace: DelegationTraceSpan[]\n /** True when oldest spans were dropped to honor the caps. */\n truncated: boolean\n}\n\n/**\n * Derive the compact span tree for ONE loop run from its buffered\n * `LoopTraceEvent` stream. Same reconstruction as the OTEL exporter\n * ({@link buildLoopSpanNodes}); tolerates partial streams.\n *\n * @experimental\n */\nexport function buildDelegationTraceSpans(\n events: ReadonlyArray<LoopTraceEvent>,\n): DelegationTraceSpan[] {\n return buildLoopSpanNodes(events).map((node) => ({\n spanId: node.spanId,\n ...(node.parentSpanId !== undefined ? { parentSpanId: node.parentSpanId } : {}),\n name: node.name,\n kind: node.kind,\n startMs: node.startMs,\n endMs: node.endMs,\n ...(Object.keys(node.attrs).length > 0 ? { meta: node.attrs } : {}),\n }))\n}\n\n/**\n * Enforce the trace caps over an ordered (oldest-first) span list. Drops the\n * OLDEST spans first and reports `truncated: true` when anything was dropped;\n * the newest span always survives, so a non-empty input never caps to empty.\n * Dropping a parent may orphan surviving children's `parentSpanId` references\n * — acceptable for the flat journal shape; consumers treat unresolved parents\n * as roots.\n *\n * @experimental\n */\nexport function capDelegationTrace(\n spans: ReadonlyArray<DelegationTraceSpan>,\n caps?: DelegationTraceCaps,\n): CappedDelegationTrace {\n const maxSpans = caps?.maxSpans ?? DELEGATION_TRACE_MAX_SPANS\n const maxBytes = caps?.maxBytes ?? DELEGATION_TRACE_MAX_BYTES\n let start = Math.max(0, spans.length - maxSpans)\n const sizes = spans.map((span) => JSON.stringify(span).length + 1)\n let total = 0\n for (let i = start; i < sizes.length; i += 1) total += sizes[i]!\n while (start < spans.length - 1 && total > maxBytes) {\n total -= sizes[start]!\n start += 1\n }\n return { trace: spans.slice(start), truncated: start > 0 }\n}\n\n/**\n * Per-delegation trace collector. Buffers `LoopTraceEvent`s per runId\n * (mirroring the OTEL emitter's buffering) and hands the derived compact\n * spans to `onSpans` when a run reaches `loop.ended`. `settle()` drains runs\n * that never ended — a hard-aborted loop still leaves its partial tree in the\n * journal, unlike the OTEL path which drops it.\n *\n * @experimental\n */\nexport interface DelegationTraceCollector {\n emitter: LoopTraceEmitter\n /** Flush buffered events of runs that never reached `loop.ended`. */\n settle(): void\n}\n\n/** @experimental */\nexport function createDelegationTraceCollector(\n onSpans: (spans: DelegationTraceSpan[]) => void,\n): DelegationTraceCollector {\n const buffers = new Map<string, LoopTraceEvent[]>()\n const flush = (events: LoopTraceEvent[]): void => {\n const spans = buildDelegationTraceSpans(events)\n if (spans.length > 0) onSpans(spans)\n }\n return {\n emitter: {\n emit(event: LoopTraceEvent): void {\n const buf = buffers.get(event.runId)\n if (buf) buf.push(event)\n else buffers.set(event.runId, [event])\n if (event.kind === 'loop.ended') {\n const events = buffers.get(event.runId) ?? [event]\n buffers.delete(event.runId)\n flush(events)\n }\n },\n },\n settle(): void {\n for (const events of buffers.values()) flush(events)\n buffers.clear()\n },\n }\n}\n\n/**\n * 16-hex-char span id for journal spans synthesized outside the shared loop\n * builder (e.g. the queue's detached-resume segment).\n *\n * @experimental\n */\nexport function generateDelegationSpanId(): string {\n const bytes = new Uint8Array(8)\n if (typeof globalThis.crypto?.getRandomValues === 'function') {\n globalThis.crypto.getRandomValues(bytes)\n } else {\n for (let i = 0; i < 8; i += 1) bytes[i] = Math.floor(Math.random() * 256)\n }\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n/**\n * Fan one `LoopTraceEvent` stream into several emitters — e.g. the\n * process-wide OTEL exporter AND the per-delegation journal collector.\n * `undefined` entries are skipped; returns `undefined` when nothing is left\n * so callers keep the kernel's \"no emitter, no events\" fast path.\n *\n * @experimental\n */\nexport function composeLoopTraceEmitters(\n ...emitters: ReadonlyArray<LoopTraceEmitter | undefined>\n): LoopTraceEmitter | undefined {\n const live = emitters.filter((e): e is LoopTraceEmitter => e !== undefined)\n if (live.length === 0) return undefined\n if (live.length === 1) return live[0]\n return {\n emit(event: LoopTraceEvent): void | Promise<void> {\n const pending: Promise<void>[] = []\n for (const emitter of live) {\n const result = emitter.emit(event)\n if (result) pending.push(result)\n }\n if (pending.length > 0) return Promise.all(pending).then(() => undefined)\n },\n }\n}\n","/**\n * @experimental\n *\n * State machine for async MCP delegations:\n *\n * pending → running → completed | failed\n * ↘ cancelled (from any non-terminal state via cancel())\n *\n * Each `submit` returns a `taskId` immediately and kicks the work off in the\n * background. The work function receives an `AbortSignal` the queue fires\n * when `cancel(taskId)` is called. The queue does NOT supervise runtime\n * timeouts — the underlying `runLoop` driver / sandbox imposes those.\n *\n * Idempotency: callers may supply an `idempotencyKey` (hash of the input).\n * A duplicate `submit` with a known key returns the existing task instead of\n * starting a new one. Mutated input → different key → different task.\n *\n * Durability: the working set lives in memory (reads stay synchronous) and\n * every record mutation is journaled through a `DelegationStore`. The default\n * `InMemoryDelegationStore` keeps today's semantics — a process restart drops\n * all state. Construct via `DelegationTaskQueue.restore({ store })` with a\n * `FileDelegationStore` to reload prior records on startup: terminal records\n * stay queryable, in-flight records either re-attach through the\n * `resumeDelegate` seam (when they carry a `detachedSessionRef`) or fail\n * loud with a driver-restart error so `delegation_status` tells the truth.\n */\n\nimport { ValidationError } from '../errors'\nimport type { LoopTraceEmitter } from '../runtime/types'\nimport {\n DelegationPersistenceError,\n type DelegationStore,\n InMemoryDelegationStore,\n} from './delegation-store'\nimport {\n capDelegationTrace,\n createDelegationTraceCollector,\n type DelegationTraceSpan,\n generateDelegationSpanId,\n} from './delegation-trace'\nimport type { TraceContext } from './trace-propagation'\nimport type {\n DelegateCodeArgs,\n DelegateResearchArgs,\n DelegateUiAuditArgs,\n DelegationError,\n DelegationFeedbackSnapshot,\n DelegationHistoryArgs,\n DelegationHistoryEntry,\n DelegationProfile,\n DelegationProgress,\n DelegationResultPayload,\n DelegationStatus,\n DelegationStatusResult,\n} from './types'\n\ntype AnyDelegateArgs = DelegateCodeArgs | DelegateResearchArgs | DelegateUiAuditArgs\n\n/**\n * Must be JSON-safe end to end (`args`, `result`, `error`, `feedback`) —\n * persistent stores round-trip records through `JSON.stringify`.\n *\n * @experimental\n */\nexport interface DelegationRecord {\n taskId: string\n profile: DelegationProfile\n namespace?: string\n args: AnyDelegateArgs\n status: DelegationStatus\n progress?: DelegationProgress\n result?: DelegationResultPayload\n error?: DelegationError\n costUsd?: number\n startedAt: string\n completedAt?: string\n /** Sha-prefix hash of the canonical input — used for idempotency lookup. */\n idempotencyKey?: string\n /**\n * Caller-generated deterministic id of a detached run (e.g. the sandbox\n * session id a single-tick driver resumes by). Presence is what makes a\n * restored in-flight record resumable via `resumeDelegate`; without it a\n * restart settles the record as failed.\n */\n detachedSessionRef?: string\n /** Feedback events keyed by this delegation's taskId. */\n feedback: DelegationFeedbackSnapshot[]\n /**\n * Compact loop-trace span tree teed from the delegation's run, oldest\n * spans first. Appended when a delegated loop reaches `loop.ended` and\n * settled (partial buffers included) at the terminal transition. Capped\n * via `capDelegationTrace` — see `traceTruncated`.\n */\n trace?: DelegationTraceSpan[]\n /** Present when oldest trace spans were dropped to honor the trace caps. */\n traceTruncated?: true\n /**\n * Inherited trace identity (the queue's `traceContext` at submit time —\n * typically `readTraceContextFromEnv()`), distinct from the span payload:\n * a journal consumer joins records into the parent trace by these ids\n * without parsing spans. Restored records keep their persisted identity.\n */\n traceId?: string\n /** Caller span that dispatched the delegation, when one was inherited. */\n parentSpanId?: string\n}\n\n/** @experimental */\nexport interface SubmitInput<Args extends AnyDelegateArgs> {\n profile: DelegationProfile\n args: Args\n namespace?: string\n idempotencyKey?: string\n /**\n * Records the detached-run resume key on the new record. The submitted\n * `run` function still executes in-process exactly as without it — the\n * ref only matters after a restart, when `DelegationTaskQueue.restore`\n * hands it to the `resumeDelegate` seam instead of failing the record.\n */\n detachedSessionRef?: string\n /**\n * Runs the underlying delegation. The queue passes a fresh `AbortSignal`\n * and a `report` channel for incremental progress updates. The function\n * MUST resolve with the typed `DelegationResultPayload['output']`; the\n * queue wraps it with the profile tag.\n */\n run: (ctx: DelegationRunContext) => Promise<DelegationResultPayload['output']>\n}\n\n/** @experimental Context handed to a `SubmitInput.run` function. */\nexport interface DelegationRunContext {\n signal: AbortSignal\n report(progress: DelegationProgress): void\n /** The `detachedSessionRef` recorded at submit, when one was supplied. */\n detachedSessionRef?: string\n /**\n * Replace the record's detached-run resume key — the detached dispatch path\n * calls this once the sandbox id is known so the persisted ref names a\n * resolvable box. Ignored after the record settles (a cancel racing the\n * rebind is legitimate; the ref no longer matters then). Throws on an empty\n * ref — erasing the resume key would silently make the record unresumable.\n */\n updateDetachedSessionRef(ref: string): void\n /**\n * Per-delegation loop-trace sink, always provided by the queue. Events\n * emitted here are journaled onto the record as a compact span tree\n * (`record.trace`) when each loop run ends and at the delegation's\n * terminal transition. Delegates forward it into their `runLoop` ctx,\n * composed with any process-wide OTEL emitter\n * (`composeLoopTraceEmitters`). Optional in the type so consumer-built\n * contexts stay source-compatible.\n */\n traceEmitter?: LoopTraceEmitter\n}\n\n/** @experimental */\nexport interface SubmitOutput {\n taskId: string\n /** True when a prior matching `idempotencyKey` returned an existing record. */\n reused: boolean\n}\n\n/**\n * One observation of a detached run, mapped 1:1 from a single-tick driver\n * (e.g. the sandbox SDK's `driveTurn`, which reports\n * completed | running | failed per pass). `running` schedules another tick\n * after `intervalMs`; `completed` / `failed` settle the record.\n *\n * @experimental\n */\nexport type DelegationResumeTick =\n | { state: 'running' }\n | { state: 'completed'; output: DelegationResultPayload['output']; costUsd?: number }\n | { state: 'failed'; error: DelegationError }\n\n/** @experimental */\nexport interface DelegationResumeContext {\n /** Fired by `cancel(taskId)`; the driver should stop the remote run when it can. */\n signal: AbortSignal\n report(progress: DelegationProgress): void\n}\n\n/**\n * Re-attaches restored in-flight records to their detached runs. The queue\n * calls `tick` repeatedly — it never awaits a whole run — so the driver can\n * be a thin wrapper over a one-pass primitive: resolve the run named by\n * `detachedSessionRef`, advance/poll it once, report where it stands. A\n * thrown error settles the record as failed; `failed` ticks are treated as\n * terminal and are not retried.\n *\n * @experimental\n */\nexport interface DelegationResumeDriver {\n tick(\n task: { record: DelegationRecord; detachedSessionRef: string },\n ctx: DelegationResumeContext,\n ): Promise<DelegationResumeTick>\n /** Delay between `running` ticks, in milliseconds. Default 5000. */\n intervalMs?: number\n}\n\n/** @experimental */\nexport interface DelegationTaskQueueOptions {\n /** ID generator override; default `randomTaskId`. */\n generateId?: () => string\n /** Clock override; default `() => new Date().toISOString()`. */\n now?: () => string\n /**\n * Journal for record mutations and the `restore()` load source. Default\n * `InMemoryDelegationStore` — observably identical to an unjournaled\n * queue. Pass a `FileDelegationStore` through\n * `DelegationTaskQueue.restore` for state that survives a restart;\n * constructing with `new` never loads prior state.\n */\n store?: DelegationStore\n /** Resume seam for restored in-flight records that carry a `detachedSessionRef`. */\n resumeDelegate?: DelegationResumeDriver\n /**\n * Maximum number of terminal (completed | failed | cancelled) records\n * retained; the oldest (by `completedAt`) are evicted from memory and\n * store once the cap is exceeded. Default unbounded.\n */\n maxTerminalRecords?: number\n /**\n * Observes the first store failure. After it fires, the queue refuses\n * new submissions and `flush()` rejects with the same error. Default:\n * rethrow on a microtask — an unhandled crash — because silently\n * degrading durable mode to memory-only would lie to the caller.\n */\n onPersistError?: (error: DelegationPersistenceError) => void\n /**\n * Inherited trace identity stamped on every submitted record\n * (`traceId` / `parentSpanId`). The bin passes\n * `readTraceContextFromEnv()` so journal consumers can join delegation\n * records into the caller's trace. Restored records keep the identity\n * they were persisted with.\n */\n traceContext?: TraceContext\n}\n\n/** @experimental */\nexport class DelegationTaskQueue {\n private readonly records = new Map<string, DelegationRecord>()\n private readonly controllers = new Map<string, AbortController>()\n private readonly byIdempotencyKey = new Map<string, string>()\n private readonly generateId: () => string\n private readonly now: () => string\n private readonly store: DelegationStore\n private readonly resumeDelegate?: DelegationResumeDriver\n private readonly maxTerminalRecords: number\n private readonly onPersistError: (error: DelegationPersistenceError) => void\n private readonly traceContext: TraceContext | undefined\n private persistTail: Promise<void> = Promise.resolve()\n private persistFailure: DelegationPersistenceError | undefined\n\n constructor(options: DelegationTaskQueueOptions = {}) {\n this.generateId = options.generateId ?? randomTaskId\n this.now = options.now ?? (() => new Date().toISOString())\n this.store = options.store ?? new InMemoryDelegationStore()\n this.resumeDelegate = options.resumeDelegate\n if (options.maxTerminalRecords !== undefined) {\n if (!Number.isInteger(options.maxTerminalRecords) || options.maxTerminalRecords < 1) {\n throw new ValidationError(\n `DelegationTaskQueue: maxTerminalRecords must be a positive integer, got ${String(options.maxTerminalRecords)}`,\n )\n }\n }\n this.maxTerminalRecords = options.maxTerminalRecords ?? Number.POSITIVE_INFINITY\n this.traceContext = options.traceContext\n this.onPersistError =\n options.onPersistError ??\n ((error) => {\n queueMicrotask(() => {\n throw error\n })\n })\n }\n\n /**\n * Construct a queue from previously-persisted state. Loads every record\n * from `options.store`, rebuilds the idempotency index (so a re-submitted\n * identical task returns the prior taskId and its terminal state), then:\n *\n * - terminal records stay queryable via `status()` / `history()`\n * - in-flight records with a `detachedSessionRef` re-attach through\n * `options.resumeDelegate` and report `running`\n * - other in-flight records settle as failed — their driver died with\n * the previous process and the result is unrecoverable\n *\n * The retention cap applies to the loaded set as well.\n */\n static async restore(options: DelegationTaskQueueOptions = {}): Promise<DelegationTaskQueue> {\n const queue = new DelegationTaskQueue(options)\n const loaded = await queue.store.loadAll()\n await queue.rehydrate(loaded)\n return queue\n }\n\n /**\n * Kick off a delegation in the background. Returns immediately. The\n * `taskId` is queryable via `status` once this method returns. Throws\n * the recorded `DelegationPersistenceError` once the store has failed —\n * the queue does not accept work it cannot journal.\n */\n submit<Args extends AnyDelegateArgs>(input: SubmitInput<Args>): SubmitOutput {\n if (this.persistFailure) throw this.persistFailure\n if (input.idempotencyKey) {\n const existing = this.byIdempotencyKey.get(input.idempotencyKey)\n if (existing && this.records.has(existing)) {\n return { taskId: existing, reused: true }\n }\n }\n const taskId = this.generateId()\n const controller = new AbortController()\n const record: DelegationRecord = {\n taskId,\n profile: input.profile,\n namespace: input.namespace,\n args: input.args,\n status: 'pending',\n startedAt: this.now(),\n feedback: [],\n idempotencyKey: input.idempotencyKey,\n detachedSessionRef: input.detachedSessionRef,\n ...(this.traceContext !== undefined\n ? {\n traceId: this.traceContext.traceId,\n ...(this.traceContext.parentSpanId !== undefined\n ? { parentSpanId: this.traceContext.parentSpanId }\n : {}),\n }\n : {}),\n }\n this.records.set(taskId, record)\n this.controllers.set(taskId, controller)\n if (input.idempotencyKey) this.byIdempotencyKey.set(input.idempotencyKey, taskId)\n this.persist(record)\n\n // Fire-and-forget the run function. Errors flow into the record so the\n // status poll surfaces them; the promise itself is intentionally\n // unobserved by the queue.\n queueMicrotask(() => {\n this.execute(taskId, input, controller)\n })\n\n return { taskId, reused: false }\n }\n\n /**\n * Snapshot the current state of a delegation. Returns `undefined` for\n * unknown ids so callers can distinguish missing from terminal.\n * `includeTrace` attaches the journaled loop-trace span tree — off by\n * default so status polls stay light.\n */\n status(taskId: string, opts?: { includeTrace?: boolean }): DelegationStatusResult | undefined {\n const record = this.records.get(taskId)\n if (!record) return undefined\n return toStatusResult(record, opts)\n }\n\n /**\n * Abort an in-flight delegation. Returns `false` if the task is unknown\n * or already terminal. The underlying `run` function MUST honor the\n * abort signal for the cancel to take effect; the queue marks the\n * record `cancelled` regardless so a misbehaving runner cannot pin the\n * UI on `running` forever.\n */\n cancel(taskId: string): boolean {\n const record = this.records.get(taskId)\n if (!record) return false\n if (isTerminal(record.status)) return false\n const controller = this.controllers.get(taskId)\n controller?.abort()\n record.status = 'cancelled'\n record.completedAt = this.now()\n record.error = { message: 'cancelled by caller', kind: 'CancelledError' }\n this.persist(record)\n this.enforceRetention()\n return true\n }\n\n /**\n * Append a feedback event to the matching delegation. Returns `false`\n * when `ref` does not name a known taskId — the caller should still\n * record the feedback through a different surface (artifact/outcome\n * kinds are not queue-bound).\n */\n attachFeedback(taskId: string, snapshot: DelegationFeedbackSnapshot): boolean {\n const record = this.records.get(taskId)\n if (!record) return false\n record.feedback.push(snapshot)\n this.persist(record)\n return true\n }\n\n /**\n * Query the recorded delegations. Returns entries newest-first (by\n * `startedAt`), truncated to `limit`.\n */\n history(args: DelegationHistoryArgs = {}): DelegationHistoryEntry[] {\n const limit = clampLimit(args.limit)\n const since = args.since ? Date.parse(args.since) : Number.NEGATIVE_INFINITY\n const out: DelegationHistoryEntry[] = []\n for (const record of this.records.values()) {\n if (args.namespace && record.namespace !== args.namespace) continue\n if (args.profile && record.profile !== args.profile) continue\n if (Number.isFinite(since) && Date.parse(record.startedAt) < since) continue\n out.push(toHistoryEntry(record))\n }\n out.sort((a, b) => b.startedAt.localeCompare(a.startedAt))\n return out.slice(0, limit)\n }\n\n /**\n * Await every journal write issued so far. Rejects with the recorded\n * `DelegationPersistenceError` when any of them failed. Call before\n * handing the store's backing file to another process.\n */\n async flush(): Promise<void> {\n // Drain to quiescence: a write that completes while we await the tail can\n // chain another (the resume loop persisting a settle, a late `report`,\n // retention removals). Awaiting a single snapshot of `persistTail` would\n // miss those follow-on writes, letting a `store.upsert` land after the\n // caller has torn the backing dir down. Re-await until the tail stops\n // advancing.\n let tail: typeof this.persistTail | undefined\n while (this.persistTail !== tail) {\n tail = this.persistTail\n await tail\n }\n if (this.persistFailure) throw this.persistFailure\n }\n\n /** Test-only — number of in-flight (non-terminal) records. */\n inflightCount(): number {\n let n = 0\n for (const record of this.records.values()) {\n if (!isTerminal(record.status)) n += 1\n }\n return n\n }\n\n private async execute<Args extends AnyDelegateArgs>(\n taskId: string,\n input: SubmitInput<Args>,\n controller: AbortController,\n ): Promise<void> {\n const record = this.records.get(taskId)\n if (!record) return\n record.status = 'running'\n this.persist(record)\n // Journal tee: each finished loop run inside the delegation appends its\n // compact span tree to the record immediately (a long delegation's trace\n // is durable before the terminal transition); `settle()` below drains\n // partial buffers from runs that never reached `loop.ended`.\n const traceCollector = createDelegationTraceCollector((spans) => {\n if (isTerminal(currentStatus(record))) return\n this.appendTrace(record, spans)\n this.persist(record)\n })\n try {\n const output = await input.run({\n signal: controller.signal,\n report: (progress) => {\n if (record.status === 'running') {\n record.progress = progress\n this.persist(record)\n }\n },\n traceEmitter: traceCollector.emitter,\n ...(record.detachedSessionRef !== undefined\n ? { detachedSessionRef: record.detachedSessionRef }\n : {}),\n updateDetachedSessionRef: (ref) => {\n if (typeof ref !== 'string' || ref.length === 0) {\n throw new ValidationError(\n 'DelegationTaskQueue: updateDetachedSessionRef requires a non-empty ref',\n )\n }\n if (isTerminal(currentStatus(record))) return\n record.detachedSessionRef = ref\n this.persist(record)\n },\n })\n traceCollector.settle()\n // `cancel()` may have flipped the status to `cancelled` while the\n // run promise was pending. Read the field through a widening\n // helper so the narrowed `'running'` type from the assignment\n // above does not exclude that case at compile time.\n if (currentStatus(record) === 'cancelled') return\n record.status = 'completed'\n record.completedAt = this.now()\n record.result = { profile: input.profile, output } as DelegationResultPayload\n this.persist(record)\n this.enforceRetention()\n } catch (err) {\n traceCollector.settle()\n if (currentStatus(record) === 'cancelled') return\n record.status = 'failed'\n record.completedAt = this.now()\n record.error = errorToShape(err)\n this.persist(record)\n this.enforceRetention()\n } finally {\n this.controllers.delete(taskId)\n }\n }\n\n private appendTrace(record: DelegationRecord, spans: DelegationTraceSpan[]): void {\n if (spans.length === 0) return\n const { trace, truncated } = capDelegationTrace([...(record.trace ?? []), ...spans])\n record.trace = trace\n if (truncated) record.traceTruncated = true\n }\n\n private async rehydrate(loaded: DelegationRecord[]): Promise<void> {\n const records = [...loaded].sort((a, b) => a.startedAt.localeCompare(b.startedAt))\n for (const record of records) {\n this.records.set(record.taskId, record)\n if (record.idempotencyKey) this.byIdempotencyKey.set(record.idempotencyKey, record.taskId)\n }\n const restoreWrites: Promise<void>[] = []\n for (const record of this.records.values()) {\n if (isTerminal(record.status)) continue\n if (record.detachedSessionRef && this.resumeDelegate) {\n record.status = 'running'\n restoreWrites.push(this.persist(record))\n this.startResume(record, record.detachedSessionRef, this.resumeDelegate)\n continue\n }\n record.status = 'failed'\n record.completedAt = this.now()\n record.error = {\n message: record.detachedSessionRef\n ? `delegation driver restarted while the task was in flight; detached session \"${record.detachedSessionRef}\" needs a resumeDelegate to be resumed`\n : 'delegation driver restarted while the task was in flight; the run was not detached and cannot be resumed',\n kind: 'DriverRestartError',\n }\n restoreWrites.push(this.persist(record))\n }\n const retentionWrite = this.enforceRetention()\n if (retentionWrite) restoreWrites.push(retentionWrite)\n await Promise.all(restoreWrites)\n if (this.persistFailure) throw this.persistFailure\n }\n\n private startResume(\n record: DelegationRecord,\n detachedSessionRef: string,\n driver: DelegationResumeDriver,\n ): void {\n const controller = new AbortController()\n this.controllers.set(record.taskId, controller)\n void this.driveResume(record, detachedSessionRef, driver, controller)\n }\n\n private async driveResume(\n record: DelegationRecord,\n detachedSessionRef: string,\n driver: DelegationResumeDriver,\n controller: AbortController,\n ): Promise<void> {\n const intervalMs = driver.intervalMs ?? 5000\n const resumeStartMs = Date.parse(this.now())\n const ctx: DelegationResumeContext = {\n signal: controller.signal,\n report: (progress) => {\n if (currentStatus(record) !== 'running') return\n record.progress = progress\n this.persist(record)\n },\n }\n try {\n while (!controller.signal.aborted && currentStatus(record) === 'running') {\n const tick = await driver.tick({ record: structuredClone(record), detachedSessionRef }, ctx)\n if (currentStatus(record) === 'cancelled') return\n if (tick.state === 'completed') {\n this.appendResumeSpan(record, detachedSessionRef, resumeStartMs)\n record.status = 'completed'\n record.completedAt = this.now()\n record.result = {\n profile: record.profile,\n output: tick.output,\n } as DelegationResultPayload\n if (tick.costUsd !== undefined) record.costUsd = tick.costUsd\n this.persist(record)\n this.enforceRetention()\n return\n }\n if (tick.state === 'failed') {\n this.appendResumeSpan(record, detachedSessionRef, resumeStartMs, tick.error.message)\n record.status = 'failed'\n record.completedAt = this.now()\n record.error = tick.error\n this.persist(record)\n this.enforceRetention()\n return\n }\n await abortableDelay(intervalMs, controller.signal)\n }\n } catch (err) {\n if (currentStatus(record) === 'cancelled') return\n this.appendResumeSpan(record, detachedSessionRef, resumeStartMs, errorToShape(err).message)\n record.status = 'failed'\n record.completedAt = this.now()\n record.error = errorToShape(err)\n this.persist(record)\n this.enforceRetention()\n } finally {\n this.controllers.delete(record.taskId)\n }\n }\n\n /**\n * Journal the resumed segment of a detached run as one compact span. The\n * resume driver re-attaches after a process restart, so the original\n * process's loop events are gone — this span records the post-restart\n * observation window (re-attach → terminal tick) under the\n * `'detached-resume'` driver tag, keeping restored delegations observable\n * in the journal alongside trace-carrying live runs.\n */\n private appendResumeSpan(\n record: DelegationRecord,\n detachedSessionRef: string,\n startMs: number,\n error?: string,\n ): void {\n this.appendTrace(record, [\n {\n spanId: generateDelegationSpanId(),\n name: 'loop',\n kind: 'loop',\n startMs,\n endMs: Date.parse(this.now()),\n meta: {\n 'tangle.loop.driver': 'detached-resume',\n 'tangle.loop.detached_session_ref': detachedSessionRef,\n ...(error !== undefined ? { 'tangle.loop.error': error } : {}),\n },\n },\n ])\n }\n\n private persist(record: DelegationRecord): Promise<void> {\n if (this.persistFailure) return Promise.resolve()\n const snapshot = structuredClone(record)\n this.persistTail = this.persistTail.then(async () => {\n if (this.persistFailure) return\n try {\n await this.store.upsert(snapshot)\n } catch (err) {\n this.failPersistence(err)\n }\n })\n return this.persistTail\n }\n\n private persistRemoval(taskIds: string[]): Promise<void> | undefined {\n if (this.persistFailure || taskIds.length === 0) return undefined\n this.persistTail = this.persistTail.then(async () => {\n if (this.persistFailure) return\n try {\n await this.store.remove(taskIds)\n } catch (err) {\n this.failPersistence(err)\n }\n })\n return this.persistTail\n }\n\n private failPersistence(cause: unknown): void {\n if (this.persistFailure) return\n const error =\n cause instanceof DelegationPersistenceError\n ? cause\n : new DelegationPersistenceError(\n `DelegationTaskQueue: store write failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n { cause },\n )\n this.persistFailure = error\n this.onPersistError(error)\n }\n\n private enforceRetention(): Promise<void> | undefined {\n if (!Number.isFinite(this.maxTerminalRecords)) return undefined\n const terminal: DelegationRecord[] = []\n for (const record of this.records.values()) {\n if (isTerminal(record.status)) terminal.push(record)\n }\n const excess = terminal.length - this.maxTerminalRecords\n if (excess <= 0) return undefined\n terminal.sort((a, b) =>\n (a.completedAt ?? a.startedAt).localeCompare(b.completedAt ?? b.startedAt),\n )\n const evicted = terminal.slice(0, excess)\n for (const record of evicted) {\n this.records.delete(record.taskId)\n if (\n record.idempotencyKey &&\n this.byIdempotencyKey.get(record.idempotencyKey) === record.taskId\n ) {\n this.byIdempotencyKey.delete(record.idempotencyKey)\n }\n }\n return this.persistRemoval(evicted.map((record) => record.taskId))\n }\n}\n\nfunction isTerminal(status: DelegationStatus): boolean {\n return status === 'completed' || status === 'failed' || status === 'cancelled'\n}\n\nfunction currentStatus(record: DelegationRecord): DelegationStatus {\n return record.status\n}\n\nfunction clampLimit(raw: number | undefined): number {\n if (!Number.isFinite(raw)) return 50\n const n = Math.trunc(raw as number)\n if (n <= 0) return 50\n return Math.min(n, 500)\n}\n\nfunction abortableDelay(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal.aborted) {\n resolve()\n return\n }\n const onAbort = () => {\n clearTimeout(timer)\n resolve()\n }\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n signal.addEventListener('abort', onAbort, { once: true })\n })\n}\n\nfunction toStatusResult(\n record: DelegationRecord,\n opts?: { includeTrace?: boolean },\n): DelegationStatusResult {\n const out: DelegationStatusResult = {\n taskId: record.taskId,\n profile: record.profile,\n status: record.status,\n startedAt: record.startedAt,\n }\n if (record.progress) out.progress = record.progress\n if (record.result) out.result = record.result\n if (record.error) out.error = record.error\n if (record.costUsd !== undefined) out.costUsd = record.costUsd\n if (record.completedAt) out.completedAt = record.completedAt\n if (record.traceId !== undefined) out.traceId = record.traceId\n if (record.parentSpanId !== undefined) out.parentSpanId = record.parentSpanId\n if (opts?.includeTrace === true && record.trace && record.trace.length > 0) {\n out.trace = record.trace.map((span) => ({ ...span }))\n if (record.traceTruncated) out.traceTruncated = true\n }\n return out\n}\n\nfunction toHistoryEntry(record: DelegationRecord): DelegationHistoryEntry {\n const entry: DelegationHistoryEntry = {\n taskId: record.taskId,\n profile: record.profile,\n args: record.args,\n status: record.status,\n startedAt: record.startedAt,\n hasTrace: record.trace !== undefined && record.trace.length > 0,\n }\n if (record.namespace) entry.namespace = record.namespace\n if (record.completedAt) entry.completedAt = record.completedAt\n if (record.costUsd !== undefined) entry.costUsd = record.costUsd\n if (record.feedback.length > 0) entry.feedback = [...record.feedback]\n if (record.traceId !== undefined) entry.traceId = record.traceId\n return entry\n}\n\nfunction errorToShape(err: unknown): DelegationError {\n if (err instanceof Error) {\n return { message: err.message, kind: err.name || 'Error' }\n }\n return { message: String(err), kind: 'NonError' }\n}\n\nfunction randomTaskId(): string {\n // Caller-stable id: `dlg-${timestamp}-${random}`. The timestamp portion\n // makes lexicographic sort match chronological order in history queries\n // even when the system clock skews under the second.\n const t = Date.now().toString(36)\n const r = Math.random().toString(36).slice(2, 10)\n return `dlg-${t}-${r}`\n}\n\n/**\n * Best-effort stable hash for use as `idempotencyKey`. Not cryptographic;\n * collisions only affect dedupe, never correctness.\n *\n * @experimental\n */\nexport function hashIdempotencyInput(value: unknown): string {\n let str: string\n try {\n str = JSON.stringify(canonicalize(value))\n } catch {\n str = String(value)\n }\n // FNV-1a 32-bit\n let h = 0x811c9dc5\n for (let i = 0; i < str.length; i += 1) {\n h ^= str.charCodeAt(i)\n h = Math.imul(h, 0x01000193)\n }\n return (h >>> 0).toString(16).padStart(8, '0')\n}\n\nfunction canonicalize(value: unknown): unknown {\n if (value === null || typeof value !== 'object') return value\n if (Array.isArray(value)) return value.map(canonicalize)\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => a.localeCompare(b))\n const out: Record<string, unknown> = {}\n for (const [k, v] of entries) out[k] = canonicalize(v)\n return out\n}\n\n// Re-exports re-used by the feedback-store + handler glue. Kept local so\n// consumers of the queue don't have to import from `./types` separately.\nexport type {\n DelegateCodeArgs,\n DelegateCodeResult,\n DelegateFeedbackArgs,\n DelegateFeedbackResult,\n DelegateResearchArgs,\n DelegateResearchResult,\n DelegateUiAuditArgs,\n DelegateUiAuditConfig,\n DelegateUiAuditResult,\n DelegateUiAuditRoute,\n DelegationError,\n DelegationFeedbackSnapshot,\n DelegationHistoryArgs,\n DelegationHistoryEntry,\n DelegationHistoryResult,\n DelegationProfile,\n DelegationProgress,\n DelegationResultPayload,\n DelegationStatus,\n DelegationStatusArgs,\n DelegationStatusResult,\n UiAuditorDelegationOutput,\n} from './types'\n","/**\n * @experimental\n *\n * The recursive driver-executor — the seam that lets a SPAWNED child be a DRIVER, so\n * agents drive agents drive agents over the one keystone atom.\n *\n * A spawned child resolves through the open registry to an `Executor`; the built-in\n * executors (router/inline, sandbox, cli) are LEAVES — `execute(task, signal)` runs the\n * work and settles. This executor is the recursive case: on `execute`, it mounts a NESTED\n * `Scope` (the scope hands it the mount via the `nested-scope` seam) over the SAME\n * conserved pool + shared journal/blobs + the same open registry, one `depth` deeper, then\n * runs the wrapped driver `Agent.act(task, nestedScope)`. The driver spawns its own\n * children into that nested scope; each resolves to EITHER a leaf executor (a worker child)\n * OR this same driver-executor (a driver child) — recursively. So a driver spawns a driver\n * spawns a worker, all on one budget-conserving tree.\n *\n * Why this preserves every keystone invariant (the scope owns the sharing; this executor\n * only runs the driver over what the scope mounts):\n * - Conserved budget: the nested scope reserves from the SAME `BudgetPool` the root owns\n * (the scope mounts it over `args.pool`), so `Σk` is conserved ACROSS depth by\n * construction — a deep tree cannot overspend the root ceiling (reserve-on-spawn fails\n * closed at any depth).\n * - Journal: the nested scope writes to its OWN tree key (`${journalRoot}/${nodeId}`) so\n * its cursor `seq`s never collide with the parent's in the per-tree uniqueness guard,\n * while every nested tree shares the one `SpawnJournal` — the whole recursion is one\n * journal, queryable tree by tree.\n * - Settlement bubbling: the driver child settles into its PARENT scope with the conserved\n * spend summed off its nested tree's settled events, so the parent's pool reconcile +\n * the supervisor's `spentTotal` see the whole sub-tree's spend rolled up — settlements\n * bubble to the root.\n * - Depth ceiling: the nested scope runs at `depth+1`, so the supervisor's `maxDepth`\n * (paired with the conserved pool per R3) fails a spawn closed once the recursion is too\n * deep — exactly as it does for a flat tree.\n *\n * Layering: pure keystone composition. It reuses the scope's `NestedScopeSeam` + the shared\n * `SpawnJournal`; it builds NO new budget, journal, or selection logic. The recursion rides\n * the existing atom.\n */\n\nimport { ValidationError } from '../../errors'\nimport { type NestedScopeSeam, nestedScopeSeamKey } from './scope'\nimport type {\n Agent,\n AgentSpec,\n DefaultVerdict,\n ExecutorContext,\n ExecutorFactory,\n ExecutorRegistry,\n ExecutorResult,\n Scope,\n SpawnEvent,\n SpawnJournal,\n Spend,\n} from './types'\n\n/** The runtime tag the registry maps a driver child to. */\nexport const driverRuntime = 'driver' as const\n\n/** The metadata marker on a driver child's spec the recursive registry routes on. */\nconst driverRole = 'driver'\n\n/** A driver child's spec carries the `Agent` to run inside the nested scope. */\ninterface DriverSpec extends AgentSpec {\n readonly driver: Agent<unknown, unknown>\n /** The shared journal the nested tree is one tree key inside (so the executor can\n * begin its nested tree + sum its spend off the same record). */\n readonly journal: SpawnJournal\n}\n\n/**\n * Mark + carry a driver `Agent` so the recursive registry resolves it to the\n * driver-executor. The returned agent is SPAWNED (never run directly): its\n * `executorSpec` is marked `role: 'driver'` and carries the driver agent + the shared\n * journal so the executor can run its `act` inside a nested scope. `act` fails loud if\n * called directly — a driver child runs THROUGH its nested-scope executor, never as a root.\n */\nexport function driverChild<Out>(\n name: string,\n driver: Agent<unknown, Out>,\n journal: SpawnJournal,\n): Agent<unknown, Out> {\n const spec: DriverSpec = {\n profile: { name, metadata: { role: driverRole } } as AgentSpec['profile'],\n harness: null,\n driver: driver as Agent<unknown, unknown>,\n journal,\n }\n return {\n name,\n executorSpec: spec,\n act(): Promise<Out> {\n throw new ValidationError(\n `driverChild: \"${name}\" was run directly; a driver child runs through its nested-scope executor`,\n )\n },\n } as Agent<unknown, Out> & { executorSpec: AgentSpec }\n}\n\n/** True when a spec is a driver child (carries the role marker + a driver Agent). */\nexport function isDriverSpec(spec: AgentSpec): spec is DriverSpec {\n const role = (spec.profile.metadata as { role?: unknown } | undefined)?.role\n if (role !== driverRole) return false\n const driver = (spec as { driver?: unknown }).driver\n if (!isAgent(driver)) {\n throw new ValidationError(\n 'driverExecutor: a driver-role spec must carry a `driver` Agent to run inside its nested scope',\n )\n }\n return true\n}\n\n/**\n * The recursive driver-executor factory. `withDriverExecutor` routes a child marked\n * `role: 'driver'` here; any other child resolves to a leaf built-in. On `execute`, it\n * reads the `nested-scope` seam the SCOPE seeded, mounts a nested `Scope` one `depth`\n * deeper over the shared pool/journal/blobs/registry, runs the driver\n * `Agent.act(task, nestedScope)`, and reports the conserved spend summed off the nested\n * tree's settled events — so the parent scope's reconcile rolls the whole sub-tree's spend\n * into the conserved total.\n *\n * A `down` from the nested driver (a thrown `act` or an aborted scope) propagates as a\n * thrown executor, which the parent scope types into a `down` settlement — the same\n * fail-loud-into-typed-down discipline a leaf gets.\n */\nexport const driverExecutorFactory: ExecutorFactory<unknown> = (spec, ctx) => {\n if (!isDriverSpec(spec)) {\n throw new ValidationError(\n 'driverExecutorFactory: spec is not a driver child (no role:\"driver\" marker)',\n )\n }\n const driver = spec.driver\n const journal = spec.journal\n const seam = readNestedScopeSeam(ctx)\n\n let artifact: ExecutorResult<unknown> | undefined\n // The nested subtree's driver INFERENCE, cached so the parent re-homes it on settle. Computed\n // on BOTH the success AND crash paths (metered events are durable in the nested tree regardless),\n // so a sub-driver that crashes mid-run still re-homes its partial inference — pool + journal agree.\n let meteredSpend: Spend | undefined\n\n return {\n runtime: driverRuntime,\n async execute(task, signal): Promise<ExecutorResult<unknown>> {\n // The nested tree key namespaces this driver's children inside the ONE shared\n // journal, so its cursor seqs never collide with the parent's per-tree guard.\n const nestedRoot = nestedTreeKey(seam, journal)\n await journal.beginTree(nestedRoot, new Date(0).toISOString())\n\n const nestedScope: Scope<unknown> = seam.mount(nestedRoot, signal)\n\n try {\n // Run the driver. Its `act` spawns children into the nested scope and reacts via\n // `scope.next()`; a thrown `act` propagates so the PARENT scope types it into a down.\n const out = await driver.act(task, nestedScope)\n\n // Read the nested tree's events ONCE. Two roll-ups, kept separate so the conserved invariant\n // is not double-charged:\n // - `spent` = settled child WORK → reconciled against THIS driver's reservation (as before).\n // - `metered` = the nested subtree's driver INFERENCE → re-homed by the parent scope as a\n // `metered` event, NOT reconciled (already pool-debited live via `observe`).\n const events = await loadTreeEvents(journal, nestedRoot)\n const settled = events.filter(isSettled)\n meteredSpend = nonZeroOrUndef(sumMetered(events))\n // Completion-oracle propagation: a driver \"delivered\" iff at least one of its DIRECT\n // children settled `valid` (the child its keep-best finalize returns). Deriving the\n // driver child's verdict this way composes delivery UP the recursion — a sub-driver is\n // `valid` only when it itself selected a delivered child — so a node never settles\n // \"done = delivered\" on a sub-tree that delivered nothing (Foreman's 0/18 lesson).\n const verdict = deriveDeliveryVerdict(settled)\n artifact = {\n outRef: `${driverRuntime}:${nestedRoot}`,\n out,\n spent: sumSpend(settled),\n ...(verdict ? { verdict } : {}),\n }\n return artifact\n } catch (err) {\n // Crash mid-run: the nested tree still holds the durable `metered` events the sub-driver\n // already wrote (pool already debited them). Cache them so the parent's down-path re-home\n // lands the partial inference and the two ledgers stay in agreement. A missing tree must\n // not mask the original error.\n meteredSpend = await safeSumMetered(journal, nestedRoot)\n throw err\n }\n },\n metered(): Spend | undefined {\n return meteredSpend\n },\n teardown(): Promise<{ destroyed: boolean }> {\n // The nested scope's live children are torn down by the driver's own `act` discipline\n // (it drains to settlement) and by the parent's abort cascade through `signal`; there\n // is no separate box/process to reap here.\n return Promise.resolve({ destroyed: true })\n },\n resultArtifact(): ExecutorResult<unknown> {\n if (!artifact) {\n throw new ValidationError('driverExecutor: resultArtifact() read before execute()')\n }\n return artifact\n },\n }\n}\n\n/**\n * Register the driver-executor so a child marked `role: 'driver'` resolves to it. The base\n * registry resolves by harness alone (it does not read `role`), so a recursive run needs a\n * registry that routes the driver tag here FIRST. Returns a registry decorator: a\n * driver-role spec → the driver-executor; everything else → the base registry's resolution\n * (leaf built-ins + BYO).\n */\nexport function withDriverExecutor(base: ExecutorRegistry): ExecutorRegistry {\n return {\n register: base.register.bind(base),\n resolve<Out>(spec: AgentSpec) {\n const role = (spec.profile.metadata as { role?: unknown } | undefined)?.role\n if (role === driverRole && !spec.executor) {\n return { succeeded: true as const, value: driverExecutorFactory as ExecutorFactory<Out> }\n }\n return base.resolve<Out>(spec)\n },\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────\n\n/** Mint a unique nested-tree key under the parent's journal root. Uses the parent's\n * `journalRoot` + a per-journal monotonic ordinal so two sibling driver trees never\n * collide their keys (each driver child mints exactly one nested tree). */\nfunction nestedTreeKey(seam: NestedScopeSeam, journal: SpawnJournal): string {\n return `${seam.journalRoot}/d${nextNestOrdinal(journal)}`\n}\n\n/** Per-journal monotonic nest counter — keyed on the journal instance so a single run's\n * nested-tree keys are unique without a shared module global. */\nconst nestCounters = new WeakMap<SpawnJournal, { n: number }>()\nfunction nextNestOrdinal(journal: SpawnJournal): number {\n let c = nestCounters.get(journal)\n if (!c) {\n c = { n: 0 }\n nestCounters.set(journal, c)\n }\n return c.n++\n}\n\n/** The nested tree's full event list — the one evidence the spend, verdict, AND driver-inference\n * roll-ups read off the same journal the supervisor sums. */\nasync function loadTreeEvents(journal: SpawnJournal, nestedRoot: string): Promise<SpawnEvent[]> {\n const events = await journal.loadTree(nestedRoot)\n if (events === undefined) {\n throw new ValidationError(\n `driverExecutor: nested tree '${nestedRoot}' missing from the journal after run (corrupted log)`,\n )\n }\n return events\n}\n\nfunction isSettled(ev: SpawnEvent): ev is Extract<SpawnEvent, { kind: 'settled' }> {\n return ev.kind === 'settled'\n}\n\n/** Sum the conserved spend over the nested tree's settled events — the honest per-channel\n * roll-up of the whole sub-tree's child WORK. */\nfunction sumSpend(settled: ReadonlyArray<{ spent: Spend }>): Spend {\n const total: Spend = { iterations: 0, tokens: { input: 0, output: 0 }, usd: 0, ms: 0 }\n for (const ev of settled) {\n total.iterations += ev.spent.iterations\n total.tokens.input += ev.spent.tokens.input\n total.tokens.output += ev.spent.tokens.output\n total.usd += ev.spent.usd\n total.ms += ev.spent.ms\n }\n return total\n}\n\n/** Sum the nested tree's `metered` events — the sub-tree's whole driver INFERENCE (this driver's\n * own turns + any sub-driver inference already re-homed into this tree). Re-homed up to the parent\n * as one `metered` event; never reconciled (already pool-debited live via `observe`). */\nfunction sumMetered(events: ReadonlyArray<SpawnEvent>): Spend {\n const total: Spend = { iterations: 0, tokens: { input: 0, output: 0 }, usd: 0, ms: 0 }\n for (const ev of events) {\n if (ev.kind !== 'metered') continue\n total.iterations += ev.spend.iterations\n total.tokens.input += ev.spend.tokens.input\n total.tokens.output += ev.spend.tokens.output\n total.usd += ev.spend.usd\n total.ms += ev.spend.ms\n }\n return total\n}\n\nfunction isNonZeroSpend(s: Spend): boolean {\n return s.iterations > 0 || s.tokens.input > 0 || s.tokens.output > 0 || s.usd > 0 || s.ms > 0\n}\n\n/** A spend, or `undefined` when it is all-zero — so `metered()` returns undefined for a driver\n * whose sub-tree did no inference (and the parent journals no empty `metered` event). */\nfunction nonZeroOrUndef(s: Spend): Spend | undefined {\n return isNonZeroSpend(s) ? s : undefined\n}\n\n/** Sum the nested tree's metered events, tolerating a missing tree (a crash before `beginTree`\n * landed) — never throw here, or it would mask the original `act` error on the crash path. */\nasync function safeSumMetered(\n journal: SpawnJournal,\n nestedRoot: string,\n): Promise<Spend | undefined> {\n try {\n return nonZeroOrUndef(sumMetered(await loadTreeEvents(journal, nestedRoot)))\n } catch {\n return undefined\n }\n}\n\n/** Derive the driver child's delivery verdict from its DIRECT children's settlements:\n * `valid` iff any direct child settled `done` AND `valid` (the keep-best finalize's pick);\n * `score` = the best delivered score. Returns `undefined` when no child settled at all (the\n * driver itself produced nothing to bubble a verdict from). Fail-closed: a child whose verdict\n * carried no `valid` counts as not-delivered. */\nfunction deriveDeliveryVerdict(\n settled: ReadonlyArray<{ status: 'done' | 'down'; verdict?: DefaultVerdict }>,\n): DefaultVerdict | undefined {\n let sawChild = false\n let anyValid = false\n let bestValidScore: number | undefined\n let bestDoneScore: number | undefined\n for (const ev of settled) {\n sawChild = true\n if (ev.status !== 'done') continue\n const score = ev.verdict?.score\n if (score !== undefined && (bestDoneScore === undefined || score > bestDoneScore)) {\n bestDoneScore = score\n }\n if (ev.verdict?.valid === true) {\n anyValid = true\n if (score !== undefined && (bestValidScore === undefined || score > bestValidScore)) {\n bestValidScore = score\n }\n }\n }\n if (!sawChild) return undefined\n return {\n valid: anyValid,\n score: anyValid ? (bestValidScore ?? 1) : (bestDoneScore ?? 0),\n }\n}\n\nfunction readNestedScopeSeam(ctx: ExecutorContext): NestedScopeSeam {\n const seam = ctx.seams[nestedScopeSeamKey] as NestedScopeSeam | undefined\n if (!seam || typeof seam.mount !== 'function') {\n throw new ValidationError(\n `driverExecutor: missing required seam \"${nestedScopeSeamKey}\" — a driver child must be spawned through a Scope that seeds it (the keystone scope does)`,\n )\n }\n return seam\n}\n\nfunction isAgent(value: unknown): value is Agent<unknown, unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { act?: unknown }).act === 'function' &&\n typeof (value as { name?: unknown }).name === 'string'\n )\n}\n","/**\n * @experimental\n *\n * `createInMemoryRunContext` — the one-call bundle of the in-memory stores a\n * `createSupervisor().run(root, task, opts)` needs: a fresh `InMemorySpawnJournal`\n * (the event-sourced spawn log), a fresh `InMemoryResultBlobStore` (the\n * content-addressed `outRef` payload store the driver's `observe`/`finalize` reads\n * settled outputs through), and a fresh `createExecutorRegistry()` (the open\n * `AgentSpec → Executor` resolver).\n *\n * It exists to kill the boilerplate every offline/local supervised run repeats by\n * hand — three constructors threaded into `SupervisorOpts` — and to single-source the\n * ONE wiring invariant that is easy to get wrong: when the root is the recursive\n * `driverAgent` LLM-driver brain AND it may spawn DRIVER children (agents\n * driving agents), the registry MUST be wrapped with `withDriverExecutor` so a\n * `role: 'driver'` child resolves to the nested-scope executor — and that SAME blob\n * store MUST be the one passed to `driverAgent({ blobs })`, or the driver\n * reads from a different store than the scope writes to. Pass `{ withDriver: true }`\n * and reuse the returned `blobs` for both.\n *\n * The spread shape matches `SupervisorOpts` exactly, so the call site reads:\n * const run = createInMemoryRunContext()\n * await createSupervisor().run(root, task, { budget, runId, ...run })\n */\n\nimport { InMemoryResultBlobStore, InMemorySpawnJournal } from '../../durable/spawn-journal'\nimport { withDriverExecutor } from './driver-executor'\nimport { createExecutorRegistry } from './runtime'\nimport type { ExecutorRegistry, ResultBlobStore, SpawnJournal } from './types'\n\n/** Options for the in-memory run context. */\nexport interface InMemoryRunContextOptions {\n /**\n * Wrap the executor registry with `withDriverExecutor` so a spawned child marked\n * `role: 'driver'` resolves to the recursive driver-executor (agents driving agents\n * over a nested `Scope` on the same conserved pool). Leave `false` for a flat tree of\n * leaf workers. Default `false`.\n */\n readonly withDriver?: boolean\n}\n\n/**\n * The bundle of stores a supervised run needs, shaped to spread into `SupervisorOpts`.\n * The fields are exactly `SupervisorOpts`' `journal` / `blobs` / `executors`.\n */\nexport interface InMemoryRunContext {\n readonly journal: SpawnJournal\n readonly blobs: ResultBlobStore\n readonly executors: ExecutorRegistry\n}\n\n/**\n * Build a fresh in-memory run context. Every call returns NEW stores (no shared global\n * state between runs), so two runs never cross-contaminate their journals/blobs.\n */\nexport function createInMemoryRunContext(opts: InMemoryRunContextOptions = {}): InMemoryRunContext {\n const base = createExecutorRegistry()\n return {\n journal: new InMemorySpawnJournal(),\n blobs: new InMemoryResultBlobStore(),\n executors: opts.withDriver ? withDriverExecutor(base) : base,\n }\n}\n","/**\n * @experimental\n *\n * Serve the coordination verbs (spawn_agent / await_event / observe_agent / steer_agent / stop)\n * as a real HTTP MCP server over a LIVE `Scope`. This is the keystone that lets a coding-harness\n * agent (opencode via the cli-bridge, claude-code, codex) BE the supervisor: it mounts this MCP\n * (`mcp.mcpServers.coordination`) and calls `spawn_agent` 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\nimport { createServer, type Server } from 'node:http'\nimport { createMcpServer } from '../../mcp/server'\nimport {\n type AnalystRegistry,\n type CoordinationEvent,\n type CoordinationTools,\n createCoordinationTools,\n type MakeWorkerAgent,\n type QuestionPolicy,\n} from '../../mcp/tools/coordination'\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 /** The coordination tools' settled-worker ledger (for the driver's finalize). */\n settled(): ReadonlyArray<{ status: string; score?: number; valid?: boolean; outRef?: string }>\n isStopped(): boolean\n /** The full ordered bus-event log — observability audit + replay trail. */\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 close(): Promise<void>\n}\n\n/** Stand up the coordination MCP over a live scope. The HOST address is `127.0.0.1` (the bridge runs\n * opencode locally, same host); pass `host` to bind elsewhere when the harness is remote. */\nexport async function serveCoordinationMcp(opts: {\n scope: Scope<unknown>\n blobs: ResultBlobStore\n makeWorkerAgent: MakeWorkerAgent\n perWorker: Budget\n /** Hard cap on simultaneously-LIVE workers — `spawn_agent` fails closed once this many are in\n * flight (a concurrency fence on top of the conserved-pool fence). Omit/`<= 0` = no cap. */\n maxLiveWorkers?: number\n port?: number\n host?: string\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>\n /** Pass-through subscriber for every bus event (settled / question / finding). */\n onEvent?: (event: CoordinationEvent) => void | Promise<void>\n questionPolicy?: QuestionPolicy\n}): Promise<CoordinationMcpHandle> {\n const coord = createCoordinationTools({\n scope: opts.scope,\n blobs: opts.blobs,\n makeWorkerAgent: opts.makeWorkerAgent,\n perWorker: opts.perWorker,\n ...(opts.maxLiveWorkers !== undefined ? { maxLiveWorkers: opts.maxLiveWorkers } : {}),\n ...(opts.analysts ? { analysts: opts.analysts } : {}),\n ...(opts.analyzeOnSettle ? { analyzeOnSettle: opts.analyzeOnSettle } : {}),\n ...(opts.onEvent ? { onEvent: opts.onEvent } : {}),\n ...(opts.questionPolicy ? { questionPolicy: opts.questionPolicy } : {}),\n })\n const mcp = createMcpServer({ extraTools: coord.tools, serverName: 'coordination' })\n const host = opts.host ?? '127.0.0.1'\n\n const server: Server = createServer((req, res) => {\n if (req.method !== 'POST') {\n res.writeHead(405, { allow: 'POST' })\n res.end()\n return\n }\n let body = ''\n req.on('data', (c) => {\n body += c\n })\n req.on('end', () => {\n void (async () => {\n try {\n const message = JSON.parse(body) as Parameters<typeof mcp.handle>[0]\n const response = await mcp.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 // A malformed request is the client's to recover from — a typed JSON-RPC error, not a crash.\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 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 return {\n url: `http://${host}:${port}/mcp`,\n port,\n settled: () => coord.settled(),\n isStopped: () => coord.isStopped(),\n history: () => coord.history(),\n stats: () => coord.stats(),\n raiseFinding: (finding) => coord.raiseFinding(finding),\n close: () =>\n new Promise<void>((resolve) => {\n server.close(() => resolve())\n }),\n }\n}\n","/**\n * @experimental\n *\n * Stdio JSON-RPC MCP server exposing the delegation tools to sandbox\n * coding-harness agents (claude-code, codex, opencode, ...): the generic\n * `delegate` verb plus the queue-bound `delegate_feedback`,\n * `delegation_status`, and `delegation_history`. `delegate_ui_audit` is served\n * when a `uiAuditorDelegate` is wired.\n *\n * The server is transport-bound but topology-free: tool execution is\n * delegated to handler functions composed from a queue, a feedback\n * store, and the wired run delegates. Consumers wire those at\n * construction time. The `agent-runtime-mcp` bin serves the generic\n * `delegate` verb over a real sandbox client when `MCP_ENABLE_DELEGATE=1`.\n *\n * Wire protocol: line-delimited JSON-RPC 2.0 over stdio. Each line is\n * one request; each response is one line. `tools/list` and `tools/call`\n * mirror the MCP 2024-11-05 spec; we do not pull in\n * `@modelcontextprotocol/sdk` to keep the dependency footprint zero.\n */\n\nimport { createInterface, type Interface as ReadlineInterface } from 'node:readline'\nimport { Readable, Writable } from 'node:stream'\nimport { ValidationError } from '../errors'\nimport type { UiAuditorDelegate } from './delegates'\nimport { type FeedbackStore, InMemoryFeedbackStore } from './feedback-store'\nimport { DelegationTaskQueue } from './task-queue'\nimport {\n createDelegateHandler,\n DELEGATE_DESCRIPTION,\n DELEGATE_INPUT_SCHEMA,\n DELEGATE_TOOL_NAME,\n type DelegateHandlerOptions,\n} from './tools/delegate'\nimport {\n createDelegateFeedbackHandler,\n DELEGATE_FEEDBACK_DESCRIPTION,\n DELEGATE_FEEDBACK_INPUT_SCHEMA,\n DELEGATE_FEEDBACK_TOOL_NAME,\n} from './tools/delegate-feedback'\nimport {\n createDelegateUiAuditHandler,\n DELEGATE_UI_AUDIT_DESCRIPTION,\n DELEGATE_UI_AUDIT_INPUT_SCHEMA,\n DELEGATE_UI_AUDIT_TOOL_NAME,\n} from './tools/delegate-ui-audit'\nimport {\n createDelegationHistoryHandler,\n DELEGATION_HISTORY_DESCRIPTION,\n DELEGATION_HISTORY_INPUT_SCHEMA,\n DELEGATION_HISTORY_TOOL_NAME,\n} from './tools/delegation-history'\nimport {\n createDelegationStatusHandler,\n DELEGATION_STATUS_DESCRIPTION,\n DELEGATION_STATUS_INPUT_SCHEMA,\n DELEGATION_STATUS_TOOL_NAME,\n} from './tools/delegation-status'\nimport type { TraceContext } from './trace-propagation'\n\n/** @experimental */\nexport interface McpServerOptions {\n /**\n * Required to enable `delegate` — the ONE generic delegation verb. Inject the supervisor\n * substrate: its brain `router`, the worker `backend`, and the completion `deliverable`. The\n * supervisor AUTHORS its own worker from the agent's intent, so there is no worker profile to\n * wire here.\n */\n delegateSupervisor?: DelegateHandlerOptions\n /**\n * Required to enable delegate_ui_audit. Wire one that closes over your\n * `runLoop` + `uiAuditorProfile` + a `SandboxClient` (the\n * canonical in-process choice is `createInProcessUiAuditClient` from\n * `@tangle-network/agent-runtime/profiles`) + your vision judge.\n */\n uiAuditorDelegate?: UiAuditorDelegate\n /** Override the default in-memory feedback store. */\n feedbackStore?: FeedbackStore\n /** Override the default in-memory task queue. */\n queue?: DelegationTaskQueue\n /**\n * Extra tools to serve alongside the delegation tools, for example\n * `createCoordinationTools(...).tools`. Registered after the built-ins; a\n * duplicate name throws so delegation tools cannot be shadowed silently.\n */\n extraTools?: McpToolDescriptor[]\n /**\n * Inherited trace identity (`readTraceContextFromEnv()`) stamped on every\n * record the DEFAULT queue creates. Ignored when `queue` is supplied —\n * pass `traceContext` to that queue's constructor instead.\n */\n traceContext?: TraceContext\n /** Server display name surfaced via `initialize`. Default `'agent-runtime-mcp'`. */\n serverName?: string\n /** Server version surfaced via `initialize`. Default = the package version baked at build time. */\n serverVersion?: string\n}\n\n/** @experimental */\nexport interface McpToolDescriptor {\n name: string\n description: string\n inputSchema: Record<string, unknown>\n handler: (raw: unknown) => Promise<unknown>\n}\n\n/** @experimental */\nexport interface McpServer {\n /** Tools currently registered (depend on which delegates were wired). */\n readonly tools: ReadonlyMap<string, McpToolDescriptor>\n /** The underlying queue — exposed so tests can introspect it. */\n readonly queue: DelegationTaskQueue\n /** The feedback store — exposed for the same reason. */\n readonly feedbackStore: FeedbackStore\n /** Handle a single parsed JSON-RPC message. Returns the response object (or `null` for notifications). */\n handle(message: JsonRpcMessage): Promise<JsonRpcResponse | null>\n /** Drive the server on a stdio-shaped transport until `stop()` is called. */\n serve(transport?: McpTransport): Promise<void>\n /** Stop a `serve` call. Subsequent requests are rejected. */\n stop(): void\n}\n\n/** @experimental */\nexport interface McpTransport {\n input: NodeJS.ReadableStream\n output: NodeJS.WritableStream\n}\n\n/** @experimental */\nexport interface JsonRpcMessage {\n jsonrpc: '2.0'\n id?: number | string | null\n method: string\n params?: unknown\n}\n\n/** @experimental */\nexport interface JsonRpcResponse {\n jsonrpc: '2.0'\n id: number | string | null\n result?: unknown\n error?: { code: number; message: string; data?: unknown }\n}\n\nconst PROTOCOL_VERSION = '2024-11-05'\nconst DEFAULT_SERVER_NAME = 'agent-runtime-mcp'\nconst DEFAULT_SERVER_VERSION = '0.22.0'\n\n/** @experimental */\nexport function createMcpServer(options: McpServerOptions = {}): McpServer {\n const queue =\n options.queue ??\n new DelegationTaskQueue(\n options.traceContext !== undefined ? { traceContext: options.traceContext } : {},\n )\n const feedbackStore = options.feedbackStore ?? new InMemoryFeedbackStore()\n const serverName = options.serverName ?? DEFAULT_SERVER_NAME\n const serverVersion = options.serverVersion ?? DEFAULT_SERVER_VERSION\n\n const tools = new Map<string, McpToolDescriptor>()\n\n if (options.delegateSupervisor) {\n tools.set(DELEGATE_TOOL_NAME, {\n name: DELEGATE_TOOL_NAME,\n description: DELEGATE_DESCRIPTION,\n inputSchema: DELEGATE_INPUT_SCHEMA as unknown as Record<string, unknown>,\n handler: createDelegateHandler(options.delegateSupervisor),\n })\n }\n if (options.uiAuditorDelegate) {\n tools.set(DELEGATE_UI_AUDIT_TOOL_NAME, {\n name: DELEGATE_UI_AUDIT_TOOL_NAME,\n description: DELEGATE_UI_AUDIT_DESCRIPTION,\n inputSchema: DELEGATE_UI_AUDIT_INPUT_SCHEMA as unknown as Record<string, unknown>,\n handler: createDelegateUiAuditHandler({ queue, delegate: options.uiAuditorDelegate }),\n })\n }\n tools.set(DELEGATE_FEEDBACK_TOOL_NAME, {\n name: DELEGATE_FEEDBACK_TOOL_NAME,\n description: DELEGATE_FEEDBACK_DESCRIPTION,\n inputSchema: DELEGATE_FEEDBACK_INPUT_SCHEMA as unknown as Record<string, unknown>,\n handler: createDelegateFeedbackHandler({ queue, store: feedbackStore }),\n })\n tools.set(DELEGATION_STATUS_TOOL_NAME, {\n name: DELEGATION_STATUS_TOOL_NAME,\n description: DELEGATION_STATUS_DESCRIPTION,\n inputSchema: DELEGATION_STATUS_INPUT_SCHEMA as unknown as Record<string, unknown>,\n handler: createDelegationStatusHandler({ queue }),\n })\n tools.set(DELEGATION_HISTORY_TOOL_NAME, {\n name: DELEGATION_HISTORY_TOOL_NAME,\n description: DELEGATION_HISTORY_DESCRIPTION,\n inputSchema: DELEGATION_HISTORY_INPUT_SCHEMA as unknown as Record<string, unknown>,\n handler: createDelegationHistoryHandler({ queue }),\n })\n for (const tool of options.extraTools ?? []) {\n if (tools.has(tool.name)) {\n throw new ValidationError(\n `createMcpServer: extra tool \"${tool.name}\" shadows a built-in tool`,\n )\n }\n tools.set(tool.name, tool)\n }\n\n let stopped = false\n let activeReadline: ReadlineInterface | undefined\n\n async function handle(message: JsonRpcMessage): Promise<JsonRpcResponse | null> {\n if (stopped) {\n return rpcError(message.id ?? null, -32099, 'server stopped')\n }\n if (message.method === 'initialize') {\n return rpcResult(message.id ?? null, {\n protocolVersion: PROTOCOL_VERSION,\n capabilities: { tools: {} },\n serverInfo: { name: serverName, version: serverVersion },\n })\n }\n if (message.method === 'notifications/initialized') {\n // MCP clients send this after the handshake; it has no id and expects\n // no response.\n return null\n }\n if (message.method === 'tools/list') {\n return rpcResult(message.id ?? null, {\n tools: [...tools.values()].map((tool) => ({\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n })),\n })\n }\n if (message.method === 'tools/call') {\n const params = (message.params ?? {}) as { name?: unknown; arguments?: unknown }\n const name = typeof params.name === 'string' ? params.name : ''\n const tool = tools.get(name)\n if (!tool) {\n return rpcError(message.id ?? null, -32601, `unknown tool: ${name}`)\n }\n try {\n const output = await tool.handler(params.arguments ?? {})\n return rpcResult(message.id ?? null, {\n content: [{ type: 'text', text: JSON.stringify(output) }],\n structuredContent: output,\n isError: false,\n })\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n const code = err instanceof TypeError || err instanceof RangeError ? -32602 : -32000\n return rpcError(message.id ?? null, code, reason)\n }\n }\n if (message.id === undefined || message.id === null) return null\n return rpcError(message.id, -32601, `unknown method: ${message.method}`)\n }\n\n async function serve(transport?: McpTransport): Promise<void> {\n const input = transport?.input ?? process.stdin\n const output = transport?.output ?? process.stdout\n const rl = createInterface({ input, crlfDelay: Number.POSITIVE_INFINITY })\n activeReadline = rl\n return new Promise<void>((resolve, reject) => {\n rl.on('line', (line) => {\n const trimmed = line.trim()\n if (!trimmed) return\n let parsed: JsonRpcMessage | undefined\n try {\n parsed = JSON.parse(trimmed) as JsonRpcMessage\n } catch (err) {\n writeResponse(output, rpcError(null, -32700, `parse error: ${(err as Error).message}`))\n return\n }\n if (!parsed || parsed.jsonrpc !== '2.0' || typeof parsed.method !== 'string') {\n writeResponse(output, rpcError(parsed?.id ?? null, -32600, 'invalid request'))\n return\n }\n void handle(parsed).then((response) => {\n if (response) writeResponse(output, response)\n })\n })\n rl.on('close', () => resolve())\n rl.on('error', (err) => reject(err))\n if (stopped) {\n rl.close()\n resolve()\n }\n })\n }\n\n function stop(): void {\n stopped = true\n activeReadline?.close()\n activeReadline = undefined\n }\n\n return {\n tools,\n queue,\n feedbackStore,\n handle,\n serve,\n stop,\n }\n}\n\nfunction rpcResult(id: number | string | null, result: unknown): JsonRpcResponse {\n return { jsonrpc: '2.0', id, result }\n}\n\nfunction rpcError(\n id: number | string | null,\n code: number,\n message: string,\n data?: unknown,\n): JsonRpcResponse {\n return {\n jsonrpc: '2.0',\n id,\n error: data === undefined ? { code, message } : { code, message, data },\n }\n}\n\nfunction writeResponse(output: NodeJS.WritableStream, response: JsonRpcResponse): void {\n output.write(`${JSON.stringify(response)}\\n`)\n}\n\n/**\n * In-process pair of `Readable` + `Writable` streams suitable for driving\n * `server.serve(...)` from a test. Returns the agent-side stream (the\n * client writes to it) and the server-side stream (the test reads from it).\n *\n * @experimental\n */\nexport function createInProcessTransport(): {\n transport: McpTransport\n clientWrite(line: string): void\n clientClose(): void\n readServer(): Promise<JsonRpcResponse[]>\n} {\n const responses: JsonRpcResponse[] = []\n const input = new Readable({ read() {} })\n const output = new Writable({\n write(chunk, _enc, cb) {\n const text = chunk.toString('utf8')\n for (const line of text.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n try {\n responses.push(JSON.parse(trimmed) as JsonRpcResponse)\n } catch {\n // Non-JSON output should never appear; drop it silently in the\n // test transport rather than crashing.\n }\n }\n cb()\n },\n })\n return {\n transport: { input, output },\n clientWrite(line: string) {\n input.push(`${line}\\n`)\n },\n clientClose() {\n input.push(null)\n },\n async readServer() {\n // Yield to the event loop a few times so async handlers drain.\n for (let i = 0; i < 5; i += 1) await new Promise((r) => setImmediate(r))\n return [...responses]\n },\n }\n}\n","/**\n * `supervise` — the one-call \"just invoke the supervisor\". Builds + runs a supervisor from its\n * profile with sensible defaults, so the common case is `supervise(profile, task, { backend, budget })`\n * instead of hand-wiring `blobs` / `perWorker` / `journal` / `executors` / `maxDepth`. The raw seams\n * (`supervisorAgent` + `createSupervisor().run`) stay available for power use.\n *\n * `workerFromBackend` derives the worker seam (`makeWorkerAgent`) from a backend config + an optional\n * completion oracle — so \"where the workers run\" is one data choice, not a hand-rolled factory.\n */\nimport type { AgentProfile } from '@tangle-network/sandbox'\nimport { ValidationError } from '../../errors'\nimport type { MakeWorkerAgent } from '../../mcp/tools/coordination'\nimport type { RouterConfig } from '../router-client'\nimport type { ToolLoopChat } from '../tool-loop'\nimport { type DeliverableSpec, gateOnDeliverable } from './completion-gate'\nimport { assertModelAllowed } from './model-policy'\nimport { createInMemoryRunContext } from './run-context'\nimport { createExecutor, type ExecutorConfig } from './runtime'\nimport { createSupervisor } from './supervisor'\nimport { type DriveHarness, type SupervisorProfile, supervisorAgent } from './supervisor-agent'\nimport type { Agent, AgentSpec, Budget, ExecutorContext, ResultBlobStore } from './types'\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. */\nexport function workerFromBackend(\n backend: ExecutorConfig,\n deliverable?: DeliverableSpec<unknown>,\n): MakeWorkerAgent {\n return (rawProfile) => {\n const p = (rawProfile ?? {}) as { name?: unknown }\n const name = typeof p.name === 'string' && p.name.length > 0 ? p.name : 'worker'\n // harness:null — createExecutor(backend) carries the harness in its config (the sandbox case-arm\n // reads config.harness when the spec leaves it null); the BYO executor below resolves the leaf.\n const spec: AgentSpec = { profile: rawProfile as AgentProfile, harness: null }\n const ctx: ExecutorContext = { signal: new AbortController().signal, seams: {} }\n const built = createExecutor(backend)(spec, ctx)\n const executor = deliverable ? gateOnDeliverable(built, deliverable) : built\n return { name, act: async () => '', executorSpec: { ...spec, executor } } as Agent<\n unknown,\n unknown\n > & { executorSpec: AgentSpec }\n }\n}\n\nexport interface SuperviseOptions {\n /** The conserved compute pool for the whole run. */\n readonly budget: Budget\n /** WHERE workers run — derives the worker seam. Provide this OR an explicit `makeWorkerAgent`. */\n readonly backend?: ExecutorConfig\n /** The completion oracle for backend-derived workers (settled ⟺ delivered). Strongly recommended:\n * without it the supervisor trusts a worker's self-report — exactly the \"ran but didn't deliver\"\n * failure mode of a static orchestrator. */\n readonly deliverable?: DeliverableSpec<unknown>\n /** Override the worker seam directly (tests / advanced) instead of deriving it from `backend`. */\n readonly makeWorkerAgent?: MakeWorkerAgent\n /** The supervisor's router substrate (`harness` null). The profile's model wins. */\n readonly router?: RouterConfig\n /** Inject the supervisor brain directly (tests / advanced). */\n readonly brain?: ToolLoopChat\n /** Run a sandboxed-harness supervisor (`harness` set). */\n readonly driveHarness?: DriveHarness\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 (`harness` null). */\n readonly extraTools?: ReadonlyArray<{\n readonly name: string\n readonly description?: string\n readonly parameters: Record<string, unknown>\n }>\n /** Runs an `extraTools` call; null/undefined falls through to the coordination dispatch. */\n readonly executeExtraTool?: (\n name: string,\n args: Record<string, unknown>,\n ) => Promise<string | null | undefined>\n /** Per-child budget reserved on each spawn. Defaults to a quarter of the pool's tokens. */\n readonly perWorker?: Budget\n /** Hard cap on simultaneously-LIVE workers — `spawn_agent` fails closed once this many are in\n * flight. The conserved pool bounds TOTAL work; this bounds SIMULTANEOUS work (live boxes/\n * sandboxes a real fleet runs at once). Omit/`<= 0` = no cap (the pool stays the only fence). */\n readonly maxLiveWorkers?: number\n /** Worker output store. Defaults to in-memory. */\n readonly blobs?: ResultBlobStore\n readonly maxDepth?: number\n readonly maxTurns?: number\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 readonly allowedModels?: readonly string[]\n}\n\n/** A quarter of the token pool per worker → ~4 workers fit before `poolStarved` halts spawning. */\nfunction defaultPerWorker(budget: Budget): Budget {\n return {\n maxIterations: budget.maxIterations,\n maxTokens: Math.max(1, Math.floor(budget.maxTokens / 4)),\n }\n}\n\nexport function supervise(profile: SupervisorProfile, task: unknown, opts: SuperviseOptions) {\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 backendModel = (opts.backend as { model?: unknown } | undefined)?.model\n assertModelAllowed(opts.router?.model, opts.allowedModels)\n assertModelAllowed(profile.model, opts.allowedModels)\n assertModelAllowed(\n typeof backendModel === 'string' ? backendModel : undefined,\n opts.allowedModels,\n )\n\n const ctx = createInMemoryRunContext({ withDriver: true })\n const blobs = opts.blobs ?? ctx.blobs\n const perWorker = opts.perWorker ?? defaultPerWorker(opts.budget)\n\n let makeWorkerAgent = opts.makeWorkerAgent\n if (!makeWorkerAgent) {\n if (!opts.backend) {\n throw new ValidationError(\n 'supervise: provide opts.backend (where workers run) or opts.makeWorkerAgent',\n )\n }\n makeWorkerAgent = workerFromBackend(opts.backend, opts.deliverable)\n }\n\n const agent = supervisorAgent(profile, {\n blobs,\n makeWorkerAgent,\n perWorker,\n ...(opts.maxLiveWorkers !== undefined ? { maxLiveWorkers: opts.maxLiveWorkers } : {}),\n ...(opts.router ? { router: opts.router } : {}),\n ...(opts.brain ? { brain: opts.brain } : {}),\n ...(opts.driveHarness ? { driveHarness: opts.driveHarness } : {}),\n ...(opts.extraTools ? { extraTools: opts.extraTools } : {}),\n ...(opts.executeExtraTool ? { executeExtraTool: opts.executeExtraTool } : {}),\n ...(opts.maxTurns !== undefined ? { maxTurns: opts.maxTurns } : {}),\n })\n\n return createSupervisor<unknown, unknown>().run(agent, task, {\n budget: opts.budget,\n runId: opts.runId ?? 'supervise',\n journal: ctx.journal,\n blobs,\n executors: ctx.executors,\n maxDepth: opts.maxDepth ?? 8,\n ...(opts.now ? { now: opts.now } : {}),\n })\n}\n","/**\n * @experimental\n *\n * `delegate` — the one generic delegation verb. You hand it an INTENT (what you want done) and it\n * hands that intent to a default AUTHORING supervisor: a router-brained supervisor whose standing\n * instruction is `supervisorInstructions()` (the authoring-agent-profiles skill). The supervisor\n * DECOMPOSES the intent and AUTHORS the worker profile it needs per sub-task — there is NO hardcoded\n * coder/researcher profile here. That is the whole point: `delegate('fix the failing test', …)` and\n * `delegate('research X and cite sources', …)` route through the SAME front door; the supervisor\n * writes a code-shaped or research-shaped worker on its own.\n *\n * It is a thin wrapper over `supervise()` — the one front door — so the conserved-budget pool, the\n * completion oracle (`deliverable`), the coordination toolbox, and equal-compute accounting all come\n * for free; nothing is hand-rolled. The result is `supervise()`'s `SupervisedResult` returned\n * UNCHANGED, so its `spentTotal` (`{ iterations, tokens, usd, ms }`) rides straight back to the\n * caller on BOTH paths — a `winner` carries the delivered worker's spend, a `no-winner` carries the\n * spend incurred before it failed. That cost channel means a `delegate()` caller always learns what\n * the delegation actually spent.\n */\n\nimport { ConfigError } from '../../errors'\nimport type { RouterConfig } from '../router-client'\nimport type { ToolLoopChat } from '../tool-loop'\nimport { supervisorInstructions } from './authoring'\nimport type { DeliverableSpec } from './completion-gate'\nimport type { ExecutorConfig } from './runtime'\nimport { supervise } from './supervise'\nimport type { SupervisorProfile } from './supervisor-agent'\nimport type { Budget, SupervisedResult } from './types'\n\n/** The conserved pool a `delegate()` call applies when the caller does not pass its own `budget`.\n * A modest token ceiling + a small iteration ceiling — generous enough for a few-worker decompose,\n * bounded enough that an unsupervised intent cannot run away. Callers override via `opts.budget`. */\nexport const defaultDelegateBudget: Budget = { maxIterations: 50, maxTokens: 200_000 }\n\n/** Inputs to {@link delegate}. The intent is the first positional arg; everything here is optional\n * with sensible defaults, so the common call is `delegate(intent, { backend, router })`. */\nexport interface DelegateOptions<Out = unknown> {\n /** The completion oracle (settled ⟺ delivered) the authored workers settle against. Strongly\n * recommended — without it the supervisor trusts a worker's self-report. For a code intent,\n * `patchDelivered()` is the canonical example; for a free-form answer, a content check. */\n readonly deliverable?: DeliverableSpec<Out>\n /** WHERE the authored workers run — the worker-execution backend (`router-tools` / `sandbox` /\n * `cli-worktree` / …). The supervisor authors the worker PROFILE; this is the substrate it runs\n * on. Provide this OR `makeWorkerAgent`-style wiring through `supervise()` is unavailable. */\n readonly backend?: ExecutorConfig\n /** The conserved compute pool for the whole delegation. Defaults to {@link defaultDelegateBudget}. */\n readonly budget?: Budget\n /** The model the supervisor BRAIN runs on (the router model). The brain must tool-call\n * (`spawn_agent` / `await_event`), so a delegator model, not a hidden-reasoning model. */\n readonly model?: string\n /** The supervisor brain's router substrate. REQUIRED for the default router-brained supervisor\n * (the brain is resolved from this), unless a test injects `brain` directly. `model` overrides\n * `router.model`. (Design delta vs the bare `supervise()` profile: the brain needs a router.) */\n readonly router?: RouterConfig\n /** Inject the supervisor brain directly (tests / advanced) instead of resolving it from `router`. */\n readonly brain?: ToolLoopChat\n /** Override the default authoring-supervisor profile (name / extra system-prompt stance). The\n * default already carries the authoring skill; override only to add a goal or rename. */\n readonly supervisor?: Partial<Pick<SupervisorProfile, 'name' | 'systemPrompt'>>\n /** Restrict the run to this subset of models (forwarded to `supervise()`). */\n readonly allowedModels?: readonly string[]\n readonly runId?: string\n}\n\n/** Build the DEFAULT authoring supervisor profile: a router-brained supervisor (`harness: null`)\n * whose standing instruction IS the authoring-agent-profiles skill, so it decomposes the intent and\n * AUTHORS a worker profile per sub-task. No worker profile is baked in here. */\nfunction authoringSupervisorProfile(\n model: string | undefined,\n override?: Partial<Pick<SupervisorProfile, 'name' | 'systemPrompt'>>,\n): SupervisorProfile {\n return {\n name: override?.name ?? 'delegate-supervisor',\n harness: null,\n ...(model ? { model } : {}),\n systemPrompt: override?.systemPrompt ?? supervisorInstructions(),\n }\n}\n\n/**\n * Delegate an INTENT to a default authoring supervisor and return its `SupervisedResult` unchanged.\n *\n * The supervisor authors + spawns whatever worker the intent needs over the conserved-budget pool;\n * `result.spentTotal` reports what the whole delegation actually cost. A `winner` result carries the\n * authored worker's delivered output; a `no-winner` result names why (never a fabricated success).\n */\nexport async function delegate<Out = unknown>(\n intent: string,\n opts: DelegateOptions<Out> = {},\n): Promise<SupervisedResult<Out>> {\n if (typeof intent !== 'string' || intent.trim().length === 0) {\n throw new ConfigError('delegate: `intent` must be a non-empty string')\n }\n if (!opts.brain && !opts.router) {\n throw new ConfigError(\n 'delegate: provide opts.router (the supervisor brain substrate) or opts.brain (tests)',\n )\n }\n\n const profile = authoringSupervisorProfile(opts.model, opts.supervisor)\n\n return supervise(profile, intent, {\n budget: opts.budget ?? defaultDelegateBudget,\n ...(opts.backend ? { backend: opts.backend } : {}),\n ...(opts.deliverable ? { deliverable: opts.deliverable as DeliverableSpec<unknown> } : {}),\n ...(opts.router ? { router: opts.router } : {}),\n ...(opts.brain ? { brain: opts.brain } : {}),\n ...(opts.allowedModels ? { allowedModels: opts.allowedModels } : {}),\n ...(opts.runId ? { runId: opts.runId } : {}),\n }) as Promise<SupervisedResult<Out>>\n}\n","/**\n * @experimental\n *\n * `delegate` MCP tool — the ONE generic delegation verb, the agent-facing front door to\n * `delegate()` / `supervise()`. The agent hands it an INTENT (what it wants done); a default\n * authoring supervisor decomposes the intent and AUTHORS the worker profile it needs — there is no\n * hardcoded coder/researcher profile, so one verb covers code, research, and anything else.\n *\n * `delegate` is SYNCHRONOUS: it awaits the full supervised run and returns the delivered output\n * TOGETHER WITH `spentTotal` — the conserved cost of the whole delegation (`iterations` / `tokens` /\n * `usd` / `ms`), so the caller always learns what the delegation actually spent.\n *\n * The supervisor's substrate (its brain `router`, the worker `backend`, the completion `deliverable`)\n * is INJECTED at server construction — never an agent-supplied arg. The agent supplies only the\n * intent (+ an optional per-call `model` / `runId`).\n */\n\nimport type { RouterConfig } from '../../runtime/router-client'\nimport type { DeliverableSpec } from '../../runtime/supervise/completion-gate'\nimport { type DelegateOptions, delegate } from '../../runtime/supervise/delegate'\nimport type { ExecutorConfig } from '../../runtime/supervise/runtime'\nimport type { Spend, SupervisedResult } from '../../runtime/supervise/types'\n\n/** @experimental */\nexport const DELEGATE_TOOL_NAME = 'delegate'\n\n/** @experimental */\nexport const DELEGATE_DESCRIPTION = [\n 'Delegate an INTENT to a supervisor that AUTHORS and drives whatever worker the intent needs.',\n '',\n 'Use when: you want a task done but do not want to specify HOW. State the outcome — \"fix the',\n 'failing auth test\", \"research competitor pricing with citations\", \"refactor the parser for',\n 'clarity\" — and the supervisor decomposes it, writes a tailored worker profile per sub-task, runs',\n 'the workers over a conserved compute budget, and settles only when a deployable check passes.',\n '',\n 'There is no fixed worker type: this ONE verb replaces separate code / research delegation. The',\n 'supervisor picks the worker shape from your intent.',\n '',\n 'Returns synchronously with the delivered result AND the real cost of the whole delegation',\n '(spentTotal: iterations, input/output tokens, usd, ms) — so you always know what it spent. A run',\n 'that produced no delivered worker returns status \"no-winner\" with the reason; it never fabricates',\n 'a success.',\n].join('\\n')\n\n/** @experimental */\nexport const DELEGATE_INPUT_SCHEMA = {\n type: 'object',\n properties: {\n intent: {\n type: 'string',\n description: 'What you want accomplished, as an outcome. The supervisor authors the worker.',\n },\n model: {\n type: 'string',\n description: 'Optional per-call override for the supervisor brain model.',\n },\n runId: {\n type: 'string',\n description: 'Optional trace-correlation id for this delegation.',\n },\n },\n required: ['intent'],\n additionalProperties: false,\n} as const\n\n/** Parsed `delegate` tool arguments. */\nexport interface DelegateArgs {\n intent: string\n model?: string\n runId?: string\n}\n\n/** @experimental */\nexport function validateDelegateArgs(raw: unknown): DelegateArgs {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError('delegate: arguments must be an object')\n }\n const value = raw as Record<string, unknown>\n const intent = value.intent\n if (typeof intent !== 'string' || intent.trim().length === 0) {\n throw new TypeError('delegate: `intent` must be a non-empty string')\n }\n const args: DelegateArgs = { intent: intent.trim() }\n if (value.model !== undefined) {\n if (typeof value.model !== 'string') throw new TypeError('delegate: `model` must be a string')\n args.model = value.model\n }\n if (value.runId !== undefined) {\n if (typeof value.runId !== 'string') throw new TypeError('delegate: `runId` must be a string')\n args.runId = value.runId\n }\n return args\n}\n\n/** The synchronous result the `delegate` tool returns to the calling agent: the delivered output (or\n * the no-winner reason) PLUS the conserved spend of the whole delegation. */\nexport type DelegateResult =\n | { status: 'winner'; out: unknown; outRef: string; spentTotal: Spend }\n | { status: 'no-winner'; reason: string; spentTotal: Spend }\n\n/** @experimental */\nexport interface DelegateHandlerOptions {\n /** The supervisor brain's router substrate (REQUIRED — the default supervisor is router-brained). */\n router: RouterConfig\n /** WHERE the authored workers run. Required for `supervise()` to spawn anything. */\n backend: ExecutorConfig\n /** The completion oracle the authored workers settle against (settled ⟺ delivered). */\n deliverable?: DeliverableSpec\n /** Default supervisor brain model when a call omits `model`. */\n model?: string\n /** Restrict the run to this subset of models. */\n allowedModels?: readonly string[]\n}\n\n/** Project a `SupervisedResult` onto the tool's flat `DelegateResult`. Both variants carry the real\n * conserved `spentTotal`, so the agent always learns the cost — even on a no-winner, never a faked\n * output and never a fabricated zero spend. */\nfunction toDelegateResult(result: SupervisedResult<unknown>): DelegateResult {\n if (result.kind === 'no-winner') {\n return { status: 'no-winner', reason: result.reason, spentTotal: result.spentTotal }\n }\n return {\n status: 'winner',\n out: result.out,\n outRef: result.outRef,\n spentTotal: result.spentTotal,\n }\n}\n\n/**\n * Build the `delegate` tool handler. Closes over the injected supervisor substrate (`router` /\n * `backend` / `deliverable`); each call routes the agent's intent to `delegate()` and returns the\n * delivered output with its conserved cost.\n */\nexport function createDelegateHandler(\n options: DelegateHandlerOptions,\n): (raw: unknown) => Promise<DelegateResult> {\n return async (raw) => {\n const args = validateDelegateArgs(raw)\n const opts: DelegateOptions = {\n backend: options.backend,\n router: options.router,\n model: args.model ?? options.model,\n ...(options.deliverable ? { deliverable: options.deliverable } : {}),\n ...(options.allowedModels ? { allowedModels: options.allowedModels } : {}),\n ...(args.runId ? { runId: args.runId } : {}),\n }\n const result = await delegate(args.intent, opts)\n return toDelegateResult(result)\n }\n}\n","/**\n * @experimental\n *\n * `delegate_feedback` MCP tool — synchronous record of agent / user /\n * downstream-judge feedback on a delegation, artifact, or outcome.\n *\n * The store is append-only. Every rating is its own event; no dedupe.\n * When `refersTo.kind === 'delegation'`, the snapshot is also attached\n * to the matching queue record so `delegation_history` surfaces it\n * inline without a join.\n */\n\nimport type { FeedbackStore } from '../feedback-store'\nimport { eventToSnapshot } from '../feedback-store'\nimport type { DelegationTaskQueue } from '../task-queue'\nimport type {\n DelegateFeedbackArgs,\n DelegateFeedbackResult,\n FeedbackRating,\n FeedbackRefersTo,\n} from '../types'\n\n/** @experimental */\nexport const DELEGATE_FEEDBACK_TOOL_NAME = 'delegate_feedback'\n\n/** @experimental */\nexport const DELEGATE_FEEDBACK_DESCRIPTION = [\n 'Record feedback on a delegation, artifact, or outcome. Synchronous — the',\n 'event is durably stored when this call returns.',\n '',\n 'Use when: you (the agent), the user, or a downstream judge has formed an',\n 'opinion about a piece of work and want it persisted for calibration,',\n 'pricing, or future routing. Every call is a new event — multiple ratings',\n 'on the same target are expected and never deduped.',\n '',\n '`refersTo.kind`:',\n ' - \"delegation\": ref is a taskId returned by delegate_ui_audit',\n ' - \"artifact\": ref is a URI/path/git-sha — anything you can dereference',\n ' - \"outcome\": ref is a free-form description of a downstream result',\n '',\n '`by`:',\n ' - \"agent\": the agent itself rated the work',\n ' - \"user\": the human user rated it',\n ' - \"downstream-judge\": an automated evaluator emitted the rating',\n '',\n 'When ref names a known taskId, the rating is also attached to the',\n 'delegation record so delegation_history surfaces it inline.',\n].join('\\n')\n\n/** @experimental */\nexport const DELEGATE_FEEDBACK_INPUT_SCHEMA = {\n type: 'object',\n properties: {\n refersTo: {\n type: 'object',\n properties: {\n kind: { type: 'string', enum: ['delegation', 'artifact', 'outcome'] },\n ref: { type: 'string' },\n },\n required: ['kind', 'ref'],\n additionalProperties: false,\n },\n rating: {\n type: 'object',\n properties: {\n score: { type: 'number', minimum: 0, maximum: 1 },\n label: { type: 'string', enum: ['good', 'bad', 'neutral', 'mixed'] },\n notes: { type: 'string' },\n },\n required: ['score', 'notes'],\n additionalProperties: false,\n },\n by: { type: 'string', enum: ['agent', 'user', 'downstream-judge'] },\n capturedAt: { type: 'string' },\n namespace: { type: 'string' },\n },\n required: ['refersTo', 'rating', 'by'],\n additionalProperties: false,\n} as const\n\n/** @experimental */\nexport function validateDelegateFeedbackArgs(raw: unknown): DelegateFeedbackArgs {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError('delegate_feedback: arguments must be an object')\n }\n const value = raw as Record<string, unknown>\n const refersTo = validateRefersTo(value.refersTo)\n const rating = validateRating(value.rating)\n const by = value.by\n if (by !== 'agent' && by !== 'user' && by !== 'downstream-judge') {\n throw new TypeError(\n 'delegate_feedback: `by` must be one of \"agent\" | \"user\" | \"downstream-judge\"',\n )\n }\n const args: DelegateFeedbackArgs = { refersTo, rating, by }\n if (value.capturedAt !== undefined) {\n if (typeof value.capturedAt !== 'string' || Number.isNaN(Date.parse(value.capturedAt))) {\n throw new TypeError('delegate_feedback: `capturedAt` must be an ISO datetime')\n }\n args.capturedAt = value.capturedAt\n }\n if (typeof value.namespace === 'string') args.namespace = value.namespace\n return args\n}\n\nfunction validateRefersTo(raw: unknown): FeedbackRefersTo {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError('delegate_feedback: `refersTo` must be an object')\n }\n const value = raw as Record<string, unknown>\n const kind = value.kind\n if (kind !== 'delegation' && kind !== 'artifact' && kind !== 'outcome') {\n throw new TypeError(\n 'delegate_feedback: `refersTo.kind` must be one of \"delegation\" | \"artifact\" | \"outcome\"',\n )\n }\n const ref = value.ref\n if (typeof ref !== 'string' || ref.trim().length === 0) {\n throw new TypeError('delegate_feedback: `refersTo.ref` must be a non-empty string')\n }\n return { kind, ref: ref.trim() }\n}\n\nfunction validateRating(raw: unknown): FeedbackRating {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError('delegate_feedback: `rating` must be an object')\n }\n const value = raw as Record<string, unknown>\n const score = Number(value.score)\n if (!Number.isFinite(score) || score < 0 || score > 1) {\n throw new RangeError('delegate_feedback: `rating.score` must be a number in [0, 1]')\n }\n const notes = value.notes\n if (typeof notes !== 'string') {\n throw new TypeError('delegate_feedback: `rating.notes` must be a string')\n }\n const rating: FeedbackRating = { score, notes }\n const label = value.label\n if (label !== undefined) {\n if (label !== 'good' && label !== 'bad' && label !== 'neutral' && label !== 'mixed') {\n throw new TypeError(\n 'delegate_feedback: `rating.label` must be one of \"good\" | \"bad\" | \"neutral\" | \"mixed\"',\n )\n }\n rating.label = label\n }\n return rating\n}\n\n/** @experimental */\nexport interface DelegateFeedbackHandlerOptions {\n queue: DelegationTaskQueue\n store: FeedbackStore\n generateId?: () => string\n now?: () => string\n}\n\n/** @experimental */\nexport function createDelegateFeedbackHandler(\n options: DelegateFeedbackHandlerOptions,\n): (raw: unknown) => Promise<DelegateFeedbackResult> {\n const generateId = options.generateId ?? randomFeedbackId\n const now = options.now ?? (() => new Date().toISOString())\n return async (raw) => {\n const args = validateDelegateFeedbackArgs(raw)\n const id = generateId()\n const event = {\n id,\n refersTo: args.refersTo,\n rating: args.rating,\n by: args.by,\n capturedAt: args.capturedAt ?? now(),\n namespace: args.namespace,\n }\n await options.store.put(event)\n if (args.refersTo.kind === 'delegation') {\n options.queue.attachFeedback(args.refersTo.ref, eventToSnapshot(event))\n }\n return { recorded: true, id }\n }\n}\n\nfunction randomFeedbackId(): string {\n const t = Date.now().toString(36)\n const r = Math.random().toString(36).slice(2, 10)\n return `fbk-${t}-${r}`\n}\n","/**\n * @experimental\n *\n * `delegate_ui_audit` MCP tool — async kickoff for UI audit runs. Validates\n * the input, computes an idempotency key over the canonical fields, hands\n * the task to the queue, and returns a taskId. Identical inputs return\n * the same taskId.\n *\n * The handler does not import the auditor profile directly — consumers\n * inject a `UiAuditorDelegate` via `createMcpServer({ uiAuditorDelegate })`.\n * The delegate is the seam where the consumer chooses the judge (vision\n * model) and the `SandboxClient` (in-process Playwright vs fleet vs\n * remote browser). agent-runtime ships the in-process client under\n * `./profiles` so consumers who want the canonical setup can wire it\n * with a few lines.\n */\n\nimport path from 'node:path'\nimport { UI_LENSES, type UiLens } from '../../profiles/ui-auditor/substrate'\nimport type { UiAuditorDelegate } from '../delegates'\nimport {\n type DelegateUiAuditArgs,\n type DelegateUiAuditResult,\n type DelegationTaskQueue,\n hashIdempotencyInput,\n} from '../task-queue'\n\n/** @experimental */\nexport const DELEGATE_UI_AUDIT_TOOL_NAME = 'delegate_ui_audit'\n\n/** @experimental */\nexport const DELEGATE_UI_AUDIT_DESCRIPTION = [\n 'Delegate a UI/UX audit to a vision-driven auditor that produces self-contained',\n 'GitHub-issue-ready Markdown findings — one file per finding, with embedded',\n 'screenshot evidence and a suggested fix.',\n '',\n 'Use when: you want a thorough pass over a running web app for consistency,',\n 'hierarchy, layout, ux-flow, duplication, accessibility, responsive, states,',\n 'content, interaction, or perceived-performance issues. The auditor iterates',\n 'lens-by-lens so each pass finds new classes of issues; the workspace registry',\n 'deduplicates across iterations.',\n '',\n 'Returns immediately with a taskId. Poll delegation_status to retrieve the',\n 'workspace path + indexed findings (typically minutes per audited route).',\n 'Identical inputs return the same taskId — safe to retry.',\n '',\n 'Output layout under workspaceDir:',\n ' registry.json — finding index + capture sidecar',\n ' index.md — human-readable rollup',\n ' issues/NNN--<lens>--<slug>.md — one self-contained GitHub-issue',\n ' screenshots/<route>--<viewport>.png — capture archive',\n '',\n 'Multi-tenant isolation: every finding is scoped to `namespace` when set.',\n \"Never pass another tenant's namespace.\",\n].join('\\n')\n\nconst VIEWPORT_SCHEMA = {\n type: 'object',\n properties: {\n width: { type: 'integer', minimum: 1 },\n height: { type: 'integer', minimum: 1 },\n },\n required: ['width', 'height'],\n additionalProperties: false,\n} as const\n\nconst ROUTE_SCHEMA = {\n type: 'object',\n properties: {\n name: { type: 'string', description: 'Stable route name (used in screenshot filenames).' },\n url: { type: 'string', description: 'Fully-qualified URL.' },\n viewports: {\n type: 'array',\n items: VIEWPORT_SCHEMA,\n description: 'Viewports to capture at. Default [{1280, 800}].',\n },\n fullPage: { type: 'boolean' },\n waitFor: { type: 'string', description: 'CSS selector to wait for before capturing.' },\n },\n required: ['name', 'url'],\n additionalProperties: false,\n} as const\n\n/** @experimental */\nexport const DELEGATE_UI_AUDIT_INPUT_SCHEMA = {\n type: 'object',\n properties: {\n workspaceDir: { type: 'string', description: 'Absolute path for the audit workspace.' },\n routes: { type: 'array', items: ROUTE_SCHEMA, minItems: 1 },\n namespace: { type: 'string', description: 'Multi-tenant scope.' },\n config: {\n type: 'object',\n properties: {\n lenses: {\n type: 'array',\n items: { type: 'string', enum: [...UI_LENSES] },\n description: 'Lenses to iterate. Default: every lens except \"other\".',\n },\n maxIterations: { type: 'integer', minimum: 1 },\n maxConcurrency: { type: 'integer', minimum: 1 },\n productContext: { type: 'string' },\n },\n additionalProperties: false,\n },\n },\n required: ['workspaceDir', 'routes'],\n additionalProperties: false,\n} as const\n\nconst PER_LENS_PER_ROUTE_ESTIMATE_MS = 45_000\n\n/** @experimental */\nexport function validateDelegateUiAuditArgs(raw: unknown): DelegateUiAuditArgs {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError('delegate_ui_audit: arguments must be an object')\n }\n const value = raw as Record<string, unknown>\n const workspaceDir = value.workspaceDir\n if (typeof workspaceDir !== 'string' || workspaceDir.trim().length === 0) {\n throw new TypeError('delegate_ui_audit: `workspaceDir` must be a non-empty string')\n }\n // Reject relative paths at the boundary. Without this, the writer joins a\n // relative workspaceDir against the process CWD, so the same MCP call\n // produces different file layouts depending on where the server was\n // launched — a silent fail-loud violation for a public API.\n const trimmedWs = workspaceDir.trim()\n if (!path.isAbsolute(trimmedWs)) {\n throw new TypeError(\n `delegate_ui_audit: \\`workspaceDir\\` must be an absolute path (got ${JSON.stringify(workspaceDir)})`,\n )\n }\n // Reject `..` segments. An absolute path like `/tmp/../../etc` passes\n // `isAbsolute`, then `path.join(workspaceDir, 'issues', …)` normalises it\n // to `/etc/issues/…`, escaping the intended workspace. Check the RAW\n // input split on the platform separator; `path.resolve` already collapses\n // `..` and would silently launder a traversal attempt past us.\n if (trimmedWs.split(path.sep).includes('..')) {\n throw new TypeError(\n `delegate_ui_audit: \\`workspaceDir\\` must not contain '..' segments (got ${JSON.stringify(workspaceDir)})`,\n )\n }\n const routesRaw = value.routes\n if (!Array.isArray(routesRaw) || routesRaw.length === 0) {\n throw new TypeError('delegate_ui_audit: `routes` must be a non-empty array')\n }\n const routes = routesRaw.map((r, i) => validateRoute(r, i))\n const args: DelegateUiAuditArgs = { workspaceDir: workspaceDir.trim(), routes }\n if (value.namespace !== undefined) {\n if (typeof value.namespace !== 'string' || value.namespace.trim().length === 0) {\n throw new TypeError('delegate_ui_audit: `namespace` must be a non-empty string when set')\n }\n args.namespace = value.namespace.trim()\n }\n if (value.config !== undefined) {\n args.config = validateConfig(value.config)\n }\n return args\n}\n\nfunction validateRoute(raw: unknown, index: number): DelegateUiAuditArgs['routes'][number] {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError(`delegate_ui_audit: routes[${index}] must be an object`)\n }\n const v = raw as Record<string, unknown>\n if (typeof v.name !== 'string' || v.name.trim().length === 0) {\n throw new TypeError(`delegate_ui_audit: routes[${index}].name must be a non-empty string`)\n }\n // Defense-in-depth: the slug helpers downstream strip non-alphanumerics, so\n // a route name with `..`, `/`, `\\`, or NUL cannot actually escape the\n // workspace. Rejecting them at the wire boundary keeps the invariant\n // explicit and matches the lens-allowlist style of validation.\n const trimmedName = v.name.trim()\n if (/[./\\\\]/.test(trimmedName) || trimmedName.includes('\\u0000')) {\n throw new TypeError(\n `delegate_ui_audit: routes[${index}].name must not contain path separators, dots, or NUL (got ${JSON.stringify(v.name)})`,\n )\n }\n if (typeof v.url !== 'string' || v.url.trim().length === 0) {\n throw new TypeError(`delegate_ui_audit: routes[${index}].url must be a non-empty string`)\n }\n // Parse + restrict to http/https. The in-process auditor client navigates\n // to whatever URL the MCP caller supplies; permitting `file://`, `data:`,\n // `javascript:` would let an attacker controlling the tool input pull\n // local files or run inline scripts.\n let parsedUrl: URL\n try {\n parsedUrl = new URL(v.url)\n } catch {\n throw new TypeError(\n `delegate_ui_audit: routes[${index}].url is not a parseable URL (got ${JSON.stringify(v.url)})`,\n )\n }\n if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {\n throw new TypeError(\n `delegate_ui_audit: routes[${index}].url must use http or https (got ${parsedUrl.protocol})`,\n )\n }\n const out: DelegateUiAuditArgs['routes'][number] = { name: v.name.trim(), url: v.url.trim() }\n if (v.viewports !== undefined) {\n if (!Array.isArray(v.viewports) || v.viewports.length === 0) {\n throw new TypeError(\n `delegate_ui_audit: routes[${index}].viewports must be a non-empty array when set`,\n )\n }\n out.viewports = v.viewports.map((vp, j) => validateViewport(vp, index, j))\n }\n if (v.fullPage !== undefined) {\n if (typeof v.fullPage !== 'boolean') {\n throw new TypeError(`delegate_ui_audit: routes[${index}].fullPage must be a boolean`)\n }\n out.fullPage = v.fullPage\n }\n if (v.waitFor !== undefined) {\n if (typeof v.waitFor !== 'string' || v.waitFor.trim().length === 0) {\n throw new TypeError(\n `delegate_ui_audit: routes[${index}].waitFor must be a non-empty string when set`,\n )\n }\n out.waitFor = v.waitFor.trim()\n }\n return out\n}\n\nfunction validateViewport(\n raw: unknown,\n routeIndex: number,\n viewportIndex: number,\n): { width: number; height: number } {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError(\n `delegate_ui_audit: routes[${routeIndex}].viewports[${viewportIndex}] must be an object`,\n )\n }\n const v = raw as Record<string, unknown>\n const w = Number(v.width)\n const h = Number(v.height)\n if (!Number.isInteger(w) || w <= 0 || !Number.isInteger(h) || h <= 0) {\n throw new RangeError(\n `delegate_ui_audit: routes[${routeIndex}].viewports[${viewportIndex}] must have positive integer width/height`,\n )\n }\n return { width: w, height: h }\n}\n\nfunction validateConfig(raw: unknown): DelegateUiAuditArgs['config'] {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError('delegate_ui_audit: `config` must be an object')\n }\n const v = raw as Record<string, unknown>\n const out: NonNullable<DelegateUiAuditArgs['config']> = {}\n if (v.lenses !== undefined) {\n if (!Array.isArray(v.lenses) || v.lenses.length === 0) {\n throw new TypeError('delegate_ui_audit: `config.lenses` must be a non-empty array when set')\n }\n const knownSet = new Set<string>(UI_LENSES)\n const lenses: UiLens[] = []\n for (let i = 0; i < v.lenses.length; i += 1) {\n const lens = v.lenses[i]\n if (typeof lens !== 'string' || !knownSet.has(lens)) {\n throw new TypeError(\n `delegate_ui_audit: config.lenses[${i}] must be one of ${UI_LENSES.join('|')}`,\n )\n }\n lenses.push(lens as UiLens)\n }\n out.lenses = lenses\n }\n if (v.maxIterations !== undefined) {\n const n = Number(v.maxIterations)\n if (!Number.isInteger(n) || n < 1) {\n throw new RangeError('delegate_ui_audit: `config.maxIterations` must be a positive integer')\n }\n out.maxIterations = n\n }\n if (v.maxConcurrency !== undefined) {\n const n = Number(v.maxConcurrency)\n if (!Number.isInteger(n) || n < 1) {\n throw new RangeError('delegate_ui_audit: `config.maxConcurrency` must be a positive integer')\n }\n out.maxConcurrency = n\n }\n if (v.productContext !== undefined) {\n if (typeof v.productContext !== 'string') {\n throw new TypeError('delegate_ui_audit: `config.productContext` must be a string')\n }\n out.productContext = v.productContext\n }\n return out\n}\n\n/** @experimental */\nexport interface DelegateUiAuditHandlerOptions {\n queue: DelegationTaskQueue\n delegate: UiAuditorDelegate\n estimateDurationMs?: (args: DelegateUiAuditArgs) => number\n}\n\n/** @experimental */\nexport function createDelegateUiAuditHandler(\n options: DelegateUiAuditHandlerOptions,\n): (raw: unknown) => Promise<DelegateUiAuditResult> {\n const estimateDurationMs = options.estimateDurationMs ?? defaultEstimate\n return async (raw) => {\n const args = validateDelegateUiAuditArgs(raw)\n const idempotencyKey = hashIdempotencyInput({\n profile: 'ui-auditor',\n workspaceDir: args.workspaceDir,\n routes: args.routes,\n namespace: args.namespace,\n config: args.config,\n })\n const submitted = options.queue.submit<DelegateUiAuditArgs>({\n profile: 'ui-auditor',\n args,\n namespace: args.namespace,\n idempotencyKey,\n run: async (ctx) => options.delegate(args, ctx),\n })\n return {\n taskId: submitted.taskId,\n estimatedDurationMs: estimateDurationMs(args),\n }\n }\n}\n\nfunction defaultEstimate(args: DelegateUiAuditArgs): number {\n const lenses = args.config?.lenses?.length ?? UI_LENSES.length - 1\n const routes = args.routes.length\n return PER_LENS_PER_ROUTE_ESTIMATE_MS * lenses * routes\n}\n","/**\n * @experimental\n *\n * `delegation_history` MCP tool — synchronous read of past delegations.\n * The agent uses this for self-introspection — \"have I delegated this\n * kind of task before? did it work?\" — and calibration.\n */\n\nimport type {\n DelegationHistoryArgs,\n DelegationHistoryResult,\n DelegationProfile,\n DelegationTaskQueue,\n} from '../task-queue'\n\n/** @experimental */\nexport const DELEGATION_HISTORY_TOOL_NAME = 'delegation_history'\n\n/** @experimental */\nexport const DELEGATION_HISTORY_DESCRIPTION = [\n 'Read past delegations newest-first. Each entry carries the original',\n 'arguments, current status, cost, and any feedback attached via',\n 'delegate_feedback.',\n '',\n 'Use when: you want to introspect prior decisions — \"have I asked this',\n 'question before?',\n 'did the last patch land?',\n \"what's the historical\",\n 'success rate of coder delegations on this repo?\". Feed the results back',\n 'into your own routing and calibration.',\n '',\n 'Each entry carries `hasTrace` — when true, the full loop-trace span tree',\n 'is retrievable via delegation_status { taskId, includeTrace: true }.',\n '',\n 'Filters: `namespace` (multi-tenant scope), `profile` (\"coder\" | \"researcher\"),',\n '`since` (ISO date — only delegations started at-or-after). `limit` defaults',\n 'to 50, capped at 500.',\n].join('\\n')\n\n/** @experimental */\nexport const DELEGATION_HISTORY_INPUT_SCHEMA = {\n type: 'object',\n properties: {\n namespace: { type: 'string' },\n profile: { type: 'string', enum: ['coder', 'researcher'] },\n since: { type: 'string', description: 'ISO datetime — earliest startedAt to include.' },\n limit: { type: 'integer', minimum: 1, maximum: 500 },\n },\n additionalProperties: false,\n} as const\n\n/** @experimental */\nexport function validateDelegationHistoryArgs(raw: unknown): DelegationHistoryArgs {\n if (raw === undefined || raw === null) return {}\n if (typeof raw !== 'object') {\n throw new TypeError('delegation_history: arguments must be an object')\n }\n const value = raw as Record<string, unknown>\n const out: DelegationHistoryArgs = {}\n if (value.namespace !== undefined) {\n if (typeof value.namespace !== 'string') {\n throw new TypeError('delegation_history: `namespace` must be a string')\n }\n out.namespace = value.namespace\n }\n if (value.profile !== undefined) {\n if (value.profile !== 'coder' && value.profile !== 'researcher') {\n throw new TypeError('delegation_history: `profile` must be \"coder\" or \"researcher\"')\n }\n out.profile = value.profile as DelegationProfile\n }\n if (value.since !== undefined) {\n if (typeof value.since !== 'string' || Number.isNaN(Date.parse(value.since))) {\n throw new TypeError('delegation_history: `since` must be an ISO datetime')\n }\n out.since = value.since\n }\n if (value.limit !== undefined) {\n const n = Number(value.limit)\n if (!Number.isFinite(n) || n < 1 || n > 500) {\n throw new RangeError('delegation_history: `limit` must be an integer in [1, 500]')\n }\n out.limit = Math.trunc(n)\n }\n return out\n}\n\n/** @experimental */\nexport interface DelegationHistoryHandlerOptions {\n queue: DelegationTaskQueue\n}\n\n/** @experimental */\nexport function createDelegationHistoryHandler(\n options: DelegationHistoryHandlerOptions,\n): (raw: unknown) => Promise<DelegationHistoryResult> {\n return async (raw) => {\n const args = validateDelegationHistoryArgs(raw)\n return { delegations: options.queue.history(args) }\n }\n}\n","/**\n * @experimental\n *\n * `delegation_status` MCP tool — synchronous poll. Returns the current\n * state machine + optional progress + final result (when terminal).\n */\n\nimport { NotFoundError } from '../../errors'\nimport type {\n DelegationStatusArgs,\n DelegationStatusResult,\n DelegationTaskQueue,\n} from '../task-queue'\n\n/** @experimental */\nexport const DELEGATION_STATUS_TOOL_NAME = 'delegation_status'\n\n/** @experimental */\nexport const DELEGATION_STATUS_DESCRIPTION = [\n 'Poll the status of an async delegation. Returns the current state',\n '(pending | running | completed | failed | cancelled), optional progress,',\n 'and the final result when status === \"completed\".',\n '',\n 'Use when: you previously kicked off an async delegation (delegate_ui_audit)',\n \"and need to know whether the work is done. The agent's right rhythm is to\",\n 'call this every minute or two while waiting; do not busy-poll.',\n '',\n 'For a completed delegate_ui_audit run, `result.output` is the array of UI',\n 'findings — one self-contained Markdown finding per issue, each with an',\n 'embedded screenshot and a suggested fix.',\n '',\n 'Pass includeTrace: true to also receive the journaled loop-trace span',\n 'tree (loop → round → iteration, with placement/cost/verdict metadata).',\n 'Default false — keep routine polls light.',\n '',\n 'Throws NotFoundError when taskId is unknown — never silently returns',\n '`pending` for a typo.',\n].join('\\n')\n\n/** @experimental */\nexport const DELEGATION_STATUS_INPUT_SCHEMA = {\n type: 'object',\n properties: {\n taskId: { type: 'string', description: 'Returned by delegate_ui_audit.' },\n includeTrace: {\n type: 'boolean',\n description:\n 'Also return the journaled loop-trace span tree for this delegation. Default false.',\n },\n },\n required: ['taskId'],\n additionalProperties: false,\n} as const\n\n/** @experimental */\nexport function validateDelegationStatusArgs(raw: unknown): DelegationStatusArgs {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError('delegation_status: arguments must be an object')\n }\n const value = raw as Record<string, unknown>\n const taskId = value.taskId\n if (typeof taskId !== 'string' || taskId.trim().length === 0) {\n throw new TypeError('delegation_status: `taskId` must be a non-empty string')\n }\n const out: DelegationStatusArgs = { taskId: taskId.trim() }\n if (value.includeTrace !== undefined) {\n if (typeof value.includeTrace !== 'boolean') {\n throw new TypeError('delegation_status: `includeTrace` must be a boolean')\n }\n out.includeTrace = value.includeTrace\n }\n return out\n}\n\n/** @experimental */\nexport interface DelegationStatusHandlerOptions {\n queue: DelegationTaskQueue\n}\n\n/** @experimental */\nexport function createDelegationStatusHandler(\n options: DelegationStatusHandlerOptions,\n): (raw: unknown) => Promise<DelegationStatusResult> {\n return async (raw) => {\n const args = validateDelegationStatusArgs(raw)\n const status = options.queue.status(\n args.taskId,\n args.includeTrace !== undefined ? { includeTrace: args.includeTrace } : undefined,\n )\n if (!status) {\n throw new NotFoundError(`delegation_status: unknown taskId \"${args.taskId}\"`)\n }\n return status\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` null/undefined → 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`/…) → a SANDBOXED 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. The harness IS the brain.\n *\n * Both arms spawn children through the SAME `makeWorkerAgent` seam and settle on the SAME completion\n * oracle (`finalizeBestDelivered` — the best DELIVERED child, never the driver's own prose).\n */\nimport { ValidationError } from '../../errors'\nimport type { MakeWorkerAgent } from '../../mcp/tools/coordination'\nimport { type RouterConfig, routerBrain } from '../router-client'\nimport type { ToolLoopChat } from '../tool-loop'\nimport { driverAgent, finalizeBestDelivered } from './coordination-driver'\nimport { serveCoordinationMcp } from './coordination-mcp'\nimport type { Agent, Budget, ResultBlobStore, Scope } from './types'\n\n/** The supervisor's profile — the subset of an `AgentProfile` that selects + shapes its brain.\n * `harness` is the backend-as-data discriminant; `systemPrompt` is the standing instruction. */\nexport interface SupervisorProfile {\n readonly name?: string\n /** null/undefined → router brain (in-process tool-loop); a coding-CLI harness → sandboxed brain. */\n readonly harness?: string | null\n /** The router model when the brain is router-driven (falls back to the deps router config). */\n readonly model?: string\n /** The standing instructions (\"you delegate, you do not solve\"). */\n readonly systemPrompt?: string\n}\n\n/** How to run a sandboxed 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 (sandbox / cli-bridge) with `coordinationMcpUrl` mounted as an MCP server,\n * so the harness calls spawn_agent / await_event / stop as native tools over the live scope. */\nexport type DriveHarness = (args: {\n readonly profile: SupervisorProfile\n readonly task: unknown\n readonly scope: Scope<unknown>\n readonly coordinationMcpUrl: string\n}) => Promise<void>\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 /** Per-child budget reserved from the conserved pool on each spawn. */\n readonly perWorker: Budget\n /** Hard cap on simultaneously-LIVE workers across both arms — `spawn_agent` fails closed once\n * this many are in flight (a concurrency fence on top of the conserved-pool fence; bounds live\n * boxes/sandboxes, not total work). Omit/`<= 0` = no cap. */\n readonly maxLiveWorkers?: number\n /** Router substrate for a router-brained supervisor (`harness` null). The profile's model wins. */\n readonly router?: RouterConfig\n /** Inject the brain directly (tests / advanced) instead of resolving `routerBrain` from the profile. */\n readonly brain?: ToolLoopChat\n /** Required for a sandboxed-harness supervisor (`harness` set): runs the harness as the driver. */\n readonly driveHarness?: DriveHarness\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 readonly maxTurns?: number\n}\n\nexport function supervisorAgent(\n profile: SupervisorProfile,\n deps: SupervisorAgentDeps,\n): Agent<unknown, unknown> {\n const name = profile.name ?? 'supervisor'\n const systemPrompt = profile.systemPrompt ?? ''\n const harness = profile.harness ?? null\n\n if (harness === null) {\n // ROUTER arm: the in-process tool-loop. `routerBrain` is now an internal detail — the caller\n // passes a profile, not a hand-built brain (a test may still inject `deps.brain`).\n const brain = deps.brain ?? routerBrainFromProfile(profile, deps)\n return driverAgent({\n name,\n brain,\n blobs: deps.blobs,\n makeWorkerAgent: deps.makeWorkerAgent,\n perWorker: deps.perWorker,\n systemPrompt,\n ...(deps.maxLiveWorkers !== undefined ? { maxLiveWorkers: deps.maxLiveWorkers } : {}),\n ...(deps.extraTools ? { extraTools: deps.extraTools } : {}),\n ...(deps.executeExtraTool ? { executeExtraTool: deps.executeExtraTool } : {}),\n ...(deps.maxTurns !== undefined ? { maxTurns: deps.maxTurns } : {}),\n })\n }\n\n // SANDBOX arm: a sandboxed harness drives 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 return {\n name,\n async act(task, scope) {\n const mcp = await serveCoordinationMcp({\n scope,\n blobs: deps.blobs,\n makeWorkerAgent: deps.makeWorkerAgent,\n perWorker: deps.perWorker,\n ...(deps.maxLiveWorkers !== undefined ? { maxLiveWorkers: deps.maxLiveWorkers } : {}),\n })\n try {\n await driveHarness({ profile, task, scope, coordinationMcpUrl: mcp.url })\n // The deliverable is the best DELIVERED child, never the harness's own output (Foreman 0/18).\n return await finalizeBestDelivered(mcp.settled(), deps.blobs)\n } finally {\n await mcp.close()\n }\n },\n }\n}\n\nfunction routerBrainFromProfile(\n profile: SupervisorProfile,\n deps: SupervisorAgentDeps,\n): ToolLoopChat {\n if (!deps.router) {\n throw new ValidationError(\n 'supervisorAgent: a router-brained supervisor (harness null) needs deps.router (or deps.brain)',\n )\n }\n return routerBrain({ ...deps.router, model: profile.model ?? deps.router.model })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaO,SAAS,mBACd,OACA,SACM;AACN,MAAI,CAAC,WAAW,UAAU,OAAW;AACrC,MAAI,CAAC,QAAQ,SAAS,KAAK,GAAG;AAC5B,UAAM,IAAI;AAAA,MACR,SAAS,KAAK,UAAU,KAAK,CAAC,8BAA8B,KAAK,UAAU,CAAC,GAAG,OAAO,CAAC,CAAC;AAAA,IAC1F;AAAA,EACF;AACF;;;ACFA,SAAS,kBAAkB;AA0BpB,SAAS,eAAe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AAG,KAAK,QAAQ,OAAO,QAAQ,SAAS,KAAK,OAAO,MAAM,CAAC;AAClF;","names":["sleep","box","sessionId","TEARDOWN_TIMEOUT_MS","copy","spawn","isAbortError","totalTokens","path","spawn","spawn","c","spawn","randomUUID","estimateCost","isModelPriced","zeroSpend","linkSignals","isModelPriced","estimateCost","spawn","randomUUID","f","c","isAsyncIterable","finalize"]}
|