@tangle-network/agent-runtime 0.47.0 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +79 -15
  2. package/dist/agent.js +1 -1
  3. package/dist/chunk-GHX7XOJ2.js +433 -0
  4. package/dist/chunk-GHX7XOJ2.js.map +1 -0
  5. package/dist/{chunk-T4OQQEE3.js → chunk-IQS4HI3F.js} +14 -5
  6. package/dist/chunk-IQS4HI3F.js.map +1 -0
  7. package/dist/{chunk-72JQCHOZ.js → chunk-PXUTIMGJ.js} +2318 -237
  8. package/dist/chunk-PXUTIMGJ.js.map +1 -0
  9. package/dist/{chunk-MGFEUYOH.js → chunk-U2VEWKKK.js} +3 -3
  10. package/dist/{chunk-JNPK46YH.js → chunk-VIEDXELL.js} +408 -6
  11. package/dist/chunk-VIEDXELL.js.map +1 -0
  12. package/dist/{chunk-VR4JIC5H.js → chunk-XTEZ3YJ4.js} +2 -2
  13. package/dist/index.d.ts +29 -4
  14. package/dist/index.js +109 -21
  15. package/dist/index.js.map +1 -1
  16. package/dist/kb-gate-CsXpNRk7.d.ts +1145 -0
  17. package/dist/{loop-runner-bin-DEm4roYF.d.ts → loop-runner-bin-Cgn0A-NW.d.ts} +1 -1
  18. package/dist/loop-runner-bin.d.ts +2 -2
  19. package/dist/loop-runner-bin.js +3 -3
  20. package/dist/loops.d.ts +3 -3
  21. package/dist/loops.js +57 -1
  22. package/dist/mcp/bin.js +187 -24
  23. package/dist/mcp/bin.js.map +1 -1
  24. package/dist/mcp/index.d.ts +28 -125
  25. package/dist/mcp/index.js +28 -6
  26. package/dist/mcp/index.js.map +1 -1
  27. package/dist/platform.js +2 -2
  28. package/dist/platform.js.map +1 -1
  29. package/dist/runtime.d.ts +1100 -62
  30. package/dist/runtime.js +57 -1
  31. package/dist/{types-Cbx3dNK5.d.ts → types-BpDfCPUp.d.ts} +1 -1
  32. package/dist/workflow.js +1 -1
  33. package/package.json +7 -6
  34. package/dist/chunk-5YDS7BLC.js +0 -218
  35. package/dist/chunk-5YDS7BLC.js.map +0 -1
  36. package/dist/chunk-72JQCHOZ.js.map +0 -1
  37. package/dist/chunk-JNPK46YH.js.map +0 -1
  38. package/dist/chunk-T4OQQEE3.js.map +0 -1
  39. package/dist/kb-gate-51BlLlVM.d.ts +0 -529
  40. /package/dist/{chunk-MGFEUYOH.js.map → chunk-U2VEWKKK.js.map} +0 -0
  41. /package/dist/{chunk-VR4JIC5H.js.map → chunk-XTEZ3YJ4.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/durable/spawn-journal.ts","../src/runtime/util.ts","../src/runtime/completion.ts","../src/runtime/personify/analyst.ts","../src/runtime/driver.ts","../src/runtime/inline-sandbox-client.ts","../src/runtime/report-usage.ts","../src/runtime-hooks.ts","../src/runtime/sandbox-acquire.ts","../src/runtime/sandbox-backend.ts","../src/runtime/sandbox-capabilities.ts","../src/runtime/sandbox-lineage.ts","../src/runtime/run-loop.ts","../src/runtime/loop-dispatch.ts","../src/runtime/observe.ts","../src/runtime/supervise/scope.ts","../src/runtime/personify/combinators.ts","../src/runtime/personify/corpus.ts","../src/runtime/supervise/runtime.ts","../src/runtime/supervise/budget.ts","../src/runtime/supervise/supervisor.ts","../src/runtime/personify/registry.ts","../src/runtime/personify/persona.ts","../src/runtime/personify/trajectory.ts","../src/runtime/sandbox-run.ts","../src/runtime/workspace.ts"],"sourcesContent":["/**\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 if (ev.kind === 'spawned') return\n if (events.some((e) => e.kind !== 'spawned' && 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 === '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 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.filter((ev) => ev.kind !== 'spawned').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 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\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 * Internal loop-kernel utilities shared across the kernel, drivers, and the\n * sandbox-acquire layer. Not part of the public barrel surface.\n */\n\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport type { LoopTokenUsage } from './types'\n\n/**\n * Best-effort sandbox delete. Skips instances without a `delete` (test fakes);\n * swallows errors (the platform reaps on expiry). Returns `false` when delete\n * threw, `true` otherwise, so callers can surface a leak if they choose.\n */\nexport async function deleteBoxSafe(box: SandboxInstance | undefined): Promise<boolean> {\n if (!box || typeof (box as { delete?: unknown }).delete !== 'function') return true\n try {\n await box.delete()\n return true\n } catch {\n return false\n }\n}\n\n/** Short base36 id for trace correlation. Not cryptographic, not collision-free. */\nexport function randomSuffix(len = 8): string {\n return Math.random()\n .toString(36)\n .slice(2, 2 + len)\n}\n\n/** Collision-resistant id for sandbox naming (find-by-name recovery must be unique). */\nexport function randomUuid(): string {\n return crypto.randomUUID()\n}\n\n/** Construct an AbortError. Downstream code pattern-matches on `err.name`. */\nexport function abortError(): Error {\n const err = new Error('aborted')\n err.name = 'AbortError'\n return err\n}\n\n/** Throw an AbortError. */\nexport function throwAbort(): never {\n throw abortError()\n}\n\n/** Throw if the signal is already aborted; otherwise no-op. */\nexport function throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw abortError()\n}\n\n/**\n * Sleep that resolves early on abort and always clears its timer so it never\n * keeps the event loop alive. Resolves (does not reject) on abort — callers\n * re-check the signal explicitly after the sleep.\n */\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal?.aborted) {\n resolve()\n return\n }\n let onAbort: (() => void) | undefined\n const timer = setTimeout(() => {\n if (onAbort && signal) signal.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n if (signal) {\n onAbort = () => {\n clearTimeout(timer)\n resolve()\n }\n signal.addEventListener('abort', onAbort, { once: true })\n }\n })\n}\n\n/**\n * Race a promise against a timeout. Resolves with the value if it settles in\n * time, otherwise resolves with `undefined`. Always clears the timer.\n */\nexport function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {\n return new Promise<T | undefined>((resolve) => {\n const timer = setTimeout(() => resolve(undefined), ms)\n promise.then(\n (value) => {\n clearTimeout(timer)\n resolve(value)\n },\n () => {\n clearTimeout(timer)\n resolve(undefined)\n },\n )\n })\n}\n\ninterface StringifyOptions {\n /** Pretty-print with 2-space indent. Default false (compact). */\n pretty?: boolean\n /** Truncate to this many chars, appending `…`. Default unbounded. */\n max?: number\n}\n\n/**\n * `JSON.stringify` with a `String()` fallback on throw (cyclic / non-JSON).\n * Strings pass through unstringified so a preview of a string output is the\n * string itself, not a quoted re-encoding.\n */\nexport function stringifySafe(value: unknown, opts: StringifyOptions = {}): string {\n let s: string\n try {\n if (typeof value === 'string') {\n s = value\n } else {\n const json = opts.pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value)\n s = json ?? String(value)\n }\n } catch {\n s = String(value)\n }\n if (opts.max !== undefined && s.length > opts.max) return `${s.slice(0, opts.max)}…`\n return s\n}\n\n/** A fresh zero token-usage accumulator. */\nexport function zeroTokenUsage(): LoopTokenUsage {\n return { input: 0, output: 0 }\n}\n\n/** Add `delta` into `acc` in place. Missing fields count as zero. */\nexport function addTokenUsage(acc: LoopTokenUsage, delta: Partial<LoopTokenUsage>): void {\n acc.input += delta.input ?? 0\n acc.output += delta.output ?? 0\n}\n\n/**\n * Map `items` through `fn` with at most `limit` calls in flight at once,\n * preserving input order in the result. On the first `fn` rejection no NEW\n * items are picked up; already-in-flight calls are awaited, then the first\n * error is rethrown. `limit` is clamped to ≥ 1.\n *\n * Used where a burst of provisioning (e.g. forking N child boxes) must respect\n * the loop's concurrency bound instead of firing all N at once.\n */\nexport async function mapWithConcurrency<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const bound = Math.max(1, Math.floor(limit))\n const results = new Array<R>(items.length)\n let next = 0\n let failed = false\n const worker = async (): Promise<void> => {\n while (!failed) {\n const i = next\n next += 1\n if (i >= items.length) return\n try {\n results[i] = await fn(items[i] as T, i)\n } catch (err) {\n failed = true\n throw err\n }\n }\n }\n const workerCount = Math.min(bound, items.length)\n await Promise.all(Array.from({ length: workerCount }, () => worker()))\n return results\n}\n","/**\n * @experimental\n *\n * Completion / satisfiability — the OTHER output of the pluggable analyst (the steer output\n * is `AnalystFinding[]` via the `analyze` hook; this is the \"is it done?\" output via the\n * `complete` hook). A `CompletionAnalyst` reads a node's trace and returns a `CompletionVerdict`\n * the PARENT (driver) acts on: end the node, or keep going. It fits ANY node and composes to\n * any depth — a 1-deep loop has one; an N-deep tree has one per node.\n *\n * The verdict's authority scales with its DETERMINISM (the thing that varies by task):\n * - `deterministic` — build/test/lint pass, a proof checks, every claim's citation resolves:\n * ground truth, the driver TRUSTS it and ends. Not an opinion.\n * - `probabilistic` — a quality/soundness judgment (marketing, \"the experiment is sound\"):\n * ADVISORY. It passes to the driver with its reasons; the driver validates (here: a\n * confidence threshold; a richer driver may re-examine the reasons) before ending.\n *\n * Two stop-signal mechanisms, by node mode, both → one `CompletionVerdict`:\n * - sandbox-agent (text stream): a unique per-node STOP SENTINEL the agent emits when done\n * (`stopSentinel` / `sentinelCompletion`) — ralph-loop style; the seed makes it\n * unguessable + attributable, so it can't be spuriously emitted or confused with content.\n * - deterministic check (compile/test/citation/proof): `deterministicCompletion(check)` —\n * a verifier over the output, never the judge verdict (selector ≠ judge holds).\n */\n\nimport type { Iteration } from './types'\n\n/** Trace-derived evidence for a completion claim — an artifact (output) or a verifier metric,\n * never the judge's own verdict. Mirrors the steer-firewall's provenance discipline. */\nexport interface CompletionEvidence {\n kind: 'artifact' | 'metric'\n uri: string\n}\n\n/** The \"is it done?\" verdict an analyst returns to the parent. */\nexport interface CompletionVerdict {\n done: boolean\n /** How verifiable the claim is — sets whether the driver trusts it or validates it. */\n determinism: 'deterministic' | 'probabilistic'\n /** Why the analyst believes it is (or isn't) done — what the driver validates. */\n reasons?: string\n /** 0..1, for probabilistic verdicts; the driver's validation threshold reads this. */\n confidence?: number\n evidence?: ReadonlyArray<CompletionEvidence>\n}\n\n/** Reads a node's trace → a completion verdict. Same input shape as the `analyze` hook, so\n * ONE analyst node can back both channels (findings for steer, a verdict for stop). */\nexport interface CompletionAnalyst<Task, Output> {\n assess(input: {\n task: Task\n history: ReadonlyArray<Iteration<Task, Output>>\n }): CompletionVerdict | Promise<CompletionVerdict>\n}\n\n/** When a verdict authorizes the driver to END. Deterministic → trust (ground truth);\n * probabilistic → validate by confidence threshold (the driver's check). */\nexport interface CompletionPolicy {\n /** Minimum confidence a PROBABILISTIC verdict must clear to end. Default 0.8. */\n minConfidence?: number\n}\n\nexport function completionAuthorizes(v: CompletionVerdict, policy?: CompletionPolicy): boolean {\n if (!v?.done) return false\n if (v.determinism === 'deterministic') return true\n return (v.confidence ?? 0) >= (policy?.minConfidence ?? 0.8)\n}\n\n/**\n * A unique, attributable stop sentinel for a node (ralph-loop style). Deterministic from the\n * seed (no Math.random — reproducible + attributable to the node); the agent is instructed to\n * emit it VERBATIM when it judges itself done. Unguessable enough that content never trips it.\n */\nexport function stopSentinel(seed: string): string {\n let h = 0x811c9dc5\n for (let i = 0; i < seed.length; i += 1) {\n h ^= seed.charCodeAt(i)\n h = Math.imul(h, 0x01000193)\n }\n return `<<<{{STOP:${(h >>> 0).toString(16).padStart(8, '0')}}}>>>`\n}\n\n/**\n * Completion for a sandbox-agent node: done iff the latest output carries the node's stop\n * sentinel. PROBABILISTIC (the agent's own self-judgment) — the driver validates it.\n */\nexport function sentinelCompletion<Task>(\n sentinel: string,\n opts?: { confidence?: number },\n): CompletionAnalyst<Task, string> {\n return {\n assess({ history }) {\n const last = history[history.length - 1]\n const out = typeof last?.output === 'string' ? last.output : ''\n const done = out.includes(sentinel)\n return {\n done,\n determinism: 'probabilistic',\n confidence: done ? (opts?.confidence ?? 0.9) : 0,\n reasons: done ? 'agent emitted its assigned stop sentinel' : undefined,\n evidence: done && last ? [{ kind: 'artifact', uri: `attempt:${last.index}` }] : [],\n }\n },\n }\n}\n\n/**\n * Completion for a DETERMINISTIC check (build/test/lint/citation/proof): done iff the check\n * passes. Ground truth — the driver ends directly, no validation. The check reads the output\n * (a verifier), never the judge verdict — selector ≠ judge stays intact.\n */\nexport function deterministicCompletion<Task, Output>(\n check: (\n output: Output,\n history: ReadonlyArray<Iteration<Task, Output>>,\n ) => { passed: boolean; reasons?: string },\n): CompletionAnalyst<Task, Output> {\n return {\n assess({ history }) {\n const last = history[history.length - 1]\n if (last?.output === undefined) {\n return { done: false, determinism: 'deterministic', reasons: 'no output yet' }\n }\n const r = check(last.output, history)\n return {\n done: r.passed,\n determinism: 'deterministic',\n reasons: r.reasons,\n evidence: [{ kind: 'artifact', uri: `attempt:${last.index}` }],\n }\n },\n }\n}\n","/**\n * @experimental\n *\n * Analyst-on-scope (G1) — the PORT of the round-synchronous driver's analyze→findings→steer\n * wire (`dynamic.ts`) onto the reactive `Scope`.\n *\n * The old dynamic driver wired the analyst at round boundaries: `plan` ran the analyst over\n * `history` BEFORE the planner and handed the findings forward via `PlannerContext.analyses`,\n * behind a provenance firewall (`assertTraceDerivedFindings`) that keeps the external write-only\n * judge out of the steer decision (selector ≠ judge). The reactive `Scope` has no rounds, so this\n * module carries the same wire across: a combinator's `act` asks a `ScopeAnalyst` to turn the\n * children it has drained off `scope.next()` SO FAR into `AnalystFinding[]`, and steers from THOSE\n * findings through a single `SteerContext`.\n *\n * The analyst itself is not a new type — it is \"just an `Agent<unknown, AnalystFinding[]>`\" the\n * combinator spawns over a child's trace (harness `null`/`cli`). `createScopeAnalyst` spawns that\n * agent through `Scope.spawn` (so its compute is metered by the conserved pool like any child),\n * drains its settlement, then enforces the firewall on the way out — a judge-derived finding\n * ABORTS, it is never filtered. Fail loud: a down analyst, a non-array result, or a tainted finding\n * throws; there is no silent empty-findings path that would let a combinator steer on nothing.\n */\n\nimport type { AnalystFinding } from '@tangle-network/agent-eval'\nimport { AnalystError, PlannerError } from '../../errors'\nimport type { Agent, Budget, DefaultVerdict, NodeId, Scope, Settled } from '../supervise/types'\nimport { stringifySafe } from '../util'\nimport type {\n AssertTraceDerivedFindings,\n Outcome,\n ScopeAnalyst,\n ScopeAnalyzeInput,\n SteerContext,\n} from './wave-types'\n\n// ── The steer firewall (selector ≠ judge) — the single canonical impl ───────\n\n/**\n * The diagnosis a combinator steers from must be TRACE-derived, never JUDGE-derived. A finding\n * whose evidence is a judge/verdict score (an `EvidenceRef` of `kind:'metric'` with a\n * verdict/judge/score uri scheme) would smuggle the external write-only judge back into steering —\n * the one coupling the architecture forbids. This is a PROVENANCE check, not a content check:\n * span/event/artifact/finding refs and empty-evidence findings are allowed; only a judge-scheme\n * metric ref is rejected. Fail loud — a tainted finding aborts.\n */\nconst judgeEvidenceUri = /^(verdict|judge|score)\\b/i\n\nexport const assertTraceDerivedFindings: AssertTraceDerivedFindings = (findings) => {\n for (const f of findings) {\n for (const ref of f.evidence_refs ?? []) {\n if (ref.kind === 'metric' && judgeEvidenceUri.test(ref.uri)) {\n throw new PlannerError(\n `steer-firewall: finding ${stringifySafe(f.finding_id)} cites judge-derived evidence ` +\n `(${stringifySafe(ref.uri)}); findings fed to a combinator's steer decision must be ` +\n 'trace-derived, not judge-derived (selector ≠ judge)',\n )\n }\n }\n }\n}\n\n// ── The reactive analyst — an Agent the combinator spawns over the trace so far ───────\n\n/**\n * The analyst run an `Agent<unknown, AnalystFinding[]>` performs over the children settled so far.\n * The combinator supplies the analyst's task projection (how to frame the drained settlements as\n * the analyst's input) — the analyst's `act` reads the trace and returns its raw findings; the\n * firewall is enforced afterwards by `createScopeAnalyst`, not by the analyst itself.\n */\nexport interface CreateScopeAnalystOptions<D> {\n /** The analyst agent the combinator spawns over the trace. `harness` is the persona's choice\n * (`null` for an inline router analyst, a `BackendType` for a sandboxed one). Its `act` returns\n * the RAW findings; this module asserts the firewall on them before returning. */\n readonly analyst: Agent<unknown, ReadonlyArray<AnalystFinding>>\n /** Build the analyst agent's task from the analyze input (the root-task framing + the children\n * drained so far). Pure projection — the analyst interprets it, this never reads it. */\n buildTask(input: ScopeAnalyzeInput<D>): unknown\n /** The conserved budget reserved for one analyst spawn. The pool reserves against it and fails\n * closed; an analyst that cannot be admitted is a fail-loud abort, never silent empty findings. */\n readonly budget: Budget\n /** Trace/journal label for the spawned analyst child. Default `'analyst'`. */\n readonly label?: string\n}\n\n/**\n * Build a `ScopeAnalyst` that spawns the analyst agent through `Scope.spawn` (so its compute is\n * metered by the conserved pool), drains its single settlement, and enforces the trace-derived\n * firewall before returning. The `scope` is the SAME scope the combinator is draining its children\n * from — the analyst is spawned as a sibling and its result is read off `scope.next()` in cursor\n * order, replay-safe like any other child.\n *\n * Fail loud (no silent empty findings):\n * - the pool refuses the analyst spawn → `AnalystError` (the steer would otherwise run on nothing)\n * - the analyst settles `down` → `AnalystError` (a broken capture path, not a verdict)\n * - the analyst returns a non-array → `PlannerError`\n * - any finding cites judge-derived metric evidence → `PlannerError` via the firewall\n */\nexport function createScopeAnalyst<D>(\n scope: Scope<Outcome<D>>,\n options: CreateScopeAnalystOptions<D>,\n): ScopeAnalyst<D> {\n if (!options.analyst || typeof options.analyst.act !== 'function') {\n throw new AnalystError('createScopeAnalyst: analyst must be an Agent with an act() method')\n }\n const label = options.label ?? 'analyst'\n return {\n async analyze(input: ScopeAnalyzeInput<D>): Promise<ReadonlyArray<AnalystFinding>> {\n const task = options.buildTask(input)\n // The analyst is spawned into the combinator's own scope so its tokens are charged to the\n // conserved pool. The pool fails closed; an analyst it cannot admit is a hard abort, not an\n // excuse to steer on an empty diagnosis. The analyst's `Out` is `AnalystFinding[]`, not the\n // scope's `Outcome<D>` — a genuinely heterogeneous child; the cast through `unknown` mirrors\n // the keystone `spawnChild` seam, and the settlement is narrowed back by `readAnalystFindings`.\n const spawned = scope.spawn(options.analyst as unknown as Agent<unknown, Outcome<D>>, task, {\n budget: options.budget,\n label,\n })\n if (!spawned.ok) {\n throw new AnalystError(\n `createScopeAnalyst: analyst spawn refused by the conserved pool (${spawned.reason}); ` +\n `cannot steer node ${stringifySafe(input.nodeId)} on an unrun analyst`,\n )\n }\n const settled = await drainAnalystSettlement(scope, spawned.handle.id)\n const findings = readAnalystFindings(settled)\n assertTraceDerivedFindings(findings)\n return findings\n },\n }\n}\n\n/**\n * Drain `scope.next()` until the analyst child's own settlement is yielded, matching on its node\n * id so an unrelated sibling that settles first is skipped, not mistaken for the analyst. A\n * `ScopeAnalyst` is invoked AFTER a combinator has drained its workers, so in practice the analyst\n * is the only live child; the id match keeps it correct even when it is not. Fails loud if the\n * scope empties before the analyst settles (the steer would otherwise run on nothing).\n */\nasync function drainAnalystSettlement<D>(\n scope: Scope<Outcome<D>>,\n analystId: NodeId,\n): Promise<Settled<Outcome<D>>> {\n for (;;) {\n const settled = await scope.next()\n if (settled === null) {\n throw new AnalystError(\n `createScopeAnalyst: scope drained before analyst ${stringifySafe(analystId)} settled`,\n )\n }\n if (settled.handle.id === analystId) return settled\n }\n}\n\n/**\n * Read the analyst child's settlement into its `AnalystFinding[]`. A `down` analyst is a broken\n * capture path (fail loud — not \"no findings\"); a `done` analyst whose `out` is not an array is a\n * malformed analyst (fail loud — the dynamic driver's `runAnalyze` contract, carried across).\n */\nfunction readAnalystFindings<D>(settled: Settled<Outcome<D>>): ReadonlyArray<AnalystFinding> {\n if (settled.kind === 'down') {\n throw new AnalystError(\n `createScopeAnalyst: analyst ${stringifySafe(settled.handle.id)} settled down ` +\n `(${settled.infra ? 'infra' : 'result'}): ${stringifySafe(settled.reason)}`,\n )\n }\n const out = settled.out as unknown\n if (!Array.isArray(out)) {\n throw new PlannerError(\n `createScopeAnalyst: analyst ${stringifySafe(settled.handle.id)} must return ` +\n `AnalystFinding[], got ${stringifySafe(out)}`,\n )\n }\n return out as ReadonlyArray<AnalystFinding>\n}\n\n// ── The single firewalled steer surface every combinator funnels through ──────────────\n\n/**\n * Build the `SteerContext` a combinator reads to steer (its `loopUntil.until`, `widen` gate, any\n * future steer). One place enforces the firewall: `findings` is asserted trace-derived before it is\n * surfaced, and `lastValidScore` is provided for OBSERVABILITY only — a combinator that steers off\n * it re-introduces selector = judge, the coupling the architecture forbids.\n *\n * `findings` is re-asserted here even when it came from `createScopeAnalyst` (which already asserted\n * it): the assertion is cheap and idempotent, and a `SteerContext` may be built from findings that\n * arrived by another path (a caller-supplied diagnosis). Belt-and-suspenders on the one coupling\n * that must never leak.\n */\nexport function buildSteerContext<D>(\n findings: ReadonlyArray<AnalystFinding>,\n settledSoFar: ReadonlyArray<Settled<Outcome<D>>>,\n): SteerContext<D> {\n assertTraceDerivedFindings(findings)\n const lastValidScore = observedBestScore(settledSoFar)\n return {\n findings,\n settledSoFar,\n ...(lastValidScore !== undefined ? { lastValidScore } : {}),\n }\n}\n\n/**\n * The best valid score among the drained children — OBSERVABILITY ONLY. Read for rendering/traces,\n * never to make a steer decision (that is the selector = judge coupling). Reads `verdict.score` off\n * `done` settlements whose verdict is `valid`; a `down` child carries no verdict and contributes\n * nothing.\n */\nfunction observedBestScore<D>(\n settledSoFar: ReadonlyArray<Settled<Outcome<D>>>,\n): number | undefined {\n let best: number | undefined\n for (const s of settledSoFar) {\n if (s.kind !== 'done') continue\n const v: DefaultVerdict | undefined = s.verdict\n if (!v || v.valid !== true || typeof v.score !== 'number') continue\n if (best === undefined || v.score > best) best = v.score\n }\n return best\n}\n","/**\n * @experimental\n *\n * Dynamic driver — the agent authors the loop topology at runtime.\n *\n * Where a fixed-shape driver encodes one topology as a pure function of\n * history, this driver delegates the per-round shape to an injected\n * `TopologyPlanner`. Each round the planner inspects the task + iteration\n * history and emits one `TopologyMove`:\n * - `refine` → one task next round (optionally rewritten from the prior attempt)\n * - `fanout` → N tasks next round (the kernel round-robins `agentRuns`, so a\n * 2-harness fanout dispatches branch 0 to harness A and branch 1 to harness B)\n * - `stop` → terminate; the kernel selects the winner across all iterations\n *\n * The planner is the brain; this driver is the structure. It maps moves onto\n * the kernel's `plan`/`decide` contract, enforces the iteration + fanout caps,\n * and fails loud on a malformed move. The planner is injected — so a test can\n * drive a deterministic policy through the real kernel, and production can wire\n * it to an LLM-backed, agent-authored planner.\n *\n * Topology is orthogonal to harness: the planner never names a backend. Which\n * harness runs a branch is decided by the `AgentRunSpec` the kernel round-robins\n * to, so one dynamic driver works across claude-code, codex, opencode, pi —\n * including fanning a single round across several at once.\n */\n\nimport type { AnalystFinding } from '@tangle-network/agent-eval'\nimport { PlannerError, ValidationError } from '../errors'\nimport {\n type CompletionAnalyst,\n type CompletionPolicy,\n type CompletionVerdict,\n completionAuthorizes,\n} from './completion'\n// The steer-firewall (selector ≠ judge) is single-sourced in `personify/analyst`; the dynamic\n// driver and the reactive combinators assert the SAME provenance check on findings.\nimport { assertTraceDerivedFindings } from './personify/analyst'\nimport type { Driver, Iteration, LoopPlanDescription } from './types'\nimport { stringifySafe } from './util'\n\n/** Terminal once `decide` returns `'done'` (a kernel terminal decision). */\nexport type DriverDecision = 'continue' | 'done'\n\n/**\n * One topology decision for the next round. `fanout` carries explicit tasks\n * rather than a count so the planner can issue heterogeneous branches (a\n * different sub-task per harness); pass N copies of one task for a homogeneous\n * fanout that relies on `agentRuns` diversity instead.\n *\n * @experimental\n */\nexport type TopologyMove<Task> =\n | { kind: 'refine'; task: Task; rationale?: string; parentIndex?: number }\n | { kind: 'fanout'; tasks: Task[]; rationale?: string; parentIndex?: number }\n // `stop` carries no parentIndex — it never produces an edge, so the\n // describePlan guard below reads parentIndex only on refine/fanout.\n | { kind: 'stop'; rationale?: string }\n // `select` — the planner AUTHORS the winner: terminal like stop, but the kernel\n // uses iteration `index` as the winner instead of its argmax. The selector role\n // made emittable. No edge → no parentIndex.\n | { kind: 'select'; index: number; rationale?: string }\n\n/** @experimental */\nexport interface PlannerContext<Task, Output> {\n /** The root task the loop was invoked with — stable across rounds. */\n task: Task\n /** Every iteration so far, in dispatch order, with outputs + verdicts. */\n history: ReadonlyArray<Iteration<Task, Output>>\n /** `history.length` — iterations already spent. */\n iterationsSpent: number\n /** Iterations left before the driver's `maxIterations` cap forces a stop. */\n iterationsRemaining: number\n /**\n * Trace-analyst findings about the attempts so far — populated only when an\n * `analyze` hook is wired into the driver (see CreateDriverOptions).\n * This is the channel that lets the planner steer from the DIAGNOSIS\n * (`f(trace, findings)`), not the verdict score alone. Undefined = no analyst\n * wired (the planner runs exactly as before). @experimental\n */\n analyses?: ReadonlyArray<AnalystFinding>\n}\n\n/**\n * Chooses the next topology move from the task + history. Sync or async; an\n * async planner is where an LLM call goes (an agent-authored topology planner).\n *\n * @experimental\n */\nexport type TopologyPlanner<Task, Output> = (\n ctx: PlannerContext<Task, Output>,\n) => TopologyMove<Task> | Promise<TopologyMove<Task>>\n\n/**\n * Input to the optional `analyze` hook: the root task + the trace so far. The\n * hook turns this into `AnalystFinding[]` — the caller's seam to `runAnalystLoop`.\n * @experimental\n */\nexport interface AnalyzeInput<Task, Output> {\n task: Task\n history: ReadonlyArray<Iteration<Task, Output>>\n}\n\n/** @experimental */\nexport interface CreateDriverOptions<Task, Output> {\n /** The agent-authored topology policy. Invoked once per round in `plan`. */\n planner: TopologyPlanner<Task, Output>\n /**\n * Optional trace-analyst hook. When set, the driver calls it each round AFTER\n * the first (a trace must exist) and BEFORE the planner, then passes the\n * findings to the planner via `PlannerContext.analyses` — so the planner\n * decides from the diagnosis, not the verdict score alone. This is the seam to\n * `runAnalystLoop`; it lives on the driver so `run-loop` stays analyst-free\n * (the layering rule). Fail-loud: a throwing or non-array hook aborts the round\n * (no silent empty findings).\n */\n analyze?: (\n input: AnalyzeInput<Task, Output>,\n ) => ReadonlyArray<AnalystFinding> | Promise<ReadonlyArray<AnalystFinding>>\n /**\n * Optional completion analyst — the DEPLOYABLE, non-oracle stop. Each round (after a\n * trace exists) the driver asks \"is it done?\"; if the verdict AUTHORIZES ending\n * (deterministic = trust ground truth; probabilistic = clears `completionPolicy`'s\n * confidence), the driver stops BEFORE consulting the planner. This is the satisfiability\n * primitive — usable at 1 deep, composing to any depth (one per node). Fail-loud: a\n * throwing or non-verdict assess aborts the round. Distinct from `analyze` (the steer\n * channel) though one analyst node may back both.\n */\n complete?: CompletionAnalyst<Task, Output>\n /** Validation policy for a probabilistic completion verdict (the driver's check). */\n completionPolicy?: CompletionPolicy\n /**\n * Hard safety cap on total iterations. When reached, the driver stops before\n * consulting the planner. Default 8. Set the kernel's `runLoop`\n * `maxIterations >= ` this so the driver's cap governs and the loop closes on\n * a clean `'done'` rather than a truncated `'continue'`.\n */\n maxIterations?: number\n /** Max branches a single `fanout` move may dispatch. Default 4. */\n maxFanout?: number\n /** Stable identifier surfaced in trace events. Default `'dynamic'`. */\n name?: string\n}\n\n/** @experimental */\nexport function createDriver<Task, Output>(\n options: CreateDriverOptions<Task, Output>,\n): Driver<Task, Output, DriverDecision> {\n if (typeof options.planner !== 'function') {\n throw new ValidationError('createDriver: planner must be a function')\n }\n const maxIterations = options.maxIterations ?? 8\n if (!Number.isFinite(maxIterations) || maxIterations <= 0) {\n throw new ValidationError('createDriver: maxIterations must be > 0')\n }\n const maxFanout = options.maxFanout ?? 4\n if (!Number.isFinite(maxFanout) || maxFanout < 1) {\n throw new ValidationError('createDriver: maxFanout must be >= 1')\n }\n\n // The kernel calls plan(), runs the batch, then calls decide() — strictly\n // sequential, one driver instance per loop. Caching the move the planner\n // chose this round lets decide() report terminality without re-invoking the\n // planner (which would double every LLM call).\n let pending: TopologyMove<Task> | undefined\n\n return {\n name: options.name ?? 'dynamic',\n async plan(task, history) {\n if (history.length >= maxIterations) {\n pending = { kind: 'stop', rationale: `maxIterations (${maxIterations}) reached` }\n return []\n }\n // The wire: turn the trace into a diagnosis BEFORE the planner decides, so\n // the move is f(trace, findings), not f(verdict-score). Skipped on round 0\n // (no trace to analyze). Fail-loud — a broken analyst aborts the round.\n const analyses =\n options.analyze && history.length > 0\n ? await runAnalyze(options.analyze, task, history)\n : undefined\n // Deployable, non-oracle stop: ask the completion analyst \"is it done?\" BEFORE the\n // planner. If the verdict authorizes ending (deterministic trust / probabilistic\n // threshold), terminate now. This is the satisfiability primitive at this node.\n if (options.complete && history.length > 0) {\n const verdict = await runComplete(options.complete, task, history)\n if (completionAuthorizes(verdict, options.completionPolicy)) {\n pending = {\n kind: 'stop',\n rationale: `complete (${verdict.determinism}): ${verdict.reasons ?? 'satisfied'}`,\n }\n return []\n }\n }\n const move = await options.planner({\n task,\n history,\n iterationsSpent: history.length,\n iterationsRemaining: maxIterations - history.length,\n ...(analyses ? { analyses } : {}),\n })\n pending = validateMove(move, maxFanout)\n if (pending.kind === 'select') {\n // The planner may override the kernel's argmax, but not invent a winner:\n // the selected iteration must be a completed attempt that produced output.\n // Range + output are checked here, where history is in scope. Fail loud.\n const iter = history[pending.index]\n if (!iter || iter.output === undefined) {\n throw new PlannerError(\n `dynamic planner select.index ${pending.index} is not a completed iteration with output (history length ${history.length})`,\n )\n }\n }\n switch (pending.kind) {\n case 'refine':\n return [pending.task]\n case 'fanout':\n return pending.tasks\n case 'stop':\n case 'select':\n return []\n }\n },\n decide() {\n // pending is set by the plan() call that immediately precedes every\n // decide(). `stop` and `select` terminate; refine/fanout keep looping so\n // plan() — and thus the planner — runs again next round.\n return pending?.kind === 'stop' || pending?.kind === 'select' ? 'done' : 'continue'\n },\n describePlan() {\n // Surface the move the planner just chose (kind + rationale + an optional\n // DECLARED branch source) so the kernel's loop.plan trace carries the\n // agent's intent — including faithful edge lineage when the planner\n // branched off a specific (non-winner) iteration. `pending` is the move\n // set by the preceding plan().\n if (!pending) return undefined\n const out: LoopPlanDescription = { kind: pending.kind }\n if (pending.rationale !== undefined) out.rationale = pending.rationale\n if (\n (pending.kind === 'refine' || pending.kind === 'fanout') &&\n pending.parentIndex !== undefined\n ) {\n out.parentIndex = pending.parentIndex\n }\n return out\n },\n selectWinner(history) {\n // Authored winner: only when the last move was `select`. The kernel calls\n // this at finalize (absent a caller-supplied selectWinner); returning\n // undefined for every other move falls through to the default argmax. The\n // selected iteration's output presence was enforced in plan().\n if (pending?.kind !== 'select') return undefined\n const iter = history[pending.index]\n if (!iter || iter.output === undefined) return undefined\n return {\n task: iter.task,\n output: iter.output,\n verdict: iter.verdict,\n iterationIndex: iter.index,\n agentRunName: iter.agentRunName,\n }\n },\n }\n}\n\nfunction validateMove<Task>(move: TopologyMove<Task>, maxFanout: number): TopologyMove<Task> {\n if (!move || typeof move !== 'object' || typeof (move as { kind?: unknown }).kind !== 'string') {\n throw new PlannerError(`dynamic planner returned a non-move value: ${stringifySafe(move)}`)\n }\n switch (move.kind) {\n case 'refine':\n return move\n case 'stop':\n return move\n case 'select': {\n if (!Number.isInteger(move.index) || move.index < 0) {\n throw new PlannerError(\n `dynamic planner select move must carry a non-negative integer index, got ${stringifySafe(move.index)}`,\n )\n }\n return move\n }\n case 'fanout': {\n if (!Array.isArray(move.tasks) || move.tasks.length === 0) {\n throw new PlannerError('dynamic planner fanout move must carry a non-empty tasks[]')\n }\n if (move.tasks.length <= maxFanout) return move\n // Clamp rather than reject — over-fanning is a budget concern, not a\n // structural error. The clamp is recorded in the rationale for traces.\n return {\n kind: 'fanout',\n tasks: move.tasks.slice(0, maxFanout),\n rationale: `${move.rationale ?? ''} [clamped ${move.tasks.length}→${maxFanout}]`.trim(),\n }\n }\n default:\n throw new PlannerError(\n `dynamic planner returned unknown move kind: ${stringifySafe((move as { kind: unknown }).kind)}`,\n )\n }\n}\n\n/** Call the analyze hook and fail loud on a non-array return (no silent empty). */\nasync function runAnalyze<Task, Output>(\n analyze: NonNullable<CreateDriverOptions<Task, Output>['analyze']>,\n task: Task,\n history: ReadonlyArray<Iteration<Task, Output>>,\n): Promise<ReadonlyArray<AnalystFinding>> {\n const findings = await analyze({ task, history })\n if (!Array.isArray(findings)) {\n throw new PlannerError(\n `createDriver: analyze hook must return AnalystFinding[], got ${stringifySafe(findings)}`,\n )\n }\n assertTraceDerivedFindings(findings)\n return findings\n}\n\n/** Call the completion analyst and fail loud on a non-verdict return (no silent \"not done\"). */\nasync function runComplete<Task, Output>(\n complete: CompletionAnalyst<Task, Output>,\n task: Task,\n history: ReadonlyArray<Iteration<Task, Output>>,\n): Promise<CompletionVerdict> {\n const verdict = await complete.assess({ task, history })\n if (\n !verdict ||\n typeof verdict.done !== 'boolean' ||\n (verdict.determinism !== 'deterministic' && verdict.determinism !== 'probabilistic')\n ) {\n throw new PlannerError(\n `createDriver: complete.assess must return a CompletionVerdict {done, determinism}, got ${stringifySafe(verdict)}`,\n )\n }\n return verdict\n}\n\n/**\n * Compact, planner-facing rendering of trace-analyst findings — the diagnosis the\n * planner steers from. Empty input renders to '' (callers omit the section). Shows\n * severity·area·claim·recommended_action·confidence; raw evidence_refs/metadata are\n * for renderers that know the analyst, not the topology decision.\n * @experimental\n */\nexport function renderAnalyses(findings: ReadonlyArray<AnalystFinding>): string {\n if (findings.length === 0) return ''\n const rows = findings.map((f) => {\n const action = f.recommended_action ? ` → ${f.recommended_action}` : ''\n return ` - [${f.severity}/${f.area}] ${f.claim}${action} (conf ${f.confidence.toFixed(2)})`\n })\n return `Trace-analyst findings (diagnosis of the attempts so far — steer from these, not the verdict score alone):\\n${rows.join('\\n')}`\n}\n","/**\n * The ONE pseudo-box adapter: present any one-shot `Executor` (router / bridge /\n * BYO) as a `SandboxClient` so the round-synchronous `runLoop` can drive it\n * without each call site re-faking a box. This is the single shell that\n * `bench/src/router-executor.ts`, generate-eval's old `bridgeSandboxClient`, and\n * the search-bench bridge transport were each re-implementing.\n *\n * It is deliberately for NON-box executors only — a real sandbox harness already\n * IS a `SandboxClient` (boxes, sessions, fs, fork are real there). Here each\n * `streamPrompt` runs the executor once and emits the terminal\n * `{type:'result', data:{finalText, tokenUsage, costUsd}}` event that\n * `answerOutput`/the kernel's cost ledger already parse — no sessions, no fs,\n * no fork (those degrade gracefully via the optional `SandboxClient` methods).\n */\nimport type { CreateSandboxOptions, SandboxEvent, SandboxInstance } from '@tangle-network/sandbox'\nimport type { AgentSpec, Executor, ExecutorFactory, ExecutorResult } from './supervise/types'\nimport type { SandboxClient } from './types'\n\nfunction isAsyncIterable(v: unknown): v is AsyncIterable<unknown> {\n return typeof v === 'object' && v !== null && Symbol.asyncIterator in v\n}\n\n/** Drive a (possibly streaming) executor to its terminal artifact. */\nasync function settle(\n exec: Executor<unknown>,\n task: unknown,\n signal: AbortSignal,\n): Promise<ExecutorResult<unknown>> {\n const r = exec.execute(task, signal)\n if (isAsyncIterable(r)) {\n for await (const _ of r) {\n // streaming executors meter as they run; the artifact is read after drain.\n }\n return exec.resultArtifact()\n }\n return r\n}\n\n/**\n * Adapt an `ExecutorFactory` into a `SandboxClient` for `runLoop`. The factory is\n * instantiated fresh per `streamPrompt` (mirrors the per-spawn executor lifecycle):\n * run once on the prompt, emit the terminal result event, tear down.\n */\nexport function inlineSandboxClient(factory: ExecutorFactory<unknown>): SandboxClient {\n let seq = 0\n return {\n async create(_options?: CreateSandboxOptions): Promise<SandboxInstance> {\n const id = `inline-${seq++}`\n return {\n id,\n async *streamPrompt(message: string): AsyncGenerator<SandboxEvent> {\n const controller = new AbortController()\n const spec: AgentSpec = { profile: { name: id }, harness: null }\n const exec = factory(spec, { signal: controller.signal, seams: {} })\n try {\n const artifact = await settle(exec, message, controller.signal)\n const out = artifact.out as { content?: string } | undefined\n yield {\n type: 'result',\n data: {\n finalText: out?.content ?? '',\n tokenUsage: {\n inputTokens: artifact.spent.tokens.input,\n outputTokens: artifact.spent.tokens.output,\n },\n costUsd: artifact.spent.usd,\n },\n } as unknown as SandboxEvent\n } finally {\n await exec.teardown('brutalKill').catch(() => {})\n }\n },\n async delete(): Promise<void> {},\n } as unknown as SandboxInstance\n },\n }\n}\n","/**\n * Bridge a finished `runLoop` into an agent-eval campaign / profile-matrix\n * dispatch.\n *\n * `runProfileMatrix` (and `runCampaign`) run the backend-integrity guard over\n * the token usage a dispatch reports through `ctx.cost`. A dispatch that wraps\n * `runLoop` must forward the loop's cost AND token usage, or the guard reads\n * the run as a stub and throws. `reportLoopUsage` is that one line:\n *\n * const dispatch: ProfileDispatchFn<S, A> = async (profile, scenario, ctx) => {\n * const result = await runLoop({ ...optsFor(profile, scenario), ctx: loopCtx })\n * reportLoopUsage(ctx, result)\n * return result.winner?.output as A\n * }\n *\n * Typed structurally against the campaign `DispatchContext.cost` so this module\n * stays free of an agent-eval import — it works with any cost meter exposing\n * `observe` + `observeTokens`.\n */\n\nimport type { LoopResult, LoopTokenUsage } from './types'\n\n/** The slice of an agent-eval campaign `DispatchContext.cost` this needs. */\nexport interface UsageSink {\n observe(amountUsd: number, source: string): void\n observeTokens(usage: LoopTokenUsage): void\n}\n\n/**\n * Forward a `LoopResult`'s aggregated cost + token usage into a campaign cost\n * meter so the backend-integrity guard sees real LLM activity. `source`\n * defaults to `'loop'`.\n */\nexport function reportLoopUsage<Task, Output, Decision>(\n cost: UsageSink,\n result: Pick<LoopResult<Task, Output, Decision>, 'costUsd' | 'tokenUsage'>,\n source = 'loop',\n): void {\n cost.observe(result.costUsd, source)\n cost.observeTokens(result.tokenUsage)\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\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\nexport function defineRuntimeHooks(hooks: RuntimeHooks): RuntimeHooks {\n return hooks\n}\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 * 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, 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 * 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 * `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, 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: { maxConcurrency?: number; streaming?: 'sse' | 'poll' } = {},\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 // 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 })\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 })\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 OutputAdapter,\n SandboxClient,\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 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)\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 })\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(options, decision, iterations, loopStart, now, runId)\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)\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): 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 }),\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}\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)\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 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 */\nexport async function createSandboxForSpec<Task>(\n client: SandboxClient,\n spec: AgentRunSpec<Task>,\n signal: AbortSignal,\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 spec.prepareBox?.(box, { signal })\n return box\n}\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}\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 const winner = args.options.selectWinner\n ? args.options.selectWinner(args.iterations)\n : (args.options.driver.selectWinner?.(args.iterations) ?? defaultSelectWinner(args.iterations))\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 }\n return result\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): 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)\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): Promise<LoopResult<Task, Output, Decision>> {\n const result = finalize({ options, decision, iterations, startMs, now, runId })\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 * 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 * `loopDispatch` — turn `runLoop` into an agent-eval campaign dispatch.\n *\n * Without this adapter a consumer wiring `runLoop` into `runProfileMatrix` /\n * `runCampaign` has to, by hand, every time: (a) build an `ExecCtx` with a\n * sandbox client, (b) adapt the campaign `DispatchContext.trace` into a\n * `LoopTraceEmitter` (or lose all loop trace correlation), and (c) remember to\n * forward the loop's cost + tokens via `ctx.cost` (forgetting it yields a\n * `{0,0}` cell the backend-integrity guard reads as a stub). Three foot-guns,\n * the third silent. The fleet's products skipped (c) and fell back to a\n * `workerRecords[]` side-channel — the exact anti-pattern the substrate exists\n * to kill.\n *\n * `loopDispatch` collapses all three into one typed call:\n *\n * const dispatch = loopDispatch({\n * sandboxClient,\n * toLoopOptions: (scenario, profile) => ({ driver, agentRun, output, validator, task }),\n * })\n * await runProfileMatrix({ profiles, scenarios, dispatch, judges, commitSha })\n *\n * Usage is reported automatically; trace events are forwarded automatically;\n * the ctx is built automatically. The seam becomes impossible to mis-wire.\n *\n * Typed structurally against the campaign `DispatchContext` (imported type-only\n * from `@tangle-network/agent-eval/campaign`) — a downward dependency, never an\n * inversion.\n */\n\n// agent-eval's AgentProfile (the eval-harness unit of variation, `model: string`)\n// — NOT sandbox's AgentProfile. ProfileDispatchFn is keyed on the former.\nimport type { AgentProfile } from '@tangle-network/agent-eval'\nimport type {\n CampaignTraceWriter,\n DispatchContext,\n ProfileDispatchFn,\n Scenario,\n} from '@tangle-network/agent-eval/campaign'\nimport { reportLoopUsage } from './report-usage'\nimport { type RunLoopOptions, runLoop } from './run-loop'\nimport type { LoopResult, LoopTraceEmitter, SandboxClient } from './types'\n\n/** runLoop options minus the `ctx` (loopDispatch builds the ctx). */\nexport type LoopOptionsForDispatch<Task, Output, Decision> = Omit<\n RunLoopOptions<Task, Output, Decision>,\n 'ctx'\n>\n\nexport interface LoopDispatchOptions<\n Task,\n Output,\n Decision,\n TScenario extends Scenario,\n TArtifact,\n> {\n /** Sandbox client used for every cell's `runLoop`. Supplied once. */\n sandboxClient: SandboxClient\n /** Build the per-cell runLoop options from the scenario (+ profile, when\n * used with `runProfileMatrix`). */\n toLoopOptions: (\n scenario: TScenario,\n profile: AgentProfile,\n ) => LoopOptionsForDispatch<Task, Output, Decision>\n /** Map the finished loop to the artifact the judges score. Default:\n * `result.winner?.output`. A loop with no winner yields `undefined` (judges\n * skip the cell) — but the loop's token usage is STILL reported, so the\n * integrity guard sees real activity. */\n toArtifact?: (result: LoopResult<Task, Output, Decision>) => TArtifact\n /** Forward `loop.*` trace events into the campaign's scoped trace so loop\n * spans correlate with the cell. Default true. */\n forwardTrace?: boolean\n /** Cost-meter source label for the loop's spend. Default `'loop'`. */\n costSource?: string\n}\n\n/** Bridge a campaign `DispatchContext.trace` to a `LoopTraceEmitter` so every\n * `loop.*` event lands as a span under the cell's scoped trace. */\nfunction campaignTraceToLoopEmitter(trace: CampaignTraceWriter): LoopTraceEmitter {\n return {\n emit(event) {\n trace\n .span(event.kind, { runId: event.runId, timestamp: event.timestamp, ...event.payload })\n .end()\n },\n }\n}\n\nasync function runLoopForCell<Task, Output, Decision, TScenario extends Scenario, TArtifact>(\n opts: LoopDispatchOptions<Task, Output, Decision, TScenario, TArtifact>,\n scenario: TScenario,\n profile: AgentProfile,\n ctx: DispatchContext,\n): Promise<TArtifact> {\n const loopOptions = opts.toLoopOptions(scenario, profile)\n const result = await runLoop<Task, Output, Decision>({\n ...loopOptions,\n ctx: {\n sandboxClient: opts.sandboxClient,\n signal: ctx.signal,\n traceEmitter: opts.forwardTrace === false ? undefined : campaignTraceToLoopEmitter(ctx.trace),\n },\n })\n reportLoopUsage(ctx.cost, result, opts.costSource ?? 'loop')\n const toArtifact =\n opts.toArtifact ?? ((r: LoopResult<Task, Output, Decision>) => r.winner?.output as TArtifact)\n return toArtifact(result)\n}\n\n/**\n * Adapter for `runProfileMatrix` (profile is an axis). Returns a\n * `ProfileDispatchFn` that runs `runLoop` per (profile, scenario) cell and\n * reports usage automatically.\n */\nexport function loopDispatch<Task, Output, Decision, TScenario extends Scenario, TArtifact>(\n opts: LoopDispatchOptions<Task, Output, Decision, TScenario, TArtifact>,\n): ProfileDispatchFn<TScenario, TArtifact> {\n return (profile, scenario, ctx) => runLoopForCell(opts, scenario, profile, ctx)\n}\n","/**\n * The third-person observer — the connective tissue that closes the loop.\n *\n * A driver spawns a worker; the worker can't see itself. `observe` reads the\n * worker's TRACE (what it actually did — every tool call, cost, failure) and\n * produces two streams:\n * - `findings` / `report` — fed back DOWN (a steer for the next attempt) and\n * OUT (the operator-facing \"what I noticed + what to change\").\n * - `learned` — durable facts written to the cross-run `Corpus` so the NEXT\n * run starts smarter (the continuous half of \"continuous self-improvement\").\n *\n * Findings are TRACE-derived, never JUDGE-derived (`derived_from_judge:false`):\n * the observer reads behavior, never the acceptance verdict — the selector≠judge\n * firewall (docs/learning-flywheel.md). The observer is harness-agnostic: it\n * reads a trace + an output, so it watches opencode, codex, hermes, or a BYO\n * agent identically.\n */\nimport { type AnalystFinding, type ChatClient, makeFinding } from '@tangle-network/agent-eval'\nimport type { Corpus, CorpusRecord } from './personify/wave-types'\n\nconst observerId = 'observe/trace'\n\nexport interface ObserveInput {\n /** What the worker was asked to do. */\n task: string\n /** What it produced (its final answer / artifact summary). */\n output: string\n /** The worker's trace — any event array (sandbox events, tool-call records). */\n trace: ReadonlyArray<unknown>\n /** Terminal status only (passed/failed/unknown) — NOT a judge score; the\n * observer never reads the verdict, it reads behavior. */\n outcome?: 'passed' | 'failed' | 'unknown'\n /** Provenance back to the run. */\n runId?: string\n}\n\nexport interface ObserveOptions {\n /** The model-call seam (agent-eval `createChatClient`: router / cli-bridge / …). */\n chat: ChatClient\n model?: string\n /** When set, learned facts are appended (idempotent) for the next run to read. */\n corpus?: Corpus\n /** Tags written onto learned facts + used by the next run's corpus query. */\n tags?: ReadonlyArray<string>\n signal?: AbortSignal\n /** Cap the trace lines fed to the observer (keeps the call cheap). Default 80. */\n maxTraceLines?: number\n}\n\nexport interface Observation {\n findings: AnalystFinding[]\n /** Facts persisted to the corpus (empty when no corpus was supplied). */\n learned: CorpusRecord[]\n /** Operator-facing markdown: what the observer noticed + what to change. */\n report: string\n}\n\n/** Compact the trace into the lines the observer reasons over — tool calls,\n * errors, and statuses, in order. Keeps the model call bounded + grounded. */\nfunction summarizeTrace(trace: ReadonlyArray<unknown>, maxLines: number): string {\n const lines: string[] = []\n for (const ev of trace) {\n const e = ev as { type?: string; data?: Record<string, unknown> }\n const t = (e.type ?? '').toLowerCase()\n const d = e.data ?? {}\n const part = (d.part ?? {}) as { type?: string; tool?: string; state?: { status?: string } }\n if (part.type === 'tool')\n lines.push(`tool:${part.tool}${part.state?.status ? `(${part.state.status})` : ''}`)\n else if (t.includes('error'))\n lines.push(`ERROR: ${String(d.message ?? d.detail ?? '').slice(0, 200)}`)\n else if (t === 'status' && typeof d.status === 'string') lines.push(`status:${d.status}`)\n else if (t.includes('tool')) lines.push(`tool-event:${t}`)\n }\n // Collapse runs of identical lines into \"xN\" so repeated thrash is visible + short.\n const out: string[] = []\n for (const ln of lines) {\n const prev = out[out.length - 1]\n const m = prev?.match(/^(.*?)(?: x(\\d+))?$/)\n if (m && m[1] === ln) out[out.length - 1] = `${ln} x${(Number(m[2]) || 1) + 1}`\n else out.push(ln)\n }\n return out.slice(0, maxLines).join('\\n') || '(no tool/error events in trace)'\n}\n\nconst findingsSchema = {\n name: 'observer_findings',\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n findings: {\n type: 'array',\n items: {\n type: 'object',\n additionalProperties: false,\n properties: {\n area: {\n type: 'string',\n description: 'tool-use | cost | verification | process | failure | latency',\n },\n severity: { type: 'string', enum: ['critical', 'high', 'medium', 'low', 'info'] },\n claim: {\n type: 'string',\n description: 'what you OBSERVED in the trace (a fact, with the evidence)',\n },\n recommended_action: {\n type: 'string',\n description: 'the concrete change for the agent or operator',\n },\n audience: {\n type: 'string',\n enum: ['agent', 'operator'],\n description: 'who should act on this',\n },\n confidence: { type: 'number' },\n },\n required: ['area', 'severity', 'claim', 'recommended_action', 'audience', 'confidence'],\n },\n },\n },\n required: ['findings'],\n },\n} as const\n\nexport async function observe(input: ObserveInput, opts: ObserveOptions): Promise<Observation> {\n const traceSummary = summarizeTrace(input.trace, opts.maxTraceLines ?? 80)\n const res = await opts.chat.chat(\n {\n ...(opts.model ? { model: opts.model } : {}),\n jsonSchema: findingsSchema as unknown as { name: string; schema: Record<string, unknown> },\n messages: [\n {\n role: 'system',\n content:\n 'You are a third-person OBSERVER watching an AI agent work. You see its TRACE (what it did), not its grader. ' +\n 'From the trace, name SPECIFIC, behavior-grounded findings: wasted/duplicated tool calls, thrash/retries, ' +\n 'token/cost waste, missing verification, failure patterns. For each, a concrete recommended_action, and ' +\n 'whether the AGENT (fix its skills/prompt/tools) or the OPERATOR (fix framing/decomposition/config) should act. ' +\n 'Only claim what the trace shows. No findings if the run was clean.',\n },\n {\n role: 'user',\n content:\n `TASK: ${input.task}\\n\\nOUTCOME: ${input.outcome ?? 'unknown'}\\n\\n` +\n `FINAL OUTPUT (truncated):\\n${input.output.slice(0, 1200)}\\n\\n` +\n `TRACE (in order; \"xN\" = repeated):\\n${traceSummary}`,\n },\n ],\n },\n { ...(opts.signal ? { signal: opts.signal } : {}) },\n )\n\n const parsed = parseFindings(res.content)\n const producedAt = input.runId ? `${input.runId}` : observerId\n const findings: AnalystFinding[] = parsed.map((f) =>\n makeFinding({\n analyst_id: observerId,\n area: `${f.area}`,\n severity: f.severity,\n claim: f.claim,\n recommended_action: f.recommended_action,\n confidence: typeof f.confidence === 'number' ? f.confidence : 0.5,\n evidence_refs: [],\n // The observer reads BEHAVIOR, never the judge verdict — firewall provenance.\n derived_from_judge: false,\n metadata: { audience: f.audience },\n ...(input.runId ? { subject: input.runId } : {}),\n }),\n )\n\n const learned: CorpusRecord[] = []\n if (opts.corpus) {\n for (const f of findings) {\n const record: CorpusRecord = {\n schemaVersion: '1.0.0',\n id: f.finding_id,\n runId: input.runId ?? observerId,\n producedAt: f.produced_at ?? producedAt,\n area: f.area,\n claim: f.recommended_action ?? f.claim,\n ...(f.claim ? { rationale: f.claim } : {}),\n tags: [...(opts.tags ?? []), `audience:${(f.metadata?.audience as string) ?? 'agent'}`],\n confidence: f.confidence,\n evidence: [{ kind: 'finding', uri: f.finding_id }],\n }\n const r = await opts.corpus.append(record)\n if (r.succeeded) learned.push(record)\n }\n }\n\n return { findings, learned, report: renderReport(findings) }\n}\n\ninterface RawFinding {\n area: string\n severity: AnalystFinding['severity']\n claim: string\n recommended_action: string\n audience: 'agent' | 'operator'\n confidence: number\n}\n\nfunction parseFindings(content: string): RawFinding[] {\n let obj: unknown\n try {\n obj = JSON.parse(content)\n } catch {\n const m = content.match(/\\{[\\s\\S]*\\}/)\n obj = m ? JSON.parse(m[0]) : { findings: [] }\n }\n const arr = (obj as { findings?: unknown }).findings\n return Array.isArray(arr) ? (arr as RawFinding[]) : []\n}\n\n/** Operator-facing report, split by who should act. The agent block is the\n * steer; the operator block is the advice. */\nexport function renderReport(findings: ReadonlyArray<AnalystFinding>): string {\n if (findings.length === 0) return '✓ clean run — the observer found nothing to change.'\n const audience = (f: AnalystFinding): string => (f.metadata?.audience as string) ?? 'agent'\n const forAgent = findings.filter((f) => audience(f) === 'agent')\n const forOperator = findings.filter((f) => audience(f) === 'operator')\n const block = (title: string, fs: ReadonlyArray<AnalystFinding>): string =>\n fs.length === 0\n ? ''\n : `**${title}**\\n${fs\n .map((f) => `- [${f.severity}] ${f.claim}\\n → ${f.recommended_action ?? ''}`)\n .join('\\n')}\\n`\n return [\n block('For the agent (fix skills / prompt / tools)', forAgent),\n block('For you (the operator)', forOperator),\n ]\n .filter(Boolean)\n .join('\\n')\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 | { kind: 'done'; out: unknown; outRef: string; verdict?: DefaultVerdict; spent: Spend }\n | { kind: 'down'; reason: string; infra: boolean; restartCount: number }\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 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 const ctx: ExecutorContext = { signal: childAbort.signal, seams: args.seams }\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 return {\n spawn,\n next,\n send,\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 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 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 if (childAbort.signal.aborted) {\n await teardownSafe(executor, opts.shutdown ?? 'brutalKill')\n return downRecord('aborted before settle', true)\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 }\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 return downRecord(errMessage(err), aborted || isInfraError(err))\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): PreSeqSettled {\n return { kind: 'down', reason, infra, restartCount: 0 }\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 * @experimental\n *\n * The generic combinator library — the content-free act-bodies the wave's §1 contract froze.\n *\n * Each export is a `CombinatorShape<Task, D>` (an alias of `LoopShape<Task, D>`): a factory\n * `(ShapeContext) => Agent<Task, Outcome<D>>` whose `act` runs ONE composition shape over the\n * keystone `Scope` — spawn children through `ctx.spawnChild` + `scope.spawn`, drain settlements\n * via `scope.next()`, select across `done` children with the SINGLE-SOURCED `settledToIteration`\n * + `defaultSelectWinner` (selector≠judge — never a re-rank behind the driver), and synthesize a\n * terminal `Outcome<D>`.\n *\n * The shapes carry NO domain: a \"research sweep over angles\" is `fanout(angles, { synthesize })`\n * under a research persona; a \"code build test\" is `pipeline([plan, implement, integrate])` under\n * a coder persona. The SHAPE is here; the model/prompt/role/goal live on the `Persona` + task,\n * threaded to each child verbatim by the spec-objects the builders take. No model name, prompt,\n * role, or domain noun appears below.\n *\n * Two fail-loud invariants every combinator honors: a child the conserved pool cannot admit is a\n * CONCRETE blocker (never an eager over-fan, never a silent drop), and a `blocked` outcome always\n * names at least one blocker (a shape that cannot finish MUST say why — `blocked([])` throws).\n */\n\nimport { ValidationError } from '../../errors'\nimport { defaultSelectWinner } from '../run-loop'\nimport { settledToIteration } from '../supervise/scope'\nimport type { Agent, Scope, Settled } from '../supervise/types'\nimport type { Iteration } from '../types'\nimport type { Outcome, ShapeContext } from './types'\nimport type {\n CombinatorShape,\n FanoutOptions,\n LoopUntilSpec,\n LoopUntilState,\n PanelJudge,\n PanelSpec,\n PanelVerdict,\n PipelineStage,\n ScopeWidenGate,\n VerifySpec,\n WidenDecision,\n WidenSpec,\n} from './wave-types'\n\n// ── pipeline — sequential composition, first blocked stage short-circuits ─────────\n\n/**\n * `pipeline(stages)` — run the stages in order, feeding each stage's `done` deliverable into the\n * next stage's task. The first stage that ends `blocked` (a child that went down, a child the\n * pool would not admit, or a stage whose `collect` chose to block) short-circuits — its blockers\n * ARE the pipeline's blockers, never coerced past a failed stage. The terminal stage's `done`\n * deliverable is the pipeline's deliverable.\n */\nexport function pipeline<Task, D>(\n stages: ReadonlyArray<PipelineStage<Task, unknown, unknown>>,\n): CombinatorShape<Task, D> {\n if (stages.length === 0) {\n throw new ValidationError('pipeline: at least one stage is required')\n }\n return (ctx: ShapeContext<D>): Agent<Task, Outcome<D>> => ({\n name: `${ctx.persona.name}/pipeline`,\n async act(task, scope): Promise<Outcome<D>> {\n let carry: unknown = task\n for (const stage of stages) {\n const child = ctx.spawnChild(stage.label, ctx.persona.root)\n const res = scope.spawn(child, stage.feed(carry, ctx, task), {\n budget: ctx.budget.perChild,\n label: stage.label,\n })\n if (!res.ok) {\n return blocked([`${stage.label}: not admitted (${res.reason})`])\n }\n const settled = await drainOne(scope, stage.label)\n const out = stage.collect(settled as Settled<Outcome<unknown>>)\n if (out.kind === 'blocked') return out\n carry = out.deliverable\n }\n return { kind: 'done', deliverable: carry as D }\n },\n })\n}\n\n// ── fanout — N children in one round, optional single synthesis child ─────────────\n\n/**\n * `fanout(items, opts)` — spawn one child per item in a single round (bounded by the conserved\n * pool's fail-closed admission), drain via `scope.next()`, then either synthesize over the\n * gathered settlements (one SEPARATE synthesis child) or return the best-valid child via the\n * single-sourced selector. A round that admitted zero children, or whose synthesis child could\n * not be admitted, is a concrete blocker.\n */\nexport function fanout<Task, Item, D>(\n items: ReadonlyArray<Item>,\n opts: FanoutOptions<Item, D>,\n): CombinatorShape<Task, D> {\n return (ctx: ShapeContext<D>): Agent<Task, Outcome<D>> => ({\n name: `${ctx.persona.name}/fanout`,\n async act(_task, scope): Promise<Outcome<D>> {\n const rejected: string[] = []\n let opened = 0\n for (const [i, item] of items.entries()) {\n const label = opts.label ? opts.label(item, i) : `item:${i}`\n const child = ctx.spawnChild(label, ctx.persona.root)\n const res = scope.spawn(child, opts.itemTask(item, i, ctx), {\n budget: ctx.budget.perChild,\n label,\n })\n if (res.ok) opened += 1\n else rejected.push(`${label}: not admitted (${res.reason})`)\n }\n if (opened === 0) {\n return blocked(\n rejected.length > 0\n ? rejected\n : ['fanout: budget admitted no item (fanout fully rejected)'],\n )\n }\n\n const drained = await drain<D>(scope)\n if (drained.done.length === 0) {\n return blocked(\n orderedBlockers(\n drained.blockers,\n rejected,\n 'fanout: every item settled without a usable result',\n ),\n )\n }\n\n if (!opts.synthesize) {\n const winner = defaultSelectWinner(drained.iterations)\n if (!winner || winner.output === undefined) {\n return blocked(\n orderedBlockers(drained.blockers, rejected, 'fanout: no item survived selection'),\n )\n }\n return { kind: 'done', deliverable: winner.output as D }\n }\n\n const synthLabel = 'synthesize'\n const synthChild = ctx.spawnChild(synthLabel, ctx.persona.root)\n const synthRes = scope.spawn(synthChild, opts.synthesize.synthesisTask(drained.done, ctx), {\n budget: ctx.budget.perChild,\n label: synthLabel,\n })\n if (!synthRes.ok) {\n return blocked([...drained.blockers, `${synthLabel}: not admitted (${synthRes.reason})`])\n }\n const synthSettled = await drainOne(scope, synthLabel)\n const out = opts.synthesize.collect(synthSettled)\n if (out.kind === 'blocked') return out\n return out\n },\n })\n}\n\n// ── loopUntil — budget-bounded iterative deepening, deployable non-oracle stop ────\n\n/**\n * `loopUntil(seed, spec)` — one `step` child per round; `fold` accumulates each settlement into\n * the running state; `until` (reading the round's trace findings, NOT a fresh raw verdict) is\n * the deployable stop. The conserved pool IS the loop bound: once `spawn` fails closed the loop\n * stops. A loop that exhausted the pool without `until` ever satisfying is a concrete blocker.\n *\n * Findings are threaded through the `SteerContext` firewall in the analyst seam (`analyst.ts`);\n * absent a wired analyst on this surface the firewall stays dormant and `until` is consulted with\n * an empty findings array — never a fabricated finding (fail-loud honesty over a silent default).\n */\nexport function loopUntil<Task, State, D>(\n seed: State,\n spec: LoopUntilSpec<Task, State, D>,\n): CombinatorShape<Task, D> {\n return (ctx: ShapeContext<D>): Agent<Task, Outcome<D>> => ({\n name: `${ctx.persona.name}/loopUntil`,\n async act(task, scope): Promise<Outcome<D>> {\n let state: LoopUntilState<State> = { round: 0, value: seed }\n const blockers: string[] = []\n for (;;) {\n const label = spec.label ? spec.label(state.round) : `step:${state.round}`\n const child = ctx.spawnChild(label, ctx.persona.root)\n const res = scope.spawn(child, spec.step(task, state, ctx), {\n budget: ctx.budget.perChild,\n label,\n })\n if (!res.ok) {\n if (state.round === 0) return blocked([`${label}: not admitted (${res.reason})`])\n break\n }\n const settled = await drainOne(scope, label)\n if (settled.kind === 'down') blockers.push(blockerFromDown(settled))\n state = spec.fold(state, settled)\n const reached = spec.until(state, [])\n if (reached) return reached\n state = { round: state.round + 1, value: state.value }\n }\n return blocked(\n blockers.length > 0\n ? blockers\n : ['loopUntil: budget exhausted before the satisfiability gate was reached'],\n )\n },\n })\n}\n\n// ── panel — M judges over ONE artifact, write-only merge (selector≠judge limit) ───\n\n/**\n * `panel(spec)` — spawn the M judge children over the SAME artifact, drain their settlements,\n * and fold them into a panel verdict via the pure WRITE-ONLY `merge` (a judge's output never\n * reaches another judge's task; the merge never spawns or re-ranks). A `down` judge carries no\n * verdict and is excluded from the merge denominator. A panel that admitted no judge is a\n * concrete blocker before `merge` is consulted.\n */\nexport function panel<Task, Artifact, D>(spec: PanelSpec<Artifact, D>): CombinatorShape<Task, D> {\n if (spec.judges.length === 0) {\n throw new ValidationError('panel: at least one judge is required')\n }\n return (ctx: ShapeContext<D>): Agent<Task, Outcome<D>> => ({\n name: `${ctx.persona.name}/panel`,\n async act(task, scope): Promise<Outcome<D>> {\n const artifact = task as unknown as Artifact\n const byLabel = new Map<string, PanelJudge>()\n const rejected: string[] = []\n let opened = 0\n for (const judge of spec.judges) {\n const child = ctx.spawnChild(judge.label, ctx.persona.root)\n const res = scope.spawn(child, spec.judgeTask(artifact, judge, ctx), {\n budget: ctx.budget.perChild,\n label: judge.label,\n })\n if (res.ok) {\n byLabel.set(judge.label, judge)\n opened += 1\n } else {\n rejected.push(`${judge.label}: not admitted (${res.reason})`)\n }\n }\n if (opened === 0) {\n return blocked(rejected.length > 0 ? rejected : ['panel: budget admitted no judge'])\n }\n\n const verdicts: PanelVerdict[] = []\n for (let s = await scope.next(); s !== null; s = await scope.next()) {\n const judge = byLabel.get(s.handle.label)\n if (!judge) {\n throw new ValidationError(\n `panel: settled child \"${s.handle.label}\" has no judge descriptor`,\n )\n }\n if (s.kind === 'down') {\n verdicts.push({ judge, down: true })\n continue\n }\n verdicts.push({\n judge,\n down: false,\n ...(s.verdict ? { verdict: s.verdict } : {}),\n output: s.out,\n })\n }\n return spec.merge(verdicts, artifact)\n },\n })\n}\n\n// ── verify — 2-node implement→verifier gate (selector≠judge) ──────────────────────\n\n/**\n * `verify(spec)` — an IMPLEMENT child produces a candidate, then a SEPARATE VERIFIER child grades\n * it; only a `valid` verifier verdict ships. Any other outcome (implement down, verifier down,\n * verifier verdict absent or not `valid`) is a concrete blocker carrying the failure verbatim —\n * never a coerced \"done\". The implement child does not grade itself.\n */\nexport function verify<Task, Candidate, D>(\n spec: VerifySpec<Task, Candidate, D>,\n): CombinatorShape<Task, D> {\n return (ctx: ShapeContext<D>): Agent<Task, Outcome<D>> => ({\n name: `${ctx.persona.name}/verify`,\n async act(task, scope): Promise<Outcome<D>> {\n const implementLabel = spec.implementLabel ?? 'implement'\n const implChild = ctx.spawnChild(implementLabel, ctx.persona.root)\n const implRes = scope.spawn(implChild, spec.implement(task, ctx), {\n budget: ctx.budget.perChild,\n label: implementLabel,\n })\n if (!implRes.ok) return blocked([`${implementLabel}: not admitted (${implRes.reason})`])\n const candidate = await drainOne(scope, implementLabel)\n if (candidate.kind === 'down') return blocked([blockerFromDown(candidate)])\n\n const verifierLabel = spec.verifierLabel ?? 'verify'\n const verifierChild = ctx.spawnChild(verifierLabel, ctx.persona.root)\n const verifierRes = scope.spawn(\n verifierChild,\n spec.verifier(candidate as Settled<Outcome<Candidate>>, ctx),\n { budget: ctx.budget.perChild, label: verifierLabel },\n )\n if (!verifierRes.ok)\n return blocked([`${verifierLabel}: not admitted (${verifierRes.reason})`])\n const gate = await drainOne(scope, verifierLabel)\n if (gate.kind === 'down') return blocked([blockerFromDown(gate)])\n if (!gate.verdict || gate.verdict.valid !== true) {\n return blocked([`${verifierLabel}: gate rejected the candidate (${verdictDetail(gate)})`])\n }\n return spec.collect(candidate as Settled<Outcome<Candidate>>, gate.verdict)\n },\n })\n}\n\n// ── widen — streaming progressive widening (G5), FLAT by default ──────────────────\n\n/**\n * `widen(spec)` — the streaming spawn-on-completion driver. Spawns the seed lineages, then REACTS\n * to each `scope.next()`: on every settled child it consults `spec.gate.decide` and, when the gate\n * returns `widen`, spawns AT MOST ONE more child toward the chosen lineage under the remaining\n * conserved pool. `promising` is derived from the round's trace findings (the analyst seam),\n * never a child's raw `verdict` — and the default gate (`flatWidenGate`) never widens, so the R2\n * firewall stays dormant. Terminal selection is `spec.synthesize` over every settled lineage.\n *\n * No analyst is wired on this frozen surface, so `decide` is consulted with an empty findings\n * array; a flat gate ignores it. A non-flat gate that wants findings reads them through the\n * `SteerContext` firewall the analyst seam owns — never fabricated here.\n */\nexport function widen<Task, Seed, D>(spec: WidenSpec<Seed, D>): CombinatorShape<Task, D> {\n return (ctx: ShapeContext<D>): Agent<Task, Outcome<D>> => ({\n name: `${ctx.persona.name}/widen`,\n async act(_task, scope): Promise<Outcome<D>> {\n let opened = 0\n for (const [i, seed] of spec.seeds.entries()) {\n const label = `seed:${i}`\n const child = ctx.spawnChild(label, ctx.persona.root)\n const res = scope.spawn(child, spec.seedTask(seed, i, ctx), {\n budget: ctx.budget.perChild,\n label,\n })\n if (res.ok) opened += 1\n }\n if (opened === 0) {\n return blocked(['widen: budget admitted no seed lineage'])\n }\n\n const gathered: Settled<Outcome<D>>[] = []\n let widenIndex = 0\n for (let s = await scope.next(); s !== null; s = await scope.next()) {\n gathered.push(s)\n const decision: WidenDecision<D> = spec.gate.decide(s, [], scope.budget)\n if (decision.kind !== 'widen') continue\n const label = `widen:${widenIndex}`\n widenIndex += 1\n const child = ctx.spawnChild(label, ctx.persona.root)\n // Fail-closed admission bounds the widening — a rejected widen is simply not opened\n // (the gate may widen again off a later settlement); the budget is the breadth bound.\n scope.spawn(child, spec.widenTask(decision.toward, ctx), {\n budget: ctx.budget.perChild,\n label,\n })\n }\n\n const done = gathered.filter(isDone)\n if (done.length === 0) {\n return blocked(\n orderedBlockers(\n gathered.filter(isDown).map(blockerFromDown),\n [],\n 'widen: every lineage settled without a usable result',\n ),\n )\n }\n return spec.synthesize(done, ctx)\n },\n })\n}\n\n/**\n * The flat default `ScopeWidenGate` — never widens, keeping the R2 selector≠judge collision\n * dormant. A gate run passes this explicitly; a test asserts the default is flat.\n */\nexport function flatWidenGate<D>(): ScopeWidenGate<D> {\n return {\n decide(): WidenDecision<D> {\n return { kind: 'stop' }\n },\n }\n}\n\n// ── Shared drain / select / blocker microstructure ────────────────────────────────\n\n/** Drain every remaining settlement: project `done` children into kernel `Iteration`s for the\n * single-sourced selector + keep the `done` settlements (for a synthesis child), and collect\n * `down` children as concrete blockers (their reason surfaced verbatim). */\nasync function drain<D>(scope: Scope<Outcome<D>>): Promise<{\n iterations: Iteration<unknown, Outcome<D>>[]\n done: Settled<Outcome<D>>[]\n blockers: string[]\n}> {\n const iterations: Iteration<unknown, Outcome<D>>[] = []\n const done: Settled<Outcome<D>>[] = []\n const blockers: string[] = []\n for (let s = await scope.next(); s !== null; s = await scope.next()) {\n if (s.kind === 'down') {\n blockers.push(blockerFromDown(s))\n continue\n }\n iterations.push(settledToIteration(s))\n done.push(s)\n }\n return { iterations, done, blockers }\n}\n\n/**\n * Drain exactly one settlement off a scope whose prior children are fully drained, so `next()`\n * yields precisely the child just spawned. Fail loud if it yields nothing — a spawned child that\n * never settles is a keystone invariant violation, not a result the combinator may swallow.\n */\nasync function drainOne<D>(scope: Scope<Outcome<D>>, label: string): Promise<Settled<Outcome<D>>> {\n const s = await scope.next()\n if (s === null) {\n throw new ValidationError(`combinator: child \"${label}\" was spawned but never settled`)\n }\n return s\n}\n\nfunction isDone<D>(s: Settled<Outcome<D>>): s is Extract<Settled<Outcome<D>>, { kind: 'done' }> {\n return s.kind === 'done'\n}\n\nfunction isDown<D>(s: Settled<Outcome<D>>): s is Extract<Settled<Outcome<D>>, { kind: 'down' }> {\n return s.kind === 'down'\n}\n\nfunction blockerFromDown<D>(s: Extract<Settled<Outcome<D>>, { kind: 'down' }>): string {\n return `${s.handle.label}: ${s.infra ? 'infra' : 'failed'} — ${s.reason}`\n}\n\nfunction verdictDetail<D>(s: Extract<Settled<Outcome<D>>, { kind: 'done' }>): string {\n if (!s.verdict) return 'no verdict'\n return s.verdict.notes ?? `score ${s.verdict.score}`\n}\n\n/** Compose the round's drained blockers + rejected-admission reasons, falling back to a named\n * default ONLY when neither produced a reason — a `blocked` outcome must never be vacuous. */\nfunction orderedBlockers(drained: string[], rejected: string[], fallback: string): string[] {\n const all = [...drained, ...rejected]\n return all.length > 0 ? all : [fallback]\n}\n\n/** Build a `blocked` outcome, failing loud on the empty-blocker contract violation (a shape that\n * cannot finish MUST name at least one concrete blocker — never a vacuous block). */\nfunction blocked<D>(blockers: string[]): Extract<Outcome<D>, { kind: 'blocked' }> {\n if (blockers.length === 0) {\n throw new ValidationError('combinator: a blocked outcome must name at least one blocker')\n }\n return { kind: 'blocked', blockers }\n}\n","/**\n * @experimental\n *\n * The cross-run corpus (G2) — the learning-flywheel's durable accreted-fact store.\n *\n * `Corpus` is DISTINCT from the per-run `SpawnJournal` (decisions/replay) and `ResultBlobStore`\n * (payloads): a `CorpusRecord` is a FACT one run LEARNED that a FUTURE run reads back (the\n * world-model), not a replay input. This module owns the two impls the wave surface pins —\n * `InMemoryCorpus` and `FileCorpus` (JSONL, append-only) — plus `renderCorpusToInstructions`,\n * the READ side that projects accreted facts into a fresh `AgentProfile`'s instruction seams.\n *\n * The boundary is fail-loud, typed-outcome: `append` is idempotent on an identical record and\n * returns a typed error (never throws, never a silent overwrite) on a conflicting re-append under\n * the same `id`. Malformed records — a structurally-invalid `CorpusRecord` from disk or a caller —\n * fail loud (the validator throws), since a corpus that silently accepts garbage would poison\n * every downstream run that reads it back.\n */\n\nimport type { AgentProfile } from '@tangle-network/sandbox'\nimport type {\n Corpus,\n CorpusFilter,\n CorpusRecord,\n RenderCorpusToInstructionsOptions,\n} from './wave-types'\n\n// ── Record validation ────────────────────────────────────────────────────────\n\nconst corpusSchemaVersion = '1.0.0'\n\n/**\n * Assert a value is a well-formed `CorpusRecord`. A PROVENANCE-and-shape check: every\n * identity/render-gating field must be present and typed, `confidence` must be a finite 0..1,\n * `evidence` (when present) must be `{ kind, uri }[]`. Throws on any violation — a corpus that\n * silently accepted a malformed fact would project garbage into a future run's prompt. The\n * thrown message names the offending field so a bad on-disk line is diagnosable.\n */\nexport function assertCorpusRecord(value: unknown, where: string): asserts value is CorpusRecord {\n if (typeof value !== 'object' || value === null) {\n throw new Error(`${where}: corpus record is not an object`)\n }\n const r = value as Record<string, unknown>\n if (r.schemaVersion !== corpusSchemaVersion) {\n throw new Error(\n `${where}: corpus record schemaVersion '${String(r.schemaVersion)}' != '${corpusSchemaVersion}'`,\n )\n }\n requireNonEmptyString(r.id, `${where}.id`)\n requireNonEmptyString(r.runId, `${where}.runId`)\n requireNonEmptyString(r.producedAt, `${where}.producedAt`)\n requireNonEmptyString(r.area, `${where}.area`)\n requireNonEmptyString(r.claim, `${where}.claim`)\n if (r.rationale !== undefined && typeof r.rationale !== 'string') {\n throw new Error(`${where}.rationale: expected string, got ${typeof r.rationale}`)\n }\n if (!Array.isArray(r.tags) || r.tags.some((t) => typeof t !== 'string')) {\n throw new Error(`${where}.tags: expected string[]`)\n }\n if (typeof r.confidence !== 'number' || !Number.isFinite(r.confidence)) {\n throw new Error(`${where}.confidence: expected a finite number, got ${String(r.confidence)}`)\n }\n if (r.confidence < 0 || r.confidence > 1) {\n throw new Error(`${where}.confidence: ${r.confidence} is outside the [0, 1] range`)\n }\n if (r.evidence !== undefined) {\n if (!Array.isArray(r.evidence)) {\n throw new Error(`${where}.evidence: expected an array`)\n }\n for (let i = 0; i < r.evidence.length; i++) {\n const ev = r.evidence[i] as Record<string, unknown> | null\n if (typeof ev !== 'object' || ev === null) {\n throw new Error(`${where}.evidence[${i}]: not an object`)\n }\n requireNonEmptyString(ev.kind, `${where}.evidence[${i}].kind`)\n requireNonEmptyString(ev.uri, `${where}.evidence[${i}].uri`)\n }\n }\n}\n\nfunction requireNonEmptyString(value: unknown, where: string): void {\n if (typeof value !== 'string' || value.length === 0) {\n throw new Error(`${where}: expected a non-empty string, got ${describe(value)}`)\n }\n}\n\nfunction describe(value: unknown): string {\n if (value === undefined) return 'undefined'\n if (value === null) return 'null'\n if (typeof value === 'string') return `'${value}'`\n return typeof value\n}\n\n// ── Identity + idempotence ───────────────────────────────────────────────────\n\n/**\n * Two records collide IFF they share an `id`. An append under an already-stored `id` is idempotent\n * only when the new record is byte-identical to the stored one (same fact, re-learned); any other\n * field differing under the same `id` is a CONFLICT — a typed-error append, never a silent\n * overwrite. The identity field is `id`; the producer mints it over its identity-defining fields\n * (claim + tags) so a re-learned fact dedups.\n */\nfunction recordsEqual(a: CorpusRecord, b: CorpusRecord): boolean {\n return stableStringify(a) === stableStringify(b)\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(([x], [y]) => (x < y ? -1 : x > y ? 1 : 0))\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(',')}}`\n}\n\n// ── Query ─────────────────────────────────────────────────────────────────────\n\n/**\n * Apply a `CorpusFilter` as an AND-narrowing over a record list and sort most-confident first\n * (ties → most-recent `producedAt`, so the freshest of two equally-confident facts wins). Pure —\n * the in-mem and file impls both route their reads through this so query semantics are\n * single-sourced. An empty result is valid (not an error).\n */\nfunction applyFilter(\n records: ReadonlyArray<CorpusRecord>,\n filter: CorpusFilter,\n): ReadonlyArray<CorpusRecord> {\n const matched = records.filter((r) => {\n if (filter.area !== undefined && r.area !== filter.area) return false\n if (filter.runId !== undefined && r.runId !== filter.runId) return false\n if (filter.minConfidence !== undefined && r.confidence < filter.minConfidence) return false\n if (filter.tags !== undefined && !filter.tags.every((t) => r.tags.includes(t))) return false\n return true\n })\n const ordered = [...matched].sort((a, b) =>\n b.confidence !== a.confidence\n ? b.confidence - a.confidence\n : b.producedAt < a.producedAt\n ? -1\n : b.producedAt > a.producedAt\n ? 1\n : 0,\n )\n if (filter.limit !== undefined) {\n if (!Number.isInteger(filter.limit) || filter.limit < 0) {\n throw new Error(\n `corpus query: filter.limit must be a non-negative integer, got ${filter.limit}`,\n )\n }\n return ordered.slice(0, filter.limit)\n }\n return ordered\n}\n\n// ── In-memory corpus ────────────────────────────────────────────────────────\n\n/**\n * In-memory `Corpus`. Keyed by record `id`; `append` validates the record, is idempotent on an\n * identical re-append, and returns a typed `{ succeeded: false }` on a conflicting re-append under\n * the same `id` (never overwrites). `query` routes through the single-sourced `applyFilter`.\n */\nexport class InMemoryCorpus implements Corpus {\n private readonly byId = new Map<string, CorpusRecord>()\n\n async append(\n record: CorpusRecord,\n ): Promise<{ succeeded: true } | { succeeded: false; error: string }> {\n try {\n assertCorpusRecord(record, 'append: record')\n } catch (err) {\n return { succeeded: false, error: err instanceof Error ? err.message : String(err) }\n }\n const existing = this.byId.get(record.id)\n if (existing) {\n if (recordsEqual(existing, record)) return { succeeded: true }\n return {\n succeeded: false,\n error:\n `corpus conflict: id '${record.id}' is already stored with a different record; ` +\n 'a learned fact is append-only — re-mint the id or reconcile before re-appending',\n }\n }\n this.byId.set(record.id, freeze(record))\n return { succeeded: true }\n }\n\n async query(filter: CorpusFilter): Promise<ReadonlyArray<CorpusRecord>> {\n return applyFilter([...this.byId.values()], filter)\n }\n}\n\n// ── File corpus (JSONL, append-only) ──────────────────────────────────────────\n\n/**\n * JSONL on disk — one validated `CorpusRecord` per line, append-only. `query` replays the whole\n * file, validating every line (a malformed line fails loud — a corrupted corpus must never read\n * back silently) and folding by `id`: a later identical line dedups, a later conflicting line\n * under the same `id` is a corruption (fail loud). `append` first replays to enforce the same\n * idempotence/conflict contract as the in-mem impl, then fsyncs the new line so a crash between\n * writes never loses an acknowledged fact. Shares the JSONL append-line spine with the spawn\n * journal, but the interface stays separate (a learned fact is not a replay record).\n */\nexport class FileCorpus implements Corpus {\n constructor(private readonly path: string) {}\n\n async append(\n record: CorpusRecord,\n ): Promise<{ succeeded: true } | { succeeded: false; error: string }> {\n try {\n assertCorpusRecord(record, 'append: record')\n } catch (err) {\n return { succeeded: false, error: err instanceof Error ? err.message : String(err) }\n }\n let stored: Map<string, CorpusRecord>\n try {\n stored = await this.load()\n } catch (err) {\n return { succeeded: false, error: err instanceof Error ? err.message : String(err) }\n }\n const existing = stored.get(record.id)\n if (existing) {\n if (recordsEqual(existing, record)) return { succeeded: true }\n return {\n succeeded: false,\n error:\n `corpus conflict: id '${record.id}' is already stored in ${this.path} with a different ` +\n 'record; a learned fact is append-only — re-mint the id or reconcile before re-appending',\n }\n }\n await this.appendLine(record)\n return { succeeded: true }\n }\n\n async query(filter: CorpusFilter): Promise<ReadonlyArray<CorpusRecord>> {\n const stored = await this.load()\n return applyFilter([...stored.values()], filter)\n }\n\n private async load(): Promise<Map<string, CorpusRecord>> {\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 new Map()\n throw err\n }\n const lines = text.split('\\n').filter((line) => line.length > 0)\n const byId = new Map<string, CorpusRecord>()\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] as string\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n throw new Error(\n `corpus corrupted: ${this.path} line ${i + 1} is not valid JSON: ` +\n (err instanceof Error ? err.message : String(err)),\n )\n }\n assertCorpusRecord(parsed, `corpus ${this.path} line ${i + 1}`)\n const existing = byId.get(parsed.id)\n if (existing && !recordsEqual(existing, parsed)) {\n throw new Error(\n `corpus corrupted: ${this.path} has two different records for id '${parsed.id}'; ` +\n 'an append-only corpus must never hold a conflicting re-append under one id',\n )\n }\n byId.set(parsed.id, freeze(parsed))\n }\n return byId\n }\n\n private async appendLine(record: CorpusRecord): 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\n// ── Render-back: project accreted facts into a profile's instruction seams ─────\n\n/**\n * The learning-flywheel READ side. Queries the corpus through `filter`, renders the matching facts\n * (most-confident first, capped by `maxLines`) into instruction lines, and returns a FRESH\n * `AgentProfile` with them merged in — never mutates the input profile. Default `target: 'prompt'`\n * appends the lines to `prompt.instructions[]` (the additive append-line seam); `target:\n * 'resources'` folds them into the single-blob `resources.instructions` string (preserving any\n * existing blob, but failing loud on a non-string existing blob — a `resources.instructions` that\n * was already an `AgentProfileResourceRef` cannot be string-appended without dropping it).\n *\n * An empty query result returns a fresh COPY of the profile with no instruction change (a valid\n * \"nothing learned yet\" read, not an error).\n */\nexport async function renderCorpusToInstructions(\n opts: RenderCorpusToInstructionsOptions,\n): Promise<AgentProfile> {\n const { corpus, filter, profile, target = 'prompt', maxLines } = opts\n if (maxLines !== undefined && (!Number.isInteger(maxLines) || maxLines < 0)) {\n throw new Error(\n `renderCorpusToInstructions: maxLines must be a non-negative integer, got ${maxLines}`,\n )\n }\n const matched = await corpus.query(filter)\n const capped = maxLines !== undefined ? matched.slice(0, maxLines) : matched\n const lines = capped.map(renderLine)\n\n if (lines.length === 0) return structuredClone(profile)\n\n const next = structuredClone(profile)\n if (target === 'resources') {\n const resources = next.resources ?? {}\n const prior = resources.instructions\n if (prior !== undefined && typeof prior !== 'string') {\n throw new Error(\n 'renderCorpusToInstructions: resources.instructions is an AgentProfileResourceRef, not a ' +\n 'string; cannot string-append corpus facts without dropping the ref (pass target: ' +\n \"'prompt' or pre-resolve the ref)\",\n )\n }\n const blob = [prior, ...lines].filter((s): s is string => typeof s === 'string' && s.length > 0)\n next.resources = { ...resources, instructions: blob.join('\\n') }\n return next\n }\n\n const prompt = next.prompt ?? {}\n next.prompt = { ...prompt, instructions: [...(prompt.instructions ?? []), ...lines] }\n return next\n}\n\n/** One corpus fact → one instruction line. The claim is the line; a rationale (when present) is\n * appended in parentheses so a reader sees the why without a second line. Content-only — no\n * metric/score/verdict text is synthesized (the corpus holds facts, not selector evidence). */\nfunction renderLine(record: CorpusRecord): string {\n return record.rationale ? `${record.claim} (${record.rationale})` : record.claim\n}\n\n// ── Internal helpers ───────────────────────────────────────────────────────────\n\nfunction freeze(record: CorpusRecord): CorpusRecord {\n return Object.freeze({ ...record })\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 * 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 { estimateCost, isModelPriced } from '@tangle-network/agent-eval'\nimport type { BackendType, SandboxEvent } from '@tangle-network/sandbox'\nimport { ValidationError } from '../../errors'\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 type {\n AgentSpec,\n DefaultVerdict,\n Executor,\n ExecutorContext,\n ExecutorFactory,\n ExecutorRegistry,\n ExecutorResult,\n Runtime,\n Spend,\n UsageEvent,\n} from './types'\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-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 */\nexport interface BridgeSeam {\n bridgeUrl: string\n bridgeBearer: string\n model: string\n agentProfile?: Record<string, unknown>\n timeoutMs?: number\n}\n\nconst routerSeamKey = 'router'\nconst sandboxSeamKey = 'sandbox'\nconst cliSeamKey = 'cli'\nconst bridgeSeamKey = 'bridge'\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 * NOTE for the Integrate phase: this duplicates the minimal body of\n * `bench/src/router-client.ts#routerChatWithUsage`. `bench/` is a sub-package\n * outside this package's `rootDir: \"src\"`, so it cannot be imported here without\n * breaking the build. Integrate should lift that helper into `src/loops/` and\n * have both call sites share it (do not re-copy a third time).\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 res = await fetch(`${seam.routerBaseUrl.replace(/\\/$/, '')}/chat/completions`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${seam.routerKey}` },\n body: JSON.stringify({ model, messages, temperature: 0.2 }),\n ...(linked ? { signal: linked } : {}),\n })\n if (!res.ok) {\n throw new ValidationError(\n `routerInlineExecutor: router ${res.status}: ${(await res.text()).slice(0, 200)}`,\n )\n }\n const data = (await res.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 usd = usage && isModelPriced(model) ? estimateCost(usage.input, usage.output, model) : 0\n const content = data.choices?.[0]?.message?.content ?? ''\n const spent: Spend = {\n iterations: 1,\n tokens: usage ? { input: usage.input, output: usage.output } : zeroTokenUsage(),\n usd,\n ms: Date.now() - started,\n }\n const out = { content } as unknown\n artifact = { outRef: contentRef('router', { model, 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\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 * One harness turn through the cli-bridge: a single OpenAI-compatible chat call\n * whose `model` selects the harness and whose `agent_profile` carries the arm\n * (native-tool disables, provider MCPs). One-shot like router/inline; reports\n * 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 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: 'cli' 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 timer = seam.timeoutMs\n ? setTimeout(() => controller.abort(), seam.timeoutMs)\n : undefined\n try {\n const res = await fetch(`${seam.bridgeUrl.replace(/\\/$/, '')}/v1/chat/completions`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${seam.bridgeBearer}`,\n },\n body: JSON.stringify({\n model: seam.model,\n stream: false,\n ...(seam.agentProfile ? { agent_profile: seam.agentProfile } : {}),\n messages,\n }),\n ...(linked ? { signal: linked } : {}),\n })\n if (!res.ok) {\n throw new ValidationError(\n `bridgeExecutor: bridge ${res.status}: ${(await res.text()).slice(0, 300)}`,\n )\n }\n const data = (await res.json()) as {\n choices?: Array<{\n message?: { content?: string; tool_calls?: Array<{ function?: { name?: string } }> }\n }>\n usage?: { prompt_tokens?: number; completion_tokens?: number; cost?: 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 msg = data.choices?.[0]?.message\n const content = msg?.content ?? ''\n const toolCalls = (msg?.tool_calls ?? []).map((t) => t.function?.name ?? 'unknown')\n const spent: Spend = {\n iterations: 1,\n tokens: usage ? { input: usage.input, output: usage.output } : zeroTokenUsage(),\n usd: typeof u?.cost === 'number' ? u.cost : 0,\n ms: Date.now() - started,\n }\n const out = { content, toolCalls } as unknown\n artifact = { outRef: contentRef('bridge', { model: seam.model, content }), out, spent }\n return artifact\n } finally {\n if (timer) clearTimeout(timer)\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 execute()')\n }\n return { ...artifact, spent: artifact.spent }\n },\n }\n}\n\n// ── createExecutor: the ONE built-in factory (backend as data) ──────────────────\n\n/**\n * The single built-in executor entrypoint. The backend is DATA — the cost dial a\n * profile, an experiment config, or a replay journal can name — not an import\n * choice. Injects the matching seam and delegates to the built-in implementation;\n * the port stays OPEN: bring-your-own agents implement `Executor` directly and\n * never pass through here.\n */\nexport type ExecutorConfig =\n | ({ backend: 'router' } & RouterSeam)\n | ({ backend: 'bridge' } & BridgeSeam)\n | ({ backend: 'cli' } & CliSeam)\n | ({ backend: 'sandbox'; harness?: BackendType } & SandboxSeam)\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 'bridge':\n return bridgeExecutor(spec, seamed)\n case 'cli':\n return cliExecutor(spec, seamed)\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// 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). */\nexport type BudgetReadout = Readonly<{\n tokensLeft: number\n usdLeft: number\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 /** 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 readout(): BudgetReadout {\n return {\n tokensLeft: freeTokens,\n usdLeft: usdCapped ? freeUsd : 0,\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 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`,\n * reads `spentTotal` off the conserved pool, and wraps it as a typed `winner` — it does\n * 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 // The driver synthesized a winner. Content-address it for the replay `outRef`, put\n // it once, and sum the conserved spend off every journaled settlement. No\n // re-ranking — the driver already selected.\n const out = actOutcome.out\n const outRef = contentAddress(out)\n await opts.blobs.put(outRef, out)\n return {\n kind: 'winner',\n out,\n outRef,\n tree,\n spentTotal: await spentTotalFromJournal(journal, opts.runId),\n }\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 {\n kind: 'no-winner',\n reason: classifyNoWinner(controller, pool, opts, breaker),\n tree,\n downCount: breaker.downCount(),\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 spentTotalFromJournal(journal: SpawnJournal, root: string): Promise<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 total: Spend = { iterations: 0, tokens: { input: 0, output: 0 }, usd: 0, ms: 0 }\n for (const ev of events) {\n if (ev.kind !== 'settled') continue\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 * @experimental\n *\n * The loop-shape registry — the OPEN, content-free extension point for the personify layer.\n *\n * A `LoopShape` is reusable STRUCTURE (how to decompose / fan out / verify / synthesize),\n * parameterized by a persona's CONTENT. The registry lets a caller resolve a composed shape by\n * NAME: register a factory once, then `runPersonified({ shape: '<name>' })` resolves it with zero\n * edits elsewhere. `register` fails loud on a duplicate; `resolve` returns a typed outcome so an\n * unknown name is a named error, never a silent default.\n *\n * No shape is pre-registered: the generic combinators (`pipeline`/`fanout`/`loopUntil`/`panel`/\n * `verify`/`widen`) take spec arguments, so they are not bare zero-arg factories — a caller that\n * wants name-resolution registers its own COMPOSED shape (a combinator already applied to its\n * spec) on a registry instance. The registry carries SHAPE only; the domain lives on the persona.\n */\n\nimport { ValidationError } from '../../errors'\nimport type { LoopShape, ShapeRegistry } from './types'\n\n/**\n * Build a fresh open `ShapeRegistry`. A factory is stored type-erased and re-cast on resolve — the\n * caller asserts the `<Task, D>` it expects, exactly as the executor registry stores its factories.\n */\nexport function createShapeRegistry(): ShapeRegistry {\n const shapes = new Map<string, LoopShape<unknown, unknown>>()\n return {\n register<Task, D>(name: string, factory: LoopShape<Task, D>): void {\n if (shapes.has(name)) {\n throw new ValidationError(`shape registry: shape \"${name}\" already registered`)\n }\n shapes.set(name, factory as LoopShape<unknown, unknown>)\n },\n resolve<Task, D>(name: string) {\n const factory = shapes.get(name)\n if (!factory) {\n return { succeeded: false as const, error: `shape registry: unknown shape \"${name}\"` }\n }\n return { succeeded: true as const, value: factory as LoopShape<Task, D> }\n },\n names(): string[] {\n return [...shapes.keys()]\n },\n }\n}\n\n/** The default registry `runPersonified` resolves a shape name against. Empty by construction —\n * a caller registers its own composed shapes; the engine ships no domain shape. */\nexport const builtinShapes: ShapeRegistry = createShapeRegistry()\n\n/** Register a composed shape on the default `builtinShapes` registry — the one-call extension\n * point a caller invokes so its shape is resolvable by name with zero edits to the engine. */\nexport function registerShape<Task, D>(name: string, factory: LoopShape<Task, D>): void {\n builtinShapes.register(name, factory)\n}\n","/**\n * @experimental\n *\n * The personify layer impl — `definePersona` (the thin builder) + `runPersonified` (composes\n * the persona + chosen shape onto the keystone `Supervisor`), plus `createShapeContext`, the\n * seam that hands a shape its spawn helpers without it touching the registry.\n *\n * This file adds NO engine: `runPersonified` is `createSupervisor().run(rootAgent, task, …)`\n * where `rootAgent` is the persona's chosen `LoopShape` applied to a `ShapeContext`. All the\n * conserved-budget / journal / abort / typed-result machinery is the keystone's; this layer\n * only wires the persona's CONTENT (root spec + directive + context + seams) into it.\n *\n * One non-obvious invariant it must honor: `createSupervisor().run` builds the root `Scope`\n * with an EMPTY seam bag (`seams: {}`), so the built-in metered runtimes (router/sandbox/cli)\n * cannot read their seams off `ExecutorContext` through the default supervisor path. A persona\n * that supplies raw `seams` is therefore wrapped here into a registry whose resolved factories\n * receive a ctx with the persona seams merged in — so a persona never has to pre-close its\n * factories by hand. A persona may instead supply a fully-built `registry` and skip the wrap.\n */\n\nimport { InMemoryResultBlobStore, InMemorySpawnJournal } from '../../durable/spawn-journal'\nimport { ValidationError } from '../../errors'\nimport { createExecutorRegistry } from '../supervise/runtime'\nimport { createSupervisor } from '../supervise/supervisor'\nimport type {\n Agent,\n AgentSpec,\n Budget,\n ExecutorContext,\n ExecutorFactory,\n ExecutorRegistry,\n Runtime,\n SupervisedResult,\n SupervisorOpts,\n} from '../supervise/types'\nimport { builtinShapes } from './registry'\nimport type {\n DefinePersonaInput,\n LoopShape,\n Outcome,\n Persona,\n RunPersonifiedOptions,\n ShapeBudget,\n ShapeContext,\n} from './types'\n\n// ── definePersona ─────────────────────────────────────────────────────────────\n\n/**\n * Build a frozen `Persona`. Fails loud on the executors-supplied invariant: a persona with\n * neither a pre-built registry nor a seam bag cannot resolve its built-in runtimes, so it is\n * unrunnable — refuse it at definition time, not at the first spawn. Pure; no I/O.\n */\nexport function definePersona<D = unknown>(input: DefinePersonaInput<D>): Persona<D> {\n if (!input.executors.registry && !input.executors.seams) {\n throw new ValidationError(\n `definePersona(\"${input.name}\"): executors must supply a registry or a seams bag ` +\n '(built-in runtimes read their seams off ExecutorContext; neither was provided)',\n )\n }\n if (!input.root || typeof input.root !== 'object' || !('harness' in input.root)) {\n throw new ValidationError(`definePersona(\"${input.name}\"): root must be an AgentSpec`)\n }\n return Object.freeze({\n name: input.name,\n root: input.root,\n directive: input.directive,\n context: input.context,\n executors: input.executors,\n ...(input.extensions ? { extensions: input.extensions } : {}),\n }) as Persona<D>\n}\n\n// ── ShapeContext construction ───────────────────────────────────────────────────\n\n/**\n * Build the `ShapeContext` a `LoopShape` factory consumes. `spawnChild` wraps an `AgentSpec`\n * into a leaf `Agent` carrying it as `executorSpec` (the structural field `scope.spawn`\n * reads); `childSpec` derives a narrower child spec from the persona's root by overriding the\n * profile. The shape never touches the registry — resolution stays single-sourced in the\n * scope/registry the supervisor owns.\n */\nexport function createShapeContext<D>(persona: Persona<D>, budget: ShapeBudget): ShapeContext<D> {\n return {\n persona,\n budget,\n spawnChild(name, spec): Agent<unknown, Outcome<D>> {\n // The wrapped agent is SPAWNED, not run — the resolved Executor drives it. `act`\n // is never invoked by the keystone for a spawned child; it throws if mis-used as a\n // root (fail loud) rather than silently returning a vacuous outcome.\n const agent = {\n name,\n executorSpec: spec,\n act(): Promise<Outcome<D>> {\n throw new ValidationError(\n `personify: spawned child \"${name}\" was run as a driver; its executorSpec drives a leaf`,\n )\n },\n }\n return agent as Agent<unknown, Outcome<D>> & { executorSpec: AgentSpec }\n },\n childSpec(profile, harness): AgentSpec {\n return {\n profile,\n harness: harness === undefined ? persona.root.harness : harness,\n ...(persona.root.executor ? { executor: persona.root.executor } : {}),\n }\n },\n }\n}\n\n// ── runPersonified ──────────────────────────────────────────────────────────────\n\n/**\n * Compose the persona + chosen shape onto a fresh keystone `Supervisor`. Resolves the shape\n * (a factory verbatim, or a registered name through `builtinShapes`), applies it to a\n * `ShapeContext`, and runs the resulting root `Agent` to a typed `SupervisedResult<Outcome>`.\n * Fail loud on an unknown shape name or an unresolvable persona registry — never a silent\n * default-shape fallback.\n */\nexport async function runPersonified<Task, D>(\n options: RunPersonifiedOptions<Task, D>,\n): Promise<SupervisedResult<Outcome<D>>> {\n const { persona } = options\n const shape = resolveShape<Task, D>(options.shape)\n const shapeBudget = resolveShapeBudget(options.budget, options.shapeBudget)\n const ctx = createShapeContext(persona, shapeBudget)\n const rootAgent = shape(ctx)\n\n const executors = personaRegistry(persona)\n const supervisor = createSupervisor<Task, Outcome<D>>()\n if (options.handle) supervisor.attach(options.handle)\n\n const supervisorOpts: SupervisorOpts = {\n budget: options.budget,\n runId: options.runId ?? `${persona.name}:${shapeName(options.shape, shape)}`,\n journal: options.journal ?? new InMemorySpawnJournal(),\n blobs: options.blobs ?? new InMemoryResultBlobStore(),\n executors,\n ...(options.maxDepth !== undefined ? { maxDepth: options.maxDepth } : {}),\n ...(options.maxRestarts !== undefined ? { maxRestarts: options.maxRestarts } : {}),\n ...(options.withinMs !== undefined ? { withinMs: options.withinMs } : {}),\n ...(options.now ? { now: options.now } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n }\n return supervisor.run(rootAgent, options.task, supervisorOpts)\n}\n\n// ── Resolution helpers ──────────────────────────────────────────────────────────\n\nfunction resolveShape<Task, D>(shape: LoopShape<Task, D> | string): LoopShape<Task, D> {\n if (typeof shape !== 'string') return shape\n const resolved = builtinShapes.resolve<Task, D>(shape)\n if (!resolved.succeeded) {\n throw new ValidationError(\n `runPersonified: ${resolved.error} (registered: ${builtinShapes.names().join(', ')})`,\n )\n }\n return resolved.value\n}\n\nfunction shapeName<Task, D>(\n shape: LoopShape<Task, D> | string,\n _resolved: LoopShape<Task, D>,\n): string {\n return typeof shape === 'string' ? shape : shape.name || 'shape'\n}\n\n/**\n * Default the shape's per-child sizing + fanout width from the root budget when the caller\n * omits them. The per-child token ceiling is the root divided across the fanout so the\n * conserved pool can admit a full round; iterations default to the root's. A caller override\n * wins per-field.\n */\nfunction resolveShapeBudget(root: Budget, over?: Partial<ShapeBudget>): ShapeBudget {\n const fanout = over?.fanout ?? defaultFanout\n const perChild: Budget = over?.perChild ?? {\n maxIterations: Math.max(1, Math.floor(root.maxIterations / fanout)),\n maxTokens: Math.max(1, Math.floor(root.maxTokens / fanout)),\n ...(root.maxUsd !== undefined ? { maxUsd: root.maxUsd / fanout } : {}),\n ...(root.deadlineMs !== undefined ? { deadlineMs: root.deadlineMs } : {}),\n }\n return { perChild, fanout }\n}\n\nconst defaultFanout = 3\n\n/**\n * Resolve the persona's executor resolution into a single `ExecutorRegistry`. A pre-built\n * `registry` is used verbatim; otherwise the persona's raw `seams` are wrapped so resolved\n * factories receive an `ExecutorContext` with the persona seams merged in — the supervisor\n * threads an empty bag, so this is the one place the persona seams reach the built-ins.\n */\nfunction personaRegistry<D>(persona: Persona<D>): ExecutorRegistry {\n const { registry, seams } = persona.executors\n if (registry) return registry\n if (!seams) {\n throw new ValidationError(\n `personify: persona \"${persona.name}\" supplies neither a registry nor seams`,\n )\n }\n return withSeams(createExecutorRegistry(), seams)\n}\n\n/**\n * Wrap a registry so every resolved `ExecutorFactory` receives a ctx whose `seams` are\n * the persona seams merged over whatever the scope threaded (the scope threads `{}`, so the\n * persona seams win). A BYO `spec.executor` still resolves to a trivial factory that ignores\n * ctx — so this wrap is transparent for BYO and only matters for the metered built-ins.\n */\nfunction withSeams(\n base: ExecutorRegistry,\n seams: Readonly<Record<string, unknown>>,\n): ExecutorRegistry {\n return {\n register<Out>(runtime: Runtime, factory: ExecutorFactory<Out>): void {\n base.register(runtime, factory)\n },\n resolve<Out>(spec: AgentSpec) {\n const resolved = base.resolve<Out>(spec)\n if (!resolved.succeeded) return resolved\n const inner = resolved.value\n const wrapped: ExecutorFactory<Out> = (s, ctx) => inner(s, mergeSeams(ctx, seams))\n return { succeeded: true, value: wrapped }\n },\n }\n}\n\nfunction mergeSeams(\n ctx: ExecutorContext,\n seams: Readonly<Record<string, unknown>>,\n): ExecutorContext {\n return { signal: ctx.signal, seams: { ...seams, ...ctx.seams } }\n}\n","/**\n * @experimental\n *\n * Trajectory trace + cost ledger — the post-hoc tree reconstructor (§4 of `wave-types`).\n *\n * `trajectoryReport` rebuilds the WHOLE realized spawn tree from the durable\n * `SpawnJournal` (+ optionally the `ResultBlobStore` for `done` artifacts): every node\n * (driver AND leaf), the real parent/child edges, each node's terminal status, its OWN\n * conserved `Spend`, and the `Spend` ROLLED UP over its subtree. Roll-up is a post-order\n * fold over the parent edges: a node's `rolledUpSpend` is its own spend plus every\n * descendant's, so a driver is charged for the fanout it caused — the root's roll-up is\n * the whole run's conserved total (tokens + usd + iterations + ms).\n *\n * `equalKOnCost` compares separate runs (arms) on that conserved COST, not on raw\n * iteration COUNT. The sandbox executor reports tokens/usd INCLUSIVE of a leaf's internal\n * sub-agent fanout, so charging an arm by `total.tokens`/`total.usd` (not by how many\n * `next()` cursors it logged) closes the leaf-fanout confound: a treatment leaf that fanned\n * out internally pays for it in cost, where a per-iteration count would hide it. The\n * within-run conserved pool already guarantees `Σk` equal by construction; this check is the\n * CROSS-run analogue the pool cannot reach — proving equal compute before any win is claimed.\n *\n * Pure over the journal/blobs — no live agent calls; safe to run on a finished run's log.\n */\n\nimport type {\n DefaultVerdict,\n NodeId,\n ResultBlobStore,\n SpawnEvent,\n SpawnJournal,\n Spend,\n} from '../supervise/types'\nimport { addTokenUsage, zeroTokenUsage } from '../util'\nimport type {\n EqualKArm,\n EqualKOnCostOptions,\n EqualKVerdict,\n TrajectoryNode,\n TrajectoryReport,\n TrajectoryReportOptions,\n} from './wave-types'\n\nconst defaultEqualKTolerance = 0.05\n\n/**\n * Reconstruct the whole spawn tree for `root` with per-node + rolled-up `Spend`. Reads the\n * journal for structure + spend and, when `withOutputs`, the blob store for each `done`\n * node's artifact. Fail loud on a tree that was never journaled, a settle/cancel for an\n * un-spawned node (a corrupted log), or — under `withOutputs` — a `done` node whose blob the\n * store cannot rehydrate (a silent gap would mis-cost or mis-evidence the tree).\n */\nexport async function trajectoryReport(\n journal: SpawnJournal,\n blobs: ResultBlobStore,\n root: NodeId,\n options: TrajectoryReportOptions = {},\n): Promise<TrajectoryReport> {\n const events = await journal.loadTree(root)\n if (events === undefined) {\n throw new Error(`trajectoryReport: no journaled tree for root '${root}'`)\n }\n\n // Spawns (ordinal seq) create the nodes; settlements/cancellations (cursor seq) close\n // them. The two seq namespaces overlap, so create every node from its `spawned` event\n // first, then apply settlements/cancellations — mirrors `materializeTreeView`.\n const spawns = events.filter(isSpawned).sort(bySeq)\n const closes = events.filter((ev) => ev.kind !== 'spawned').sort(bySeq)\n\n const nodes = new Map<NodeId, MutableNode>()\n for (const ev of spawns) {\n nodes.set(ev.id, {\n id: ev.id,\n parent: ev.parent,\n label: ev.label,\n runtime: ev.runtime,\n status: 'pending',\n ownSpend: zeroSpend(),\n children: [],\n })\n }\n for (const ev of closes) {\n const node = requireNode(nodes, ev.id, root)\n if (ev.kind === 'cancelled') {\n node.status = 'cancelled'\n continue\n }\n node.status = ev.status === 'done' ? 'done' : 'failed'\n node.ownSpend = ev.spent\n node.verdict = ev.verdict\n node.outRef = ev.outRef\n }\n\n if (!nodes.has(root)) {\n throw new Error(\n `trajectoryReport: root '${root}' has no spawned event in its journaled tree (corrupted log)`,\n )\n }\n\n // Wire the realized parent/child edges in spawn order, then roll spend up the tree.\n for (const ev of spawns) {\n if (ev.parent === undefined) continue\n requireNode(nodes, ev.parent, root).children.push(ev.id)\n }\n const rolledUp = rollUpSpend(nodes, root)\n\n if (options.withOutputs) {\n await attachOutputs(nodes, blobs)\n }\n\n // Emit in spawn order so the node list reads as the realized tree, root first.\n const ordered = spawns.map((ev) => nodes.get(ev.id)).filter(isNode)\n const reported: TrajectoryNode[] = ordered.map((node) =>\n freezeNode(node, requireSpend(rolledUp, node.id, root)),\n )\n\n return {\n root,\n nodes: reported,\n total: requireSpend(rolledUp, root, root),\n statusCounts: countStatuses(reported),\n }\n}\n\n/**\n * Assert the arms are comparable at EQUAL conserved COST (tokens + usd), NOT raw iteration\n * count. Compares each arm's root-rolled-up `total` on the two conserved channels: an arm is\n * within-tolerance when the per-channel spread (max − min across arms) over the median is\n * `≤ tolerance`. Pure over the reports — no I/O. Fails loud on an empty arm list (nothing to\n * compare) so a vacuous \"equal\" is never returned.\n */\nexport function equalKOnCost(\n arms: ReadonlyArray<EqualKArm>,\n options: EqualKOnCostOptions = {},\n): EqualKVerdict {\n if (arms.length === 0) {\n throw new Error('equalKOnCost: no arms to compare')\n }\n const tolerance = options.tolerance ?? defaultEqualKTolerance\n\n const armCosts = arms.map((arm) => ({\n label: arm.label,\n tokens: arm.report.total.tokens.input + arm.report.total.tokens.output,\n usd: arm.report.total.usd,\n iterations: arm.report.total.iterations,\n }))\n\n const tokenValues = armCosts.map((a) => a.tokens)\n const usdValues = armCosts.map((a) => a.usd)\n const spread = {\n tokens: spreadOf(tokenValues),\n usd: spreadOf(usdValues),\n }\n const withinTolerance =\n fractionalSpread(tokenValues) <= tolerance && fractionalSpread(usdValues) <= tolerance\n\n return {\n withinTolerance,\n arms: armCosts,\n spread,\n tolerance,\n }\n}\n\n// ── Tree fold internals ────────────────────────────────────────────────────────\n\ninterface MutableNode {\n id: NodeId\n parent?: NodeId\n label: string\n runtime: string\n status: TrajectoryNode['status']\n ownSpend: Spend\n children: NodeId[]\n verdict?: DefaultVerdict\n output?: unknown\n outRef?: string\n}\n\n/**\n * Post-order fold: a node's rolled-up spend is its own spend plus every child's rolled-up\n * spend. Iterative (an explicit stack) so a deep tree never overflows the call stack; a node\n * is finalized only after all its children are, so the parent edges are honored exactly.\n */\nfunction rollUpSpend(nodes: Map<NodeId, MutableNode>, root: NodeId): Map<NodeId, Spend> {\n const rolled = new Map<NodeId, Spend>()\n const stack: { id: NodeId; expanded: boolean }[] = [{ id: root, expanded: false }]\n while (stack.length > 0) {\n const frame = stack.pop()\n if (frame === undefined) continue\n const node = requireNode(nodes, frame.id, root)\n if (!frame.expanded) {\n stack.push({ id: frame.id, expanded: true })\n for (const child of node.children) stack.push({ id: child, expanded: false })\n continue\n }\n const sum = cloneSpend(node.ownSpend)\n for (const child of node.children) addSpend(sum, requireSpend(rolled, child, root))\n rolled.set(frame.id, sum)\n }\n return rolled\n}\n\n/**\n * Rehydrate each `done` node's artifact from the blob store. Fail loud on a `done` node whose\n * blob the store cannot resolve — a missing payload under `withOutputs` is a corrupted store,\n * not an absent output (a `down`/`cancelled` node legitimately has none).\n */\nasync function attachOutputs(\n nodes: Map<NodeId, MutableNode>,\n blobs: ResultBlobStore,\n): Promise<void> {\n for (const node of nodes.values()) {\n if (node.status !== 'done' || node.outRef === undefined) continue\n const out = await blobs.get(node.outRef)\n if (out === undefined) {\n throw new Error(\n `trajectoryReport: blob store has no artifact for outRef '${node.outRef}' (node '${node.id}')`,\n )\n }\n node.output = out\n }\n}\n\nfunction freezeNode(node: MutableNode, rolledUpSpend: Spend): TrajectoryNode {\n return {\n id: node.id,\n parent: node.parent,\n children: [...node.children],\n label: node.label,\n runtime: node.runtime,\n status: node.status,\n ownSpend: node.ownSpend,\n rolledUpSpend,\n verdict: node.verdict,\n output: node.output,\n outRef: node.outRef,\n }\n}\n\nfunction countStatuses(\n reported: ReadonlyArray<TrajectoryNode>,\n): Readonly<Record<TrajectoryNode['status'], number>> {\n const counts: Record<TrajectoryNode['status'], number> = {\n done: 0,\n failed: 0,\n cancelled: 0,\n pending: 0,\n }\n for (const node of reported) counts[node.status] += 1\n return counts\n}\n\n// ── Spend arithmetic (single-sourced on `addTokenUsage`) ─────────────────────────\n\nfunction zeroSpend(): Spend {\n return { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 }\n}\n\nfunction cloneSpend(spend: Spend): Spend {\n return {\n iterations: spend.iterations,\n tokens: { input: spend.tokens.input, output: spend.tokens.output },\n usd: spend.usd,\n ms: spend.ms,\n }\n}\n\n/** Add `delta` into `acc` in place across every conserved channel. */\nfunction addSpend(acc: Spend, delta: Spend): void {\n acc.iterations += delta.iterations\n addTokenUsage(acc.tokens, delta.tokens)\n acc.usd += delta.usd\n acc.ms += delta.ms\n}\n\n// ── Cross-arm spread ─────────────────────────────────────────────────────────────\n\nfunction spreadOf(values: ReadonlyArray<number>): number {\n if (values.length === 0) return 0\n return Math.max(...values) - Math.min(...values)\n}\n\n/**\n * Fractional spread on one channel: `(max − min) / median`. A zero-median channel (every arm\n * spent zero on it) is trivially equal — spread is also zero, so it never trips the tolerance.\n */\nfunction fractionalSpread(values: ReadonlyArray<number>): number {\n const spread = spreadOf(values)\n if (spread === 0) return 0\n const median = medianOf(values)\n if (median === 0) {\n throw new Error(\n 'equalKOnCost: arms have a non-zero cost spread on a zero-median channel; cannot express it as a fraction',\n )\n }\n return spread / median\n}\n\nfunction medianOf(values: ReadonlyArray<number>): number {\n if (values.length === 0) {\n throw new Error('equalKOnCost: cannot take the median of an empty channel')\n }\n const sorted = [...values].sort((a, b) => a - b)\n const mid = Math.floor(sorted.length / 2)\n const hi = sorted[mid] as number\n if (sorted.length % 2 !== 0) return hi\n const lo = sorted[mid - 1] as number\n return (lo + hi) / 2\n}\n\n// ── Guards + narrowers ───────────────────────────────────────────────────────────\n\nfunction isSpawned(ev: SpawnEvent): ev is Extract<SpawnEvent, { kind: 'spawned' }> {\n return ev.kind === 'spawned'\n}\n\nfunction isNode(node: MutableNode | undefined): node is MutableNode {\n return node !== undefined\n}\n\nfunction bySeq(a: SpawnEvent, b: SpawnEvent): number {\n return a.seq - b.seq\n}\n\nfunction requireNode(nodes: Map<NodeId, MutableNode>, id: NodeId, root: NodeId): MutableNode {\n const node = nodes.get(id)\n if (!node) {\n throw new Error(\n `trajectoryReport: tree '${root}' references node '${id}' with no prior spawn (corrupted log)`,\n )\n }\n return node\n}\n\nfunction requireSpend(rolled: Map<NodeId, Spend>, id: NodeId, root: NodeId): Spend {\n const spend = rolled.get(id)\n if (!spend) {\n throw new Error(\n `trajectoryReport: node '${id}' was never rolled up in tree '${root}' (unreachable from root)`,\n )\n }\n return spend\n}\n","/**\n * `openSandboxRun` — the ONE harness-agnostic seam for running an agent in a\n * sandbox over a persistent artifact: run it, stream it, RESUME the same session\n * across turns. Domain-agnostic: a coding agent, a research agent, a tax/legal\n * agent — all flow through this; the domain lives only in the `Deliverable<Out>`\n * the caller supplies, never in a per-domain copy of this function.\n *\n * It is a thin facade (NOT a new layer) over code that already exists and is\n * already hardened:\n * - `acquireSandbox` — cold-start / 502-503-504 / gateway-timeout recovery,\n * - `buildBackendOptions` — the harness IS `backend.type` (opencode / codex /\n * claude-code / kimi-code / hermes / pi); the only \"which agent\" knob,\n * - `createSandboxLineage` — `start` mints a session; `resume` continues the\n * SAME server-side session with a fail-loud `assertSessionLive`.\n *\n * The one genuinely-new piece is {@link Deliverable}: it widens the pure\n * `OutputAdapter.parse(events)` to ALSO admit a post-turn read off the box FS —\n * the structural gap that made the bench gates hand-roll `box.fs.read`, because a\n * large produced file (a git diff, a generated document) truncates in the chat\n * stream and a pure events-parser cannot reach the workspace. Per the SDK, a\n * RELATIVE `deliverable.path` resolves from the workspace root and an ABSOLUTE one\n * (e.g. `/tmp/solution.patch`) reads the container filesystem directly — both are\n * valid; pick the one the agent actually wrote to. Avoid `..` traversal segments.\n *\n * What this deliberately does NOT do (so it stays a facade, not slop): no custom\n * reconnect/replay (the SDK + platform own per-session buffering + `Last-Event-ID`);\n * no fork verb (platform CRIU is probe-gated and currently absent — fork lives in\n * `SandboxLineage.fork` behind the capability probe, surfaced only if it returns).\n * It is also distinct from `runLoop`: `runLoop` is the multi-round, driver-driven\n * kernel (fresh box per round, events deliverable); this is a SINGLE rollout +\n * artifact-or-events deliverable + resume over ONE persistent box.\n */\n\nimport type { SandboxEvent, SandboxInstance } from '@tangle-network/sandbox'\nimport type { RuntimeHooks, RuntimeHookTarget } from '../runtime-hooks'\nimport { notifyRuntimeHookEvent } from '../runtime-hooks'\nimport { probeSandboxCapabilities } from './sandbox-capabilities'\nimport { createSandboxLineage, type SandboxLineageHandle } from './sandbox-lineage'\nimport type { AgentRunSpec, SandboxClient } from './types'\nimport { randomSuffix, sleep, throwIfAborted } from './util'\n\n/**\n * @experimental\n * How a typed deliverable `Out` is materialized from a finished turn.\n * - `events` — pure parse over the event array (identical to `OutputAdapter`).\n * - `artifact` — read a file off the box AFTER the turn drains, then map it (+ the\n * events). For diffs/codebases/documents that don't fit the chat\n * stream. `path` relative ⇒ workspace root; absolute ⇒ container FS.\n */\nexport type Deliverable<Out> =\n | { kind: 'events'; fromEvents: (events: SandboxEvent[]) => Out }\n | { kind: 'artifact'; path: string; fromArtifact: (raw: string, events: SandboxEvent[]) => Out }\n\n/**\n * @experimental\n * One finished turn over the artifact. A failed FS read is surfaced in `readError`\n * (never masked as an empty deliverable) so a caller distinguishes \"agent produced\n * nothing\" from a transport/FS fault.\n */\nexport interface TurnResult<Out> {\n out: Out\n events: SandboxEvent[]\n readError?: string\n}\n\n/** @experimental A live run over ONE persistent artifact (box + session). Close it\n * when done — `close()` tears the box down. */\nexport interface SandboxRun<Out> {\n readonly box: SandboxInstance\n readonly sessionId: string\n /** First turn over the fresh box (mints the session). Throws if already started. */\n start(prompt: string): Promise<TurnResult<Out>>\n /** Continue THE SAME session over THE SAME artifact — a resumed turn/rollout. */\n resume(prompt: string): Promise<TurnResult<Out>>\n close(): Promise<void>\n}\n\n/** @experimental */\nexport interface OpenSandboxRunOptions {\n /** Profile + sandbox env/overrides. `sandboxOverrides.backend.type` is the harness. */\n agentRun: AgentRunSpec<string>\n signal: AbortSignal\n /** Optional execution-scoped observers. Hook failures never fail the run. */\n hooks?: RuntimeHooks\n /** Stable run id for trace joins. Defaults to a short runtime-minted id. */\n runId?: string\n /** Optional benchmark/scenario id carried into emitted hook events. */\n scenarioId?: string\n /** Test seam for deterministic hook timestamps. Defaults to `Date.now`. */\n now?: () => number\n /** Bounds box-creation bursts inside lineage fanout. Default from lineage. */\n maxConcurrency?: number\n /** Base backoff (ms) for retrying a transient artifact `fs.read` failure; the i-th\n * retry waits `readRetryDelayMs * i`. Default 1000. Set 0 to disable the wait (tests). */\n readRetryDelayMs?: number\n}\n\n/**\n * @experimental\n * Open a sandbox run. Harness-agnostic: the harness lives in\n * `options.agentRun.sandboxOverrides.backend.type`, so opencode/codex/claude-code/\n * kimi-code all flow through this one entrypoint with identical env/auth wiring.\n */\nexport async function openSandboxRun<Out>(\n client: SandboxClient,\n options: OpenSandboxRunOptions,\n deliverable: Deliverable<Out>,\n): Promise<SandboxRun<Out>> {\n const runId = options.runId ?? `sandbox-run-${randomSuffix()}`\n const now = options.now ?? Date.now\n const capabilities = await probeSandboxCapabilities(client)\n const lineage = createSandboxLineage(client, capabilities, {\n ...(options.maxConcurrency !== undefined ? { maxConcurrency: options.maxConcurrency } : {}),\n })\n let handle: SandboxLineageHandle | undefined\n let started = false\n let runStartedAt: number | undefined\n let failed = false\n let turnCount = 0\n\n function emit(event: {\n target: RuntimeHookTarget\n phase: 'before' | 'after' | 'error'\n timestamp: number\n stepIndex?: number\n payload?: Record<string, unknown>\n }): void {\n notifyRuntimeHookEvent(\n options.hooks,\n {\n id: `${runId}:${event.target}:${event.phase}${\n event.stepIndex === undefined ? '' : `:${event.stepIndex}`\n }`,\n runId,\n scenarioId: options.scenarioId,\n target: event.target,\n phase: event.phase,\n timestamp: event.timestamp,\n stepIndex: event.stepIndex,\n payload: event.payload,\n metadata: { producer: 'openSandboxRun' },\n },\n { signal: options.signal },\n )\n }\n\n const runPayload = (): Record<string, unknown> => ({\n agentName: options.agentRun.name ?? options.agentRun.profile.name ?? 'agent',\n profileName: options.agentRun.profile.name,\n backendType: backendType(options.agentRun),\n deliverableKind: deliverable.kind,\n ...(deliverable.kind === 'artifact' ? { deliverablePath: deliverable.path } : {}),\n ...(handle ? { sessionId: handle.sessionId, sandboxId: handle.box.id } : {}),\n })\n\n const turnPayload = (\n prompt: string,\n turnKind: 'start' | 'resume',\n startedAt: number,\n result?: TurnResult<Out>,\n error?: unknown,\n ): Record<string, unknown> => ({\n ...runPayload(),\n turnKind,\n promptChars: prompt.length,\n promptHash: hashText(prompt),\n ...(result !== undefined || error !== undefined\n ? { durationMs: Math.max(0, now() - startedAt) }\n : {}),\n ...(result\n ? {\n eventCount: result.events.length,\n eventTypes: eventTypeCounts(result.events),\n ...(result.readError !== undefined ? { readError: result.readError } : {}),\n }\n : {}),\n ...(error !== undefined ? { error: errorMessage(error) } : {}),\n })\n\n // `box` is passed in (not read from the closed-over `handle`) so the invariant\n // is type-level, not call-order discipline.\n async function settle(\n box: SandboxInstance,\n events: AsyncIterable<SandboxEvent>,\n ): Promise<TurnResult<Out>> {\n const collected: SandboxEvent[] = []\n for await (const ev of events) collected.push(ev)\n if (deliverable.kind === 'events') {\n return { out: deliverable.fromEvents(collected), events: collected }\n }\n throwIfAborted(options.signal)\n let raw = ''\n let readError: string | undefined\n // The data plane can transiently 404 a just-written artifact (write not yet\n // flushed, or an edge-read blip) — retry a few times with backoff before\n // declaring the deliverable empty, so a transient read failure is not recorded\n // as \"the agent produced nothing\".\n const readAttempts = 4\n const readDelayMs = options.readRetryDelayMs ?? 1000\n for (let attempt = 0; attempt < readAttempts; attempt += 1) {\n throwIfAborted(options.signal)\n try {\n raw = await box.fs.read(deliverable.path)\n readError = undefined\n break\n } catch (err) {\n readError = err instanceof Error ? err.message : String(err)\n if (attempt < readAttempts - 1 && readDelayMs > 0)\n await sleep(readDelayMs * (attempt + 1), options.signal)\n }\n }\n return {\n out: deliverable.fromArtifact(raw, collected),\n events: collected,\n ...(readError !== undefined ? { readError } : {}),\n }\n }\n\n return {\n get box(): SandboxInstance {\n if (!handle) throw new Error('openSandboxRun: box unavailable before start()')\n return handle.box\n },\n get sessionId(): string {\n if (!handle) throw new Error('openSandboxRun: sessionId unavailable before start()')\n return handle.sessionId\n },\n async start(prompt) {\n if (started)\n throw new Error(\n 'openSandboxRun: start() already called — use resume() to continue the session',\n )\n started = true\n runStartedAt = now()\n emit({\n target: 'agent.run',\n phase: 'before',\n timestamp: runStartedAt,\n payload: { ...runPayload(), turnCount: 0 },\n })\n const stepIndex = turnCount\n const turnStartedAt = now()\n emit({\n target: 'agent.turn',\n phase: 'before',\n timestamp: turnStartedAt,\n stepIndex,\n payload: turnPayload(prompt, 'start', turnStartedAt),\n })\n // lineage.start uses only spec.profile + sandboxOverrides (the prompt is passed\n // directly, not via taskToPrompt), so the task type is irrelevant here.\n try {\n const r = await lineage.start(\n options.agentRun as AgentRunSpec<unknown>,\n prompt,\n options.signal,\n )\n handle = r.handle\n const result = await settle(handle.box, r.events)\n turnCount += 1\n emit({\n target: 'agent.turn',\n phase: 'after',\n timestamp: now(),\n stepIndex,\n payload: turnPayload(prompt, 'start', turnStartedAt, result),\n })\n return result\n } catch (error) {\n failed = true\n emit({\n target: 'agent.turn',\n phase: 'error',\n timestamp: now(),\n stepIndex,\n payload: turnPayload(prompt, 'start', turnStartedAt, undefined, error),\n })\n emit({\n target: 'agent.run',\n phase: 'error',\n timestamp: now(),\n payload: { ...runPayload(), turnCount, error: errorMessage(error) },\n })\n throw error\n }\n },\n async resume(prompt) {\n if (!handle) throw new Error('openSandboxRun: resume() called before start()')\n const stepIndex = turnCount\n const turnStartedAt = now()\n emit({\n target: 'agent.turn',\n phase: 'before',\n timestamp: turnStartedAt,\n stepIndex,\n payload: turnPayload(prompt, 'resume', turnStartedAt),\n })\n try {\n const result = await settle(\n handle.box,\n await lineage.continue(handle, prompt, options.signal),\n )\n turnCount += 1\n emit({\n target: 'agent.turn',\n phase: 'after',\n timestamp: now(),\n stepIndex,\n payload: turnPayload(prompt, 'resume', turnStartedAt, result),\n })\n return result\n } catch (error) {\n failed = true\n emit({\n target: 'agent.turn',\n phase: 'error',\n timestamp: now(),\n stepIndex,\n payload: turnPayload(prompt, 'resume', turnStartedAt, undefined, error),\n })\n emit({\n target: 'agent.run',\n phase: 'error',\n timestamp: now(),\n payload: { ...runPayload(), turnCount, error: errorMessage(error) },\n })\n throw error\n }\n },\n async close() {\n await lineage.teardown()\n if (runStartedAt !== undefined) {\n emit({\n target: 'agent.run',\n phase: 'after',\n timestamp: now(),\n payload: {\n ...runPayload(),\n turnCount,\n status: failed ? 'error' : 'completed',\n durationMs: Math.max(0, now() - runStartedAt),\n },\n })\n }\n },\n }\n}\n\nfunction backendType<Task>(spec: AgentRunSpec<Task>): unknown {\n const backend = spec.sandboxOverrides?.backend as { type?: unknown } | undefined\n return backend?.type\n}\n\nfunction eventTypeCounts(events: SandboxEvent[]): Record<string, number> {\n const counts: Record<string, number> = {}\n for (const event of events) counts[event.type] = (counts[event.type] ?? 0) + 1\n return counts\n}\n\nfunction hashText(value: string): string {\n let hash = 2166136261\n for (let i = 0; i < value.length; i += 1) {\n hash ^= value.charCodeAt(i)\n hash = Math.imul(hash, 16777619)\n }\n return (hash >>> 0).toString(16).padStart(8, '0')\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","/** Command runner seam. Host code can use `localShell`; sandbox code can wrap `box.exec`. */\nexport type Shell = (\n args: ReadonlyArray<string>,\n cwd?: string,\n) => Promise<{ stdout: string; stderr: string; code: number }>\n\nexport type WorkspaceCommit =\n | { readonly ok: true; readonly rev: string }\n | { readonly ok: false; readonly conflict: string }\n\nexport interface Workspace {\n readonly ref: string\n materialize(dir: string): Promise<void>\n commit(dir: string, message: string): Promise<WorkspaceCommit>\n head(): Promise<string>\n}\n\nexport function localShell(): Shell {\n return async (args, cwd) => {\n const { execFile } = await import('node:child_process')\n const [bin, ...rest] = args\n return new Promise((resolve) => {\n execFile(\n bin ?? '',\n rest,\n { cwd, encoding: 'utf-8', maxBuffer: 64 * 1024 * 1024 },\n (err: Error | null, stdout: string, stderr: string) => {\n resolve({\n stdout: stdout ?? '',\n stderr: stderr ?? '',\n code: err ? ((err as { code?: number }).code ?? 1) : 0,\n })\n },\n )\n })\n }\n}\n\nexport interface GitWorkspaceOptions {\n readonly ref: string\n readonly shell?: Shell\n readonly branch?: string\n readonly noHooks?: boolean\n}\n\nexport function gitWorkspace(opts: GitWorkspaceOptions): Workspace {\n const shell = opts.shell ?? localShell()\n const branch = opts.branch ?? 'main'\n const cfg = opts.noHooks === false ? [] : ['-c', 'core.hooksPath=/dev/null']\n const ident = ['-c', 'user.email=workspace@tangle.local', '-c', 'user.name=workspace']\n\n const run = async (args: string[], cwd?: string): Promise<string> => {\n const res = await shell(['git', ...cfg, ...ident, ...args], cwd)\n if (res.code !== 0) {\n throw new Error(\n `git ${args.join(' ')} failed (${res.code}): ${tail(res.stderr || res.stdout)}`,\n )\n }\n return res.stdout\n }\n\n return {\n ref: opts.ref,\n materialize: (dir) => run(['clone', '--branch', branch, opts.ref, dir]).then(() => {}),\n async commit(dir, message) {\n await run(['add', '-A'], dir)\n const status = await run(['status', '--porcelain'], dir)\n if (!status.trim()) return { ok: true, rev: (await run(['rev-parse', 'HEAD'], dir)).trim() }\n await run(['commit', '-m', message], dir)\n const pull = await shell(['git', ...cfg, ...ident, 'pull', '--rebase', 'origin', branch], dir)\n if (pull.code !== 0) {\n await shell(['git', ...cfg, 'rebase', '--abort'], dir).catch(() => {})\n return { ok: false, conflict: tail(pull.stderr || pull.stdout) }\n }\n const push = await shell(['git', ...cfg, ...ident, 'push', 'origin', branch], dir)\n if (push.code !== 0) return { ok: false, conflict: tail(push.stderr || push.stdout) }\n return { ok: true, rev: (await run(['rev-parse', 'HEAD'], dir)).trim() }\n },\n async head() {\n const out = await run(['ls-remote', opts.ref, `refs/heads/${branch}`])\n return out.split(/\\s+/)[0] ?? ''\n },\n }\n}\n\nfunction tail(s: string): string {\n return s.slice(-400)\n}\n"],"mappings":";;;;;;;;;AAqBA,SAAS,kBAAkB;;;ACN3B,eAAsB,cAAc,KAAoD;AACtF,MAAI,CAAC,OAAO,OAAQ,IAA6B,WAAW,WAAY,QAAO;AAC/E,MAAI;AACF,UAAM,IAAI,OAAO;AACjB,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGO,SAAS,aAAa,MAAM,GAAW;AAC5C,SAAO,KAAK,OAAO,EAChB,SAAS,EAAE,EACX,MAAM,GAAG,IAAI,GAAG;AACrB;AAGO,SAAS,aAAqB;AACnC,SAAO,OAAO,WAAW;AAC3B;AAGO,SAAS,aAAoB;AAClC,QAAM,MAAM,IAAI,MAAM,SAAS;AAC/B,MAAI,OAAO;AACX,SAAO;AACT;AAGO,SAAS,aAAoB;AAClC,QAAM,WAAW;AACnB;AAGO,SAAS,eAAe,QAAuC;AACpE,MAAI,QAAQ,QAAS,OAAM,WAAW;AACxC;AAOO,SAAS,MAAM,IAAY,QAAqC;AACrE,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,QAAI,QAAQ,SAAS;AACnB,cAAQ;AACR;AAAA,IACF;AACA,QAAI;AACJ,UAAM,QAAQ,WAAW,MAAM;AAC7B,UAAI,WAAW,OAAQ,QAAO,oBAAoB,SAAS,OAAO;AAClE,cAAQ;AAAA,IACV,GAAG,EAAE;AACL,QAAI,QAAQ;AACV,gBAAU,MAAM;AACd,qBAAa,KAAK;AAClB,gBAAQ;AAAA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AM,IAAI,CAAC,UAAU,MAAM,OAAO,GAAG,GAAG;AACxC,YAAM,OAAO,MAAM,MAAM,CAAC,OAAO,GAAG,KAAK,GAAG,OAAO,QAAQ,YAAY,UAAU,MAAM,GAAG,GAAG;AAC7F,UAAI,KAAK,SAAS,GAAG;AACnB,cAAM,MAAM,CAAC,OAAO,GAAG,KAAK,UAAU,SAAS,GAAG,GAAG,EAAE,MAAM,MAAM;AAAA,QAAC,CAAC;AACrE,eAAO,EAAE,IAAI,OAAO,UAAU,KAAK,KAAK,UAAU,KAAK,MAAM,EAAE;AAAA,MACjE;AACA,YAAM,OAAO,MAAM,MAAM,CAAC,OAAO,GAAG,KAAK,GAAG,OAAO,QAAQ,UAAU,MAAM,GAAG,GAAG;AACjF,UAAI,KAAK,SAAS,EAAG,QAAO,EAAE,IAAI,OAAO,UAAU,KAAK,KAAK,UAAU,KAAK,MAAM,EAAE;AACpF,aAAO,EAAE,IAAI,MAAM,MAAM,MAAM,IAAI,CAAC,aAAa,MAAM,GAAG,GAAG,GAAG,KAAK,EAAE;AAAA,IACzE;AAAA,IACA,MAAM,OAAO;AACX,YAAM,MAAM,MAAM,IAAI,CAAC,aAAa,KAAK,KAAK,cAAc,MAAM,EAAE,CAAC;AACrE,aAAO,IAAI,MAAM,KAAK,EAAE,CAAC,KAAK;AAAA,IAChC;AAAA,EACF;AACF;AAEA,SAAS,KAAK,GAAmB;AAC/B,SAAO,EAAE,MAAM,IAAI;AACrB;","names":["sleep","box","sessionId","TEARDOWN_TIMEOUT_MS","spawn","zeroSpend","isAsyncIterable","isAbortError","totalTokens","stableStringify","isNoEntError","zeroSpend","f","c","fanout","zeroSpend","requireNode","settle"]}