@tangle-network/agent-runtime 0.178.0 → 0.179.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 (69) hide show
  1. package/README.md +1 -1
  2. package/dist/{activation-BVTPfwty.js → activation-C-FAeybF.js} +2 -2
  3. package/dist/{activation-BVTPfwty.js.map → activation-C-FAeybF.js.map} +1 -1
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +2 -2
  6. package/dist/{authoring-dQjU4WrH.js → authoring-kLYzRjsB.js} +2 -2
  7. package/dist/{authoring-dQjU4WrH.js.map → authoring-kLYzRjsB.js.map} +1 -1
  8. package/dist/candidate-execution/index.js +2 -2
  9. package/dist/{candidate-execution-fBNUyWyE.js → candidate-execution-7lVEly33.js} +2 -2
  10. package/dist/{candidate-execution-fBNUyWyE.js.map → candidate-execution-7lVEly33.js.map} +1 -1
  11. package/dist/conversation.d.ts +1 -1
  12. package/dist/{coordination-driver-kN2_UQaP.js → coordination-driver-BeLF1j7n.js} +2 -2
  13. package/dist/{coordination-driver-kN2_UQaP.js.map → coordination-driver-BeLF1j7n.js.map} +1 -1
  14. package/dist/durable.d.ts +2 -2
  15. package/dist/durable.js +1 -1
  16. package/dist/{environment-provider-ykohtWSr.d.ts → environment-provider-BGCU0IRa.d.ts} +2 -2
  17. package/dist/environment-provider.d.ts +1 -1
  18. package/dist/{graph-CseWAx9q.js → graph-CZFWujWS.js} +2 -2
  19. package/dist/{graph-CseWAx9q.js.map → graph-CZFWujWS.js.map} +1 -1
  20. package/dist/graph.d.ts +3 -3
  21. package/dist/graph.js +3 -3
  22. package/dist/{improvement-cycle-2QG2XXyK.js → improvement-cycle-CADEjVOB.js} +3 -3
  23. package/dist/{improvement-cycle-2QG2XXyK.js.map → improvement-cycle-CADEjVOB.js.map} +1 -1
  24. package/dist/{index-DG48MraH.d.ts → index-DNXW665W.d.ts} +2 -2
  25. package/dist/{index-CKjkp9Uh.d.ts → index-DhnWuHkN.d.ts} +5 -5
  26. package/dist/{index-BL5K-qBf.d.ts → index-lu9HFbv5.d.ts} +4 -4
  27. package/dist/index.d.ts +7 -7
  28. package/dist/index.js +9 -9
  29. package/dist/intelligence.d.ts +4 -4
  30. package/dist/intelligence.js +3 -3
  31. package/dist/kernel.d.ts +6 -6
  32. package/dist/kernel.js +8 -8
  33. package/dist/{knowledge-Ycq1urlg.js → knowledge-BZvQ7Pca.js} +4 -4
  34. package/dist/{knowledge-Ycq1urlg.js.map → knowledge-BZvQ7Pca.js.map} +1 -1
  35. package/dist/knowledge.d.ts +1 -1
  36. package/dist/knowledge.js +1 -1
  37. package/dist/{loop-runner-bin-Cv8_0WCC.d.ts → loop-runner-bin-BnSUNv5h.d.ts} +3 -3
  38. package/dist/{loop-runner-bin-DkaB5edJ.js → loop-runner-bin-CeMD66qH.js} +3 -3
  39. package/dist/{loop-runner-bin-DkaB5edJ.js.map → loop-runner-bin-CeMD66qH.js.map} +1 -1
  40. package/dist/loop-runner-bin.d.ts +1 -1
  41. package/dist/loop-runner-bin.js +1 -1
  42. package/dist/mcp/bin.js +3 -3
  43. package/dist/mcp/index.d.ts +3 -3
  44. package/dist/mcp/index.js +5 -5
  45. package/dist/{openai-tools-Cv1ZVB-e.js → openai-tools-CQq1fhJ0.js} +2 -2
  46. package/dist/{openai-tools-Cv1ZVB-e.js.map → openai-tools-CQq1fhJ0.js.map} +1 -1
  47. package/dist/primeintellect/index.d.ts +1 -1
  48. package/dist/{provision-supervisor-B4wOvmpW.js → provision-supervisor-C_o4UH8c.js} +3 -3
  49. package/dist/{provision-supervisor-B4wOvmpW.js.map → provision-supervisor-C_o4UH8c.js.map} +1 -1
  50. package/dist/{redact-CptO2wfX.d.ts → redact-GpYsFenv.d.ts} +3 -3
  51. package/dist/{runtime-7W9UYNMN.js → runtime-BblXWn4d.js} +8 -8
  52. package/dist/{runtime-7W9UYNMN.js.map → runtime-BblXWn4d.js.map} +1 -1
  53. package/dist/{runtime-BhU1Bt3y.d.ts → runtime-oGfkncdd.d.ts} +3 -3
  54. package/dist/{stream-agent-turn-CNyYxEc0.d.ts → stream-agent-turn-esfjghd9.d.ts} +2 -2
  55. package/dist/{structural-rollout-BSdSJ_Lr.js → structural-rollout-D4uIcI7I.js} +2 -2
  56. package/dist/{structural-rollout-BSdSJ_Lr.js.map → structural-rollout-D4uIcI7I.js.map} +1 -1
  57. package/dist/{supervise-DMgM9SYN.js → supervise-Ckj6Ewdi.js} +3 -3
  58. package/dist/{supervise-DMgM9SYN.js.map → supervise-Ckj6Ewdi.js.map} +1 -1
  59. package/dist/{supervisor-DyDgxgpl.js → supervisor--tj9JsFo.js} +18 -8
  60. package/dist/{supervisor-DyDgxgpl.js.map → supervisor--tj9JsFo.js.map} +1 -1
  61. package/dist/testing.d.ts +2 -2
  62. package/dist/testing.js +12 -12
  63. package/dist/tui/index.d.ts +1 -1
  64. package/dist/tui/index.js +1 -1
  65. package/dist/{types-C6HjIpJ3.d.ts → types-CPpvwwTx.d.ts} +10 -9
  66. package/dist/{workspace-archive-DOZAeeKU.js → workspace-archive-ByonPBl-.js} +3 -1
  67. package/dist/workspace-archive-ByonPBl-.js.map +1 -0
  68. package/package.json +17 -17
  69. package/dist/workspace-archive-DOZAeeKU.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"coordination-driver-kN2_UQaP.js","names":[],"sources":["../src/runtime/supervise/detector-monitor.ts","../src/runtime/supervise/event-bus.ts","../src/mcp/tools/coordination.ts","../src/runtime/supervise/coordination-log.ts","../src/runtime/supervise/run-context.ts","../src/runtime/anytime.ts","../src/runtime/supervise/stop-rules.ts","../src/runtime/supervise/coordination-driver.ts"],"sourcesContent":["/**\n *\n * The ONLINE analyst: watch a `TraceSource` and fold each tool span through agent-eval's published\n * streaming detector kernel (`repeatedActionDetector`/`errorStreakDetector` — the SAME kernel the\n * control loop folds), firing `onSignal` the moment a worker loops or error-storms. Substrate-\n * agnostic: it consumes spans from any source (owned router/bridge loop OR a sandbox box session),\n * never the raw tool seam. Detection logic + the failure taxonomy live in agent-eval; not reimplemented.\n *\n * @experimental\n */\n\nimport {\n argHash,\n type DetectorSignal,\n errorStreakDetector,\n observeAll,\n repeatedActionDetector,\n type StreamingDetector,\n type ToolSpan,\n} from '@tangle-network/agent-eval'\nimport type { TraceSource } from './trace-source'\n\nexport interface WatchTraceOptions {\n /** The detectors to run online. Defaults to a stuck-loop + error-streak panel. */\n readonly detectors?: ReadonlyArray<StreamingDetector>\n /** Fired for each signal a detector raises — the seam that raises a `finding` on the bus. */\n readonly onSignal?: (signal: DetectorSignal, span: ToolSpan) => void | Promise<void>\n}\n\n/** The default online panel for a tool-call pipe: a worker repeating the same call, or hammering\n * consecutive errors. (No-progress needs a domain progress-probe, so it is opt-in, not default.)\n *\n * Coverage note: `repeated-action` works for EVERY harness (it needs only tool name + args, which\n * every adapter provides). `error-streak` needs per-call status — opencode carries it inline\n * (`state.status`, VALIDATED live), but claude-code/codex tool-call parts do NOT (their errors live\n * in separate result blocks not yet decoded), so error-streak is silent for those until result-block\n * decoding is added + live-validated. It is in the panel because it is correct where status exists. */\nexport function defaultToolDetectors(): StreamingDetector[] {\n return [repeatedActionDetector({ maxRepeated: 3 }), errorStreakDetector({ maxErrors: 3 })]\n}\n\n/** Subscribe to a `TraceSource` and run the streaming detectors over its live spans. Returns an\n * unsubscribe. A defensive `argHash` failure (circular args) never throws out of the side-channel. */\nexport function watchTrace(source: TraceSource, opts: WatchTraceOptions = {}): () => void {\n const detectors = opts.detectors ?? defaultToolDetectors()\n return source.onSpan((span) => {\n let fingerprint: string\n try {\n // Same fingerprint scheme as agent-eval's batch stuck-loop view: tool name + hashed args.\n fingerprint = `${span.toolName}|${argHash(span.args)}`\n } catch {\n fingerprint = `${span.toolName}|<unhashable>`\n }\n const signals = observeAll(detectors, {\n actionFingerprint: fingerprint,\n ...(span.status ? { status: span.status } : {}),\n label: span.toolName,\n })\n for (const s of signals) void opts.onSignal?.(s, span)\n })\n}\n","/**\n *\n * The child→parent message bus: the ONE pipe carrying every message a worker, sub-driver, or\n * analyst sends up to the driver — settled outputs, questions, and trace-analyst findings. It\n * unifies channels that were ad-hoc before (the settled-worker cursor, the ask-parent question\n * channel, and analyst results) into a single typed primitive with two lanes:\n *\n * - PASS-THROUGH (`subscribe`): every published event reaches subscribers immediately — the\n * express lane for online steering and live observation (a UI, a hook, the parent's box).\n * - STANDBY (`pull`): events also queue so the driver consumes them on its own cadence. The queue\n * is PRIORITY-ordered: a higher-`priority` event (a blocking question) is bumped ahead of\n * queued settles/findings so the driver sees it first; ties resolve FIFO by publish order.\n *\n * Observability is first-class (A++): every event is stamped with a monotonic `seq` and wall-clock\n * `at`, the full ordered `history()` is retained as current-process audit evidence, and `stats()`\n * exposes published/pulled counts by kind. Subscribers receive the stamped record, not a bare event.\n *\n * The interface is transport-agnostic on purpose. Same box → this in-process queue. Cross box →\n * the SAME publish/pull/subscribe surface backed by a durable mailbox on the parent's box (children\n * POST events with at-least-once retry; payloads are blob refs so the event stays small). Consumers\n * depend only on this interface, so distribution is a transport swap, never an architecture change.\n *\n * @experimental\n */\n\n/** Every bus event is a discriminated union member keyed by `type`. */\nexport interface BusEvent {\n readonly type: string\n}\n\n/** A published event stamped for ordering and observability. `seq` is the monotonic publish index;\n * `priority` drives pull order (higher = bumped ahead); `at` is the wall-clock publish time (ms). */\nexport interface BusRecord<E extends BusEvent> {\n readonly seq: number\n readonly at: number\n readonly priority: number\n readonly event: E\n}\n\nexport interface PublishOptions {\n /** Higher = pulled ahead of lower-priority queued events (default 0). A blocking question sets\n * this so it bumps to the front of the driver's inbox. */\n readonly priority?: number\n /** Whether the event enters the pull queue (default true). Set `false` for record-only events —\n * the parent→child down-leg (steer / answer / resume): they belong in `history()` and reach\n * `subscribe` observers, but the parent must never `pull` its own outbound message back. */\n readonly queue?: boolean\n}\n\nexport interface BusStats {\n readonly published: number\n readonly pulled: number\n /** Count published per event `type`. */\n readonly byKind: Readonly<Record<string, number>>\n}\n\n/** The child→parent coordination bus surface: publish, priority-ordered pull, pass-through subscribe, history, and stats.\n * @experimental In-process only — the durable cross-process mailbox this interface is designed\n * to admit is not implemented (docs/agent-managed-compute/README.md). */\nexport interface EventBus<E extends BusEvent> {\n /** Stamp the event, await every subscriber in order, then make it pull-visible. A subscriber\n * failure leaves the event invisible and retrying the SAME event object reuses the exact stamp.\n * This lets an awaited product observer commit its record before a supervisor can consume it. */\n publish(event: E, opts?: PublishOptions): Promise<BusRecord<E>>\n /** Remove and return the highest-priority QUEUED event whose type is in `kinds` (any if omitted),\n * ties broken FIFO by `seq`; `undefined` when nothing matches. */\n pull(kinds?: ReadonlyArray<E['type']>): E | undefined\n /** Register a pass-through handler; it receives the stamped record of every event published after\n * registration. Returns an unsubscribe fn. */\n subscribe(handler: (record: BusRecord<E>) => void | Promise<void>): () => void\n /** Count of queued, not-yet-pulled events (filtered by `kinds` when given). */\n pending(kinds?: ReadonlyArray<E['type']>): number\n /** The full ordered log of every event published in this process (audit evidence, not replay). */\n history(): ReadonlyArray<BusRecord<E>>\n /** Throughput counters for observability dashboards. */\n stats(): BusStats\n}\n\n/** Create the child→parent coordination bus: one typed pipe for settled outputs, questions, and analyst findings, with a priority-ordered pull queue and a pass-through subscribe lane.\n * @experimental In-process queue; durability is a transport swap that does not exist yet. */\nexport function createEventBus<E extends BusEvent>(now: () => number = Date.now): EventBus<E> {\n const queue: BusRecord<E>[] = []\n const log: BusRecord<E>[] = []\n const subscribers: Array<(record: BusRecord<E>) => void | Promise<void>> = []\n const byKind: Record<string, number> = {}\n // A failed publication is staged, not published. Coordination retains and retries the same event\n // object, so the exact BusRecord survives a lost acknowledgement and downstream idempotency keys\n // do not change between attempts.\n const staged = new WeakMap<object, BusRecord<E>>()\n let seq = 0\n let published = 0\n let pulled = 0\n\n const matches = (r: BusRecord<E>, kinds?: ReadonlyArray<E['type']>) =>\n !kinds || kinds.includes(r.event.type)\n\n // Index of the highest-priority matching record; ties resolve to the earliest `seq` (the queue is\n // maintained in publish order, so the first scan hit at the max priority is the oldest).\n const bestIndex = (kinds?: ReadonlyArray<E['type']>): number => {\n let best = -1\n let bestPriority = Number.NEGATIVE_INFINITY\n for (let i = 0; i < queue.length; i++) {\n const r = queue[i]\n if (!r || !matches(r, kinds)) continue\n if (r.priority > bestPriority) {\n best = i\n bestPriority = r.priority\n }\n }\n return best\n }\n\n return {\n async publish(event, opts) {\n const record =\n staged.get(event) ??\n ({ seq: seq++, at: now(), priority: opts?.priority ?? 0, event } satisfies BusRecord<E>)\n staged.set(event, record)\n // Sequential, not Promise.all: transaction observers must see causal order. Nothing enters\n // the pull queue or successful history until all observers acknowledge the record.\n for (const handler of subscribers) await handler(record)\n staged.delete(event)\n // Record-only events (the down-leg) skip the pull queue but still hit the log + subscribers.\n if (opts?.queue !== false) queue.push(record)\n log.push(record)\n published += 1\n byKind[event.type] = (byKind[event.type] ?? 0) + 1\n return record\n },\n pull(kinds) {\n const i = bestIndex(kinds)\n if (i < 0) return undefined\n pulled++\n return queue.splice(i, 1)[0]?.event\n },\n subscribe(handler) {\n subscribers.push(handler)\n return () => {\n const i = subscribers.indexOf(handler)\n if (i >= 0) subscribers.splice(i, 1)\n }\n },\n pending(kinds) {\n return kinds ? queue.filter((r) => matches(r, kinds)).length : queue.length\n },\n history() {\n return log\n },\n stats() {\n return { published, pulled, byKind: { ...byKind } }\n },\n }\n}\n","/**\n *\n * MCP binding for a live `Scope`. A sandbox driver gets the same small verbs\n * the in-process driver has: spawn, observe, await, steer, ask/answer, analyze,\n * and stop. Settled outputs remain Scope artifacts; product code can project\n * them into any UI/report envelope it needs.\n *\n * @experimental\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { AnalystFinding, TraceAnalysisStore } from '@tangle-network/agent-eval'\nimport {\n type AgentProfile,\n agentProfileSchema,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentExecutionRef,\n Budget,\n ExecutionBindingReceipt,\n Handle,\n NodeExecutionIdentity,\n ProfileMaterializationReceipt,\n ResultBlobStore,\n Scope,\n Settled,\n Spend,\n Agent as SuperviseAgent,\n WorkerTraceEvidence,\n} from '../../runtime'\nimport { assertValidBudget } from '../../runtime/supervise/budget'\nimport type { DeliverableSpec } from '../../runtime/supervise/completion-gate'\nimport { type WatchTraceOptions, watchTrace } from '../../runtime/supervise/detector-monitor'\nimport { freeSlots } from '../../runtime/supervise/dispatch'\nimport { type BusRecord, type BusStats, createEventBus } from '../../runtime/supervise/event-bus'\nimport { isLiveNodeStatus } from '../../runtime/supervise/node-status'\nimport {\n createPeerMailbox,\n type PeerMailbox,\n type PeerMailEvent,\n type PeerMailLimits,\n} from '../../runtime/supervise/peer-mail'\nimport type { WorkerProgress } from '../../runtime/supervise/progress'\nimport { detachedFrozen } from '../../runtime/supervise/snapshot'\nimport {\n parseWorkerToolTraceArtifact,\n workerTraceAnalysisStore,\n} from '../../runtime/supervise/trace-evidence'\nimport type { McpToolDescriptor } from '../server'\n\n/** A worker the driver has drained via `await_event`. */\nexport interface SettledWorker {\n readonly id: string\n readonly status: 'done' | 'down'\n /** Stable manager-scoped assignment, including deterministic unkeyed siblings. */\n readonly assignmentId?: string\n /** Exact profile/task/candidate identity authorized for this node. */\n readonly identity?: NodeExecutionIdentity\n /** Stable effective execution plan, or an explicit unknown receipt. */\n readonly materialization?: ProfileMaterializationReceipt\n /** Backend bindings for each attempt, in durable oldest-first order. */\n readonly executionBindings?: ReadonlyArray<ExecutionBindingReceipt>\n /** Conserved spend. Missing means unavailable; unknown accounting remains explicitly unknown. */\n readonly spent?: Spend\n readonly score?: number\n readonly valid?: boolean\n readonly outRef?: string\n readonly reason?: string\n /** Structured tool-call evidence, never the worker's final prose. */\n readonly trace: WorkerTraceEvidence\n /** True when projected from a prior process of the same durable run. */\n readonly resumed?: boolean\n /** Epoch ms from the durable terminal record — the resolution a progress-based stop rule needs\n * to answer \"how long since anything landed?\" without inventing a timestamp at read time. */\n readonly settledAt?: number\n}\n\nexport type QuestionLevel = 'worker' | 'driver' | 'loop'\nexport type QuestionUrgency = 'continue-without' | 'blocks-step' | 'blocks-run'\n\nexport interface QuestionOption {\n readonly label: string\n readonly tradeoff: string\n}\n\nexport interface Question {\n readonly id: string\n readonly from: string\n readonly level: QuestionLevel\n readonly question: string\n readonly reason: string\n readonly urgency: QuestionUrgency\n readonly options?: ReadonlyArray<QuestionOption>\n}\n\n/** Where a question this driver cannot answer goes next. `answer_question` accepts these and\n * nothing else, so the decision type states them and nothing else. */\nexport const questionEscalationTargets = ['parent', 'user'] as const\n\nexport type QuestionEscalationTarget = (typeof questionEscalationTargets)[number]\n\nconst isQuestionEscalationTarget = (value: unknown): value is QuestionEscalationTarget =>\n (questionEscalationTargets as ReadonlyArray<unknown>).includes(value)\n\nexport type QuestionDecision =\n | { readonly kind: 'answer'; readonly answer: string; readonly by: string }\n | { readonly kind: 'defer'; readonly reason: string }\n | {\n readonly kind: 'escalate'\n readonly to: QuestionEscalationTarget\n readonly reason: string\n }\n\nexport interface QuestionRecord extends Question {\n readonly status: 'open' | 'answered' | 'deferred' | 'escalated'\n readonly decision?: QuestionDecision\n readonly openedAt: number\n}\n\ntype QuestionInput = Omit<Question, 'id'> & { readonly id?: string }\nexport type QuestionPolicy = 'auto' | 'mustDecide' | 'bubble' | 'failClosed'\n\n/**\n * What one analyst lens may return.\n *\n * Two shapes, because two real producers exist and neither can be dropped. An eval-registry lens\n * returns validated `AnalystFinding`s — the schema every upstream consumer already reads. An\n * authored lens like `failuresAnalyst` returns a written brief for the driver and has no findings\n * to validate against. The union names both, so the boundary can no longer silently accept an\n * unvalidated shape (#630) while the authored lens keeps working.\n */\nexport type AnalystLensOutput = ReadonlyArray<AnalystFinding> | { readonly summary: string }\n\nexport interface AnalystRegistry {\n readonly kinds: ReadonlyArray<{ id: string; description: string; area: string }>\n readonly run: (kindId: string, trace: TraceAnalysisStore) => Promise<AnalystLensOutput>\n}\n\n/** A trace-analyst result re-entered as a message on the bus (the `finding` event kind). */\nexport interface AnalystFindingEvent {\n readonly fromWorker: string\n readonly analyst: string\n /** The analyst's result. ABSENT when the analyst returned `undefined` (no findings); any other\n * value is canonicalized to finite RFC 8785 JSON at publish (`canonicalFindingEvent`), so\n * digesting subscribers (the coordination-event id) never throw on analyst-shaped data. */\n readonly findings?: unknown\n}\n\n/** Producer-side cleanliness for the `finding` event. The findings payload is arbitrary analyst\n * output, the digest a subscriber computes (RFC 8785) throws on ANY `undefined` value — nested\n * included — and a throwing subscriber leaves the event invisible to EVERY subscriber. The\n * producer, not the digest, owns keeping the event canonical: an `undefined` payload is stripped\n * to key-absence, everything else is JSON round-tripped (nested `undefined` object values drop,\n * `undefined` array slots become `null`), and a payload JSON cannot represent at all (cycle,\n * BigInt, bare function) becomes a record OF that fact — degraded findings beat a vanished\n * event. */\nexport function canonicalFindingEvent(finding: AnalystFindingEvent): AnalystFindingEvent {\n if (finding.findings === undefined) {\n const { findings: _absent, ...present } = finding\n return present\n }\n try {\n // JSON.stringify returns undefined (not a string) for a bare function/symbol payload;\n // JSON.parse then throws, landing in the same non-canonical fallback as cycles and BigInt.\n return { ...finding, findings: JSON.parse(JSON.stringify(finding.findings)) as unknown }\n } catch (error) {\n return {\n ...finding,\n findings: { nonCanonicalFindings: error instanceof Error ? error.message : String(error) },\n }\n }\n}\n\n/**\n * One analyst-on-settle ROUTE: which lens runs (`kind`), over WHICH settled workers (`over`),\n * delivered to WHOM (`to`), wrapped in WHAT standing instruction (`directive`). The generalized\n * form of the bare-string entry — a string `k` is exactly `{ kind: k }`: every settle feeds the\n * lens and the findings go to the driver via the bus. This is the analyzes-edge of an agent\n * graph expressed at the coordination layer; the finding is ALWAYS also published on the bus\n * (the audit trail), routing adds delivery, never replaces the record.\n */\nexport interface AnalyzeOnSettleRoute {\n /** The analyst id: a lens id resolved against the `analysts` registry, or — when `agent` is\n * present — the AGENT analyst's stable identity carried on its finding/steer events (it need\n * not exist in any registry). */\n readonly kind: string\n /**\n * Make this analyst a tool-equipped AGENT instead of a registry lens: on each matching settle\n * the runtime spawns this profile as a WORKER through the SAME spawn machinery a driver spawn\n * uses (`Scope.spawn` + the run's `makeWorkerAgent` seam) — so its spend reserves from the\n * conserved pool, its node is journaled and traced like any worker, and a node-pinning seam\n * sees the spawn context marker (`WorkerSpawnContext.analyst`). Its task is `directive` plus\n * the settled worker's tool-trace evidence; its settle OUTPUT is the findings, published as a\n * `finding` event (same canonicalization) and delivered per `to` exactly like registry-analyst\n * findings. A settle that failed publishes `{ analystRunFailed }`; a spawn the pool or fences\n * refuse publishes `{ analystSpawnRefused }` — observable, never a silent drop. An agent\n * analyst's settlement never enters the settled-worker ledger, never feeds the finalizer, and\n * never re-fires the analyst-on-settle hook (no analyst-on-analyst cascade by construction).\n */\n readonly agent?: AgentProfile\n /** Deliver the findings to this live worker, named by its PROFILE NAME (the stable node\n * identity a graph pins) or its spawn label. Omit = the driver (bus only). Delivery goes\n * through the same authorization + steer machinery a driver-authored steer uses and is\n * recorded as a `steer` event carrying `analyst`, so a routed delivery is observable and a\n * failed one (`delivered: false`) is a recorded outcome, never a silent drop. */\n readonly to?: string\n /** Standing instruction wrapped around the findings on a routed delivery — what the recipient\n * should DO with the analysis. For an AGENT analyst (`agent` set) it is instead the analysis\n * directive handed to the agent as its task; the routed delivery then carries the bare\n * findings, because the directive was already consumed upstream. Omit = the bare findings\n * JSON (and, for an agent analyst, a task of evidence only). */\n readonly directive?: string\n /** Restrict which settled workers feed this lens, by profile name or spawn label. Omit =\n * every settled `done` worker. */\n readonly over?: ReadonlyArray<string>\n}\n\n/** Normalize the two spellings of an analyst-on-settle entry to the route form. */\nexport function normalizeAnalyzeOnSettle(\n entry: string | AnalyzeOnSettleRoute,\n): AnalyzeOnSettleRoute {\n return typeof entry === 'string' ? { kind: entry } : entry\n}\n\n/** How a spawn CONTINUES a node's prior work: `'fresh'` starts a brand-new session (the default,\n * and the only pre-continuity behavior); `'resume'` re-attaches to the node's most recent\n * SETTLED worker — a NEW live worker is spawned whose spawn context carries the prior worker's\n * identity ({@link WorkerResumeContext}), and the executor seam owns the actual session\n * re-attachment. */\nexport type ContinuityMode = 'fresh' | 'resume'\n\n/** The resume lineage a `'resume'` spawn hands the executor seam\n * ({@link WorkerSpawnContext.resume}). The kernel owns identity, ordering, ledger truth, and\n * spend continuity (the resumed worker reserves from the same conserved pool); the seam owns the\n * re-attachment itself — e.g. mapping `ofWorker` to a backend session id. */\nexport interface WorkerResumeContext {\n /** The prior SETTLED worker whose session the new worker continues. */\n readonly ofWorker: string\n /** 1-based position of the NEW worker in the node's continuity chain: a node spawned once and\n * resumed once hands the resumed worker `sequence: 2`. */\n readonly sequence: number\n}\n\n/** The exact result of one parent→child delivery attempt. */\nexport type DownMessageDeliveryOutcome =\n | 'delivered'\n | 'unknown-worker'\n | 'already-settled'\n | 'runtime-has-no-inbox'\n | 'scope-stopped'\n | 'runtime-error'\n\n/** A durable marker written after authorization and immediately before Runtime calls `Scope.send`.\n * If a process dies with this marker but no matching outcome, delivery is unknown and is never\n * replayed automatically. */\nexport interface DownMessageDeliveryAttempt {\n readonly receiptId: string\n readonly kind: 'steer' | 'answer'\n readonly toWorker: string\n readonly instructionDigest: string\n readonly interrupt: boolean\n readonly questionId?: string\n}\n\n/** A parent→child delivery result (the down-leg): recorded for observability, never pulled back by\n * the parent. `receiptId` and `instructionDigest` link it to the pre-delivery authorization receipt\n * and attempt marker. */\nexport interface DownMessageEvent {\n readonly receiptId: string\n readonly toWorker: string\n readonly instruction: string\n readonly instructionDigest: string\n readonly delivered: boolean\n readonly outcome: DownMessageDeliveryOutcome\n readonly error?: string\n}\n\n/** Durable authorization receipt written before a continuation reaches a worker. */\nexport interface ContinuationInstruction {\n readonly receiptId: string\n readonly kind: 'steer' | 'answer'\n readonly toWorker: string\n readonly instruction: string\n readonly instructionDigest: string\n readonly workerIdentity?: NodeExecutionIdentity\n readonly interrupt: boolean\n readonly questionId?: string\n}\n\n/** Detached continuation bytes and exact worker identity presented to product authorization before\n * Runtime records or delivers a steer/answer. */\nexport interface DownMessageAuthorizationInput {\n readonly kind: 'steer' | 'answer'\n readonly workerId: string\n readonly workerIdentity: NodeExecutionIdentity\n readonly instruction: string\n readonly interrupt: boolean\n readonly questionId?: string\n}\n\n/** Product-authorized continuation bytes. Returning a narrowed instruction replaces the proposed\n * bytes; throwing refuses delivery. */\nexport interface AuthorizedDownMessage {\n readonly instruction: string\n}\n\n/** Product decision over an exact continuation before it is durably recorded or delivered. */\nexport type AuthorizeDownMessage = (input: DownMessageAuthorizationInput) => AuthorizedDownMessage\n\n/** Every message on the one typed pipe. UP (child→parent): question / settled / finding — queued for\n * the driver to `pull`. An `instruction` is the pre-delivery authorization receipt and is retained\n * as evidence. DOWN (parent→child): steer / answer — record-only (history + subscribers), routed\n * to the child inbox. SIDEWAYS (child→sibling): mail — also record-only, and deliberately NOT\n * queued, so peer traffic audits through the parent without flooding the inbox it pulls from.\n * Receipts are never auto-delivered on restart. New kinds are additive. */\nexport type CoordinationEvent =\n | { readonly type: 'question'; readonly question: QuestionRecord }\n | { readonly type: 'settled'; readonly worker: SettledWorker }\n | { readonly type: 'finding'; readonly finding: AnalystFindingEvent }\n | {\n readonly type: 'steer'\n readonly down: DownMessageEvent\n /** Present when this steer DELIVERED an analyst's routed findings (an analyzes-edge\n * traversal), naming the lens — absent on an ordinary driver-authored steer. */\n readonly analyst?: string\n }\n | { readonly type: 'answer'; readonly down: DownMessageEvent; readonly questionId: string }\n | { readonly type: 'instruction'; readonly instruction: ContinuationInstruction }\n | { readonly type: 'delivery-attempt'; readonly attempt: DownMessageDeliveryAttempt }\n | { readonly type: 'mail'; readonly mail: PeerMailEvent }\n\n/** Immutable task, allocation, identity attribution, and semantic key supplied while a manager's\n * complete worker profile is prepared for one spawn. */\nexport interface WorkerSpawnContext {\n /** Stable assignment identity within this manager. A semantic key wins; otherwise Runtime mints\n * the manager's deterministic pre-factory spawn ordinal so identical unkeyed siblings stay\n * isolated and can recover by issuing the same assignments in the same order. */\n readonly assignmentId: string\n /** Trusted concrete manager node authorizing this spawn. Never accepted from model arguments. */\n readonly parentNodeId: string\n /** The exact allocation this node receives after the tool's optional override is merged. */\n readonly budget: Budget\n /** Detached, deeply immutable task bytes from this spawn request. */\n readonly task: unknown\n /** Exact trace label selected for this spawn. */\n readonly label: string\n /** Semantic restart key, when the manager supplied one. */\n readonly key?: string\n /** Trusted candidate/campaign attribution attached by product authorization. */\n readonly execution?: AgentExecutionRef\n /** Present (as the analyst id) ONLY when this spawn is an analyst-AGENT run initiated by the\n * runtime's analyst-on-settle hook ({@link AnalyzeOnSettleRoute.agent}) — authored by the\n * runtime, never accepted from a driver's tool arguments. A node-pinning `makeWorkerAgent`\n * reads it to admit the analyst node it would refuse as a driver-authored spawn. */\n readonly analyst?: string\n /** The EFFECTIVE continuity mode of this spawn — the spawn tool's per-call argument when given,\n * else the profile name's declared default ({@link CoordinationToolsOptions.continuityByProfile}),\n * else `'fresh'`. Absent only from producers that predate continuity — read absence as\n * `'fresh'`. */\n readonly continuity?: ContinuityMode\n /** Present iff `continuity === 'resume'`: the lineage the executor seam re-attaches with. */\n readonly resume?: WorkerResumeContext\n /**\n * The PEER MAIL capability endpoint minted for this exact spawn, when the run enabled peer mail\n * ({@link CoordinationToolsOptions.peerMail}). It serves `send_mail` / `read_mail` and nothing\n * else, and it speaks as this worker: the sender is bound to the capability, never passed as an\n * argument. Mount it on the worker the way `coordinationMcpUrl` is mounted on a driver.\n *\n * It arrives HERE, out of band, rather than being merged into the worker's `AgentProfile.mcp`,\n * for the same reason the driver's coordination URL does: the URL carries fresh random bytes per\n * process, so writing it into the profile would change the canonical profile digest every run and\n * a keyed re-spawn would then fail its identity check against the journal.\n */\n readonly peerMailUrl?: string\n}\n\nexport type MakeWorkerAgent = (\n profile: AgentProfile,\n context?: WorkerSpawnContext,\n) => SuperviseAgent<unknown, unknown>\n\nexport interface CoordinationToolsOptions {\n readonly scope: Scope<unknown>\n readonly blobs: ResultBlobStore\n readonly makeWorkerAgent: MakeWorkerAgent\n readonly perWorker: Budget\n /** Called once when this manager declares completion through `stop` or an accepted submission. */\n readonly onStop?: (reason: string | undefined) => void\n /**\n * The same independent completion check used for workers. When present, the driver receives a\n * `submit_result` tool and may finish work itself instead of being forced to delegate it. The\n * first passing submission is retained; a false or throwing check fails closed.\n */\n readonly deliverable?: DeliverableSpec<unknown>\n readonly analysts?: AnalystRegistry\n /** Event-first for source compatibility; the second argument is its exact bus ordering stamp. */\n readonly onEvent?: (\n event: CoordinationEvent,\n record: BusRecord<CoordinationEvent>,\n ) => void | Promise<void>\n /** Re-publish resumed settlements through the awaited observer before the driver starts. This is\n * the crash-window recovery path for product transactions; off preserves low-level legacy reads. */\n readonly replaySettlements?: boolean\n /** Authorize each continuation against the exact worker identity. The returned instruction is\n * detached, recorded durably through `onEvent`, and only then delivered. */\n readonly authorizeDownMessage?: AuthorizeDownMessage\n readonly questionPolicy?: QuestionPolicy\n /** Analyst lenses run AUTOMATICALLY when a worker settles `done` (the analyst-on-settle hook).\n * A bare string names a lens whose findings go to THE DRIVER: published as a `finding` event on\n * the bus — pass-through to subscribers and queued for `await_event`. An\n * {@link AnalyzeOnSettleRoute} generalizes the DESTINATION: findings can be delivered to a\n * named live WORKER (wrapped in the route's directive, through the same authorized steer\n * machinery a driver steer uses) instead of being hardwired to the spawning driver, and `over`\n * restricts which settled workers feed the lens. A route carrying `agent` generalizes the\n * ANALYST itself: a tool-equipped agent spawned as a worker whose settle output is the\n * findings (see {@link AnalyzeOnSettleRoute.agent}). Omit/empty = no auto-analysis (default;\n * the driver can still run lenses on demand via `run_analyst`). Lens routes require\n * `analysts`; agent routes do not. */\n readonly analyzeOnSettle?: ReadonlyArray<string | AnalyzeOnSettleRoute>\n /** Hard cap on how many workers may be LIVE (spawned but not yet settled) at once. `spawn_agent`\n * counts the scope's non-terminal nodes and fails closed (`error: 'max-live-workers'`) BEFORE\n * reserving from the pool when the cap is already met — a concurrency fence on top of the\n * conserved-budget fence (the pool bounds total work; this bounds simultaneous work, e.g. live\n * sandboxes/boxes). A tree-wide limit owned by `Scope` takes precedence when present; this field\n * is the local form for a caller-owned scope. Omit or `<= 0` = no local cap. */\n readonly maxLiveWorkers?: number\n /** Max wall-clock ms a single `await_event` call may block waiting on a live worker to settle\n * before it returns a non-error `{ pending: true, live }` snapshot and lets the caller re-poll.\n * The underlying `scope.next()` blocks for the WHOLE (multi-minute) worker run; over a remote MCP\n * transport that block outlives the client's per-request timeout, so an unbounded await surfaces\n * to the supervisor as a hard tool ERROR on every call — the exact failure that leaves it flying\n * blind. Bounding the wait converts that error into a re-pollable liveness signal. The background\n * drain keeps running, so a settlement that lands after the bound is published to the bus and\n * pulled by the next call — nothing is lost. Omit = {@link DEFAULT_AWAIT_EVENT_TIMEOUT_MS}; `<= 0`\n * restores the prior UNBOUNDED block (only safe for in-process drivers with no transport timeout). */\n readonly awaitTimeoutMs?: number\n /**\n * OPT-IN: run the ONLINE detector panel over each spawned worker's live tool trace and raise a\n * `finding` on the bus the moment a detector fires — so the driver learns \"this worker is\n * looping\" mid-run, from `await_event`, instead of at settle.\n *\n * This closes the `watchTrace` → `raiseFinding` wire whose own docstring already described it\n * (\"the seam an ONLINE detector uses to tell the driver 'this worker is looping/erroring' the\n * moment it happens\") but which nothing connected. Workers whose executor exposes no\n * `traceSource` are simply not watched; nothing fails.\n *\n * Omit = no online watching (the settle-time analysts are unaffected).\n */\n readonly watchWorkers?: WorkerWatchOptions\n /**\n * How long a worker may go without metered activity before `observe_agent` reports it as\n * `stalled`. A derived read at observation time, never a background watchdog — nothing is\n * killed or retried. Omit = the runtime default.\n */\n readonly stallAfterMs?: number\n /**\n * Questions carried over from a prior process of the SAME run (a durable coordination log a\n * resuming caller replays). Seeded into the question ledger verbatim — `list_questions` shows\n * them, the stop policy counts the still-blocking ones, and `answer_question` can decide them.\n * Omit/empty = fresh ledger (every run that is not a resume).\n */\n readonly priorQuestions?: ReadonlyArray<QuestionRecord>\n /**\n * Default continuity per PROFILE NAME (the stable node identity a graph pins). A name mapping\n * to `'resume'` makes its spawns re-attach to the node's most recent settled worker whenever\n * one exists — the node's FIRST spawn is effectively `'fresh'`, and a spawn while a prior\n * worker of the node is still LIVE fails closed (`resume-while-live`; steer is the live-worker\n * channel). The spawn tool's per-call `continuity` argument overrides the declared default in\n * either direction. Omit = every spawn is `'fresh'` (status quo). Resume lineage is\n * PROCESS-LOCAL (the same boundary as the analyst-run marker): workers settled by a prior\n * process of a durable run are not resume targets.\n */\n readonly continuityByProfile?: Readonly<Record<string, ContinuityMode>>\n /**\n * OPT-IN: give this manager's workers a bounded SIBLING channel (`../../runtime/supervise/\n * peer-mail`). Each spawn is minted a capability endpoint handed out on\n * {@link WorkerSpawnContext.peerMailUrl}; every attempt, delivered or refused, publishes a\n * `mail` event so the parent audits a channel it no longer relays. Omit = no peer channel and no\n * capability is minted (the status quo: a worker is reachable only by its parent).\n */\n readonly peerMail?: { readonly limits?: Partial<PeerMailLimits> }\n /**\n * OPT-IN async gate run on every spawn BEFORE an assignment is minted, budget is reserved, or\n * `Scope.spawn` is called — the one pre-journal point where a network question may be asked.\n *\n * `Scope.spawn` and `MakeWorkerAgent` are synchronous, so a check that needs the backend's\n * answer (does this bridge route the child's wire id; is it already at admission capacity)\n * cannot live there. Returning a {@link SpawnRefusal} refuses the spawn as a tool result: no\n * assignment, no reservation, no journal entry, no worker — and the refusal is counted on\n * {@link CoordinationTools.stats} so a gate that never refuses is visible as such.\n *\n * Returning `undefined` admits the spawn. A THROW is not a refusal: it propagates, because a\n * pre-flight that fails open would hand back exactly the silent admission it exists to stop.\n */\n readonly preflightSpawn?: SpawnPreflight\n /**\n * OPT-IN pre-journal PROFILE resolution: maps the profile a driver authored to the profile that\n * will actually run, before `preflightSpawn` asks the backend about it. A layer that pins\n * profiles by name (an agent graph) installs this so the gate judges the canonical profile —\n * its real model, tools and harness — never the `{ name }` stub the driver wrote. Synchronous,\n * throw-on-refusal, identity-free: it sees only the profile, never the assignment or budget,\n * because both are minted AFTER the pre-journal point. Omit = the authored profile is used.\n */\n readonly resolveSpawnProfile?: (profile: AgentProfile) => AgentProfile\n}\n\n/** Why a pre-flight refused a spawn. Each cause is a distinct, separately countable decision. */\nexport type SpawnRefusalCause = 'model-route' | 'bridge-full' | 'unmountable-tool'\n\n/** A pre-flight's refusal: the cause it decided on, and the operator-facing evidence for it. */\nexport interface SpawnRefusal {\n readonly cause: SpawnRefusalCause\n /** Names the exact thing that failed — the unrouted wire id, the admission numbers, the tool. */\n readonly detail: string\n}\n\n/** What a pre-flight sees: the authored child profile and the spawn it is being asked to admit. */\nexport interface SpawnPreflightContext {\n readonly label: string\n readonly key?: string\n readonly task: unknown\n}\n\n/** The gate `CoordinationToolsOptions.preflightSpawn` installs. */\nexport type SpawnPreflight = (\n profile: AgentProfile,\n context: SpawnPreflightContext,\n) => Promise<SpawnRefusal | undefined>\n\n/** Bus throughput plus the pre-flight's own refusal ledger. */\nexport interface CoordinationStats extends BusStats {\n /** One counter per refusal cause, present only when a pre-flight is installed. */\n readonly preflight?: Readonly<Record<SpawnRefusalCause, number>>\n}\n\n/** Every cause at zero — a pre-flight publishes its whole ledger from the first read. */\nfunction emptyPreflightCounts(): Record<SpawnRefusalCause, number> {\n return { 'model-route': 0, 'bridge-full': 0, 'unmountable-tool': 0 }\n}\n\n/** Online-detector wiring for spawned workers (`CoordinationToolsOptions.watchWorkers`). */\nexport interface WorkerWatchOptions {\n /** Detector panel; omit for the default stuck-loop + error-streak pair. */\n readonly detectors?: WatchTraceOptions['detectors']\n /** Raise at most this many findings per worker, so one pathological worker cannot flood the\n * driver's inbox with the same signal every span. Default 3; `<= 0` = unlimited. */\n readonly maxFindingsPerWorker?: number\n}\n\n/** Default ceiling for a single `await_event` block (ms). Chosen well under any reasonable remote\n * MCP client request timeout so the call returns a `pending` liveness snapshot instead of erroring;\n * the supervisor re-polls until the worker settles. */\nexport const DEFAULT_AWAIT_EVENT_TIMEOUT_MS = 15_000\n\n/**\n * The supervisor-side toolbox returned by {@link createCoordinationTools}: the MCP tool\n * descriptors a driver `AgentProfile` calls to spawn, steer, observe, and settle workers\n * over a live `Scope`, plus the typed accessors (`settled`/`questions`/`history`/`stats`/\n * `raiseFinding`) for the bidirectional coordination bus. This is the live, backend-of-your-\n * choice, steerable counterpart to the one-shot own-sandbox delegation MCP.\n */\nexport interface CoordinationTools {\n readonly tools: McpToolDescriptor[]\n /** Commit any resume-time event replay before a supervisor can reason or an MCP can listen. */\n ready(): Promise<void>\n isStopped(): boolean\n stopReason(): string | undefined\n /** The first result whose injected independent check passed, if the driver submitted one. */\n submittedResult(): { readonly result: unknown } | undefined\n settled(): ReadonlyArray<SettledWorker>\n questions(): ReadonlyArray<QuestionRecord>\n /** The full ordered log of every bus event — UP (settled / question / finding), authorized\n * instruction receipts, and DOWN delivery outcomes (steer / answer). Each record carries seq,\n * timestamp, and priority. A receipt is evidence and is never auto-delivered on restart. */\n history(): ReadonlyArray<BusRecord<CoordinationEvent>>\n /** Bus throughput counters (published / pulled / by-kind) for live dashboards, plus one\n * counter per {@link SpawnRefusalCause} the pre-flight refused. `preflight` is present\n * whenever `preflightSpawn` is installed, with every cause at 0 until one fires — a gate that\n * never refuses has to be readable as such. */\n stats(): CoordinationStats\n /** The run's peer-mail post office, present only when `peerMail` was enabled. The transport\n * layer stands the capability endpoint up over it; the parent reads `history()` for the audit\n * trail and calls `stopThread` to end a peer exchange. */\n readonly peerMail?: PeerMailbox\n /** Raise a `finding` on the bus from outside the settle hook — the seam an ONLINE detector\n * (mid-run, on the worker pipe) uses to tell the driver \"this worker is looping/erroring\" the\n * moment it happens, instead of only at settle. Queued for `await_event` + pass-through. */\n raiseFinding(finding: AnalystFindingEvent): Promise<void>\n /** Authorize, durably record, and attempt one external steer through the same down-leg used by\n * `steer_agent`. The returned outcome is exact and is never inferred from queue admission. */\n steerWorker(\n workerId: string,\n instruction: string,\n options?: { readonly interrupt?: boolean },\n ): Promise<DownMessageEvent>\n /**\n * Abort ONE live worker this manager spawned, through the worker's own per-child abort chain\n * (the scope cascades that abort into the worker's subtree and no sibling). `ref` resolves\n * workerId-first, then profile name, then spawn label, against LIVE workers only. Returns the\n * resolved identity, or `undefined` when no live worker matches — an already-settled or unknown\n * reference is never reported as aborted. The runtime cancel acknowledger is the intended\n * caller; the durable contract around it lives in `supervise/run-layout`.\n */\n abortWorker(\n ref: string,\n reason?: string,\n ): { readonly id: string; readonly label: string } | undefined\n /**\n * Post-loop drain: pull every ALREADY-settled, unpulled child into the ledger (publishing each\n * as a `settled` bus event for the audit trail) WITHOUT awaiting live children. The driver\n * calls this once its brain loop ends, so a delivered child the brain never awaited still\n * reaches `finalizeBestDelivered` — a gate-verified delivery must never be lost to the\n * driver's pull discipline. Analyst-on-settle hooks do NOT fire here (the driver has stopped;\n * nobody is left to read a finding, and analysts spend real compute). Returns the count.\n */\n drainResolved(): Promise<number>\n}\n\n/** The reserved coordination verb names — the complete set `createCoordinationTools` can emit\n * (the analyst pair is conditional but still reserved). A driver's extra WORK tools must not\n * collide with any of these, or it could no longer coordinate; callers validate eagerly against\n * this set so the conflict fails loud at construction, not buried in a swallowed `act()` throw. */\nexport const coordinationVerbNames = [\n 'spawn_agent',\n 'observe_agent',\n 'steer_agent',\n 'await_event',\n 'list_questions',\n 'answer_question',\n 'ask_parent',\n 'submit_result',\n 'stop',\n 'list_analysts',\n 'run_analyst',\n] as const\n\n/**\n * The `CoordinationEvent` kinds a driver may name in `await_event`. The pull queue carries the\n * UP-leg only: `steer` / `answer` / `instruction` / `delivery-attempt` are recorded `queue: false`\n * (history and subscribers, never pulled back), and `mail` is delivered to its addressee's inbox.\n *\n * Declared once because the tool advertises this list in its JSON Schema AND filters on it at\n * dispatch. Written twice, the two drift and the schema promises a kind the filter drops — a\n * driver then blocks on a queue that already holds its event.\n */\nconst awaitableEventKinds = ['settled', 'question', 'finding'] as const satisfies ReadonlyArray<\n CoordinationEvent['type']\n>\n\ntype AwaitableEventKind = (typeof awaitableEventKinds)[number]\n\nfunction isAwaitableEventKind(value: unknown): value is AwaitableEventKind {\n return (awaitableEventKinds as ReadonlyArray<unknown>).includes(value)\n}\n\nconst idArg = { type: 'string', description: 'The workerId returned by spawn_agent.' } as const\n\n/**\n * Strip zod's object-KEY CODEC artifact from a derived JSON Schema, at every depth.\n *\n * `z.record(z.string(), …)` converts to `propertyNames: { type: 'string', pattern:\n * '^u(?:[0-9a-f]{4})*$' }` — a marker of the lossy key round-trip, not a constraint anything\n * enforces: `agentProfileSchema.safeParse({ name: 'r', tools: { bash: true, Read: false } })`\n * succeeds with those plain keys. Published verbatim it reads to a model as \"every key must be a\n * run of hex quads\", and the model either emits hex-encoded garbage keys or drops the field —\n * on `tools`, `permissions`, `metadata`, `mcp`, `mcp.*.env`, and `model.metadata`, which is most\n * of what a parent actually configures.\n *\n * Every `propertyNames` in the canonical profile schema is this artifact (25 of 25 at Interface\n * 0.40), and the canonical schema constrains no key by pattern, so dropping the keyword outright\n * loses nothing real and cannot be defeated by zod changing the encoding's exact regex.\n *\n * Rebuilds rather than mutates: the canonical conversion output must stay untouched for callers\n * that compare against it.\n */\nconst stripKeyCodecArtifacts = (node: unknown): unknown => {\n if (Array.isArray(node)) return node.map(stripKeyCodecArtifacts)\n if (!node || typeof node !== 'object') return node\n return Object.fromEntries(\n Object.entries(node as Record<string, unknown>)\n .filter(([key]) => key !== 'propertyNames')\n .map(([key, value]) => [key, stripKeyCodecArtifacts(value)]),\n )\n}\n\n/** One field of the published child-profile shape: the canonical field it mirrors, the one-line\n * description a model can act on (what it is, what a child typically sets), and — for the two\n * fields whose canonical sub-tree dwarfs the rest of the tool surface — the BRIEF schema published\n * in place of that sub-tree. */\ninterface PublishedProfileField {\n readonly name: string\n readonly description: string\n readonly brief?: Record<string, unknown>\n}\n\n/** The canonical profile fields a spawning parent actually sets on a child, in the order a reader\n * needs them, each with the description published alongside it. Everything else stays legal to\n * pass — see {@link deriveSpawnProfileArg}.\n *\n * Why these eleven, with the measured numbers (serialized JSON bytes, Interface 0.40). The\n * canonical `properties` map is 10629 bytes, against 2424 bytes for every argument of every other\n * coordination tool COMBINED — publishing it whole makes one parameter four times the rest of the\n * surface a driver re-reads each turn. Of the seven omitted fields (tags, connections, subagents,\n * hooks, modes, confidential, extensions) none is something a parent hands a worker; `permissions`\n * (321 bytes) IS, so it is published — a child that must not touch the network or the filesystem\n * is fenced there and nowhere else. `mcp` (2663 bytes) and `resources` (3122 bytes) are the two a\n * parent is least likely to author inline and were together 85% of the published cost, so they\n * carry a brief shape plus a description naming the full form instead of the canonical sub-tree. */\nconst spawnProfileFields: readonly PublishedProfileField[] = [\n {\n name: 'name',\n description:\n 'Short identifier for this child, e.g. \"researcher\" or \"patch-writer\". A child normally ' +\n 'sets it to its role; it shows up in traces and worker labels.',\n },\n {\n name: 'description',\n description:\n 'One line saying what this child is for. Read by humans and by a parent listing its workers.',\n },\n {\n name: 'version',\n description:\n 'Optional version string for this profile, so two revisions of the same role are ' +\n 'distinguishable in evidence. A child usually omits it.',\n },\n {\n name: 'harness',\n description:\n 'Which coding backend runs the child. Omit to inherit the run default; set it only when ' +\n 'this child needs a specific backend (e.g. a long refactor on \"claude-code\").',\n },\n {\n name: 'model',\n description:\n 'Model routing: `default` model id, optional `small` for cheap sub-calls, `provider`, and ' +\n '`reasoningEffort`. A child typically sets `default` and `reasoningEffort` — raise effort ' +\n 'for a hard reasoning task, lower it for bulk mechanical work.',\n },\n {\n name: 'prompt',\n description:\n \"The child's standing instructions: `systemPrompt` (who it is and how it works) and \" +\n '`instructions` (durable rules). This is the role; the separate `task` argument carries ' +\n 'what to do right now. A child with no systemPrompt has no role — always set one.',\n },\n {\n name: 'tools',\n description:\n 'Per-tool on/off map keyed by tool name, e.g. `{ \"bash\": true, \"webfetch\": false }`. Omit ' +\n \"to inherit the backend's default tool set; set it to narrow a child to the tools its task \" +\n 'needs. Keys are plain tool names.',\n },\n {\n name: 'permissions',\n description:\n 'Per-tool permission decisions: each tool name maps to \"allow\", \"deny\", or \"ask\", or to a ' +\n 'nested map of finer-grained rules. This is where a parent fences a child it does not fully ' +\n 'trust — a read-only child denies write and network tools here, not in `tools`.',\n },\n {\n name: 'mcp',\n description:\n 'MCP tool servers to mount for the child, keyed by server name. Brief form: each value is ' +\n 'either `{ transport: \"stdio\", command, args?, env?, cwd? }` or ' +\n '`{ transport: \"sse\" | \"http\", url, headers? }`. A child normally sets this only when it ' +\n 'needs a tool server the task requires; the canonical AgentProfile schema carries the full ' +\n 'form (secret-ref values for env/headers, per-server metadata) and governs validation.',\n brief: { type: 'object', additionalProperties: { type: 'object' } },\n },\n {\n name: 'resources',\n description:\n 'Files, tools, skills, and agents materialized into the child workspace before it starts. ' +\n 'Brief form: `{ files?, tools?, skills?, agents? }`, each an array whose entries are ' +\n '`{ kind: \"inline\", name, content }` or `{ kind: \"github\", repository?, path, ref? }` ' +\n '(`files` entries wrap that as `{ path, resource, executable? }`). A child typically gets ' +\n '`files` for seed inputs and `skills` for a procedure it must follow; the canonical ' +\n 'AgentProfile schema carries the full form and governs validation.',\n brief: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'object' } },\n tools: { type: 'array', items: { type: 'object' } },\n skills: { type: 'array', items: { type: 'object' } },\n agents: { type: 'array', items: { type: 'object' } },\n },\n additionalProperties: true,\n },\n },\n {\n name: 'metadata',\n description:\n 'Free-form key/value bag carried with the profile (plain string keys). Use it for run ' +\n 'bookkeeping a reader will want later; it does not change how the child executes.',\n },\n]\n\n/**\n * Build the published shape of `spawn_agent`'s `profile` argument from the canonical\n * `agentProfileSchema` conversion's `properties` map, so it cannot drift from the profile the\n * runtime materializes.\n *\n * DEGRADES, never throws. A canonical field that is absent — renamed or removed upstream — is\n * simply omitted from the published shape, and a canonical schema that is no longer an object\n * publishes no properties at all. This function is reached from a statically-imported module, so a\n * throw here bricks `import '@tangle-network/agent-runtime/kernel'` for every consumer over an\n * upstream rename that costs them, at worst, one advisory field. The drift itself is still caught\n * loudly — as a test assertion in `tests/kernel/coordination.test.ts`, in CI, where it is our\n * problem rather than at a consumer's import, where it is theirs.\n *\n * Permissive on purpose: `additionalProperties: true` with no `required` list, so every canonical\n * field this shape omits stays legal to pass. This tool layer performs no profile validation.\n *\n * @internal exported for the drift and degradation tests; not part of the package's public API.\n */\nexport function deriveSpawnProfileArg(\n canonicalProperties: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n const published: Array<[string, unknown]> = []\n for (const field of spawnProfileFields) {\n const canonical = canonicalProperties?.[field.name]\n if (canonical === undefined) continue\n const shape = field.brief ?? (stripKeyCodecArtifacts(canonical) as Record<string, unknown>)\n published.push([field.name, { ...shape, description: field.description }])\n }\n return {\n type: 'object',\n description:\n 'The child agent profile to run — this is the shape the DEFAULT worker seam accepts; a run ' +\n 'wired with a custom makeWorkerAgent may accept a different one. The properties below are ' +\n 'derived from the canonical AgentProfile schema and reduced to what a spawning parent sets ' +\n '(`mcp` and `resources` in a brief form); every other canonical field — tags, connections, ' +\n 'subagents, hooks, modes, confidential, extensions — may still be passed. This tool does ' +\n 'not validate the profile: the canonical AgentProfile schema governs validation downstream.',\n properties: Object.fromEntries(published),\n additionalProperties: true,\n }\n}\n\n/** The canonical field names this module publishes, in published order — the drift test's input.\n *\n * @internal */\nexport const spawnProfileFieldNames: readonly string[] = spawnProfileFields.map((f) => f.name)\n\nlet spawnProfileArgCache: Record<string, unknown> | undefined\n\n/** The published `profile` shape, computed on FIRST tool-definition access and memoized — not at\n * module load. The conversion walks the whole canonical profile tree, and the strip walk rebuilds\n * it: 3.5ms on the first `createCoordinationTools`, 0.017ms on every later one (measured, Interface\n * 0.40, node 24). `src/runtime/index.ts` imports this module statically, so paying that at import\n * taxes every consumer of the kernel entrypoint — including the ones that never build a\n * coordination toolbox. The memo keeps it at once per process for the ones that do.\n *\n * Conversion choices. `io: 'input'` is the CALLER's view — pre-default, pre-transform — which is\n * what a spawning parent may pass, not what the runtime ends up holding. `unrepresentable: 'any'`\n * keeps the conversion total: the canonical schema contains transforms with no JSON Schema form,\n * and zod's default is to throw on them, which would leave the tool with no published shape. */\nfunction spawnProfileArg(): Record<string, unknown> {\n if (!spawnProfileArgCache) {\n const canonical = agentProfileSchema.toJSONSchema({\n io: 'input',\n target: 'draft-07',\n unrepresentable: 'any',\n })\n // Deep-frozen because ONE memoized object is handed to every coordination toolbox in the\n // process: an unfrozen shared schema lets one consumer's mutation corrupt every later one.\n spawnProfileArgCache = detachedFrozen(deriveSpawnProfileArg(canonical.properties))\n }\n return spawnProfileArgCache\n}\n\n/** Build the driver's MCP tools over a live scope. */\nexport function createCoordinationTools(opts: CoordinationToolsOptions): CoordinationTools {\n const deliverable = opts.deliverable\n let stopped = false\n let reason: string | undefined\n let stopNotified = false\n let submitted: { readonly result: unknown } | undefined\n let questionSeq = 0\n const ledger: SettledWorker[] = []\n const questions: QuestionRecord[] = [...(opts.priorQuestions ?? [])]\n const questionPolicy = opts.questionPolicy ?? 'auto'\n\n const notifyStop = (): void => {\n if (stopNotified) return\n stopNotified = true\n opts.onStop?.(reason)\n }\n\n // Keyed-assignment bookkeeping for the live-worker fence. `completedKeys` is every key this run\n // can already answer from committed work — seeded from the prior journal on a resume, extended as\n // keyed workers deliver in THIS process. A spawn under such a key starts nothing and occupies no\n // slot, so the fence must not hold it back. `keyByWorker` is what lets a settlement find its key.\n const completedKeys = new Set<string>()\n const keyByWorker = new Map<string, string>()\n // Worker id → the AUTHORED profile name it was spawned from. The stable identity an\n // `AnalyzeOnSettleRoute` names (`to`/`over`): labels are the driver's free-text choice, while\n // the profile name is what a graph pins a node by. Recorded at spawn, dropped never (a settled\n // source can still be matched by `over` after it is gone).\n const profileNameByWorker = new Map<string, string>()\n // Worker id → the live child Handle from its spawn. `Handle.abort` is the ONLY per-child abort\n // (its controller cascades to that child's subtree and no sibling), and the scope does not\n // re-expose it, so `abortWorker` must keep the handle from the spawn that minted it. Entries\n // are never deleted (liveness is re-checked against the view at abort time); the map is\n // bounded by the run's spawn count, like `profileNameByWorker`.\n const liveHandles = new Map<string, Handle<unknown>>()\n // `Scope` advances its node/cursor ordinals on resume, but assignment identity belongs to this\n // manager. Seed it independently from durable evidence so a restarted manager never calls new\n // work `ordinal:0` when a prior process already used that assignment. Use the maximum rather\n // than the number of rows: journals can contain gaps, keyed assignments, and legacy/custom ids.\n let unkeyedAssignmentOrdinal = nextUnkeyedAssignmentOrdinal(opts.scope)\n const preflightCounts = emptyPreflightCounts()\n for (const [key, prior] of opts.scope.resume?.keys ?? []) {\n if (prior.state === 'completed') completedKeys.add(key)\n }\n\n const nodeForWorker = (id: string) =>\n opts.scope.view.nodes.find((node) => node.id === id) ??\n opts.scope.resume?.view.nodes.find((node) => node.id === id)\n\n const projectSettled = (settled: Settled<unknown>, resumed = false): SettledWorker => {\n const node = nodeForWorker(settled.handle.id)\n const assignmentId = settled.handle.assignmentId ?? node?.assignmentId\n const identity = settled.handle.identity ?? node?.identity\n const materialization = settled.handle.materialization ?? node?.materialization\n const executionBindings = settled.handle.executionBindings ?? node?.executionBindings\n const settledAt = settled.settledAt ?? node?.settledAt\n const trace =\n settled.trace ??\n node?.trace ??\n ({\n status: 'unavailable',\n reason: 'legacy-settlement-without-trace-evidence',\n } as const)\n const common = {\n id: settled.handle.id,\n ...(assignmentId === undefined ? {} : { assignmentId }),\n ...(identity === undefined ? {} : { identity }),\n ...(materialization === undefined ? {} : { materialization }),\n ...(executionBindings === undefined ? {} : { executionBindings }),\n ...(settledAt === undefined ? {} : { settledAt }),\n trace,\n ...(resumed ? { resumed: true as const } : {}),\n }\n return detachedFrozen<SettledWorker>(\n settled.kind === 'done'\n ? {\n ...common,\n status: 'done',\n spent: settled.spent,\n ...(settled.verdict?.score === undefined ? {} : { score: settled.verdict.score }),\n ...(settled.verdict?.valid === undefined ? {} : { valid: settled.verdict.valid }),\n outRef: settled.outRef,\n }\n : {\n ...common,\n status: 'down',\n ...(node?.spent === undefined ? {} : { spent: node.spent }),\n reason: settled.reason,\n },\n )\n }\n\n // A resumed scope's replayed settlements enter the ledger AT CONSTRUCTION, so `settled()` — and\n // therefore the finalize that reads it — spans processes exactly as the journal does.\n const resumedWorkers: SettledWorker[] = []\n for (const s of opts.scope.resume?.settled ?? []) {\n const worker = projectSettled(s, true)\n resumedWorkers.push(worker)\n ledger.push(worker)\n }\n\n // The one child→parent pipe. Keep the event-first callback and also pass its exact stamp, so a\n // durable subscriber retains causal sequence, original timestamp, and priority.\n const bus = createEventBus<CoordinationEvent>()\n if (opts.onEvent) {\n const cb = opts.onEvent\n bus.subscribe((rec) => cb(rec.event, rec))\n }\n // A settlement can be durable in the spawn journal while the process dies before the product\n // observer acknowledges it. Opted-in high-level callers replay those events at least once. Keep\n // each frozen event object across an in-process retry so EventBus reuses its exact BusRecord.\n const resumeEvents = opts.replaySettlements\n ? resumedWorkers.map((worker) => detachedFrozen<CoordinationEvent>({ type: 'settled', worker }))\n : []\n let resumeEventIndex = 0\n let readyInFlight: Promise<void> | undefined\n const ready = (): Promise<void> => {\n if (resumeEventIndex >= resumeEvents.length) return Promise.resolve()\n if (readyInFlight) return readyInFlight\n readyInFlight = (async () => {\n while (resumeEventIndex < resumeEvents.length) {\n const event = resumeEvents[resumeEventIndex]\n if (!event) break\n await bus.publish(event)\n resumeEventIndex += 1\n }\n })().finally(() => {\n readyInFlight = undefined\n })\n return readyInFlight\n }\n\n // Urgency → bus priority: a blocking question is bumped ahead of queued settles/findings so the\n // driver sees it FIRST when it drains the inbox (and pass-through already delivered it the instant\n // it was raised). Non-blocking messages share priority 0 and resolve FIFO.\n const urgencyPriority = (u: QuestionUrgency): number =>\n u === 'blocks-run' ? 20 : u === 'blocks-step' ? 10 : 0\n\n const str = (v: unknown, field: string): string => {\n if (typeof v !== 'string' || v.length === 0)\n throw new Error(`coordination tools: \"${field}\" must be a non-empty string`)\n return v\n }\n const obj = (raw: unknown): Record<string, unknown> => {\n if (!raw || typeof raw !== 'object')\n throw new Error('coordination tools: arguments must be an object')\n return raw as Record<string, unknown>\n }\n // Parse a per-spawn `budget` override and merge it over the per-worker default (per field).\n // Fails loud on a non-object or a non-finite numeric field — a malformed budget must never\n // silently fall back to the default and run a sub-task on a ceiling nobody chose.\n const mergeBudget = (base: Budget, raw: unknown): Budget => {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw))\n throw new Error('coordination tools: \"budget\" must be an object')\n const o = raw as Record<string, unknown>\n const field = (name: keyof Budget): number | undefined => {\n const v = o[name]\n if (v === undefined) return undefined\n if (typeof v !== 'number' || !Number.isFinite(v))\n throw new Error(`coordination tools: \"budget.${name}\" must be a finite number`)\n return v\n }\n const maxIterations = field('maxIterations')\n const maxTokens = field('maxTokens')\n const maxUsd = field('maxUsd')\n const deadlineMs = field('deadlineMs')\n const merged: Budget = {\n maxIterations: maxIterations ?? base.maxIterations,\n maxTokens: maxTokens ?? base.maxTokens,\n ...((maxUsd ?? base.maxUsd) === undefined ? {} : { maxUsd: maxUsd ?? base.maxUsd }),\n ...((deadlineMs ?? base.deadlineMs) === undefined\n ? {}\n : { deadlineMs: deadlineMs ?? base.deadlineMs }),\n }\n assertValidBudget(merged, 'coordination tools: budget')\n return merged\n }\n const level = (v: unknown): Question['level'] => {\n if (v === 'worker' || v === 'driver' || v === 'loop') return v\n throw new Error('coordination tools: \"level\" must be worker, driver, or loop')\n }\n const urgency = (v: unknown): Question['urgency'] => {\n if (v === 'continue-without' || v === 'blocks-step' || v === 'blocks-run') return v\n throw new Error(\n 'coordination tools: \"urgency\" must be continue-without, blocks-step, or blocks-run',\n )\n }\n\n const commitSettled = (s: Settled<unknown>, w: SettledWorker): void => {\n // A keyed assignment that just delivered is complete for the rest of this run, so a later\n // spawn under the same key resolves for free instead of being held behind the live-worker\n // fence (it starts no worker, so it occupies no slot).\n const settledKey = keyByWorker.get(s.handle.id)\n if (settledKey !== undefined && s.kind === 'done') completedKeys.add(settledKey)\n ledger.push(w)\n // A settled worker's trace source is finished; drop the online subscription with it.\n unwatchWorker(w.id)\n }\n\n // `Scope.next()` is once-only, while an awaited observer may commit and lose its acknowledgement.\n // Retain the exact event until publication succeeds so the next await retries rather than losing\n // the settlement between the spawn journal and the product transaction. `analystRun` marks a\n // settlement that IS an analyst-agent's findings (see `analystRuns`), whose event is a `finding`.\n let pendingSettlement:\n | {\n readonly settled: Settled<unknown>\n readonly worker: SettledWorker\n readonly event: CoordinationEvent\n readonly analyze: boolean\n readonly analystRun?: AnalystRunInFlight\n }\n | undefined\n\n // Analyst-AGENT runs in flight (`AnalyzeOnSettleRoute.agent`): worker id → the route that\n // spawned it + the settled source worker whose evidence it analyzes. A member's settlement is a\n // FINDING, not a worker settle: it never enters the settled ledger, never feeds the finalizer,\n // and never re-fires the analyst-on-settle hook — so an analyst cannot cascade onto itself.\n interface AnalystRunInFlight {\n readonly route: AnalyzeOnSettleRoute\n readonly sourceWorker: string\n }\n // PROCESS-LOCAL by design: a durable-run RESUME does not repopulate this map, so an\n // analyst spawn from a PRIOR process settles as an ordinary worker on resume (it re-enters\n // the settled ledger instead of being intercepted as a finding). Journal-level marking of\n // analyst assignments is the fix; until then resume + analyst-node graphs do not compose.\n const analystRuns = new Map<string, AnalystRunInFlight>()\n let analystRunOrdinal = 0\n\n /** The `finding` event an analyst-agent settlement becomes: its settle OUTPUT is the findings\n * (a failed run publishes the failure as findings — degraded beats vanished). */\n const analystRunFinding = (\n run: AnalystRunInFlight,\n settled: Settled<unknown>,\n ): CoordinationEvent =>\n detachedFrozen<CoordinationEvent>({\n type: 'finding',\n finding: canonicalFindingEvent({\n fromWorker: run.sourceWorker,\n analyst: run.route.kind,\n findings: settled.kind === 'done' ? settled.out : { analystRunFailed: settled.reason },\n }),\n })\n\n /**\n * Spawn one analyst-AGENT run over a settled worker's evidence, through the SAME spawn\n * machinery a driver spawn uses (`scope.spawn` + `makeWorkerAgent`): the analyst's spend\n * reserves from the conserved pool, its node is journaled/traced like any worker, and a\n * node-pinning seam sees `context.analyst`. Its task is the route directive plus the settled\n * worker's persisted tool-trace spans. A refused spawn publishes a finding RECORDING the\n * refusal — observable, never silent — and must never take down the settlement path.\n */\n const spawnAnalystRun = async (\n route: AnalyzeOnSettleRoute,\n worker: SettledWorker,\n ): Promise<void> => {\n let spansText = ''\n let spanCount = 0\n if (worker.trace.status === 'available') {\n try {\n const raw = await opts.blobs.get(worker.trace.traceRef)\n const artifact = parseWorkerToolTraceArtifact(raw, worker.trace.traceRef)\n spanCount = artifact.spans.length\n spansText = safeJsonText(artifact.spans)\n } catch {\n spansText = '' // degraded evidence is stated below, never a thrown settle path\n }\n }\n const task = [\n ...(route.directive === undefined || route.directive.length === 0 ? [] : [route.directive]),\n `Evidence — settled worker '${worker.id}' tool trace (${spanCount} spans):`,\n spansText.length === 0 ? '(no tool spans available)' : spansText,\n ].join('\\n\\n')\n const assignmentId = `analyst:${route.kind}:o${analystRunOrdinal++}`\n const label = `analyst:${route.kind}`\n const context: WorkerSpawnContext = Object.freeze({\n assignmentId,\n parentNodeId: opts.scope.view.root,\n budget: opts.perWorker,\n task,\n label,\n analyst: route.kind,\n // An analyst run is always a brand-new session over settled evidence — never a resume.\n continuity: 'fresh' as const,\n })\n let refusal: string | undefined\n let spawnedId: string | undefined\n try {\n const res = opts.scope.spawn(\n () => opts.makeWorkerAgent(route.agent as AgentProfile, context),\n task,\n { budget: opts.perWorker, label, assignmentId },\n )\n if (res.ok) spawnedId = res.handle.id\n else refusal = String(res.reason)\n } catch (cause) {\n refusal = cause instanceof Error ? cause.message : String(cause)\n }\n if (spawnedId === undefined) {\n await bus.publish({\n type: 'finding',\n finding: canonicalFindingEvent({\n fromWorker: worker.id,\n analyst: route.kind,\n findings: { analystSpawnRefused: refusal ?? 'unknown' },\n }),\n })\n return\n }\n analystRuns.set(spawnedId, { route, sourceWorker: worker.id })\n watchWorker(spawnedId)\n }\n\n // The names an analyst route may know a worker by: its authored profile name (the stable node\n // identity) and its spawn label (the driver's free-text choice).\n const workerRouteNames = (workerId: string): Set<string> => {\n const names = new Set<string>()\n const profileName = profileNameByWorker.get(workerId)\n if (profileName !== undefined) names.add(profileName)\n const label = nodeForWorker(workerId)?.label\n if (label !== undefined) names.add(label)\n return names\n }\n\n /** The LIVE worker a route destination names, by profile name first, label second. */\n const liveWorkerIdNamed = (destination: string): string | undefined => {\n const live = opts.scope.view.nodes.filter((node) => isLiveNodeStatus(node.status))\n return (\n live.find((node) => profileNameByWorker.get(node.id) === destination)?.id ??\n live.find((node) => node.label === destination)?.id\n )\n }\n\n // ── Continuity: how a spawn continues a node's prior work ──\n // Node identity is the PROFILE NAME only (never the label): resume re-attaches to a specific\n // prior session, and the label is the driver's free-text choice. All three reads are\n // process-local by construction — `profileNameByWorker` records only this process's spawns —\n // which is the documented resume boundary (a prior process's workers are not resume targets).\n const liveWorkerForNode = (name: string): string | undefined =>\n opts.scope.view.nodes.find(\n (node) => isLiveNodeStatus(node.status) && profileNameByWorker.get(node.id) === name,\n )?.id\n const latestSettledWorkerForNode = (name: string): string | undefined => {\n for (let i = ledger.length - 1; i >= 0; i -= 1) {\n const worker = ledger[i] as SettledWorker\n if (profileNameByWorker.get(worker.id) === name) return worker.id\n }\n return undefined\n }\n const nodeSpawnCount = (name: string): number => {\n let count = 0\n for (const profileName of profileNameByWorker.values()) if (profileName === name) count += 1\n return count\n }\n const parseContinuity = (v: unknown): ContinuityMode | undefined => {\n if (v === undefined) return undefined\n if (v === 'fresh' || v === 'resume') return v\n throw new Error('coordination tools: \"continuity\" must be \"fresh\" or \"resume\"')\n }\n type ResolvedContinuity =\n | { readonly continuity: 'fresh' }\n | { readonly continuity: 'resume'; readonly resume: WorkerResumeContext }\n | { readonly error: string; readonly hint: string }\n /**\n * Resolve the EFFECTIVE continuity of one spawn: the per-call request wins, else the profile\n * name's declared default, else `'fresh'`. Every refusal is loud and actionable:\n * - an EXPLICIT `'resume'` with no settled prior worker refuses (`resume-no-prior`) — the\n * DECLARED default degrades to `'fresh'` instead, so a resume edge's first traversal is\n * simply the first spawn;\n * - resume while a prior worker of the node is still LIVE refuses (`resume-while-live`) —\n * that is what steer is for, and the error says so;\n * - resume under a semantic `key` refuses (`resume-with-key`) — a key makes an assignment\n * run-once, resume explicitly runs the node again.\n */\n const resolveContinuity = (\n requested: ContinuityMode | undefined,\n profileName: string | undefined,\n key: string | undefined,\n ): ResolvedContinuity => {\n const declared =\n profileName === undefined ? 'fresh' : (opts.continuityByProfile?.[profileName] ?? 'fresh')\n const wantsResume = requested === 'resume' || (requested === undefined && declared === 'resume')\n if (!wantsResume) return { continuity: 'fresh' }\n if (profileName === undefined || profileName.length === 0) {\n return {\n error: 'resume-unnamed-profile',\n hint:\n 'Resume targets a node by profile.name — the stable node identity — and this profile ' +\n 'has none. Name the profile, or spawn fresh.',\n }\n }\n if (key !== undefined) {\n return {\n error: 'resume-with-key',\n hint:\n 'A semantic key makes an assignment run-once (a completed key returns its committed ' +\n 'result instead of running again); resume explicitly runs the node AGAIN. Drop the ' +\n 'key to resume, or keep the key and spawn fresh.',\n }\n }\n const live = liveWorkerForNode(profileName)\n if (live !== undefined) {\n return {\n error: 'resume-while-live',\n hint:\n `Worker '${live}' on node '${profileName}' is still LIVE — resume re-attaches to a ` +\n 'SETTLED session. To redirect the live worker, use steer_agent (that is the ' +\n \"live-worker channel); to run a parallel sibling instead, pass continuity: 'fresh'.\",\n }\n }\n const prior = latestSettledWorkerForNode(profileName)\n if (prior === undefined) {\n // The DECLARED default asked for resume-when-possible; with nothing to resume this is the\n // node's effective first spawn. Only an explicit per-call demand fails loud here.\n if (requested === undefined) return { continuity: 'fresh' }\n return {\n error: 'resume-no-prior',\n hint:\n `Node '${profileName}' has no settled prior worker in this process to resume — ` +\n 'resume continues a FINISHED session. Spawn the node fresh first (omit continuity or ' +\n \"pass 'fresh').\",\n }\n }\n return {\n continuity: 'resume',\n resume: { ofWorker: prior, sequence: nodeSpawnCount(profileName) + 1 },\n }\n }\n\n /**\n * Deliver one routed analyst finding to its destination worker through the SAME authorized\n * steer machinery a driver steer uses, so the delivery is recorded (`steer` event carrying\n * `analyst`) and its outcome is a fact. No live destination ⇒ a record-only failed steer —\n * observable, never a silent drop. A throw here must not kill the settle path: failures are\n * recorded on the bus (a `steer` with `delivered: false`) before being swallowed, with ONE\n * narrow exception — a bus that refuses the `delivery-attempt` record itself leaves only the\n * `instruction` receipt (an attempt with no outcome = explicitly unknown, per\n * recordDeliveryAttempt's own contract).\n */\n const deliverRoutedFinding = async (\n route: AnalyzeOnSettleRoute,\n findings: AnalystLensOutput | unknown,\n ): Promise<void> => {\n const destination = route.to as string\n const text =\n route.directive === undefined || route.directive.length === 0\n ? safeJsonText(findings)\n : `${route.directive}\\n\\n${safeJsonText(findings)}`\n const targetId = liveWorkerIdNamed(destination)\n if (targetId === undefined) {\n await bus.publish(\n {\n type: 'steer',\n down: detachedFrozen({\n receiptId: randomUUID(),\n toWorker: destination,\n instruction: text,\n instructionDigest: canonicalCandidateDigest(text),\n delivered: false,\n outcome: 'unknown-worker' as const,\n }),\n analyst: route.kind,\n },\n { queue: false },\n )\n return\n }\n let instruction: ContinuationInstruction\n try {\n instruction = authorizeInstruction('steer', targetId, text, false)\n await recordInstruction(instruction)\n } catch (cause) {\n // NOTHING reached the bus for this failure (an authorization refusal, a target without\n // durable identity, a durable subscriber rejecting the instruction record) — record the\n // failed delivery now, in the same `steer` shape a failed attempt publishes, so a routed\n // finding is observable on EVERY failure path, never a silent drop.\n try {\n await sendDown(\n 'steer',\n detachedFrozen({\n receiptId: randomUUID(),\n toWorker: targetId,\n instruction: text,\n instructionDigest: canonicalCandidateDigest(text),\n delivered: false,\n outcome: 'runtime-error' as const,\n error: cause instanceof Error ? cause.message : String(cause),\n }),\n route.kind,\n )\n } catch {\n // The bus itself refused the failure record — there is nothing left to record ON, and a\n // routed finding must never take down the settlement path.\n }\n return\n }\n try {\n await attemptDelivery(\n instruction,\n { steer: instruction.instruction, interrupt: false },\n {\n analyst: route.kind,\n },\n )\n } catch {\n // `attemptDelivery` publishes the failed `steer` (delivered:false + outcome) BEFORE\n // rethrowing, so the failure is already on the bus — except when the bus refused the\n // `delivery-attempt` record itself, where only the `instruction` receipt lands (see the\n // docstring). A routed finding must never take down the settlement path.\n }\n }\n\n const flushPendingSettlement = async (): Promise<boolean> => {\n const pending = pendingSettlement\n if (!pending) return false\n await bus.publish(pending.event)\n // An analyst-AGENT settlement IS its finding (just published): it never enters the settled\n // ledger or the finalizer, and it re-fires no analyst hook. Its routed delivery goes through\n // the exact machinery a registry-analyst finding uses — with no wrap directive, because the\n // route's directive was already consumed as the analyst's task.\n if (pending.analystRun) {\n analystRuns.delete(pending.worker.id)\n unwatchWorker(pending.worker.id)\n pendingSettlement = undefined\n const { route } = pending.analystRun\n if (route.to !== undefined && pending.event.type === 'finding') {\n await deliverRoutedFinding(\n { kind: route.kind, to: route.to },\n pending.event.finding.findings,\n )\n }\n return true\n }\n commitSettled(pending.settled, pending.worker)\n pendingSettlement = undefined\n if (\n pending.analyze &&\n pending.worker.status === 'done' &&\n pending.worker.trace.status === 'available' &&\n opts.analyzeOnSettle?.length\n ) {\n const routes = opts.analyzeOnSettle.map(normalizeAnalyzeOnSettle)\n const sourceNames = workerRouteNames(pending.worker.id)\n const applicable = routes.filter(\n (route) => route.over === undefined || route.over.some((name) => sourceNames.has(name)),\n )\n // Registry lenses run in-process over the trace store; agent analysts spawn as workers.\n const lensRoutes = applicable.filter((route) => route.agent === undefined)\n const agentRoutes = applicable.filter((route) => route.agent !== undefined)\n if (lensRoutes.length > 0 && opts.analysts) {\n const trace = await workerTraceAnalysisStore(pending.worker.trace, opts.blobs)\n for (const route of lensRoutes) {\n const findings = await opts.analysts.run(route.kind, trace)\n // The finding ALWAYS lands on the bus — the audit trail and the driver's pullable copy —\n // whether or not the route also delivers it to a named worker.\n await bus.publish({\n type: 'finding',\n finding: canonicalFindingEvent({\n fromWorker: pending.worker.id,\n analyst: route.kind,\n findings,\n }),\n })\n if (route.to !== undefined) await deliverRoutedFinding(route, findings)\n }\n }\n for (const route of agentRoutes) await spawnAnalystRun(route, pending.worker)\n }\n return true\n }\n\n // Producer: drain exactly one settlement from the scope cursor onto the bus (a `settled` event),\n // then fire the analyst-on-settle hook — auto-run each configured lens over the worker's trace and\n // publish its result as a `finding`. Returns false when the cursor is idle (no live workers). The\n // cursor is a once-per-child source, so a settlement is produced at most once.\n const drainSettlement = async (): Promise<boolean> => {\n if (!pendingSettlement) {\n const settled = await opts.scope.next()\n if (!settled) return false\n const worker = projectSettled(settled)\n const run = analystRuns.get(settled.handle.id)\n pendingSettlement = run\n ? {\n settled,\n worker,\n event: analystRunFinding(run, settled),\n analyze: false,\n analystRun: run,\n }\n : {\n settled,\n worker,\n event: detachedFrozen<CoordinationEvent>({ type: 'settled', worker }),\n analyze: true,\n }\n }\n return flushPendingSettlement()\n }\n\n // Post-loop drain: every ALREADY-settled, unpulled child enters the ledger + audit trail. No\n // analyst-on-settle here — the driver has stopped, so a finding has no reader and an analyst\n // spawn would spend real compute for nothing. An analyst-agent run ALREADY in flight is not a\n // new spawn: its settlement still becomes its finding (the audit trail must not lose paid-for\n // findings), though a routed delivery will usually record `delivered:false` this late.\n const drainResolved = async (): Promise<number> => {\n let drained = 0\n for (;;) {\n if (!pendingSettlement) {\n const settled = await opts.scope.nextResolved()\n if (!settled) return drained\n const worker = projectSettled(settled)\n const run = analystRuns.get(settled.handle.id)\n pendingSettlement = run\n ? {\n settled,\n worker,\n event: analystRunFinding(run, settled),\n analyze: false,\n analystRun: run,\n }\n : {\n settled,\n worker,\n event: detachedFrozen<CoordinationEvent>({ type: 'settled', worker }),\n analyze: false,\n }\n }\n await flushPendingSettlement()\n drained += 1\n }\n }\n\n // The down-leg: record a parent→child message on the bus for the audit trail (history +\n // subscribers) WITHOUT enqueuing it — the parent must never pull its own outbound message back.\n // Overloaded so the `answer` kind REQUIRES a questionId (no silent `?? ''` fallback to mask a bug).\n function sendDown(type: 'steer', down: DownMessageEvent, analyst?: string): Promise<void>\n function sendDown(type: 'answer', down: DownMessageEvent, questionId: string): Promise<void>\n async function sendDown(\n type: 'steer' | 'answer',\n down: DownMessageEvent,\n questionIdOrAnalyst?: string,\n ): Promise<void> {\n await bus.publish(\n type === 'answer'\n ? { type, down, questionId: str(questionIdOrAnalyst, 'questionId') }\n : questionIdOrAnalyst !== undefined\n ? { type, down, analyst: questionIdOrAnalyst }\n : { type, down },\n { queue: false },\n )\n }\n\n const authorizeInstruction = (\n kind: 'steer' | 'answer',\n workerId: string,\n instruction: string,\n interrupt: boolean,\n questionId?: string,\n ): ContinuationInstruction => {\n const workerIdentity = opts.scope.view.nodes.find((node) => node.id === workerId)?.identity\n let authorizedInstruction = instruction\n if (opts.authorizeDownMessage) {\n if (workerIdentity === undefined) {\n throw new Error(\n `coordination tools: cannot authorize ${kind} for worker ${JSON.stringify(workerId)} without durable identity`,\n )\n }\n const decision = detachedFrozen(\n opts.authorizeDownMessage(\n detachedFrozen({\n kind,\n workerId,\n workerIdentity,\n instruction,\n interrupt,\n ...(questionId !== undefined ? { questionId } : {}),\n }),\n ),\n )\n if (\n typeof decision !== 'object' ||\n decision === null ||\n Array.isArray(decision) ||\n typeof decision.instruction !== 'string' ||\n decision.instruction.length === 0\n ) {\n throw new Error('coordination tools: authorizeDownMessage must return an instruction')\n }\n authorizedInstruction = decision.instruction\n }\n return detachedFrozen({\n receiptId: randomUUID(),\n kind,\n toWorker: workerId,\n instruction: authorizedInstruction,\n instructionDigest: canonicalCandidateDigest(authorizedInstruction),\n ...(workerIdentity !== undefined ? { workerIdentity } : {}),\n interrupt,\n ...(questionId !== undefined ? { questionId } : {}),\n })\n }\n\n /** Publish before `scope.send`: an awaited durable subscriber therefore commits the exact bytes\n * before the worker can observe them. */\n const recordInstruction = async (instruction: ContinuationInstruction): Promise<void> => {\n await bus.publish({ type: 'instruction', instruction }, { queue: false })\n }\n\n /** Commit delivery intent after the authorization receipt and before `Scope.send`. An attempt with\n * no matching outcome after a crash is explicitly unknown and must never be replayed. */\n const recordDeliveryAttempt = async (\n instruction: ContinuationInstruction,\n ): Promise<DownMessageDeliveryAttempt> => {\n const attempt = detachedFrozen({\n receiptId: instruction.receiptId,\n kind: instruction.kind,\n toWorker: instruction.toWorker,\n instructionDigest: instruction.instructionDigest,\n interrupt: instruction.interrupt,\n ...(instruction.questionId !== undefined ? { questionId: instruction.questionId } : {}),\n })\n await bus.publish({ type: 'delivery-attempt', attempt }, { queue: false })\n return attempt\n }\n\n const deliveryOutcome = (workerId: string, delivered: boolean): DownMessageDeliveryOutcome => {\n if (delivered) return 'delivered'\n if (opts.scope.signal.aborted) return 'scope-stopped'\n const node = opts.scope.view.nodes.find((candidate) => candidate.id === workerId)\n if (!node) return 'unknown-worker'\n if (!isLiveNodeStatus(node.status)) return 'already-settled'\n return 'runtime-has-no-inbox'\n }\n\n const attemptDelivery = async (\n instruction: ContinuationInstruction,\n message: unknown,\n origin?: { readonly analyst?: string },\n ): Promise<DownMessageEvent> => {\n await recordDeliveryAttempt(instruction)\n let delivered = false\n let outcome: DownMessageDeliveryOutcome\n let error: string | undefined\n try {\n delivered = opts.scope.send(instruction.toWorker, message)\n outcome = deliveryOutcome(instruction.toWorker, delivered)\n } catch (cause) {\n outcome = 'runtime-error'\n error = cause instanceof Error ? cause.message : String(cause)\n }\n const down = detachedFrozen({\n receiptId: instruction.receiptId,\n toWorker: instruction.toWorker,\n instruction: instruction.instruction,\n instructionDigest: instruction.instructionDigest,\n delivered,\n outcome,\n ...(error !== undefined ? { error } : {}),\n })\n if (instruction.kind === 'answer') {\n await sendDown('answer', down, str(instruction.questionId, 'questionId'))\n } else {\n await sendDown('steer', down, origin?.analyst)\n }\n if (error !== undefined) throw new Error(`coordination tools: delivery failed: ${error}`)\n return down\n }\n\n const steerWorker = async (\n workerId: string,\n instruction: string,\n options: { readonly interrupt?: boolean } = {},\n ): Promise<DownMessageEvent> => {\n const interrupt = options.interrupt === true\n const authorized = authorizeInstruction('steer', workerId, instruction, interrupt)\n await recordInstruction(authorized)\n return await attemptDelivery(authorized, {\n steer: authorized.instruction,\n interrupt,\n })\n }\n\n // Consumer projection: the wire shape the driver sees for a pulled bus event.\n const projectEvent = (ev: CoordinationEvent): Record<string, unknown> => {\n if (ev.type === 'settled') {\n const { id, status, ...evidence } = ev.worker\n return { type: 'settled', settled: id, status, ...evidence }\n }\n if (ev.type === 'question') return { type: 'question', question: ev.question }\n if (ev.type === 'finding') return { type: 'finding', ...ev.finding }\n if (ev.type === 'answer') return { type: 'answer', ...ev.down, questionId: ev.questionId }\n if (ev.type === 'instruction') return { type: 'instruction', ...ev.instruction }\n if (ev.type === 'delivery-attempt') return { type: 'delivery-attempt', ...ev.attempt }\n // Peer mail is sideways and record-only, so the driver never pulls it either. Projected\n // explicitly rather than through the `down` fallback below: a member with no `down` property\n // spread through that fallback would yield a bare `{ type }` and drop the whole payload.\n if (ev.type === 'mail') return { type: 'mail', ...ev.mail }\n // Down-leg `steer` is record-only (never queued), so the driver never pulls it; project\n // defensively for completeness.\n return { type: ev.type, ...ev.down }\n }\n\n // The sibling channel, when this run enabled it. Publishing is record-only (`queue: false`) for\n // the same reason a steer is: the parent audits and can stop a thread, but peer traffic must not\n // enter the queue the driver pulls from — a busy channel would otherwise starve `await_event` of\n // the settlements and questions it exists to deliver.\n const peerMail: PeerMailbox | undefined = opts.peerMail\n ? createPeerMailbox({\n scope: opts.scope,\n publish: (mail) =>\n bus.publish({ type: 'mail', mail }, { queue: false }).then(() => undefined),\n ...(opts.peerMail.limits ? { limits: opts.peerMail.limits } : {}),\n })\n : undefined\n\n const nextQuestionId = (from: string): string => {\n for (;;) {\n const id = `${from}:q${questionSeq++}`\n if (!questions.some((question) => question.id === id)) return id\n }\n }\n const normalizeQuestion = (q: QuestionInput, fallbackFrom: string): Question => {\n const from = str(q.from ?? fallbackFrom, 'from')\n return {\n id: typeof q.id === 'string' && q.id.length > 0 ? q.id : nextQuestionId(from),\n from,\n level: level(q.level),\n question: str(q.question, 'question'),\n reason: str(q.reason, 'reason'),\n ...(q.options ? { options: q.options } : {}),\n urgency: urgency(q.urgency),\n }\n }\n const addQuestion = (\n raw: QuestionInput,\n fallbackFrom: string,\n decision?: QuestionDecision,\n ): { question: QuestionRecord; added: boolean } => {\n const q = normalizeQuestion(raw, fallbackFrom)\n const existing = questions.find((x) => x.id === q.id)\n if (existing) return { question: existing, added: false }\n const effectiveDecision =\n decision ??\n (questionPolicy === 'bubble'\n ? ({\n kind: 'escalate',\n to: 'parent',\n reason: 'question policy bubbled to parent',\n } as const)\n : undefined)\n const status: QuestionRecord['status'] =\n effectiveDecision?.kind === 'answer'\n ? 'answered'\n : effectiveDecision?.kind === 'defer'\n ? 'deferred'\n : effectiveDecision?.kind === 'escalate'\n ? 'escalated'\n : 'open'\n const record: QuestionRecord = {\n ...q,\n status,\n openedAt: Date.now(),\n ...(effectiveDecision ? { decision: effectiveDecision } : {}),\n }\n questions.push(record)\n return { question: record, added: true }\n }\n const emitNewQuestion = async (record: {\n question: QuestionRecord\n added: boolean\n }): Promise<QuestionRecord> => {\n if (record.added)\n await bus.publish(\n { type: 'question', question: record.question },\n { priority: urgencyPriority(record.question.urgency) },\n )\n return record.question\n }\n const decideQuestion = (questionId: string, decision: QuestionDecision): QuestionRecord => {\n const idx = questions.findIndex((q) => q.id === questionId)\n if (idx < 0) throw new Error(`unknown questionId ${JSON.stringify(questionId)}`)\n const prior = questions[idx] as QuestionRecord\n const status: QuestionRecord['status'] =\n decision.kind === 'answer' ? 'answered' : decision.kind === 'defer' ? 'deferred' : 'escalated'\n const next: QuestionRecord = { ...prior, status, decision }\n questions[idx] = next\n return next\n }\n const blockingQuestionsForStop = (): QuestionRecord[] => {\n if (questionPolicy === 'auto' || questionPolicy === 'bubble') return []\n return questions.filter((q) => {\n const blocking = q.urgency === 'blocks-step' || q.urgency === 'blocks-run'\n if (!blocking) return false\n if (questionPolicy === 'mustDecide') return q.status === 'open'\n return q.status !== 'answered' && q.status !== 'deferred'\n })\n }\n\n // A supervised tree exposes one shared capacity reading; a caller-owned legacy scope falls back\n // to this toolbox's direct-child count. The shared reading is what prevents each nested manager\n // from multiplying the same cap independently.\n const maxLiveWorkers = opts.maxLiveWorkers\n const localLiveWorkerCount = (): number =>\n opts.scope.view.nodes.filter((n) => isLiveNodeStatus(n.status)).length\n const sharedWorkerCapacity = (): Scope<unknown>['workerCapacity'] | undefined => {\n const scope = opts.scope as Partial<Scope<unknown>>\n return scope.workerCapacity\n }\n const usesTreeWideLimit = (): boolean => {\n const capacity = sharedWorkerCapacity()\n return capacity !== undefined && capacity.freeSlots !== null\n }\n const liveWorkerCount = (): number =>\n usesTreeWideLimit()\n ? (sharedWorkerCapacity()?.live ?? localLiveWorkerCount())\n : localLiveWorkerCount()\n\n // A snapshot of every still-in-flight worker — the liveness signal a bounded `await_event`\n // returns when its wait elapses, so the supervisor can tell \"worker still running, keep waiting\"\n // apart from \"nothing is happening\" (the distinction it lost when the unbounded await erred out).\n const projectNodeEvidence = (\n node: Scope<unknown>['view']['nodes'][number],\n resumed = false,\n ): Record<string, unknown> => ({\n id: node.id,\n status: node.status,\n ...(node.assignmentId === undefined ? {} : { assignmentId: node.assignmentId }),\n ...(node.identity === undefined ? {} : { identity: node.identity }),\n ...(node.materialization === undefined ? {} : { materialization: node.materialization }),\n ...(node.executionBindings === undefined ? {} : { executionBindings: node.executionBindings }),\n spent: node.spent,\n ...(node.settledAt === undefined ? {} : { settledAt: node.settledAt }),\n ...(node.outRef === undefined ? {} : { outRef: node.outRef }),\n ...(node.trace === undefined ? {} : { trace: node.trace }),\n ...(resumed ? { resumed: true } : {}),\n })\n\n const liveSnapshot = (): Array<Record<string, unknown>> =>\n opts.scope.view.nodes\n .filter((n) => isLiveNodeStatus(n.status))\n .map((n) => projectNodeEvidence(n))\n\n // How many workers the driver could open RIGHT NOW without hitting the simultaneity fence, or\n // `null` when no cap is set (the conserved pool is then the only fence, so there is no finite\n // slot count). Without this the brain could see WHO is running but never that capacity was idle,\n // so filling N slots meant emitting N blind tool calls with no feedback telling it to — the\n // mechanical reason a 5-worker run peaked at 2 live workers. Policy (whether to fill) stays with\n // the driver; this is only the reading.\n const freeWorkerSlots = (): number | null =>\n usesTreeWideLimit()\n ? (sharedWorkerCapacity()?.freeSlots ?? null)\n : freeSlots(localLiveWorkerCount(), maxLiveWorkers)\n\n // The LIVE read of one worker. Guarded because `createCoordinationTools` is bound to a `Scope`\n // it did not construct — an older or hand-rolled scope may not implement `progress` at all, and\n // an observation must degrade to \"no progress available\", never throw at the driver.\n const readProgress = (id: string): WorkerProgress | undefined => {\n const scope = opts.scope as Partial<Scope<unknown>>\n if (typeof scope.progress !== 'function') return undefined\n try {\n return scope.progress(\n id,\n opts.stallAfterMs !== undefined ? { stallAfterMs: opts.stallAfterMs } : {},\n )\n } catch {\n return undefined\n }\n }\n\n // ONLINE detection: subscribe the streaming detector panel to a freshly-spawned worker's live\n // tool trace, and turn each signal into a `finding` the driver pulls from `await_event`. The\n // unsubscribe fires on the worker's settle (its trace source is dead from then on) and the\n // per-worker cap stops one looping worker from flooding the bus.\n const watchers = new Map<string, () => void>()\n const watchWorker = (id: string): void => {\n const watch = opts.watchWorkers\n if (!watch) return\n const scope = opts.scope as Partial<Scope<unknown>>\n if (typeof scope.traceSource !== 'function') return\n let source: ReturnType<NonNullable<Scope<unknown>['traceSource']>>\n try {\n source = scope.traceSource(id)\n } catch {\n return\n }\n if (!source) return\n const cap = watch.maxFindingsPerWorker ?? 3\n let raised = 0\n const unsub = watchTrace(source, {\n ...(watch.detectors ? { detectors: watch.detectors } : {}),\n onSignal: async (signal, span) => {\n if (cap > 0 && raised >= cap) return\n raised += 1\n await bus.publish({\n type: 'finding',\n // canonicalFindingEvent: `span.toolName` is optional — an undefined value anywhere in\n // the payload would throw in the digesting subscriber and vanish the event.\n finding: canonicalFindingEvent({\n fromWorker: id,\n analyst: `online:${signal.detector}`,\n findings: {\n detector: signal.detector,\n severity: signal.severity,\n reason: signal.reason,\n streak: signal.streak,\n ...(signal.failureClass ? { failureClass: signal.failureClass } : {}),\n toolName: span.toolName,\n at: span.endedAt,\n progress: readProgress(id),\n },\n }),\n })\n },\n })\n watchers.set(id, unsub)\n }\n const unwatchWorker = (id: string): void => {\n const unsub = watchers.get(id)\n if (!unsub) return\n watchers.delete(id)\n try {\n unsub()\n } catch {\n // an unsubscribe that throws must never break the settle path\n }\n }\n\n // The blocking `scope.next()` (via `drainSettlement`) waits on a LIVE worker for its whole run.\n // Keep at most ONE such drain in flight and let every concurrent `await_event` race THAT single\n // promise against a timeout — so a bounded call never starts a second unbounded block, and the\n // one drain still delivers the settlement (exactly-once via the scope cursor) whenever it lands.\n const awaitTimeoutMs = opts.awaitTimeoutMs ?? DEFAULT_AWAIT_EVENT_TIMEOUT_MS\n let inFlightDrain: Promise<boolean> | null = null\n const ensureDrain = (): Promise<boolean> => {\n if (!inFlightDrain)\n inFlightDrain = drainSettlement().finally(() => {\n inFlightDrain = null\n })\n return inFlightDrain\n }\n // Resolve `{ drained }` if the drain wins, or `undefined` if the bound elapses first. A `<= 0`\n // bound restores the prior unbounded block (no timer): the caller opted out of the fence.\n const raceDrainWithTimeout = async (\n drain: Promise<boolean>,\n ): Promise<{ drained: boolean } | undefined> => {\n if (awaitTimeoutMs <= 0) return { drained: await drain }\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), awaitTimeoutMs)\n // Never let this fence-timer alone keep the process alive (e.g. at teardown).\n if (typeof timer?.unref === 'function') timer.unref()\n })\n try {\n return await Promise.race([drain.then((drained) => ({ drained })), timeout])\n } finally {\n if (timer) clearTimeout(timer)\n }\n }\n\n const tools: McpToolDescriptor[] = [\n {\n name: 'spawn_agent',\n description:\n 'Start a worker the driver will drive. `profile` is the worker or another driver; ' +\n '`task` is what it should do. Reserves budget from the conserved pool and fails closed. ' +\n 'Pass an optional `budget` (per-field) to give a hard sub-task more than the default — it ' +\n 'merges over the per-worker default; the conserved pool is still the hard fence. When a ' +\n 'max-live-workers cap is set it also fails closed (`error: \"max-live-workers\"`) while that ' +\n 'many workers are still in flight — settle or steer one before spawning another. ' +\n 'Pass a `key` naming the assignment to make it run-once ACROSS restarts: a key that ' +\n 'already completed returns the finished result (`resumed: \"completed\"` — no work re-runs, ' +\n 'nothing is spent), a key whose prior attempt failed or was lost with a dead process ' +\n 'spawns fresh and says so (`resumed: \"retried\" | \"lost\"`), and a key still running is ' +\n 'refused (`error: \"duplicate-key\"`). ' +\n 'Returns `freeSlots`: how many MORE workers you can start right now (`null` = uncapped). ' +\n 'While `freeSlots > 0` there is idle capacity — call this again to fill it rather than ' +\n 'waiting; parallel workers finish the run sooner than one at a time.',\n inputSchema: {\n type: 'object',\n properties: {\n profile: spawnProfileArg(),\n task: { description: 'The task the worker should perform.' },\n label: { type: 'string', description: 'Optional trace label.' },\n key: {\n type: 'string',\n description:\n 'Optional semantic name for this assignment (e.g. \"summarize-ch3\"). The same key ' +\n 'never runs twice: completed keys return their committed result, even after a ' +\n 'coordinator restart.',\n },\n continuity: {\n type: 'string',\n enum: ['fresh', 'resume'],\n description:\n 'How this spawn continues the node\\'s prior work. \"fresh\" (the default) starts a ' +\n 'brand-new session. \"resume\" re-attaches to the node\\'s most recent SETTLED ' +\n 'worker: a NEW live worker is spawned whose session continues where that worker ' +\n 'stopped (the backend receives the prior workerId and the resume sequence). ' +\n 'Resume fails closed when the node has no settled prior worker ' +\n '(`error: \"resume-no-prior\"` — spawn it fresh first), while a prior worker of the ' +\n 'node is still live (`error: \"resume-while-live\"` — steer_agent is the ' +\n 'live-worker channel), and under a `key` (`error: \"resume-with-key\"` — keys are ' +\n \"run-once, resume runs again). Omit to use the run's declared default for this \" +\n 'profile name.',\n },\n budget: {\n type: 'object',\n description:\n 'Optional per-spawn budget that merges over the per-worker default (per field). ' +\n 'Only set the ceilings this sub-task needs raised; the conserved pool still fences.',\n properties: {\n maxIterations: { type: 'number', minimum: 0 },\n maxTokens: { type: 'number', minimum: 0 },\n maxUsd: { type: 'number', minimum: 0 },\n deadlineMs: { type: 'number', minimum: 0 },\n },\n },\n },\n required: ['profile', 'task'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const key = a.key === undefined ? undefined : str(a.key, 'key')\n // A key already proven complete — by the resumed journal or by a delivery earlier in this\n // run — resolves to committed work and starts no live worker, so the concurrency fence\n // does not apply to it.\n const keyCompleted = key !== undefined && completedKeys.has(key)\n // Concurrency fence FIRST — fail closed before reserving budget, so a rejected spawn never\n // touches the pool. The conserved pool bounds TOTAL work; this bounds SIMULTANEOUS work.\n if (\n !keyCompleted &&\n !usesTreeWideLimit() &&\n maxLiveWorkers !== undefined &&\n maxLiveWorkers > 0 &&\n liveWorkerCount() >= maxLiveWorkers\n )\n return Promise.resolve({\n error: 'max-live-workers' as const,\n live: liveWorkerCount(),\n freeSlots: freeWorkerSlots(),\n })\n const parsedProfile = agentProfileSchema.safeParse(a.profile)\n if (!parsedProfile.success) {\n return Promise.resolve({\n error: 'invalid-profile' as const,\n issues: parsedProfile.error.issues.map((issue) => ({\n path: issue.path.join('.'),\n message: issue.message,\n })),\n })\n }\n const profile = detachedFrozen(parsedProfile.data)\n // Continuity resolves BEFORE any assignment is minted or budget reserved, so a refused\n // resume touches nothing — same fail-closed discipline as the fences above.\n const continuity = resolveContinuity(parseContinuity(a.continuity), profile.name, key)\n if ('error' in continuity) {\n return Promise.resolve({\n error: continuity.error,\n hint: continuity.hint,\n live: liveWorkerCount(),\n freeSlots: freeWorkerSlots(),\n })\n }\n const task = detachedFrozen(a.task)\n const label = typeof a.label === 'string' ? a.label : 'worker'\n // The ONE pre-journal point that may ask the backend a question: everything below —\n // assignment, budget reservation, `Scope.spawn` — is synchronous and commits state.\n if (opts.preflightSpawn) {\n // The gate judges the profile that will RUN. A pinning layer resolves the authored stub\n // to its canonical profile here, so the backend is asked about the real model and tools.\n const preflightProfile = opts.resolveSpawnProfile\n ? detachedFrozen(opts.resolveSpawnProfile(profile))\n : profile\n const refusal = await opts.preflightSpawn(preflightProfile, {\n label,\n ...(key !== undefined ? { key } : {}),\n task,\n })\n if (refusal) {\n preflightCounts[refusal.cause] += 1\n return {\n error: 'preflight-refused' as const,\n cause: refusal.cause,\n detail: refusal.detail,\n live: liveWorkerCount(),\n freeSlots: freeWorkerSlots(),\n }\n }\n }\n const budget = Object.freeze(\n a.budget === undefined ? opts.perWorker : mergeBudget(opts.perWorker, a.budget),\n )\n const assignmentId =\n key !== undefined ? `key:${key}` : `ordinal:${unkeyedAssignmentOrdinal++}`\n // Minted BEFORE the worker exists, because the agent factory runs inside `scope.spawn` and\n // the node id is not known until after it. The capability is bound to the concrete worker\n // below, and sends nothing until then.\n const peerMailUrl = peerMail?.mintCapability(assignmentId)\n const context: WorkerSpawnContext = Object.freeze({\n assignmentId,\n parentNodeId: opts.scope.view.root,\n budget,\n task,\n label,\n ...(key !== undefined ? { key } : {}),\n continuity: continuity.continuity,\n ...(continuity.continuity === 'resume' ? { resume: continuity.resume } : {}),\n ...(peerMailUrl !== undefined ? { peerMailUrl } : {}),\n })\n const res = opts.scope.spawn(() => opts.makeWorkerAgent(profile, context), task, {\n budget,\n label,\n assignmentId,\n ...(key !== undefined ? { key } : {}),\n })\n // A keyed spawn that resolved to committed work: NOTHING ran — return the finished result\n // (it is already in the settled ledger, seeded from the resumed scope or recorded when the\n // cursor yielded it), so the driver folds it in without an await_event round-trip.\n if (res.ok && res.prior?.state === 'completed') {\n const s = res.prior.settled\n if (key !== undefined) completedKeys.add(key)\n const { id, status, resumed: _resumed, ...evidence } = projectSettled(s)\n return Promise.resolve({\n workerId: id,\n resumed: 'completed' as const,\n status,\n ...evidence,\n live: liveWorkerCount(),\n freeSlots: freeWorkerSlots(),\n })\n }\n if (res.ok) {\n watchWorker(res.handle.id)\n liveHandles.set(res.handle.id, res.handle)\n // The capability becomes a sender only now, when there is a concrete worker to speak as.\n peerMail?.bindCapability(assignmentId, res.handle.id)\n // Bind the new worker to its key so its settlement can mark the key complete.\n if (key !== undefined) keyByWorker.set(res.handle.id, key)\n if (typeof profile.name === 'string' && profile.name.length > 0) {\n profileNameByWorker.set(res.handle.id, profile.name)\n }\n }\n // A `completed` key returned above, so any prior still attached here is a real re-run:\n // `retried` (the prior attempt failed) or `lost` (it died in flight with its process).\n const priorHistory =\n res.ok && res.prior !== undefined && res.prior.state !== 'completed'\n ? {\n resumed: res.prior.state,\n priorWorkerId: res.prior.priorId,\n ...(res.prior.state === 'retried' ? { priorReason: res.prior.reason } : {}),\n }\n : {}\n // Report the REMAINING capacity alongside the spawn, so one tool call tells the driver\n // both \"it started\" and \"you can still open N more\" — the feedback that lets it fill\n // slots instead of opening one worker per turn. `null` = uncapped. A fresh spawn under a\n // key with a failed/lost prior attempt carries that history (`resumed`/`priorWorkerId`),\n // so a re-run is always explicit, never a silent duplicate.\n return Promise.resolve(\n res.ok\n ? {\n workerId: res.handle.id,\n assignmentId: res.handle.assignmentId ?? assignmentId,\n ...(res.handle.identity === undefined ? {} : { identity: res.handle.identity }),\n ...(res.handle.materialization === undefined\n ? {}\n : { materialization: res.handle.materialization }),\n ...(res.handle.executionBindings === undefined\n ? {}\n : { executionBindings: res.handle.executionBindings }),\n // The EFFECTIVE continuity of this spawn, with the resume lineage when it\n // re-attached — so the driver's transcript states how the node continued.\n continuity: continuity.continuity,\n ...(continuity.continuity === 'resume' ? { resume: continuity.resume } : {}),\n live: liveWorkerCount(),\n freeSlots: freeWorkerSlots(),\n ...priorHistory,\n }\n : {\n error: res.reason,\n // A refusal a driver can ACT on. `usd-unbudgeted` is the one rejection that no\n // retry can clear, so it says so: without this, a driver reads \"budget\" and walks\n // its request down until it gives up.\n ...(res.reason === 'usd-unbudgeted'\n ? {\n hint:\n \"This run's root budget declares no maxUsd, so a child budget naming maxUsd \" +\n 'can never be admitted — at any amount. Retrying with a smaller maxUsd will ' +\n 'fail identically. Spawn with a budget that omits maxUsd, or ask the caller ' +\n 'to give the run a root maxUsd.',\n }\n : {}),\n live: liveWorkerCount(),\n freeSlots: freeWorkerSlots(),\n },\n )\n },\n },\n {\n name: 'observe_agent',\n description:\n 'Inspect a worker WHILE IT RUNS, not only after it finishes: status, spend so far, and ' +\n '`progress` — how long since it last did anything (`idleMs`), whether that counts as ' +\n 'stalled, how many turns it has taken, the last tools/files it touched ' +\n '(`recentActivity`), what its executor CHANGED about the profile you gave it ' +\n '(`derived` — an MCP config it materialized, an extension it had to add), whether a ' +\n 'steer can even reach it (`steerable`), and how many ' +\n 'steers it has not yet read (`pendingMessages`). Returns the settled output artifact ' +\n 'once it exists. Use this BEFORE steer_agent: a steer is only worth sending when the ' +\n 'progress says the worker is on the wrong path or has stopped making any.',\n inputSchema: { type: 'object', properties: { workerId: idArg }, required: ['workerId'] },\n handler: async (raw) => {\n const id = str(obj(raw).workerId, 'workerId')\n const node = opts.scope.view.nodes.find((n) => n.id === id)\n if (!node) {\n // A worker from a PRIOR process of this run: not in the live nursery, but its committed\n // record is on the resumed view — observable like any settled worker, marked `resumed`.\n const resumed = opts.scope.resume?.view.nodes.find((n) => n.id === id)\n if (!resumed) return { error: `unknown workerId ${JSON.stringify(id)}` }\n const output = resumed.outRef ? await opts.blobs.get(resumed.outRef) : undefined\n return {\n ...projectNodeEvidence(resumed, true),\n outRef: resumed.outRef ?? null,\n output: output ?? null,\n progress: null,\n }\n }\n const output = node.outRef ? await opts.blobs.get(node.outRef) : undefined\n const progress = readProgress(id)\n return {\n ...projectNodeEvidence(node),\n outRef: node.outRef ?? null,\n output: output ?? null,\n progress: progress ?? null,\n }\n },\n },\n {\n name: 'steer_agent',\n description:\n 'Send a message DOWN to a still-LIVE worker (parent→child): a new instruction, a course ' +\n 'correction, or a continuation. The worker drains it at its next step boundary — and before ' +\n 'it may settle, so it cannot finish while a message it never read is pending. A worker that ' +\n 'already settled is gone (returns delivered:false) — spawn a fresh one instead.',\n inputSchema: {\n type: 'object',\n properties: {\n workerId: idArg,\n instruction: { type: 'string', description: 'What the worker should do next.' },\n interrupt: {\n type: 'boolean',\n description:\n 'true = forceful: abort the worker’s in-flight inference so it re-plans on the NEXT ' +\n 'turn (a tool already mid-execution finishes first; only the owned tool-loop honors this). ' +\n 'false/omitted = queued: it flushes at the next step boundary (and before it may settle).',\n },\n },\n required: ['workerId', 'instruction'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const workerId = str(a.workerId, 'workerId')\n const instruction = str(a.instruction, 'instruction')\n const delivery = await steerWorker(workerId, instruction, {\n interrupt: a.interrupt === true,\n })\n if (delivery.delivered) {\n return { delivered: true, progress: readProgress(workerId) ?? null }\n }\n return {\n delivered: false,\n reason: delivery.outcome,\n progress: readProgress(workerId) ?? null,\n }\n },\n },\n {\n name: 'await_event',\n description:\n 'Wait for and pull the next message a worker, sub-driver, or analyst sent up — the unified ' +\n \"inbox. An event is one of: a settled worker output ('settled'), a question needing your \" +\n \"answer ('question', from ask_parent / the worker's ask-user), or a trace-analyst finding \" +\n \"('finding', from analyze-on-settle). Pass kinds:['settled'] for just the next finished \" +\n 'worker; omit `kinds` to also receive questions and findings. Returns { idle: true } when ' +\n 'nothing is queued and no workers are live. If a worker is still running when the wait ' +\n 'elapses, returns { pending: true, live: [...] } (the workers still in flight) instead of ' +\n 'blocking indefinitely — call await_event again to keep waiting; the settlement is not lost. ' +\n 'Every reply carries `freeSlots`: how many more workers you can start right now (`null` = ' +\n 'uncapped). A settled worker frees its slot, so `freeSlots > 0` means capacity is sitting ' +\n 'idle — spawn into it before waiting again.',\n inputSchema: {\n type: 'object',\n properties: {\n kinds: {\n type: 'array',\n items: { type: 'string', enum: [...awaitableEventKinds] },\n description: 'Restrict to these event kinds (any if omitted).',\n },\n },\n },\n handler: async (raw) => {\n const k = obj(raw).kinds\n const kinds = Array.isArray(k) ? k.filter(isAwaitableEventKind) : undefined\n // Already-queued async messages (findings, questions) first — a fast, non-blocking pull.\n let ev = bus.pull(kinds)\n // Every return from this verb carries `freeSlots` — a settlement is exactly the moment\n // capacity frees up, so the answer travels with the event that freed it.\n if (ev) return { ...projectEvent(ev), freeSlots: freeWorkerSlots() }\n // Else drive the cursor to produce the next settlement — but BOUND the block. `scope.next()`\n // waits on a live worker for its entire (multi-minute) run; unbounded, that outlives a remote\n // MCP client's request timeout and surfaces as a hard tool error, leaving the supervisor with\n // no working \"wait for the worker\" primitive. Race the single in-flight drain against the\n // fence: if it settles in time, re-pull and return the event (or idle when the cursor is dry);\n // if the fence wins, return a non-error liveness snapshot the supervisor can re-poll on.\n const raced = await raceDrainWithTimeout(ensureDrain())\n if (raced === undefined)\n return { pending: true, live: liveSnapshot(), freeSlots: freeWorkerSlots() }\n ev = bus.pull(kinds)\n if (!ev) return { idle: !raced.drained, freeSlots: freeWorkerSlots() }\n return { ...projectEvent(ev), freeSlots: freeWorkerSlots() }\n },\n },\n {\n name: 'list_questions',\n description:\n 'List questions raised by workers, drivers, or analysts. Blocking stop behavior follows questionPolicy.',\n inputSchema: { type: 'object', properties: {} },\n handler: () => Promise.resolve({ questions }),\n },\n {\n name: 'answer_question',\n description: 'Record an answer, deferral, or escalation for a loop question.',\n inputSchema: {\n type: 'object',\n properties: {\n questionId: { type: 'string' },\n answer: { type: 'string' },\n by: { type: 'string', description: 'Node id or \"user\".' },\n deferReason: { type: 'string' },\n escalateTo: { type: 'string', enum: questionEscalationTargets },\n escalateReason: { type: 'string' },\n },\n required: ['questionId'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const questionId = str(a.questionId, 'questionId')\n if (typeof a.answer === 'string' && a.answer.length > 0) {\n const answer = a.answer\n const pendingQuestion = questions.find((question) => question.id === questionId)\n if (pendingQuestion === undefined) {\n throw new Error(`unknown questionId ${JSON.stringify(questionId)}`)\n }\n // Route the answer DOWN to the worker that asked, unparking it, and record the down-leg.\n // A blocking question parked the worker, so deliver forcefully — it should resume on the\n // answer immediately, not wait for its next step boundary.\n const interrupt =\n pendingQuestion.urgency === 'blocks-run' || pendingQuestion.urgency === 'blocks-step'\n const authorized = authorizeInstruction(\n 'answer',\n pendingQuestion.from,\n answer,\n interrupt,\n questionId,\n )\n await recordInstruction(authorized)\n const delivery = await attemptDelivery(authorized, {\n answer: authorized.instruction,\n questionId,\n interrupt,\n })\n // Authorization is evidence of allowed bytes, not proof the blocked worker received them.\n // Resolve the question only after the durable delivery outcome says the live inbox accepted\n // the answer. A refusal stays open both in this process and after replay.\n const question = delivery.delivered\n ? decideQuestion(questionId, {\n kind: 'answer',\n answer: authorized.instruction,\n by: typeof a.by === 'string' && a.by.length > 0 ? a.by : 'user',\n })\n : pendingQuestion\n // Surface `delivered` like steer_agent — the caller must see whether the answer actually\n // reached a live worker (false when it already settled or has no inbox).\n return {\n question,\n delivered: delivery.delivered,\n ...(delivery.delivered ? {} : { reason: delivery.outcome }),\n }\n }\n if (typeof a.deferReason === 'string' && a.deferReason.length > 0) {\n return Promise.resolve({\n question: decideQuestion(questionId, {\n kind: 'defer',\n reason: a.deferReason,\n }),\n })\n }\n if (typeof a.escalateTo === 'string' && a.escalateTo.length > 0) {\n if (!isQuestionEscalationTarget(a.escalateTo)) {\n throw new Error(\n `answer_question: escalateTo must be one of ${questionEscalationTargets.join(\n ', ',\n )}; received ${JSON.stringify(a.escalateTo)}`,\n )\n }\n const escalateReason =\n typeof a.escalateReason === 'string' && a.escalateReason.length > 0\n ? a.escalateReason\n : 'driver escalated'\n return Promise.resolve({\n question: decideQuestion(questionId, {\n kind: 'escalate',\n to: a.escalateTo,\n reason: escalateReason,\n }),\n })\n }\n throw new Error('answer_question: provide answer, deferReason, or escalateTo')\n },\n },\n {\n name: 'ask_parent',\n description: 'Raise a question to the parent driver/Pi/user when this driver cannot decide.',\n inputSchema: {\n type: 'object',\n properties: {\n from: { type: 'string' },\n level: { type: 'string', enum: ['worker', 'driver', 'loop'] },\n question: { type: 'string' },\n reason: { type: 'string' },\n urgency: { type: 'string', enum: ['continue-without', 'blocks-step', 'blocks-run'] },\n },\n required: ['from', 'level', 'question', 'reason', 'urgency'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const from = str(a.from, 'from')\n const q = await emitNewQuestion(\n addQuestion(\n {\n from,\n level: level(a.level),\n question: str(a.question, 'question'),\n reason: str(a.reason, 'reason'),\n urgency: urgency(a.urgency),\n },\n from,\n { kind: 'escalate', to: 'parent', reason: 'asked parent' },\n ),\n )\n return { question: q }\n },\n },\n ...(deliverable\n ? [\n {\n name: 'submit_result',\n description: [\n 'Submit the complete result to the injected independent check.',\n 'The first passing result is retained; stop work when accepted.',\n ...(deliverable.describe ? [`Expected result: ${deliverable.describe}`] : []),\n ].join(' '),\n inputSchema: {\n type: 'object',\n properties: {\n result: {\n description: 'The complete result in the form requested by the task.',\n },\n },\n required: ['result'],\n additionalProperties: false,\n },\n handler: async (raw: unknown) => {\n if (submitted) {\n return {\n accepted: true,\n retained: 'earlier-passing-result',\n stop: true,\n }\n }\n const a = obj(raw)\n if (!Object.hasOwn(a, 'result')) {\n throw new Error('submit_result: \"result\" is required')\n }\n\n // Copy once at intake so the value checked below is the exact value retained after\n // acceptance, even when this handler is called directly rather than through JSON-RPC.\n const result = structuredClone(a.result)\n let accepted = false\n try {\n accepted = (await deliverable.check(result)) === true\n } catch {\n accepted = false\n }\n if (!accepted) return { accepted: false, stop: false }\n // Two remote callers may submit concurrently. Whichever passing check completes\n // first owns the retained result; a later completion must never overwrite it.\n if (submitted) {\n return {\n accepted: true,\n retained: 'earlier-passing-result',\n stop: true,\n }\n }\n\n submitted = Object.freeze({ result })\n stopped = true\n reason = 'result-accepted'\n notifyStop()\n return { accepted: true, retained: 'this-result', stop: true }\n },\n } satisfies McpToolDescriptor,\n ]\n : []),\n {\n name: 'stop',\n description: 'Declare the run complete.',\n inputSchema: {\n type: 'object',\n properties: { reason: { type: 'string', description: 'Why you are stopping.' } },\n },\n handler: (raw) => {\n const blocking = blockingQuestionsForStop()\n if (blocking.length) {\n return Promise.resolve({\n stopped: false,\n error: 'unresolved-blocking-questions',\n questions: blocking,\n })\n }\n stopped = true\n const r = obj(raw).reason\n reason = typeof r === 'string' ? r : undefined\n notifyStop()\n return Promise.resolve({ stopped: true })\n },\n },\n ]\n\n if (opts.analysts) {\n tools.push({\n name: 'list_analysts',\n description: 'List trace-analyst lenses available to run over a settled worker.',\n inputSchema: { type: 'object', properties: {} },\n handler: () => Promise.resolve({ analysts: opts.analysts?.kinds }),\n })\n tools.push({\n name: 'run_analyst',\n description: 'Apply an analyst lens to a settled worker trace.',\n inputSchema: {\n type: 'object',\n properties: {\n kind: { type: 'string', description: 'The analyst kind id.' },\n workerId: idArg,\n },\n required: ['kind', 'workerId'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const id = str(a.workerId, 'workerId')\n const node = nodeForWorker(id)\n if (!node) return { error: `unknown workerId ${JSON.stringify(id)}` }\n if (isLiveNodeStatus(node.status)) {\n return { error: `worker ${JSON.stringify(id)} has not settled — no trace to analyze yet` }\n }\n const trace =\n ledger.find((worker) => worker.id === id)?.trace ??\n node.trace ??\n ({\n status: 'unavailable',\n reason: 'legacy-settlement-without-trace-evidence',\n } as const)\n let store: TraceAnalysisStore\n try {\n store = await workerTraceAnalysisStore(trace, opts.blobs)\n } catch (error) {\n return {\n error: error instanceof Error ? error.message : String(error),\n trace,\n }\n }\n return { findings: await opts.analysts?.run(str(a.kind, 'kind'), store) }\n },\n })\n }\n\n // Per-child abort by stable reference. Resolution order matches the steer destination rule\n // (profile name before label) with the exact workerId first; only LIVE workers resolve, so an\n // already-settled or unknown reference returns `undefined` instead of a false \"aborted\".\n const abortWorker = (\n ref: string,\n reason?: string,\n ): { readonly id: string; readonly label: string } | undefined => {\n const live = opts.scope.view.nodes.filter((node) => isLiveNodeStatus(node.status))\n const target =\n live.find((node) => node.id === ref) ??\n live.find((node) => profileNameByWorker.get(node.id) === ref) ??\n live.find((node) => node.label === ref)\n if (target === undefined) return undefined\n const handle = liveHandles.get(target.id)\n if (handle === undefined) return undefined\n handle.abort(reason)\n return { id: target.id, label: target.label }\n }\n\n return {\n tools,\n ready,\n history: () => bus.history(),\n raiseFinding: (finding) =>\n bus\n .publish({ type: 'finding', finding: canonicalFindingEvent(finding) })\n .then(() => undefined),\n steerWorker,\n stats: () =>\n opts.preflightSpawn === undefined\n ? bus.stats()\n : { ...bus.stats(), preflight: { ...preflightCounts } },\n isStopped: () => stopped,\n stopReason: () => reason,\n submittedResult: () => submitted,\n settled: () => ledger,\n questions: () => questions,\n drainResolved,\n abortWorker,\n ...(peerMail ? { peerMail } : {}),\n }\n}\n\nfunction nextUnkeyedAssignmentOrdinal(scope: Scope<unknown>): number {\n let next = 0\n const views = [scope.resume?.view, scope.view]\n for (const view of views) {\n if (view === undefined) continue\n for (const node of view.nodes) {\n const match = /^ordinal:(\\d+)$/.exec(node.assignmentId ?? '')\n if (match === null) continue\n const ordinal = Number(match[1])\n if (!Number.isSafeInteger(ordinal)) {\n throw new Error(\n `coordination: durable assignment id '${node.assignmentId}' exceeds the safe ordinal range`,\n )\n }\n next = Math.max(next, ordinal + 1)\n }\n }\n if (!Number.isSafeInteger(next)) {\n throw new Error('coordination: durable assignment ordinal space is exhausted')\n }\n return next\n}\n\n/** Stringify a findings payload for a routed delivery; never throws (a cyclic payload degrades to\n * its String form rather than killing the settle path). */\nfunction safeJsonText(value: unknown): string {\n if (typeof value === 'string') return value\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n","/**\n * Durable side-log for coordination evidence the spawn journal does not own: questions, analyst\n * findings, answer decisions, authorized continuation receipts, delivery-attempt markers, and\n * delivery outcomes. A durable run\n * (`supervise({ runDir })`) appends them as they publish and loads them on resume, so a restarted\n * coordinator retains the exact evidence produced by prior processes.\n *\n * Answer down-events also fold status on load: a question answered before the crash reloads as\n * `answered`, not as a re-blocking `open`. Settled events are skipped (the spawn journal is their\n * ledger). A receipt followed by an attempt but no outcome proves the process died in the delivery\n * window; that outcome remains unknown and no prior instruction is auto-delivered.\n *\n * JSONL, one fsynced record per event, keyed by `runId` — several runs may share one log file\n * exactly as they share one spawn-journal file.\n *\n * @experimental\n */\n\nimport {\n isNoEntError,\n parseCommittedJsonLines,\n prepareJsonlAppend,\n writeAllBytes,\n} from '../../durable/jsonl-file'\nimport type {\n AnalystFindingEvent,\n ContinuationInstruction,\n CoordinationEvent,\n QuestionRecord,\n} from '../../mcp/tools/coordination'\nimport type { BusRecord } from './event-bus'\nimport type { PeerMailEvent } from './peer-mail'\n\n/** Stable identity of the supervisor that owns one coordination stream. High-level supervision\n * derives it from the exact root/child execution identity plus its parent assignment. */\nexport type CoordinationOwnerId = string\n\n/** Durable delivery evidence retained in commit order. An attempt without a later event carrying\n * the same `receiptId` has an unknown outcome after a crash and is never replayed. */\nexport type CoordinationDeliveryEvidence = Extract<\n CoordinationEvent,\n { readonly type: 'delivery-attempt' | 'steer' | 'answer' }\n>\n\n/** Coordination evidence loaded from prior processes of one durable supervised run. */\nexport interface PriorCoordination {\n /** The owner filter used for this replay. Omitted only for the compatibility all-owner read. */\n readonly ownerId?: CoordinationOwnerId\n /** Every question the prior process raised, with answer-status folded in, raise order. */\n readonly questions: ReadonlyArray<QuestionRecord>\n /** Every analyst finding the prior process published, publish order. */\n readonly findings: ReadonlyArray<AnalystFindingEvent>\n /** Every authorized continuation, in commit order. These are evidence, never replayed to a new\n * worker automatically. */\n readonly continuations: ReadonlyArray<ContinuationInstruction>\n /** Delivery intent and result records in commit order, linked to receipts by `receiptId`. */\n readonly deliveryEvidence: ReadonlyArray<CoordinationDeliveryEvidence>\n /** Every peer-mail attempt the prior process made, delivered and refused alike, in commit order.\n * Evidence of what siblings told each other; never replayed into a new worker's inbox. */\n readonly mail: ReadonlyArray<PeerMailEvent>\n /** Exact source-bus stamps in durable append order. Bus `seq` restarts with each process; append\n * order remains the cross-process replay order. */\n readonly records: ReadonlyArray<BusRecord<CoordinationEvent>>\n}\n\n/** The durable coordination side-log seam. `append` records one bus event (kinds it does not\n * persist are ignored); `load` replays a run's prior records folded into `PriorCoordination`. */\nexport interface CoordinationLog {\n append(\n runId: string,\n record: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): Promise<void>\n load(runId: string, ownerId?: CoordinationOwnerId): Promise<PriorCoordination>\n}\n\ntype CoordinationLogRecord = {\n readonly runId: string\n readonly ownerId?: CoordinationOwnerId\n readonly seq: number\n readonly at: number\n readonly priority: number\n readonly event: CoordinationEvent\n}\n\ntype LegacyCoordinationLogRecord = {\n readonly runId: string\n readonly ownerId?: CoordinationOwnerId\n readonly at: string\n readonly event: CoordinationEvent\n}\n\n/** Persist prior context plus exact continuation authorization, attempt, and result evidence.\n * Settlements have their own journal. */\nfunction persisted(event: CoordinationEvent): boolean {\n return event.type !== 'settled'\n}\n\n/** FS-backed `CoordinationLog`: append-only JSONL, fsynced per record. */\nexport class FileCoordinationLog implements CoordinationLog {\n private appendTail: Promise<void> = Promise.resolve()\n\n constructor(private readonly path: string) {}\n\n async append(\n runId: string,\n record: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): Promise<void> {\n if (!persisted(record.event)) return\n const append = this.appendTail.then(() => this.appendRecord(runId, record, ownerId))\n this.appendTail = append.catch(() => undefined)\n return append\n }\n\n private async appendRecord(\n runId: string,\n busRecord: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): 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 record: CoordinationLogRecord = {\n runId,\n ...(ownerId !== undefined ? { ownerId } : {}),\n ...busRecord,\n }\n const needsSeparator = await prepareJsonlAppend(this.path)\n const fh = await fs.open(this.path, 'a')\n try {\n await writeAllBytes(fh, `${needsSeparator ? '\\n' : ''}${JSON.stringify(record)}\\n`)\n await fh.sync()\n } finally {\n await fh.close()\n }\n }\n\n async load(runId: string, ownerId?: CoordinationOwnerId): Promise<PriorCoordination> {\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 emptyPriorCoordination(ownerId)\n throw err\n }\n const byId = new Map<string, QuestionRecord>()\n const findings: AnalystFindingEvent[] = []\n const continuations: ContinuationInstruction[] = []\n const deliveryEvidence: CoordinationDeliveryEvidence[] = []\n const mail: PeerMailEvent[] = []\n const records: BusRecord<CoordinationEvent>[] = []\n let legacySeq = 0\n for (const stored of parseCommittedJsonLines<\n CoordinationLogRecord | LegacyCoordinationLogRecord\n >(text, this.path)) {\n if (stored.runId !== runId) continue\n // Omitting ownerId preserves the historical all-run read for direct consumers. Runtime always\n // supplies one, so root and nested supervisors never receive one another's evidence.\n if (ownerId !== undefined && stored.ownerId !== ownerId) continue\n const record: BusRecord<CoordinationEvent> =\n 'seq' in stored\n ? {\n seq: stored.seq,\n at: stored.at,\n priority: stored.priority,\n event: stored.event,\n }\n : {\n seq: legacySeq++,\n at: Date.parse(stored.at),\n priority: 0,\n event: stored.event,\n }\n records.push(record)\n const ev = record.event\n if (ev.type === 'delivery-attempt' || ev.type === 'steer' || ev.type === 'answer') {\n deliveryEvidence.push(ev)\n }\n if (ev.type === 'question') {\n byId.set(ev.question.id, ev.question)\n } else if (ev.type === 'finding') {\n findings.push(ev.finding)\n } else if (ev.type === 'answer') {\n // Only accepted delivery resolves a blocking question. Authorization and an attempted\n // refusal remain evidence, but cannot turn \"worker never received the answer\" into answered\n // state on replay. `by` is not on the wire; prior-run is the honest attribution.\n const prior = byId.get(ev.questionId)\n if (prior && ev.down.delivered) {\n byId.set(ev.questionId, {\n ...prior,\n status: 'answered',\n decision: { kind: 'answer', answer: ev.down.instruction, by: 'prior-run' },\n })\n }\n } else if (ev.type === 'instruction') {\n continuations.push(ev.instruction)\n } else if (ev.type === 'mail') {\n mail.push(ev.mail)\n }\n }\n return {\n ...(ownerId !== undefined ? { ownerId } : {}),\n questions: [...byId.values()],\n findings,\n continuations,\n deliveryEvidence,\n mail,\n records,\n }\n }\n}\n\nfunction emptyPriorCoordination(ownerId?: CoordinationOwnerId): PriorCoordination {\n return {\n ...(ownerId !== undefined ? { ownerId } : {}),\n questions: [],\n findings: [],\n continuations: [],\n deliveryEvidence: [],\n mail: [],\n records: [],\n }\n}\n","/**\n *\n * `createInMemoryRunContext` — the one-call bundle of the in-memory stores a\n * `createSupervisor().run(root, task, opts)` needs: a fresh `InMemorySpawnJournal`\n * (the event-sourced spawn log), a fresh `InMemoryResultBlobStore` (the\n * content-addressed `outRef` payload store the driver's `observe`/`finalize` reads\n * settled outputs through), and a fresh `createExecutorRegistry()` (the open\n * `AgentSpec → Executor` resolver).\n *\n * It exists to kill the boilerplate every offline/local supervised run repeats by\n * hand — three constructors threaded into `SupervisorOpts` — and to single-source the\n * ONE wiring invariant that is easy to get wrong: when the root is the recursive\n * `driverAgent` LLM-driver brain AND it may spawn DRIVER children (agents\n * driving agents), the registry MUST be wrapped with `withDriverExecutor` so a\n * `role: 'driver'` child resolves to the nested-scope executor — and that SAME blob\n * store MUST be the one passed to `driverAgent({ blobs })`, or the driver\n * reads from a different store than the scope writes to. Pass `{ withDriver: true }`\n * and reuse the returned `blobs` for both.\n *\n * The spread shape matches `SupervisorOpts` exactly, so the call site reads:\n * const run = createInMemoryRunContext()\n * await createSupervisor().run(root, task, { budget, runId, ...run })\n *\n * @experimental\n */\n\nimport {\n FileResultBlobStore,\n FileSpawnJournal,\n InMemoryResultBlobStore,\n InMemorySpawnJournal,\n} from '../../durable/spawn-journal'\nimport { type CoordinationLog, FileCoordinationLog } from './coordination-log'\nimport { withDriverExecutor } from './driver-executor'\nimport { createExecutorRegistry } from './runtime'\nimport type { ExecutorRegistry, ResultBlobStore, SpawnJournal } from './types'\n\n/** Options for a supervised run context. */\nexport interface InMemoryRunContextOptions {\n /**\n * Wrap the executor registry with `withDriverExecutor` so a spawned child marked\n * `role: 'driver'` resolves to the recursive driver-executor (agents driving agents\n * over a nested `Scope` on the same conserved pool). Leave `false` for a flat tree of\n * leaf workers. Default `false`.\n */\n readonly withDriver?: boolean\n}\n\n/**\n * The bundle of stores a supervised run needs, shaped to spread into `SupervisorOpts`.\n * The fields are exactly `SupervisorOpts`' `journal` / `blobs` / `executors`.\n */\nexport interface InMemoryRunContext {\n readonly journal: SpawnJournal\n readonly blobs: ResultBlobStore\n readonly executors: ExecutorRegistry\n /**\n * Present (and `true`) only on a DURABLE context (`createFileRunContext`), so spreading the\n * context into `SupervisorOpts` also opts the run into resume-first. An in-memory context\n * leaves it undefined: there is never a prior tree to resume, and the default stays fresh-run.\n */\n readonly resume?: boolean\n /**\n * Present only on a DURABLE context: the coordination side-log stores questions, analyst\n * findings, answer decisions, and authorized continuation receipts that the spawn journal does\n * not own. `supervise({ runDir })` appends them as they publish and loads them on resume.\n * Continuation receipts are evidence and are never auto-delivered to a replacement worker.\n * In-memory contexts have none: nothing outlives the process.\n */\n readonly coordinationLog?: CoordinationLog\n}\n\n/** The stores a supervised run needs, in-memory or file-backed. `InMemoryRunContext` is the\n * historical name for the same shape. */\nexport type RunContext = InMemoryRunContext\n\n/**\n * Build a fresh in-memory run context. Every call returns NEW stores (no shared global\n * state between runs), so two runs never cross-contaminate their journals/blobs.\n */\nexport function createInMemoryRunContext(opts: InMemoryRunContextOptions = {}): InMemoryRunContext {\n const base = createExecutorRegistry()\n return {\n journal: new InMemorySpawnJournal(),\n blobs: new InMemoryResultBlobStore(),\n executors: opts.withDriver ? withDriverExecutor(base) : base,\n }\n}\n\n/**\n * Build a DURABLE run context: the spawn journal and the result blobs are file-backed (fsynced\n * per append/write) under `dir`, and the context carries `resume: true` so spreading it into\n * `SupervisorOpts` makes the supervisor `loadTree`-first. A run that dies mid-flight therefore\n * resumes when it is re-run with the SAME `runId` and the SAME `dir`: the committed children come\n * back on `Scope.resume` (rehydrated by `replaySpawnTree`) instead of being re-executed.\n *\n * Layout: `${dir}/spawn-journal.jsonl` (one JSONL record per event), `${dir}/blobs/` (one\n * content-addressed JSON file per settled result), and `${dir}/coordination-log.jsonl`\n * (questions, findings, answer decisions, and authorized continuation receipts retained as\n * evidence). The directory is created on first write.\n *\n * Opt-in by construction — `createInMemoryRunContext()` is unchanged and stays the default, so no\n * existing consumer writes to disk or resumes unless it asks for this.\n */\nexport function createFileRunContext(\n dir: string,\n opts: InMemoryRunContextOptions = {},\n): RunContext {\n const base = createExecutorRegistry()\n return {\n journal: new FileSpawnJournal(`${dir}/spawn-journal.jsonl`),\n blobs: new FileResultBlobStore(`${dir}/blobs`),\n executors: opts.withDriver ? withDriverExecutor(base) : base,\n resume: true,\n coordinationLog: new FileCoordinationLog(`${dir}/coordination-log.jsonl`),\n }\n}\n","/**\n * anytimeReport — time-to-satisfactory-output metrics, derived entirely from the\n * waterfall's spans (no new instrumentation): per task, the best-so-far score after each\n * shot with its elapsed wall-clock and cumulative spend; per strategy, the standard\n * anytime-optimization metrics:\n *\n * TTT time-to-target — elapsed ms until best-so-far ≥ the target (per task; median\n * over tasks that reached it)\n * STT shots-to-target — attempts until best-so-far ≥ target\n * ERT expected running time (the COCO benchmarking convention): TOTAL time spent\n * across all tasks — including failures' full budgets — divided by the number of\n * tasks that reached the target. The honest \"how long per success, all-in\".\n * AUC the anytime curve's area (mean best-so-far score across the budget, per shot\n * index) — higher = climbs earlier.\n *\n * The \"satisfactory\" bar follows the COCO/BBOB convention: a SET of satisficing targets\n * (e.g. [0.5, 0.8, 1.0] on the normalized check score), each measured independently —\n * runtime-to-target per (task, target) pair — optionally overridden per task\n * (`targetFor`) when satisfaction is task-specific. Spans come from\n * `createWaterfallCollector().report()`; tasks are grouped by the supervisor runId\n * (`agentic:<strategy>:<taskId>`); shot spans are `shot:N` labels.\n */\nimport type { WaterfallSpan } from './waterfall'\n\nexport interface AnytimeTaskCurve {\n taskId: string\n strategy: string\n /** Best-so-far after each settled shot: elapsed ms from the task's first spawn,\n * cumulative usd, and the running max score. */\n points: Array<{ elapsedMs: number; cumUsd: number; best: number }>\n /** Per satisficing target (keyed by the target value as a string): the first point\n * where best ≥ target, or null when never reached within budget. */\n hits: Record<string, { ms: number; shots: number; usd: number } | null>\n}\n\nexport interface AnytimeStrategySummary {\n strategy: string\n /** The satisficing target this row summarizes. */\n target: number\n tasks: number\n reachedTarget: number\n /** Median time-to-target over the tasks that reached it (null when none did). */\n medianTttMs: number | null\n medianShotsToTarget: number | null\n /** COCO ERT: Σ all task wall-time (incl. failures) / #successes. Null when 0 succeed. */\n ertMs: number | null\n /** Same construction over dollars: Σ all spend / #successes. */\n erUsd: number | null\n /** Mean best-so-far score by shot index (the anytime curve, averaged over tasks). */\n curveByShot: number[]\n /** Area under the per-shot anytime curve, normalized to [0,1]. */\n auc: number\n}\n\nexport interface AnytimeReport {\n targets: number[]\n perTask: AnytimeTaskCurve[]\n /** One summary per (strategy, target) pair — the COCO-style multi-target view. */\n perStrategy: AnytimeStrategySummary[]\n}\n\n/**\n * The best-so-far fold — the ONE definition of \"how good was the run after k results\", shared by\n * the post-run anytime report below and by the LIVE progress-based stop rules\n * (`supervise/stop-rules.ts`). Given the observed objective per settled result in order, it returns\n * the running maximum. A result with no objective (`undefined` — it failed, or it was never\n * scored) carries the previous best forward rather than resetting it.\n *\n * It is extracted rather than duplicated on purpose: a stop rule that decides a run has plateaued\n * must agree, number for number, with the report that later says whether stopping was right.\n */\nexport function bestSoFar(values: ReadonlyArray<number | undefined>): number[] {\n const out: number[] = []\n let best = 0\n for (const v of values) {\n if (typeof v === 'number' && v > best) best = v\n out.push(best)\n }\n return out\n}\n\n/** Mean of a best-so-far curve — the anytime AUC when the curve is normalized to [0,1]. Higher =\n * the run climbed earlier. Shared with the stop rules so \"improving\" means one thing. */\nexport function areaUnderCurve(curve: ReadonlyArray<number>): number {\n if (curve.length === 0) return 0\n return curve.reduce((s, v) => s + v, 0) / curve.length\n}\n\n/**\n * How many trailing entries of a best-so-far curve are within `minDelta` of the curve's value\n * `window` steps back — i.e. the length of the current PLATEAU, in settles. `0` means the most\n * recent settle improved the best by more than `minDelta`.\n *\n * The plateau math the live stop rules read. Defined here, beside the report that measures whether\n * the plateau was real, so there is exactly one notion of \"not improving\".\n */\nexport function plateauLength(curve: ReadonlyArray<number>, minDelta: number): number {\n if (curve.length === 0) return 0\n const last = curve[curve.length - 1] as number\n let i = curve.length - 1\n while (i > 0 && last - (curve[i - 1] as number) <= minDelta) i -= 1\n return curve.length - 1 - i\n}\n\nconst median = (xs: number[]): number | null => {\n if (xs.length === 0) return null\n const s = [...xs].sort((a, b) => a - b)\n const mid = Math.floor(s.length / 2)\n return s.length % 2 === 1 ? (s[mid] as number) : ((s[mid - 1] as number) + (s[mid] as number)) / 2\n}\n\n/** Derive anytime metrics from waterfall spans. `targets` are the satisficing score\n * bars (default [1] = fully resolved; COCO-style multi-target: [0.5, 0.8, 1]);\n * `targetFor` overrides the bar per task (task-specific satisfaction) — when set, the\n * per-task bar replaces every entry of `targets` for that task. */\nexport function anytimeReport(\n spans: WaterfallSpan[],\n opts?: { targets?: number[]; targetFor?: (taskId: string) => number },\n): AnytimeReport {\n const targets = opts?.targets ?? [1]\n const byRun = new Map<string, WaterfallSpan[]>()\n for (const s of spans) {\n if (!s.label.startsWith('shot:')) continue\n const list = byRun.get(s.runId) ?? []\n list.push(s)\n byRun.set(s.runId, list)\n }\n\n const perTask: AnytimeTaskCurve[] = []\n for (const [runId, shots] of byRun) {\n const m = runId.match(/^agentic:(.+):(.+)$/)\n const strategy = m?.[1] ?? runId\n const taskId = m?.[2] ?? runId\n const ordered = [...shots].sort((a, b) => (a.endMs ?? a.startMs) - (b.endMs ?? b.startMs))\n const t0 = Math.min(...ordered.map((s) => s.startMs))\n const taskTargets = opts?.targetFor ? [opts.targetFor(taskId)] : targets\n // ONE best-so-far definition, shared with the live stop rules.\n const bests = bestSoFar(ordered.map((s) => (typeof s.score === 'number' ? s.score : undefined)))\n let cumUsd = 0\n const points: AnytimeTaskCurve['points'] = []\n const hits: AnytimeTaskCurve['hits'] = {}\n for (const t of taskTargets) hits[String(t)] = null\n for (const [i, s] of ordered.entries()) {\n cumUsd += s.usd\n const best = bests[i] as number\n const elapsedMs = (s.endMs ?? s.startMs) - t0\n points.push({ elapsedMs, cumUsd, best })\n for (const t of taskTargets) {\n if (hits[String(t)] === null && best >= t) {\n hits[String(t)] = { ms: elapsedMs, shots: points.length, usd: cumUsd }\n }\n }\n }\n perTask.push({ taskId, strategy, points, hits })\n }\n\n const byStrategy = new Map<string, AnytimeTaskCurve[]>()\n for (const t of perTask) {\n const list = byStrategy.get(t.strategy) ?? []\n list.push(t)\n byStrategy.set(t.strategy, list)\n }\n\n const perStrategy: AnytimeStrategySummary[] = []\n for (const [strategy, tasks] of byStrategy) {\n const totalMs = tasks.reduce((s, t) => s + (t.points[t.points.length - 1]?.elapsedMs ?? 0), 0)\n const totalUsd = tasks.reduce((s, t) => s + (t.points[t.points.length - 1]?.cumUsd ?? 0), 0)\n const maxShots = Math.max(0, ...tasks.map((t) => t.points.length))\n const curveByShot: number[] = []\n for (let i = 0; i < maxShots; i += 1) {\n // A task with fewer shots carries its final best forward (it stopped — its\n // best-so-far is what an operator would have at that point).\n const vals = tasks.map(\n (t) => (t.points[Math.min(i, t.points.length - 1)] as { best: number }).best,\n )\n curveByShot.push(vals.reduce((s, v) => s + v, 0) / vals.length)\n }\n const auc = areaUnderCurve(curveByShot)\n const summaryTargets = opts?.targetFor ? [Number.NaN] : targets\n for (const t of summaryTargets) {\n const key = (\n taskCurve: AnytimeTaskCurve,\n ): { ms: number; shots: number; usd: number } | null =>\n opts?.targetFor\n ? (Object.values(taskCurve.hits)[0] ?? null)\n : (taskCurve.hits[String(t)] ?? null)\n const reached = tasks.filter((x) => key(x) !== null)\n perStrategy.push({\n strategy,\n target: t,\n tasks: tasks.length,\n reachedTarget: reached.length,\n medianTttMs: median(reached.map((x) => (key(x) as { ms: number }).ms)),\n medianShotsToTarget: median(reached.map((x) => (key(x) as { shots: number }).shots)),\n ertMs: reached.length > 0 ? totalMs / reached.length : null,\n erUsd: reached.length > 0 ? totalUsd / reached.length : null,\n curveByShot,\n auc,\n })\n }\n }\n perStrategy.sort((a, b) => a.strategy.localeCompare(b.strategy) || a.target - b.target)\n return { targets, perTask, perStrategy }\n}\n\n/** One row per (strategy, satisficing target): the shareable time-to-satisfactory table. */\nexport function renderAnytimeTable(report: AnytimeReport): string {\n const lines = [\n `anytime metrics · satisficing targets [${report.targets.join(', ')}] · ERT = Σ all wall-time / #successes (COCO)`,\n 'strategy ≥tgt reach med-TTT med-shots ERT(all-in) $/success AUC curve',\n ]\n for (const s of report.perStrategy) {\n const curve = s.curveByShot.map((v) => '▁▂▃▄▅▆▇█'[Math.min(7, Math.floor(v * 8))]).join('')\n const tgt = Number.isNaN(s.target) ? 'task' : s.target.toFixed(2)\n lines.push(\n `${s.strategy.padEnd(19)} ${tgt.padStart(4)} ${String(s.reachedTarget).padStart(4)}/${String(s.tasks).padEnd(3)} ` +\n `${s.medianTttMs === null ? ' —' : `${(s.medianTttMs / 1000).toFixed(1).padStart(6)}s`} ` +\n `${s.medianShotsToTarget === null ? ' —' : String(s.medianShotsToTarget).padStart(5)} ` +\n `${s.ertMs === null ? ' —' : `${(s.ertMs / 1000).toFixed(1).padStart(9)}s`} ` +\n `${s.erUsd === null ? ' —' : `$${s.erUsd.toFixed(4)}`} ${s.auc.toFixed(2)} ${curve}`,\n )\n }\n return lines.join('\\n')\n}\n","/**\n *\n * PROGRESS-BASED STOP RULES — end a long-horizon run for the right reason.\n *\n * Every existing bound is a CEILING: iterations, tokens, dollars, an absolute deadline, a turn\n * cap. A ceiling answers \"may this run continue?\" and never \"is this run still getting anywhere?\".\n * So a supervision tree that stopped learning at settle 4 keeps buying workers until it hits a\n * wall — the run ends on exhaustion, and the operator cannot tell a run that finished from a run\n * that ran out.\n *\n * A stop rule reads the run's own PROGRESS and decides. Three signals feed it:\n * - the objective curve over settled work (best-so-far, from `anytime.ts` — see below),\n * - the LIVE worker feed (`WorkerProgress`: `idleMs`, `stalled`, `turns`, `tokens`),\n * - tree-level shape (how many are in flight, how many are waiting, when the last settle landed).\n *\n * ── Two boundaries this module holds deliberately ───────────────────────────────────────────────\n *\n * ENFORCEMENT lives here; THRESHOLDS do not. \"Stop after 5 settles with no improvement\" is a\n * judgment about a domain — how noisy its scores are, how expensive a worker is, how much a late\n * breakthrough is worth. That belongs to the caller (a loop, a bench, a product). Every rule below\n * takes its thresholds as required options with no hidden defaults for the numbers that decide;\n * the module ships the MECHANISM and refuses to ship the judgment.\n *\n * A stop rule can only ADD a stop, never remove one. The driver evaluates the hard ceilings\n * (`poolStarved`, `deadlinePassed`, abort, the driver's own stop) FIRST and independently; the\n * rule is consulted only when they all say \"continue\". So no rule can talk a run past its budget.\n *\n * ── What is reused, not re-derived ──────────────────────────────────────────────────────────────\n *\n * `anytime.ts` already computed best-so-far curves, their area, and plateau detection — but only\n * after a run was over, from waterfall spans. Rather than write a second copy for the live path,\n * `bestSoFar` / `areaUnderCurve` / `plateauLength` were extracted there and are imported here. A\n * stop rule that calls a run plateaued therefore agrees, number for number, with the report that\n * later judges whether stopping was right.\n *\n * @experimental\n */\n\nimport { ValidationError } from '../../errors'\nimport { areaUnderCurve, bestSoFar, plateauLength } from '../anytime'\nimport { isTerminalNodeStatus } from './node-status'\nimport type { WorkerProgress } from './progress'\nimport type { Scope, Settled } from './types'\n\n/** One settled unit of work, reduced to what a stop rule reads. `objective` is the run's own\n * quality signal (a verdict score, a test pass-rate, a judge rating); `undefined` = this\n * settlement produced no measurable objective (it failed, or nothing scored it). */\nexport interface ProgressSample {\n readonly id: string\n /** Epoch ms the settlement was observed. */\n readonly at: number\n readonly objective?: number\n /** True when the settlement passed its deliverable check — a scored-but-undelivered result is\n * not progress. */\n readonly delivered: boolean\n}\n\n/** The read-model a `StopRule` decides from — the run's progress, not its budget. */\nexport interface ProgressView {\n readonly now: number\n /** Settlements observed so far, in the order they landed. */\n readonly settles: number\n /** Of those, how many passed their deliverable check. */\n readonly delivered: number\n /** Best-so-far objective after each settlement (`anytime.bestSoFar`). */\n readonly curve: ReadonlyArray<number>\n /** The current best objective; `0` when nothing has scored. */\n readonly best: number\n /** Mean of the best-so-far curve — how EARLY the run climbed (`anytime.areaUnderCurve`). */\n readonly auc: number\n /** Epoch ms of the most recent settlement; `0` when none has landed. */\n readonly lastSettleAt: number\n /** Epoch ms of the most recent improvement in best-so-far; `0` when none. */\n readonly lastImprovementAt: number\n /** Settlements since the last improvement — `0` right after one improves. */\n readonly settlesSinceImprovement: number\n /** Live read of every non-terminal worker (the `Scope.progress` feed). Empty when the caller\n * supplied no scope. */\n readonly workers: ReadonlyArray<WorkerProgress>\n /** Nodes running or acquiring. */\n readonly inFlight: number\n /** Armed wait-state nodes — deliberately separate from `inFlight`: a tree whose only remaining\n * nodes are waits is NOT stalled, it is waiting on the world. */\n readonly waiting: number\n}\n\n/** A stop rule's answer. `reason` is required when stopping — a run that ends must be able to say\n * why in the result, and an unexplained early stop is indistinguishable from a bug. */\nexport type StopDecision =\n | { readonly stop: false }\n | { readonly stop: true; readonly reason: string }\n\n/** Evaluated from the progress feed, never from the budget. Pure and synchronous: it is called on\n * the driver's hot path, once per turn. */\nexport type StopRule = (view: ProgressView) => StopDecision\n\nconst CONTINUE: StopDecision = { stop: false }\n\n/** Accumulates settlements and materializes a `ProgressView`. Idempotent by settlement id, so a\n * caller may re-push its whole roster every turn (the driver does exactly that) without\n * double-counting or moving a recorded timestamp. */\nexport interface ProgressTracker {\n /** Record a settlement. A second call with the same `id` is ignored. Returns true when it was\n * new. */\n record(sample: ProgressSample): boolean\n /** Materialize the view. Pass the live `Scope` to include the worker feed and tree shape. */\n view(scope?: Scope<unknown>, opts?: { readonly stallAfterMs?: number }): ProgressView\n /** Evaluate a rule against the current view. */\n evaluate(\n rule: StopRule,\n scope?: Scope<unknown>,\n opts?: { readonly stallAfterMs?: number },\n ): StopDecision\n /** The samples recorded so far, in order. */\n samples(): ReadonlyArray<ProgressSample>\n}\n\nexport interface ProgressTrackerOptions {\n /** Clock for `view().now`. Defaults to `Date.now`. */\n readonly now?: () => number\n /** Treat a settlement that did NOT pass its deliverable check as having no objective. Default\n * true — \"scored 0.9 but never delivered\" is not progress, and counting it as progress is the\n * exact way a plateau rule gets talked out of firing. */\n readonly requireDelivered?: boolean\n /** How much the best-so-far must rise for a settlement to count as an IMPROVEMENT. Default 0\n * (any strict rise counts). Raise it to ignore score noise. */\n readonly minImprovement?: number\n}\n\n/** Build the settled-work ledger a `StopRule` decides from: record each settlement (idempotent by\n * id) and materialize a `ProgressView` combining the best-so-far curve with the live worker feed. */\nexport function createProgressTracker(opts: ProgressTrackerOptions = {}): ProgressTracker {\n const now = opts.now ?? Date.now\n const requireDelivered = opts.requireDelivered ?? true\n const minImprovement = opts.minImprovement ?? 0\n const seen = new Set<string>()\n const recorded: ProgressSample[] = []\n\n return {\n record(sample) {\n if (seen.has(sample.id)) return false\n seen.add(sample.id)\n recorded.push(sample)\n return true\n },\n samples: () => [...recorded],\n view(scope, viewOpts) {\n const objectives = recorded.map((s) =>\n requireDelivered && !s.delivered ? undefined : s.objective,\n )\n const curve = bestSoFar(objectives)\n const best = curve.length > 0 ? (curve[curve.length - 1] as number) : 0\n let lastImprovementAt = 0\n let lastImprovementIdx = -1\n let prev = 0\n for (const [i, value] of curve.entries()) {\n if (value - prev > minImprovement) {\n lastImprovementAt = (recorded[i] as ProgressSample).at\n lastImprovementIdx = i\n }\n prev = value\n }\n const treeView = scope?.view\n const workers: WorkerProgress[] = []\n if (scope && treeView) {\n for (const node of treeView.nodes) {\n if (isTerminalNodeStatus(node.status)) continue\n // A wait-state is not a worker. It produces no metered activity by design, so including\n // it here would make every waiting tree read as a fleet of stalled workers — the exact\n // false positive `allWorkersStalled` exists to avoid. It is counted in `waiting` instead.\n if (node.status === 'waiting') continue\n const p = scope.progress(\n node.id,\n viewOpts?.stallAfterMs !== undefined\n ? { now: now(), stallAfterMs: viewOpts.stallAfterMs }\n : { now: now() },\n )\n if (p) workers.push(p)\n }\n }\n return {\n now: now(),\n settles: recorded.length,\n delivered: recorded.filter((s) => s.delivered).length,\n curve,\n best,\n auc: areaUnderCurve(curve),\n lastSettleAt:\n recorded.length > 0 ? (recorded[recorded.length - 1] as ProgressSample).at : 0,\n lastImprovementAt,\n settlesSinceImprovement:\n lastImprovementIdx < 0 ? recorded.length : recorded.length - 1 - lastImprovementIdx,\n workers,\n inFlight: treeView?.inFlight ?? 0,\n waiting: treeView?.waiting ?? 0,\n }\n },\n evaluate(rule, scope, viewOpts) {\n return rule(this.view(scope, viewOpts))\n },\n }\n}\n\n/** Build a `ProgressSample` from a scope settlement. The objective is the verdict score and\n * `delivered` is the verdict's `valid` — the SAME single delivery signal `finalizeBestDelivered`\n * and `defaultSelectWinner` use, so \"progress\" and \"winner\" cannot disagree. */\nexport function sampleFromSettled(settled: Settled<unknown>, at: number): ProgressSample {\n if (settled.kind === 'down') {\n return { id: settled.handle.id, at, delivered: false }\n }\n return {\n id: settled.handle.id,\n at,\n ...(settled.verdict?.score !== undefined ? { objective: settled.verdict.score } : {}),\n delivered: settled.verdict?.valid === true,\n }\n}\n\n// ── The default rules ────────────────────────────────────────────────────────────────────────\n//\n// Each takes its thresholds as REQUIRED options. A default number here would be this module\n// deciding a domain's judgment for it — which is the boundary the header states.\n\nexport interface NoProgressForOptions {\n /** Stop when this many ms have passed since the last SETTLEMENT. Omit to not bound on time. */\n readonly ms?: number\n /** Stop when this many settlements have landed with no improvement in best-so-far. Omit to not\n * bound on settles. */\n readonly settles?: number\n /** Never stop before this many settlements have landed — the warm-up that stops a rule from\n * firing on an empty run. Default 1. */\n readonly minSettles?: number\n}\n\n/**\n * \"Nothing new has happened.\" Fires when the run has produced no new settled work for `ms`, or no\n * IMPROVEMENT over the last `settles` settlements.\n *\n * A tree whose only remaining nodes are armed WAITS is exempt from the time bound: a run waiting\n * on CI is not a run that stopped making progress, and killing it there would defeat mechanic C.\n */\nexport function noProgressFor(opts: NoProgressForOptions): StopRule {\n if (opts.ms === undefined && opts.settles === undefined) {\n throw new ValidationError('noProgressFor: set at least one of { ms, settles }')\n }\n if (opts.ms !== undefined && opts.ms <= 0) {\n throw new ValidationError('noProgressFor: ms must be > 0')\n }\n if (opts.settles !== undefined && opts.settles < 1) {\n throw new ValidationError('noProgressFor: settles must be >= 1')\n }\n const minSettles = opts.minSettles ?? 1\n return (v) => {\n if (v.settles < minSettles) return CONTINUE\n if (opts.settles !== undefined && v.settlesSinceImprovement >= opts.settles) {\n return {\n stop: true,\n reason: `no-progress: ${v.settlesSinceImprovement} settles with no improvement (limit ${opts.settles}), best=${v.best}`,\n }\n }\n if (opts.ms !== undefined && v.waiting === 0 && v.lastSettleAt > 0) {\n const idle = v.now - v.lastSettleAt\n if (idle >= opts.ms) {\n return {\n stop: true,\n reason: `no-progress: ${idle}ms since the last settlement (limit ${opts.ms}ms)`,\n }\n }\n }\n return CONTINUE\n }\n}\n\nexport interface PlateauOptions {\n /** How many trailing settlements to judge. The rule fires when the whole window failed to lift\n * the best-so-far by more than `minDelta`. */\n readonly window: number\n /** The rise that counts as an improvement — the domain's noise floor. `0` means any strict rise\n * counts. */\n readonly minDelta: number\n /** Never fire before this many settlements. Defaults to `window` (so the first decision is made\n * on a full window, not on a partial one). */\n readonly minSettles?: number\n}\n\n/**\n * \"The objective has stopped climbing.\" Fires when the best-so-far curve has risen by no more than\n * `minDelta` across the last `window` settlements.\n *\n * Built on `anytime.plateauLength` — the same plateau math the post-run anytime report uses, so a\n * rule that stops a run and a report that grades the decision cannot disagree about whether the\n * run was flat.\n */\nexport function plateau(opts: PlateauOptions): StopRule {\n if (!Number.isInteger(opts.window) || opts.window < 1) {\n throw new ValidationError('plateau: window must be a positive integer')\n }\n if (!Number.isFinite(opts.minDelta) || opts.minDelta < 0) {\n throw new ValidationError('plateau: minDelta must be >= 0')\n }\n const minSettles = opts.minSettles ?? opts.window\n return (v) => {\n if (v.settles < minSettles) return CONTINUE\n const flat = plateauLength(v.curve, opts.minDelta)\n if (flat >= opts.window) {\n return {\n stop: true,\n reason: `plateau: best-so-far rose <= ${opts.minDelta} over the last ${flat} settles (window ${opts.window}), best=${v.best}, auc=${v.auc.toFixed(3)}`,\n }\n }\n return CONTINUE\n }\n}\n\nexport interface AllWorkersStalledOptions {\n /** Require at least this many live workers before the rule can fire — one stalled worker in a\n * one-worker tree is a weaker signal than a whole fleet going quiet. Default 1. */\n readonly minWorkers?: number\n /** Idle time that counts as stalled, passed through to the live progress read. Omit = the\n * runtime default (`DEFAULT_STALL_AFTER_MS`). */\n readonly stallAfterMs?: number\n}\n\n/**\n * \"Everyone is stuck.\" Fires when every live worker reads `stalled` — no metered activity for\n * longer than the stall threshold — and none of the tree is merely waiting.\n *\n * `stalled` is a derived read at observation time, never a background watchdog; this rule only\n * reads it. A tree with armed waits never fires: waiting is not stalling.\n */\nexport function allWorkersStalled(opts: AllWorkersStalledOptions = {}): StopRule {\n const minWorkers = opts.minWorkers ?? 1\n return (v) => {\n if (v.waiting > 0) return CONTINUE\n if (v.workers.length < minWorkers) return CONTINUE\n if (!v.workers.every((w) => w.stalled)) return CONTINUE\n const worst = Math.max(...v.workers.map((w) => w.idleMs))\n return {\n stop: true,\n reason: `all-stalled: ${v.workers.length} live workers idle, worst ${worst}ms`,\n }\n }\n}\n\n/** Stop when ANY rule stops — the ordinary composition (each rule is a separate reason to end). */\nexport function anyOf(...rules: ReadonlyArray<StopRule>): StopRule {\n return (v) => {\n for (const rule of rules) {\n const d = rule(v)\n if (d.stop) return d\n }\n return CONTINUE\n }\n}\n\n/** Stop only when EVERY rule stops — for a conservative gate that needs corroboration. */\nexport function allOf(...rules: ReadonlyArray<StopRule>): StopRule {\n if (rules.length === 0) throw new ValidationError('allOf: needs at least one rule')\n return (v) => {\n const reasons: string[] = []\n for (const rule of rules) {\n const d = rule(v)\n if (!d.stop) return CONTINUE\n reasons.push(d.reason)\n }\n return { stop: true, reason: reasons.join(' AND ') }\n }\n}\n\n/** The settled-work ledger a stop evaluation folds — the shape both the router driver's\n * coordination tools and the harness arm's MCP handle expose. */\nexport interface SettledLedger {\n settled(): ReadonlyArray<{\n readonly id: string\n readonly status: 'done' | 'down'\n readonly score?: number\n readonly valid?: boolean\n readonly settledAt?: number\n }>\n}\n\n/**\n * Evaluate a rule against the run's settled work — the ONE evaluator both supervisor arms call.\n *\n * The router arm calls it before each driver inference turn; the harness arm calls it on each\n * worker settle. Ordering is the contract in both: the hard ceilings (`poolStarved`,\n * `deadlinePassed`, abort, the driver's own stop) are checked first and independently, so a stop\n * rule can only ever ADD a stop — it can never keep a run alive past a budget it has exhausted.\n *\n * Folding the whole roster each call is idempotent by worker id, so it costs O(settled) and never\n * double-counts. `settledAt` carries the instant the ledger recorded a settlement; `now()` is the\n * fallback resolution a per-turn guard has.\n */\nexport function progressStop(\n tracker: ProgressTracker,\n rule: StopRule,\n ledger: SettledLedger,\n scope: Scope<unknown>,\n now: () => number,\n stallAfterMs: number | undefined,\n): StopDecision {\n for (const w of ledger.settled()) {\n tracker.record({\n id: w.id,\n at: w.settledAt ?? now(),\n ...(w.score !== undefined ? { objective: w.score } : {}),\n delivered: w.status === 'done' && w.valid === true,\n })\n }\n return tracker.evaluate(rule, scope, stallAfterMs !== undefined ? { stallAfterMs } : undefined)\n}\n","/**\n *\n * `driverAgent` — the driver's BRAIN.\n *\n * The recursive driver-executor (`driver-executor.ts`) runs a driver `Agent.act` inside a\n * nested `Scope`; this is the intelligent `act`: it mounts the coordination MCP verbs\n * (`createCoordinationTools`) over that scope and runs an LLM tool-loop, so the driver\n * REASONS — spawn / observe / steer / await / stop — about how to drive its children,\n * instead of running a fixed script. Each turn: ask the driver LLM for tool calls, run them\n * against the live scope, fold the results back, repeat until the driver stops (no tool\n * calls) or the turn cap forces a keep-best finalize.\n *\n * Recursion composes through `makeWorkerAgent`: `spawn_agent` resolves a `profile` to a\n * worker LEAF or — when the profile is a driver — a `driverChild` wrapping ANOTHER\n * `driverAgent` over its own nested scope (see `driver-executor.ts`). So an agent\n * drives an agent that drives an agent, each an LLM tool-loop, all on one conserved-budget\n * tree.\n *\n * Two seams are INJECTED so the loop runs offline with no creds and stays decoupled:\n * - `brain` (`ToolLoopChat`) — one driver-LLM turn over the canonical tool-loop seam; a test\n * drives a scripted mock, production passes the router's tool-calling (`routerBrain`), a\n * sandboxed harness drives the verbs as MCP tools. The same seam every tool-loop uses.\n * - `systemPrompt` — the driver's stance (the agent-eval worker-driver prompt / the prompt\n * generator). Injected, never hardcoded — the prompt is a pluggable role.\n *\n * @experimental\n */\n\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { RuntimeRunStateError, ValidationError } from '../../errors'\nimport type { McpToolDescriptor } from '../../mcp/server'\nimport {\n type AnalystRegistry,\n type AnalyzeOnSettleRoute,\n type AuthorizeDownMessage,\n type ContinuityMode,\n type CoordinationEvent,\n coordinationVerbNames,\n createCoordinationTools,\n type DownMessageEvent,\n type MakeWorkerAgent,\n normalizeAnalyzeOnSettle,\n type SettledWorker,\n type SpawnPreflight,\n type WorkerWatchOptions,\n} from '../../mcp/tools/coordination'\nimport type { ToolSpec } from '../router-client'\nimport {\n runBrainLoop,\n type ToolLoopCallContext,\n type ToolLoopChat,\n type ToolLoopCompaction,\n type ToolLoopCompactionOptions,\n} from '../tool-loop'\nimport { chargedTokens, promptCacheTokenClasses, unmeteredSpend } from '../util'\nimport type { DeliverableSpec } from './completion-gate'\nimport type { PriorCoordination } from './coordination-log'\nimport type { BusRecord } from './event-bus'\nimport {\n bestDelivered,\n pickBestDelivered,\n runFinalizer,\n runTree,\n type SupervisorFinalizer,\n} from './finalizer'\nimport { createInbox, type Inbox } from './inbox'\nimport { providerAttemptEvidence } from './materialization'\nimport { isTerminalNodeStatus } from './node-status'\nimport {\n claimWorkerSteerDelivery,\n type RunCancellation,\n readRunCancellation,\n readRunCancelRequest,\n readWorkerCancellation,\n readWorkerCancelRequests,\n readWorkerSteerAcknowledgement,\n readWorkerSteerRequests,\n type WorkerCancellation,\n type WorkerCancelRequest,\n type WorkerSteerAcknowledgement,\n type WorkerSteerRequest,\n writeRunCancellation,\n writeWorkerCancellation,\n writeWorkerSteerAcknowledgement,\n} from './run-layout'\nimport { meterRuntimeOwnedProviderAttempt } from './scope'\nimport { createProgressTracker, progressStop, type StopRule } from './stop-rules'\nimport type {\n Agent,\n Budget,\n NodeSnapshot,\n ResultBlobStore,\n ResumedWork,\n Scope,\n Spend,\n TreeView,\n} from './types'\n\nexport interface DriverAgentOptions {\n readonly name: string\n /** The driver-LLM seam — ONE inference turn over the conversation + the coordination tool specs\n * (the canonical `ToolLoopChat`): a scripted mock offline, the router's tool-calling in\n * production, or a sandboxed harness. The same seam every tool-loop uses; no bespoke shape. */\n readonly brain: ToolLoopChat\n /** Profile-declared model for a production Router brain. When set, every turn must report this\n * exact provider-observed model before its output is accepted. Omitted by scripted test brains. */\n readonly expectedModel?: string\n /** Runtime-owned observation sink for the provider identity of each settled driver turn. */\n readonly onProviderModel?: (model: string | undefined) => void\n /** Shared blob store — `observe_agent` reads settled outputs through it. */\n readonly blobs: ResultBlobStore\n /** Resolve a spawned `profile` to a worker LEAF or a driver child (the recursion seam). */\n readonly makeWorkerAgent: MakeWorkerAgent\n readonly authorizeDownMessage?: AuthorizeDownMessage\n /** Per-child budget reserved from the conserved pool on each spawn. */\n readonly perWorker: Budget\n /** Independent completion check for work the driver performs itself. When present, the driver\n * receives `submit_result`; the first passing submission ends the loop and becomes the output. */\n readonly deliverable?: DeliverableSpec<unknown>\n /** Hard cap on simultaneously-LIVE workers — `spawn_agent` fails closed once this many are in\n * flight (a concurrency fence on top of the conserved-pool fence). Omit/`<= 0` = no cap. */\n readonly maxLiveWorkers?: number\n /** The analyst lenses available to the driver. Required for `analyzeOnSettle` (and `run_analyst`).\n * Unset → no analyst feed (status quo: the driver gets settled outputs, no findings). */\n readonly analysts?: AnalystRegistry\n /** Analyst kind ids run AUTOMATICALLY when a worker settles `done` — each result re-enters as a\n * `finding` the driver pulls and composes its next steer from. The UP-leg of the self-improving\n * loop. Omit/empty = no auto-analysis (status quo). Requires `analysts`. */\n readonly analyzeOnSettle?: ReadonlyArray<string | AnalyzeOnSettleRoute>\n /** Run the ONLINE detector panel over each worker's LIVE tool trace and raise a `finding` the\n * moment it loops/error-storms — mid-run evidence to steer on, not a settle-time post-mortem.\n * Omit = no online watching. */\n readonly watchWorkers?: WorkerWatchOptions\n /** Idle time after which `observe_agent` reports a worker as stalled (a derived read; nothing is\n * killed). Omit = the runtime default. */\n readonly stallAfterMs?: number\n /** Default continuity per worker PROFILE NAME — `'resume'` makes spawns of that name re-attach\n * to the node's latest settled worker (see\n * `CoordinationToolsOptions.continuityByProfile`); `spawn_agent`'s per-call `continuity`\n * argument overrides. Omit = every spawn fresh (status quo). */\n readonly continuityByProfile?: Readonly<Record<string, ContinuityMode>>\n /** OPT-IN async gate run before every spawn mints an assignment or reserves budget. See\n * `CoordinationToolsOptions.preflightSpawn`. */\n readonly preflightSpawn?: SpawnPreflight\n /** Pre-journal profile resolution for `preflightSpawn`; see\n * `CoordinationToolsOptions.resolveSpawnProfile`. */\n readonly resolveSpawnProfile?: (profile: AgentProfile) => AgentProfile\n /** The driver's stance — a string, or built from the task (the worker-driver prompt /\n * the generator). INJECTED so the prompt is a pluggable, optimizable role. */\n readonly systemPrompt: string | ((task: unknown) => string)\n /** Product-selected tools already bound to this exact supervisor node. The same descriptors are\n * served over MCP for external supervisors; this arm projects them into router ToolSpecs. */\n readonly nodeTools?: ReadonlyArray<McpToolDescriptor>\n /** WORK tools the driver may call DIRECTLY (alongside the coordination verbs) — so the driver is\n * not a pure manager but a full agent that can ACT (do simple work itself) OR SPAWN (delegate).\n * Each is a router tool spec; their names must not collide with the coordination verbs. Pair with\n * `executeExtraTool`. Unset → coordination-only (the prior behavior). */\n readonly extraTools?: ReadonlyArray<{\n readonly name: string\n readonly description?: string\n readonly parameters: Record<string, unknown>\n }>\n /** Runs an `extraTools` call. Returns a string result, or null/undefined to signal \"not handled\"\n * so the call falls through to the coordination dispatch. Required iff `extraTools` is set. */\n readonly executeExtraTool?: (\n name: string,\n args: Record<string, unknown>,\n ) => Promise<string | null | undefined>\n /** Max driver turns before the loop force-finalizes on the best settled child. Default 16.\n * `0` lifts the turn-COUNT cap: the loop is bounded instead by the conserved budget pool,\n * an absolute deadline, the driver's own stop, and abort (checked in-loop). A finite\n * anti-runaway tripwire still guards a degenerate driver that loops on a no-spawn tool. */\n readonly maxTurns?: number\n /** Injected clock for the in-loop absolute-deadline guard — keeps the deadline check\n * deterministic in tests. Defaults to `Date.now`. */\n readonly now?: () => number\n /**\n * PROGRESS-derived stop (mechanic D). Today a run ends on a ceiling — iterations, tokens,\n * dollars, deadline, turn cap — which answers \"may it continue?\" and never \"is it still getting\n * anywhere?\". A stop rule reads the run's own progress (best-so-far over settled work, time\n * since the last settle, the live worker feed) and ends a run that has stopped learning BEFORE\n * it exhausts a budget.\n *\n * Composes with, and can never override, the hard guards: `poolStarved` / `deadlinePassed` /\n * abort / the driver's own stop are evaluated first, so a rule can only ADD a stop.\n *\n * THRESHOLDS are the caller's judgment, not this module's — build the rule with\n * `plateau({window, minDelta})` / `noProgressFor({...})` / `allWorkersStalled({...})` from\n * `supervise/stop-rules`. Omit ⇒ ceilings only (unchanged behavior).\n */\n readonly stopRule?: StopRule\n /** Called once with the rule's reason when a `stopRule` ends the run — so a caller can record\n * WHY a run stopped early instead of inferring it from an unexhausted budget. */\n readonly onProgressStop?: (reason: string) => void\n /** Give the driver brain a chapter-lifecycle on its OWN context window. The LLM-brain front doors\n * lose to a dumb-Ralph respawn because the brain re-bills its whole coordination transcript every\n * turn — the same context overflow a single steered agent suffers, one level up. With this set,\n * once the brain's running conversation exceeds `thresholdTokens` it distills the accumulated\n * history to a compact progress note and continues fresh: the supervisor analog of respawning\n * against external tracking state, except the live `Scope` roster IS the durable state. Default\n * off (no behavior change). `distill` defaults to a self-summary authored by the brain combined\n * with the factual settled-worker roster; override to supply your own. */\n readonly compaction?: ToolLoopCompactionOptions\n /** Pass-through subscriber for every coordination bus event: settled/question/finding,\n * pre-delivery instruction receipts, and steer/answer delivery outcomes. A durable caller uses\n * this to append the coordination log. Omit = no observer. */\n readonly onEvent?: (\n event: CoordinationEvent,\n record: BusRecord<CoordinationEvent>,\n ) => void | Promise<void>\n /** Re-publish resume-time settlements through the awaited observer before the first brain turn. */\n readonly replaySettlements?: boolean\n /** Questions, findings, and authorized continuation receipts loaded from a prior process.\n * Questions seed the ledger (`list_questions`, blocking-stop policy); all three feed the resume\n * brief. Continuation receipts are evidence only and are never auto-delivered. Omit = fresh. */\n readonly priorCoordination?: PriorCoordination\n /** How the settled-worker ledger becomes the run's output. Default `bestDelivered` — the single\n * highest-scoring DELIVERED child (the exact keep-best every existing caller had). Runs under\n * the delivered-only invariant (`runFinalizer`): whatever the finalizer, an undelivered or\n * invalid child's output stays unreachable. */\n readonly finalizer?: SupervisorFinalizer\n /** Optional shared manager inbox used by a wrapper that must accept messages before async node\n * setup finishes. Ordinary callers omit it and the driver owns a fresh inbox. */\n readonly inbox?: Inbox\n /**\n * The durable run directory (`SuperviseOptions.runDir` / the `run-layout` event dir) this driver\n * ACKNOWLEDGES worker-scoped cancel requests from. Each turn the driver reads the layout's\n * cancellation inbox once, applies any request naming one of ITS OWN workers through that\n * worker's existing per-child abort (cascading to the worker's subtree and no sibling), and\n * writes the durable {@link WorkerCancellation} acknowledgement: `cancel_requested` when the\n * abort is issued, `cancelled` only when the worker reaches a terminal `down` on the settle\n * path, `not_live` when the worker is already gone — a missing worker never reads as success.\n * Which requests this driver OWNS is set by {@link controlScope}. Omit = no acknowledger\n * (in-memory runs keep in-process control via handles).\n */\n readonly controlDir?: string\n /**\n * Which cancel requests this driver's acknowledger owns when `controlDir` is set.\n *\n * `'run'` (the default, and the tree root's role): exact node ids of its OWN direct children,\n * plus every label/profile-name reference. `'subtree'` (a nested manager): exact direct-child\n * node ids ONLY — never labels or profile names, which can match workers under more than one\n * manager. Ownership makes each operation appliable by exactly ONE manager, so two acknowledgers\n * sharing one `controlDir` can never abort two workers for one operation or race on the\n * acknowledgement file. At the end of `act`, the owner writes an expiry record for each owned\n * request still open: `not_live` for one never applied, `unknown` for an abort whose settle the\n * run ended too soon to observe — so a reader can tell run-over from in-progress.\n */\n /** Called with this driver's coordination tool descriptors once they exist and before the brain\n * loop starts — the seam a node tool uses to call the same verbs in code\n * (`SupervisorToolInvocationContext.verbs`). */\n readonly onCoordinationTools?: (tools: ReadonlyArray<McpToolDescriptor>) => void\n readonly controlScope?: 'run' | 'subtree'\n /**\n * Abort the WHOLE run — the seam a run-scoped cancel request (`cancelRun`) is applied through.\n * Wired by `supervise()` to the run's ONE cascade controller (the attached root control), so a\n * run cancel takes the same path a caller's `RootHandle.abort` takes; there is no second\n * controller and no poller. Read only by the `'run'`-scoped manager with a `controlDir`; omit\n * and a run-scoped request stays unanswered.\n */\n readonly abortRun?: (reason: string) => void\n}\n\n/** The default chapter-close prompt: the brain summarizes its OWN progress for its future self before\n * the detailed history is dropped. Emphasis on PENDING work — the part a too-eager chapter-close\n * loses (the coding-burn counter-finding: closing after one fix leaves integration bugs uncircled). */\nconst distillInstruction =\n 'CONTEXT COMPACTION. Your detailed turn-by-turn history is about to be discarded to free your context window. Write a COMPLETE, compact handoff note for your future self so you can keep going without it. Cover: (1) what you have accomplished; (2) every worker you spawned and its current status/result; (3) what subtasks remain unfinished, failing, or unverified — be specific and exhaustive here, this is the part you must not lose; (4) your immediate next action. Do not call any tools; respond with the note only.'\n\n/** Factual ground truth for the digest — the live worker roster from Scope plus the delivered-result\n * ledger, independent of whatever the brain's prose summary captures. */\nfunction summarizeRoster(view: TreeView, settled: ReadonlyArray<SettledWorker>): string {\n if (view.nodes.length === 0) return 'Workers in current live scope: none yet.'\n const settledById = new Map(settled.map((w) => [w.id, w]))\n const lines = view.nodes.map((node) => formatRosterNode(node, settledById.get(node.id)))\n return `Workers in current live scope (ground truth from the run, ${view.nodes.length} total, ${view.inFlight} in flight):\\n${lines.join('\\n')}`\n}\n\nfunction formatRosterNode(node: NodeSnapshot, settled?: SettledWorker): string {\n const result =\n settled?.status === 'done'\n ? `, delivered=${settled.valid ?? false}${\n settled.score !== undefined ? `, score=${settled.score}` : ''\n }${settled.outRef ? `, outRef=${settled.outRef}` : ''}`\n : settled?.status === 'down'\n ? `, reason=${settled.reason ?? 'unknown'}`\n : node.outRef\n ? `, outRef=${node.outRef}`\n : ''\n return `- ${node.id}: ${node.status}, label=${node.label}, runtime=${node.runtime}${result}`\n}\n\n/** Spawn-progress is impossible: the pool can't afford another worker AND nothing is in flight to\n * await. A long-horizon driver bounded by the conserved pool stops here instead of spinning (the\n * in-loop budget guard the turn cap alone never provided). Checks BOTH conserved channels: tokens\n * (can't afford a worker) and usd (a usd-capped pool whose ceiling the driver's own metered\n * inference has drained — `meter` debits usd, so without this a huge-token/small-usd pool would\n * overspend usd up to the turn tripwire). */\nfunction poolStarved(scope: Scope<unknown>, perWorker: Budget): boolean {\n const b = scope.budget\n if (scope.view.inFlight > 0 || scope.view.waiting > 0) return false\n const tokenStarved = b.tokensLeft < perWorker.maxTokens\n const iterationStarved = b.iterationsLeft <= 0\n const usdStarved =\n b.usdCapped &&\n (b.usdLeft <= 0 || (perWorker.maxUsd !== undefined && b.usdLeft < perWorker.maxUsd))\n return tokenStarved || iterationStarved || usdStarved\n}\n\n/** The absolute wall-clock deadline (when the root set one) has passed. */\nfunction deadlinePassed(scope: Scope<unknown>, now: () => number): boolean {\n const b = scope.budget\n return b.deadlineMs > 0 && now() >= b.deadlineMs\n}\n\n/** The USD-denominated members of {@link PromptCacheUsage} — the schema, not a guess. Every\n * other known member (`readTokens`, `writeTokens`, `missTokens`) is a token COUNT. */\nconst PROMPT_CACHE_USD_FIELDS: ReadonlySet<string> = new Set(['readSavingsUsd'])\n\n/** Dollar amounts above this are provider nonsense, not evidence. The old all-integer rule\n * rejected them as a side effect; keeping an explicit ceiling preserves that protection\n * without pretending a dollar amount is an integer. */\nconst MAX_PROMPT_CACHE_USD = 1_000_000\n\n/**\n * Validate provider-reported prompt-cache evidence.\n *\n * Prompt-cache carries two kinds of number and they obey different rules: token COUNTS are\n * integers, and USD amounts are fractional by nature. Applying the count rule to a dollar\n * field refuses every provider that reports cache savings in dollars — a healthy router\n * response carrying `readSavingsUsd: 0.0034` failed the driver outright before this split.\n *\n * Classification is schema-first: a field named in {@link PromptCacheUsage} is validated by\n * what that member IS. `promptCache` is an open record (the sandbox path forwards provider\n * fields verbatim), so an unknown field falls back to the `usd` name-suffix convention —\n * documented here as the contract a provider must follow to report dollars.\n *\n * Returns the refusal, or `undefined` when the evidence is acceptable.\n */\nexport function validateDriverPromptCache(\n promptCache: Readonly<Record<string, number | string>> | undefined,\n): ValidationError | undefined {\n for (const [field, value] of Object.entries(promptCache ?? {})) {\n if (typeof value !== 'number') continue\n const isUsdField = PROMPT_CACHE_USD_FIELDS.has(field) || /usd$/i.test(field)\n if (isUsdField) {\n if (!Number.isFinite(value) || value < 0 || value > MAX_PROMPT_CACHE_USD) {\n return new ValidationError(\n `driverAgent: prompt-cache field ${JSON.stringify(field)} must be a non-negative finite number of dollars`,\n )\n }\n continue\n }\n if (!Number.isSafeInteger(value) || value < 0) {\n return new ValidationError(\n `driverAgent: prompt-cache field ${JSON.stringify(field)} must be a non-negative safe integer`,\n )\n }\n }\n return undefined\n}\n\n/** The journal file `createFileRunContext` writes inside the run directory. The acknowledger\n * reads it as EVIDENCE for the terminated-descendants set — the nested trees of a cancelled\n * lead journal their terminal records there before the lead settles into this scope. */\nconst SPAWN_JOURNAL_FILE = 'spawn-journal.jsonl'\n\ninterface CancelAcknowledgerDeps {\n readonly dir: string\n readonly coord: {\n settled(): ReadonlyArray<SettledWorker>\n abortWorker(\n ref: string,\n reason?: string,\n ): { readonly id: string; readonly label: string } | undefined\n }\n readonly scope: Scope<unknown>\n readonly now: () => number\n /** This manager's own node id (`scope.view.root`) — the parent every owned node id hangs off. */\n readonly ownerId: string\n /** `'run'` also owns label/profile-name references (the tree root's role); `'subtree'` owns\n * exact direct-child node ids only. See `DriverAgentOptions.controlScope`. */\n readonly controlScope: 'run' | 'subtree'\n /** Abort the WHOLE run through the one cascade controller it already has. Present only on the\n * `'run'`-scoped manager, and only when the caller wired a root control; without it a\n * run-scoped cancel request is not this manager's to apply. */\n readonly abortRun?: (reason: string) => void\n}\n\ninterface SteerAcknowledgerDeps {\n readonly dir: string\n readonly coord: {\n steerWorker(\n workerId: string,\n instruction: string,\n options?: { readonly interrupt?: boolean },\n ): Promise<DownMessageEvent>\n }\n readonly now: () => number\n readonly ownerId: string\n}\n\n/**\n * Apply externally admitted steers once from the owning manager's turn loop.\n *\n * The `unknown` acknowledgement lands before authorization or delivery. A crash after that write\n * can lose this steer, but a restarted manager never delivers it again. This is the same\n * at-most-once crash boundary as coordination instruction receipts: no duplicate instruction is\n * safer than replaying a mutation whose first delivery may already have succeeded.\n */\nexport function createSteerAcknowledger(deps: SteerAcknowledgerDeps): {\n pass(phase: 'turn' | 'final'): Promise<void>\n} {\n const iso = () => new Date(deps.now()).toISOString()\n const directChildId = (ref: string): boolean =>\n ref.startsWith(`${deps.ownerId}:s`) && /^s\\d+$/.test(ref.slice(deps.ownerId.length + 1))\n\n const base = (\n request: WorkerSteerRequest,\n ): Omit<WorkerSteerAcknowledgement, 'effect' | 'observedAt' | 'detail'> => ({\n schemaVersion: 1,\n operationId: request.operationId,\n requestDigest: request.requestDigest,\n worker: request.worker,\n requestedAt: request.at,\n })\n\n return {\n async pass(phase): Promise<void> {\n for (const request of readWorkerSteerRequests(deps.dir)) {\n if (!directChildId(request.worker)) continue\n if (readWorkerSteerAcknowledgement(deps.dir, request.operationId) !== undefined) continue\n if (phase === 'final') {\n writeWorkerSteerAcknowledgement(deps.dir, {\n ...base(request),\n effect: 'not_live',\n observedAt: iso(),\n detail: 'run ended before the steer was applied',\n })\n continue\n }\n const claimed = claimWorkerSteerDelivery(deps.dir, {\n ...base(request),\n effect: 'unknown',\n observedAt: iso(),\n detail: 'delivery admitted; outcome not yet known',\n })\n if (!claimed) continue\n try {\n const outcome = await deps.coord.steerWorker(request.worker, request.message, {\n interrupt: request.interrupt,\n })\n const effect: WorkerSteerAcknowledgement['effect'] = outcome.delivered\n ? 'delivered'\n : outcome.outcome === 'runtime-has-no-inbox'\n ? 'unsupported'\n : outcome.outcome === 'unknown-worker' ||\n outcome.outcome === 'already-settled' ||\n outcome.outcome === 'scope-stopped'\n ? 'not_live'\n : 'unknown'\n writeWorkerSteerAcknowledgement(deps.dir, {\n ...base(request),\n effect,\n observedAt: iso(),\n detail: steerAcknowledgementDetail(outcome),\n })\n } catch (error) {\n void error\n writeWorkerSteerAcknowledgement(deps.dir, {\n ...base(request),\n effect: 'unknown',\n observedAt: iso(),\n detail: 'delivery outcome is unknown after a runtime error',\n })\n }\n }\n },\n }\n}\n\nfunction steerAcknowledgementDetail(outcome: DownMessageEvent): string {\n switch (outcome.outcome) {\n case 'delivered':\n return 'the owning manager delivered the steer to the exact live worker'\n case 'runtime-has-no-inbox':\n return 'the exact worker does not expose a steer inbox'\n case 'unknown-worker':\n return 'the owning manager does not know the exact worker'\n case 'already-settled':\n return 'the exact worker settled before delivery'\n case 'scope-stopped':\n return 'the owning manager stopped before delivery'\n case 'runtime-error':\n return 'delivery outcome is unknown after a runtime error'\n }\n}\n\n/**\n * The worker-cancel ACKNOWLEDGER — the runtime-side half of `run-layout`'s `cancelWorker`\n * contract, run from the coordination driver's turn loop (one cancellation-inbox read per turn,\n * no new process, no poller, no extra lifetime). Every manager with a `controlDir` mounts one;\n * OWNERSHIP keeps them from colliding: a request naming a node id is owned by the manager whose\n * own id is that node's parent, and a label/profile-name reference is owned by the `'run'`-scoped\n * (root) manager only — so exactly one acknowledger can ever apply one operation.\n *\n * Two-phase, honestly reported: `cancel_requested` is written the moment a live worker's abort is\n * issued (through the per-child abort chain the scope already owns, so siblings are untouched);\n * `cancelled` is written only when that worker's settlement is DELIVERED on the settle path with\n * a terminal `down`, and then the record names every subtree node id proven terminated. A worker\n * that already settled — or that settles `done` despite the abort — records `not_live`; a\n * reference matching nothing this manager owns stays pending (`cancelWorker` reports it\n * `unknown`). No path reports success for a missing worker.\n *\n * Expiry is run end, not a clock: `finish()` (after the final post-drain pass) writes `not_live`\n * for every owned request never applied and `unknown` for an issued abort whose settle the run\n * ended too soon to observe. A pending request can therefore never outlive its run and abort a\n * future spawn that happens to reuse a label.\n *\n * Idempotency is a lookup, in-process and across processes: an operation with a durable\n * acknowledgement is returned as-is and never re-applied.\n */\nexport function createCancelAcknowledger(deps: CancelAcknowledgerDeps): {\n /** `'turn'` = a driver turn boundary (the only phase that APPLIES a request); `'final'` = the\n * post-drain pass, which only reconciles records the run already wrote. */\n pass(phase: 'turn' | 'final'): void\n finish(): void\n} {\n const tracked = new Map<string, WorkerCancellation>()\n // The run-scoped operation this manager has already applied, so its abort is issued once.\n let runTracked: RunCancellation | undefined\n // The abort-issue instant per operation (the `observedAt` written on its `cancel_requested`\n // record) — the terminated-set window survives the record moving to `cancelled`.\n const abortIssuedAt = new Map<string, string>()\n const iso = () => new Date(deps.now()).toISOString()\n\n const write = (record: WorkerCancellation): void => {\n writeWorkerCancellation(deps.dir, record)\n tracked.set(record.operationId, record)\n }\n\n /** `ref` is exactly one of THIS manager's direct-child node ids (`${ownerId}:s<seq>`). */\n const directChildId = (ref: string): boolean =>\n ref.startsWith(`${deps.ownerId}:s`) && /^s\\d+$/.test(ref.slice(deps.ownerId.length + 1))\n\n /** Whether this acknowledger owns `ref`. A node id deeper in this subtree belongs to the nested\n * manager that parents it; anything that is not a node id under this manager is a\n * label/profile-name reference, owned by the `'run'`-scoped manager alone. */\n const owned = (ref: string): boolean => {\n if (directChildId(ref)) return true\n if (deps.controlScope !== 'run') return false\n return !ref.startsWith(`${deps.ownerId}:`) && ref !== deps.ownerId\n }\n\n // Terminal knowledge of one node, visible only once its settlement was DELIVERED (the ledger\n // row, or the view status `finalizeSettlement` stamps on the pull). 'down' = it died.\n const deliveredTerminal = (id: string): 'down' | 'done' | undefined => {\n const row = deps.coord.settled().find((w) => w.id === id)\n if (row !== undefined) return row.status\n const node = deps.scope.view.nodes.find((n) => n.id === id)\n if (node === undefined) return undefined\n if (node.status === 'done') return 'done'\n if (node.status === 'failed' || node.status === 'cancelled') return 'down'\n return undefined\n }\n\n const apply = (request: WorkerCancelRequest): void => {\n const aborted = deps.coord.abortWorker(request.worker, request.reason ?? 'cancel requested')\n const base = {\n operationId: request.operationId,\n worker: request.worker,\n requestedAt: request.at,\n observedAt: iso(),\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n }\n if (aborted !== undefined) {\n abortIssuedAt.set(request.operationId, base.observedAt)\n write({\n ...base,\n effect: 'cancel_requested',\n workerId: aborted.id,\n detail: `abort issued to live worker '${aborted.label}' (${aborted.id}); termination not yet proven`,\n terminated: [],\n })\n return\n }\n // Not live. A reference that matches a node whose settlement was already delivered is\n // answered `not_live`; a reference matching nothing stays pending — never a success either\n // way, and a worker that appears later can still be cancelled by a later pass.\n const settledNode = deps.scope.view.nodes.find(\n (n) =>\n (n.id === request.worker || n.label === request.worker) && isTerminalNodeStatus(n.status),\n )\n const goneId = settledNode?.id ?? deps.coord.settled().find((w) => w.id === request.worker)?.id\n if (goneId !== undefined) {\n write({\n ...base,\n effect: 'not_live',\n workerId: goneId,\n detail: `worker '${goneId}' had already settled before this operation was applied`,\n terminated: [],\n })\n }\n }\n\n /** The proven-terminated set for one record: the worker plus every subtree id with a terminal\n * journal record at/after the abort was issued. Union with what the record already names, so\n * the set only ever grows (a late teardown journal adds; nothing removes). */\n const provenTerminated = (record: WorkerCancellation, workerId: string): string[] => {\n const since = abortIssuedAt.get(record.operationId) ?? record.observedAt\n const ids = new Set<string>([\n ...record.terminated,\n workerId,\n ...terminatedDescendants(deps.dir, workerId, since),\n ])\n return [...ids].sort()\n }\n\n const reconcile = (record: WorkerCancellation): void => {\n const workerId = record.workerId\n if (workerId === undefined) return\n const terminal = deliveredTerminal(workerId)\n if (terminal === undefined) return\n if (terminal === 'down') {\n write({\n ...record,\n effect: 'cancelled',\n observedAt: iso(),\n terminated: provenTerminated(record, workerId),\n detail: `worker '${workerId}' reached a terminal down state on the settle path`,\n })\n return\n }\n // The worker finished `done` despite the abort request — its result stands, so this\n // operation terminated nothing and must not read as a successful cancellation.\n write({\n ...record,\n effect: 'not_live',\n observedAt: iso(),\n terminated: [],\n detail: `worker '${workerId}' settled done despite the abort request; nothing was terminated`,\n })\n }\n\n /** Re-scan a `cancelled` record while the manager still turns: a descendant whose teardown\n * journals after the lead's settle joins the set on a later pass instead of being lost. Only\n * a grown set is re-written; the window needs the in-process abort instant, so a record a\n * PRIOR process closed stays as that process proved it. */\n const regrow = (record: WorkerCancellation): void => {\n const workerId = record.workerId\n if (workerId === undefined || !abortIssuedAt.has(record.operationId)) return\n const terminated = provenTerminated(record, workerId)\n if (terminated.length > record.terminated.length) {\n write({ ...record, observedAt: iso(), terminated })\n }\n }\n\n /**\n * The RUN-scoped request: seen once, `cancel_requested` written the moment the run's cascading\n * abort is issued through the one controller the run already has. The `supervise()` settle path\n * records what the run then actually did — this manager cannot observe its own tree's terminal\n * state from inside `act`.\n *\n * Applied only at a TURN boundary, never on the final post-drain pass: by then the driver has\n * finished and drained, so a root abort could only void work that is already delivered. A\n * request that arrives that late expires in `finish()` instead — it terminated nothing.\n */\n const passRun = (): void => {\n if (deps.controlScope !== 'run' || deps.abortRun === undefined) return\n const request = readRunCancelRequest(deps.dir)\n if (request === undefined) return\n if (runTracked !== undefined) return\n const prior = readRunCancellation(deps.dir, request.operationId)\n if (prior !== undefined) {\n runTracked = prior\n return\n }\n const record: RunCancellation = {\n operationId: request.operationId,\n effect: 'cancel_requested',\n requestedAt: request.at,\n observedAt: iso(),\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n detail: 'root abort issued to the whole run; termination not yet proven',\n }\n writeRunCancellation(deps.dir, record)\n runTracked = record\n deps.abortRun(request.reason ?? 'run cancel requested')\n }\n\n const pass = (phase: 'turn' | 'final'): void => {\n if (phase === 'turn') passRun()\n for (const request of readWorkerCancelRequests(deps.dir)) {\n if (!owned(request.worker)) continue\n let record = tracked.get(request.operationId)\n if (record === undefined) {\n // Cross-process idempotency: an acknowledgement a prior process wrote wins over\n // re-applying the operation.\n record = readWorkerCancellation(deps.dir, request.operationId)\n if (record !== undefined) tracked.set(request.operationId, record)\n }\n if (record === undefined) {\n apply(request)\n continue\n }\n if (record.effect === 'cancel_requested') reconcile(record)\n else if (record.effect === 'cancelled') regrow(record)\n }\n }\n\n return {\n pass,\n finish(): void {\n const runRequest =\n deps.controlScope === 'run' && deps.abortRun !== undefined\n ? readRunCancelRequest(deps.dir)\n : undefined\n if (\n runRequest !== undefined &&\n readRunCancellation(deps.dir, runRequest.operationId) === undefined\n ) {\n // The request landed after the last turn boundary. The run is over, so it terminated\n // nothing — recording it here keeps a reader from seeing an operation that never resolves.\n writeRunCancellation(deps.dir, {\n operationId: runRequest.operationId,\n effect: 'not_live',\n requestedAt: runRequest.at,\n observedAt: iso(),\n ...(runRequest.reason === undefined ? {} : { reason: runRequest.reason }),\n detail: 'run ended before the request was applied',\n })\n }\n for (const request of readWorkerCancelRequests(deps.dir)) {\n if (!owned(request.worker)) continue\n const record =\n tracked.get(request.operationId) ?? readWorkerCancellation(deps.dir, request.operationId)\n if (record === undefined) {\n // Never applied and the run is over: the request expires as `not_live` so it cannot\n // linger and abort a future spawn that matches by label — and never reads as success.\n write({\n operationId: request.operationId,\n worker: request.worker,\n effect: 'not_live',\n requestedAt: request.at,\n observedAt: iso(),\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n detail: 'run ended before the request was applied',\n terminated: [],\n })\n continue\n }\n if (record.effect === 'cancel_requested') {\n // The abort went out but act is returning before the settle path could prove the\n // termination. `unknown` is the honest terminal: not in progress, never a success.\n write({\n ...record,\n effect: 'unknown',\n observedAt: iso(),\n detail: 'abort issued; run ended before termination was observed',\n })\n }\n }\n },\n }\n}\n\n/**\n * Subtree node ids with a terminal `down`/`cancelled` journal record at or after `sinceIso` —\n * the abort-issue instant (the acknowledger's own `observedAt` on the `cancel_requested` record,\n * runtime clock), never the client's `requestedAt` — read from the durable spawn journal beside\n * the run layout. The set is proven at acknowledgement time and is approximate about post-abort\n * causation: a descendant that died of its OWN cause after the abort was issued is\n * indistinguishable from the cascade and may be included; one whose teardown journals late joins\n * on a later acknowledger pass; a teardown journal still absent when the run ends is absent from\n * the set. Ids are hierarchical (`parent:sN`), so `${nodeId}:` prefixes exactly the subtree.\n * Tolerant of a missing or partially-written journal: evidence that cannot be read names fewer\n * nodes, never wrong ones.\n */\nfunction terminatedDescendants(dir: string, nodeId: string, sinceIso: string): string[] {\n let raw: string\n try {\n raw = readFileSync(join(dir, SPAWN_JOURNAL_FILE), 'utf8')\n } catch {\n return []\n }\n const prefix = `${nodeId}:`\n const ids = new Set<string>()\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n let parsed: { kind?: unknown; event?: Record<string, unknown> }\n try {\n parsed = JSON.parse(trimmed) as { kind?: unknown; event?: Record<string, unknown> }\n } catch {\n continue\n }\n if (parsed.kind !== 'event' || parsed.event === undefined) continue\n const event = parsed.event\n const died = (event.kind === 'settled' && event.status === 'down') || event.kind === 'cancelled'\n if (!died) continue\n if (typeof event.id !== 'string' || !event.id.startsWith(prefix)) continue\n if (typeof event.at !== 'string' || event.at < sinceIso) continue\n ids.add(event.id)\n }\n return [...ids].sort()\n}\n\n/**\n * Build the intelligent recursive driver. Its `act` is the LLM tool-loop; spawn it as a\n * `driverChild` (`driver-executor.ts`) to run it inside a nested scope, recursively.\n */\nexport function driverAgent(opts: DriverAgentOptions): Agent<unknown, unknown> {\n if (typeof opts.brain !== 'function') {\n throw new ValidationError('driverAgent: opts.brain must be a function')\n }\n // Fail loud on a half-wired work-tool seam: extra tool specs with no executor (or an executor\n // with no specs the model can see) is a silent no-op the house rules forbid.\n if ((opts.extraTools?.length ?? 0) > 0 && typeof opts.executeExtraTool !== 'function') {\n throw new ValidationError(\n 'driverAgent: extraTools requires executeExtraTool (how to run a work-tool call)',\n )\n }\n // Fail loud on a half-wired analyst seam (matches the extraTools pattern): analyze-on-settle with no\n // lens registry is a silent no-op the house rules forbid — the driver would get no findings, no error.\n // Only LENS routes resolve against the registry; an agent route carries its own analyst profile.\n if (\n (opts.analyzeOnSettle ?? [])\n .map(normalizeAnalyzeOnSettle)\n .some((route) => route.agent === undefined) &&\n !opts.analysts\n ) {\n throw new ValidationError(\n 'driverAgent: analyzeOnSettle requires analysts (the lens registry the kinds resolve against)',\n )\n }\n // A work tool that shadows a coordination verb would leave the driver unable to coordinate.\n // Validate against the reserved verb set HERE (construction), so the conflict fails loud — not\n // buried inside act() where the supervisor would swallow the throw into a quiet no-winner.\n const reserved = new Set<string>(coordinationVerbNames)\n for (const tool of opts.nodeTools ?? []) {\n if (reserved.has(tool.name)) {\n throw new ValidationError(\n `driverAgent: node tool \"${tool.name}\" collides with a coordination verb or another node tool`,\n )\n }\n reserved.add(tool.name)\n }\n for (const t of opts.extraTools ?? []) {\n if (reserved.has(t.name)) {\n throw new ValidationError(\n `driverAgent: extra work tool \"${t.name}\" collides with a coordination verb or node tool`,\n )\n }\n reserved.add(t.name)\n }\n // Fail loud on a nonsensical cap: a negative maxTurns would silently run zero turns and\n // finalize an empty no-winner — a silent zero the house rules forbid.\n if (opts.maxTurns !== undefined && opts.maxTurns < 0) {\n throw new ValidationError(\n 'driverAgent: maxTurns must be >= 0 (0 lifts the turn cap; bounds become the conserved pool + deadline + abort)',\n )\n }\n // maxTurns=0 lifts the turn-count cap exactly. The conserved pool, deadline, abort, and explicit\n // stop remain the caller-visible bounds; Runtime does not substitute a hidden sentinel.\n const maxTurns = opts.maxTurns ?? 16\n const now = opts.now ?? Date.now\n const inbox = opts.inbox ?? createInbox()\n\n return {\n name: opts.name,\n deliver(message): boolean {\n return inbox.deliver(message)\n },\n async act(task, scope: Scope<unknown>): Promise<unknown> {\n const coord = createCoordinationTools({\n scope,\n blobs: opts.blobs,\n makeWorkerAgent: opts.makeWorkerAgent,\n ...(opts.authorizeDownMessage ? { authorizeDownMessage: opts.authorizeDownMessage } : {}),\n perWorker: opts.perWorker,\n ...(opts.deliverable ? { deliverable: opts.deliverable } : {}),\n ...(opts.maxLiveWorkers !== undefined ? { maxLiveWorkers: opts.maxLiveWorkers } : {}),\n ...(opts.analysts ? { analysts: opts.analysts } : {}),\n ...(opts.analyzeOnSettle ? { analyzeOnSettle: opts.analyzeOnSettle } : {}),\n ...(opts.watchWorkers ? { watchWorkers: opts.watchWorkers } : {}),\n ...(opts.stallAfterMs !== undefined ? { stallAfterMs: opts.stallAfterMs } : {}),\n ...(opts.continuityByProfile ? { continuityByProfile: opts.continuityByProfile } : {}),\n ...(opts.preflightSpawn ? { preflightSpawn: opts.preflightSpawn } : {}),\n ...(opts.resolveSpawnProfile ? { resolveSpawnProfile: opts.resolveSpawnProfile } : {}),\n ...(opts.onEvent ? { onEvent: opts.onEvent } : {}),\n ...(opts.replaySettlements ? { replaySettlements: true } : {}),\n ...(opts.priorCoordination?.questions.length\n ? { priorQuestions: opts.priorCoordination.questions }\n : {}),\n })\n await coord.ready()\n // Before the first brain turn: a node tool invoked on turn one must already be able to call\n // these verbs.\n opts.onCoordinationTools?.(coord.tools)\n // The worker-cancel acknowledger, mounted only for a durable run that named its layout dir.\n // It runs inside this existing turn loop — the one place that already runs every turn and\n // already holds the child handles — so external cancellation needs no second lifetime.\n const acknowledger =\n opts.controlDir === undefined\n ? undefined\n : createCancelAcknowledger({\n dir: opts.controlDir,\n coord,\n scope,\n now,\n ownerId: scope.view.root,\n controlScope: opts.controlScope ?? 'run',\n ...(opts.abortRun ? { abortRun: opts.abortRun } : {}),\n })\n const steerAcknowledger =\n opts.controlDir === undefined\n ? undefined\n : createSteerAcknowledger({\n dir: opts.controlDir,\n coord,\n now,\n ownerId: scope.view.root,\n })\n // Resume-first: re-establish the prior process's supervision state BEFORE the first brain\n // turn — its armed-but-never-woken waits become live again on their ORIGINAL deadlines\n // (they settle through the same cursor `await_event` drains). Fail loud on a wait that\n // cannot be re-armed: silently dropping supervision state is worse than stopping.\n for (const w of scope.resume?.waits ?? []) {\n const rearmed = scope.wait(w.spec, { label: w.label })\n if (!rearmed.ok) {\n throw new RuntimeRunStateError(\n `driverAgent: cannot re-arm resumed wait '${w.label}' (${rearmed.reason})`,\n )\n }\n }\n const byName = new Map<string, McpToolDescriptor>(\n [...coord.tools, ...(opts.nodeTools ?? [])].map((t) => [t.name, t]),\n )\n const toolSpecs: ToolSpec[] = [\n ...coord.tools.map((t) => ({\n type: 'function' as const,\n function: { name: t.name, description: t.description, parameters: t.inputSchema },\n })),\n ...(opts.nodeTools ?? []).map((t) => ({\n type: 'function' as const,\n function: { name: t.name, description: t.description, parameters: t.inputSchema },\n })),\n // Work tools the driver calls DIRECTLY — so it can ACT, not only delegate.\n ...(opts.extraTools ?? []).map((t) => ({\n type: 'function' as const,\n function: { name: t.name, description: t.description, parameters: t.parameters },\n })),\n ]\n const system =\n typeof opts.systemPrompt === 'function' ? opts.systemPrompt(task) : opts.systemPrompt\n\n // Built only when a rule is configured, so a run without one allocates and evaluates nothing.\n const tracker = opts.stopRule ? createProgressTracker({ now }) : undefined\n let progressStopReason: string | undefined\n\n // Meter the driver's OWN inference on EVERY turn into the conserved pool — the largest single\n // token consumer in the loop, and what makes maxTurns=0 genuinely bounded (a thinking driver\n // drains the pool → poolStarved). Driver turns never consume the child-iteration budget;\n // failed inference stays visible through unknown token/USD channels and journal detail.\n //\n // There is deliberately no branch that skips `scope.meter`. A turn whose brain reported no\n // usage is metered as an UNKNOWN turn (`tokensKnown: false`), not omitted: omitting it let the\n // pool and the journal record a turn that ran as a turn that cost nothing, which is the one\n // thing this package forbids — a missing measurement is never zero. The unknown turn debits\n // the zero it actually knows and permanently marks `pool.readout().tokensKnown` false, so a\n // reader of `tokensLeft` can see the balance is a ceiling rather than a measurement. A\n // scripted/mock turn takes this path too, so offline equal-k still debits exactly zero tokens.\n let driverTurn = 0\n let driverCall = 0\n const meteredBrain = async (\n messages: ReadonlyArray<Record<string, unknown>>,\n tools: ReadonlyArray<ToolSpec>,\n detail: Record<string, unknown>,\n ) => {\n let res: Awaited<ReturnType<typeof opts.brain>>\n const call = driverCall\n driverCall += 1\n const callContext: ToolLoopCallContext = Object.freeze({\n signal: scope.signal,\n callId: `${scope.view.root}:brain:${crypto.randomUUID()}`,\n correlationId: scope.view.root,\n })\n try {\n res = await opts.brain(messages, tools, callContext)\n } catch (error) {\n // Calling the brain is the provider-attempt boundary. A rejection after that boundary\n // carries no trusted served identity, so preserve an empty attempt for root settlement.\n opts.onProviderModel?.(undefined)\n await meterRuntimeOwnedProviderAttempt(\n scope,\n unmeteredSpend(0),\n providerAttemptEvidence(undefined),\n {\n driver: opts.name,\n inferenceFailed: true,\n call,\n callId: callContext.callId,\n correlationId: callContext.correlationId,\n ...detail,\n },\n )\n throw error\n }\n let evidenceError: ValidationError | undefined\n opts.onProviderModel?.(res.model)\n if (opts.expectedModel !== undefined) {\n if (res.model === undefined) {\n evidenceError = new ValidationError(\n `driverAgent: Router response omitted model identity; expected ${JSON.stringify(opts.expectedModel)}`,\n )\n } else if (res.model !== opts.expectedModel) {\n evidenceError = new ValidationError(\n `driverAgent: Router response reported model ${JSON.stringify(res.model)}; expected ${JSON.stringify(opts.expectedModel)}`,\n )\n }\n }\n if (\n res.transportAttempts !== undefined &&\n (!Number.isSafeInteger(res.transportAttempts) || res.transportAttempts < 1)\n ) {\n evidenceError = new ValidationError(\n 'driverAgent: transportAttempts must be a positive safe integer when reported',\n )\n }\n evidenceError = validateDriverPromptCache(res.promptCache) ?? evidenceError\n const trustedCost =\n res.costProvenance === 'provider-receipt' || res.costProvenance === 'billing-receipt'\n const cacheUsage = promptCacheTokenClasses(res.usage?.input, res.promptCache)\n const turnSpend: Spend = {\n iterations: 0,\n tokens: {\n input: res.usage?.input ?? 0,\n output: res.usage?.output ?? 0,\n ...cacheUsage,\n },\n ...(res.usage === undefined ? { tokensKnown: false } : {}),\n usd: trustedCost ? (res.costUsd ?? 0) : 0,\n ...(trustedCost && res.costUsd !== undefined ? {} : { usdKnown: false }),\n ms: 0,\n }\n await meterRuntimeOwnedProviderAttempt(\n scope,\n turnSpend,\n providerAttemptEvidence(res.model),\n {\n driver: opts.name,\n call,\n callId: callContext.callId,\n correlationId: callContext.correlationId,\n toolCalls: (res.toolCalls ?? []).map((c) => c.name),\n ...(res.model !== undefined ? { model: res.model } : {}),\n ...(res.transportAttempts !== undefined\n ? { transportAttempts: res.transportAttempts }\n : {}),\n ...(res.usage?.reasoning !== undefined ? { reasoningTokens: res.usage.reasoning } : {}),\n ...(res.promptCache !== undefined ? { promptCache: res.promptCache } : {}),\n // The streamed transport says explicitly when it finished with no usage chunk (a broken\n // `include_usage` contract), which is a different fact from a brain that never reports\n // usage at all. Recorded on the turn so the journal distinguishes them.\n ...(res.usageUnknown === true ? { streamUsageMissing: true } : {}),\n ...(res.costProvenance === 'catalog-estimate' ? { estimatedCostUsd: res.costUsd } : {}),\n ...detail,\n },\n )\n if (evidenceError !== undefined) throw evidenceError\n return res\n }\n const chat: ToolLoopChat = async (messages, tools) => {\n const turn = driverTurn\n const res = await meteredBrain(messages, tools, {\n kind: 'driver-inference',\n turn,\n })\n driverTurn += 1\n return res\n }\n\n // Chapter-close on the brain's own window. The default distiller pairs the factual settled-worker\n // roster (from the live scope) with a brain-authored progress note; the brain call runs through\n // the metered `chat`, so the one-time O(history) distill cost debits the conserved pool like any\n // turn. It replaces the per-turn O(history) re-billing it removes.\n const compaction: ToolLoopCompaction | undefined = opts.compaction\n ? {\n thresholdTokens: opts.compaction.thresholdTokens,\n distill:\n opts.compaction.distill ??\n (async (msgs) => {\n const roster = summarizeRoster(scope.view, coord.settled())\n try {\n const res = await meteredBrain(\n [...msgs, { role: 'user', content: distillInstruction }],\n [],\n { kind: 'driver-compaction', compactingTurn: driverTurn },\n )\n const narrative = (res.content ?? '').trim()\n return narrative ? `${roster}\\n\\n## Progress notes\\n${narrative}` : roster\n } catch (e) {\n return `${roster}\\n\\n## Progress notes\\nSummary unavailable: ${errMessage(e)}`\n }\n }),\n ...(opts.compaction.onCompact ? { onCompact: opts.compaction.onCompact } : {}),\n ...(opts.compaction.preserveHead !== undefined\n ? { preserveHead: opts.compaction.preserveHead }\n : {}),\n ...(opts.compaction.estimateTokens\n ? { estimateTokens: opts.compaction.estimateTokens }\n : {}),\n }\n : undefined\n\n await runBrainLoop({\n chat,\n tools: toolSpecs,\n ...(compaction ? { compaction } : {}),\n execute: async (name, args) => {\n // WORK FIRST: a work tool the driver runs itself (act). A non-null return is handled here;\n // null/undefined means \"not mine\" → fall through to the coordination dispatch (spawn/await/…).\n if (opts.executeExtraTool) {\n const worked = await runExtraTool(opts.executeExtraTool, name, args)\n if (worked !== null && worked !== undefined) return worked\n }\n const tool = byName.get(name)\n const result = tool ? await runTool(tool, args) : { error: `unknown tool: ${name}` }\n return safeJson(result)\n },\n initialMessages: [\n { role: 'system', content: system },\n { role: 'user', content: stringifyTask(task) },\n // The resume brief: on a resumed run the brain's FIRST context already carries the\n // committed settlements, the key states, the re-armed waits, carried-over questions/\n // findings, and the spend the run already paid — so it continues from the unresolved\n // work instead of re-planning (and re-paying) from scratch.\n ...(scope.resume\n ? [{ role: 'user', content: resumeBrief(scope.resume, opts.priorCoordination) }]\n : hasPriorCoordination(opts.priorCoordination)\n ? [\n {\n role: 'user',\n content: priorCoordinationBrief(opts.priorCoordination as PriorCoordination),\n },\n ]\n : []),\n ],\n maxTurns,\n // The conserved-pool + deadline + external-stop bound (what maxTurns=0 relies on): a driver\n // that can no longer spawn (pool starved) or has run past the deadline stops here instead of\n // burning turns. Checked before each inference turn.\n hooks: {\n beforeTurn: async (_turn, messages) => {\n await steerAcknowledger?.pass('turn')\n acknowledger?.pass('turn')\n const pending = inbox.drain()\n if (pending.length > 0) {\n messages.push({ role: 'user', content: inbox.fold(pending) })\n }\n },\n stopBefore: () => {\n // HARD CEILINGS FIRST, and independently — a progress rule may never keep a run alive\n // past one, so they are not folded into the same expression.\n if (\n coord.isStopped() ||\n scope.signal.aborted ||\n poolStarved(scope, opts.perWorker) ||\n deadlinePassed(scope, now)\n ) {\n return true\n }\n if (!opts.stopRule || !tracker) return false\n const decision = progressStop(\n tracker,\n opts.stopRule,\n coord,\n scope,\n now,\n opts.stallAfterMs,\n )\n if (!decision.stop) return false\n // `stopBefore` is a predicate the loop may consult more than once; the callback is a\n // one-shot notification, so it fires on the FIRST stop only.\n if (progressStopReason === undefined) {\n progressStopReason = decision.reason\n opts.onProgressStop?.(decision.reason)\n }\n return true\n },\n },\n })\n // Drain every already-settled child the brain never pulled — a gate-verified delivery must\n // never be lost to the driver's pull discipline (e.g. a brain that spawned and stopped\n // without awaiting). Non-blocking: live children are the supervisor's to tear down.\n await coord.drainResolved()\n // Final acknowledgement pass over the drained ledger, so a cancellation whose worker\n // settled after the last turn's pass still records its terminal effect before act returns.\n // Then expiry: run end closes every owned request that is still open (`not_live` never\n // applied, `unknown` issued-but-unproven) — a reader can tell run-over from in-progress,\n // and no pending request survives to abort a future spawn that matches by label.\n await steerAcknowledger?.pass('final')\n acknowledger?.pass('final')\n acknowledger?.finish()\n // Direct work is eligible only through `submit_result`, after the same injected independent\n // check workers face. Raw driver prose remains ineligible. The first passing submission wins;\n // otherwise finalize over delivered children as before.\n const submitted = coord.submittedResult()\n if (submitted) return submitted.result\n return runFinalizer(opts.finalizer ?? bestDelivered, {\n settled: coord.settled(),\n blobs: opts.blobs,\n tree: runTree(scope),\n budget: scope.budget,\n })\n },\n }\n}\n\n/**\n * The factual context a resumed driver starts from — everything the durable stores prove about\n * the prior process(es): committed settlements, per-key states (completed / lost / failed),\n * re-armed waits, carried-over questions/findings/continuation receipts, and spend already paid.\n * Injected as the brain's first user-context on a resumed run so it continues from unresolved work;\n * old continuation receipts are evidence and are never auto-delivered.\n */\nfunction resumeBrief(resume: ResumedWork<unknown>, prior?: PriorCoordination): string {\n const lines: string[] = [\n 'RESUME: this run continues a prior coordinator process. Its committed work is restored',\n 'below and already counts toward the deliverable — do NOT redo it. Continue from the',\n 'unresolved work only.',\n '',\n `Committed workers (${resume.settled.length}):`,\n ]\n if (resume.settled.length === 0) lines.push('- none')\n for (const s of resume.settled) {\n lines.push(\n s.kind === 'done'\n ? `- ${s.handle.id} (${s.handle.label}): done, score=${s.verdict?.score ?? 0}, valid=${\n s.verdict?.valid ?? false\n }, outRef=${s.outRef}`\n : `- ${s.handle.id} (${s.handle.label}): down, reason=${s.reason}`,\n )\n }\n const byState = (state: 'completed' | 'in-doubt' | 'down') =>\n [...resume.keys].filter(([, v]) => v.state === state)\n const completed = byState('completed')\n const lost = byState('in-doubt')\n const failed = byState('down')\n if (completed.length > 0) {\n lines.push(\n '',\n 'COMPLETED keys — spawn_agent with the same key returns the finished result, spending nothing:',\n ...completed.map(([k, v]) => `- ${k} → ${v.id} (${v.label})`),\n )\n }\n if (lost.length > 0) {\n lines.push(\n '',\n 'Keys LOST in flight with the prior process — this is the unresolved work; spawn_agent with the same key starts a fresh attempt:',\n ...lost.map(([k, v]) => `- ${k} (prior attempt ${v.id}, ${v.label})`),\n )\n }\n if (failed.length > 0) {\n lines.push(\n '',\n 'Keys whose prior attempt FAILED (settled down) — spawn_agent with the same key retries:',\n ...failed.map(([k, v]) => `- ${k} (prior attempt ${v.id}, ${v.label})`),\n )\n }\n if (resume.waits.length > 0) {\n lines.push(\n '',\n 'Pending waits RE-ARMED on their original deadlines (they settle through await_event):',\n ...resume.waits.map((w) => `- ${w.label} (${w.spec.kind})`),\n )\n }\n appendPriorCoordination(lines, prior)\n const spent = resume.priorSpend\n lines.push(\n '',\n 'Budget the run ALREADY spent before this process (it counts toward the run total):',\n // `charged` is what the token cap debited: newly-presented tokens, not the rolled-up prompt\n // total, which counts a cached prefix again on every turn that reads it. A driver told the\n // rolled-up number would read a cache-heavy resume as near-exhaustion of a cap it has barely\n // touched.\n `- child work: tokens charged=${chargedTokens(spent.childWork.tokens)} (in=${spent.childWork.tokens.input} out=${spent.childWork.tokens.output}), usd=${spent.childWork.usd}, iterations=${spent.childWork.iterations}`,\n `- driver inference: tokens charged=${chargedTokens(spent.driverInference.tokens)} (in=${spent.driverInference.tokens.input} out=${spent.driverInference.tokens.output}), usd=${spent.driverInference.usd}`,\n )\n return lines.join('\\n')\n}\n\nfunction hasPriorCoordination(prior?: PriorCoordination): boolean {\n return (\n prior !== undefined &&\n (prior.questions.length > 0 ||\n prior.findings.length > 0 ||\n prior.continuations.length > 0 ||\n prior.deliveryEvidence.length > 0)\n )\n}\n\nfunction priorCoordinationBrief(prior: PriorCoordination): string {\n const lines = [\n 'PRIOR COORDINATION EVIDENCE: this logical supervisor ran in an earlier process.',\n 'Use the evidence below as context. Never auto-deliver an old continuation; issue a new',\n 'authorized instruction only when current live state still warrants it.',\n ]\n appendPriorCoordination(lines, prior)\n return lines.join('\\n')\n}\n\nfunction appendPriorCoordination(lines: string[], prior?: PriorCoordination): void {\n const openQuestions = (prior?.questions ?? []).filter(\n (q) => q.status === 'open' || q.status === 'escalated',\n )\n if (openQuestions.length > 0) {\n lines.push(\n '',\n 'Questions carried over, still undecided (answer_question decides them; list_questions shows all):',\n ...openQuestions.map(\n (q) => `- [${q.id}] from=${q.from}, urgency=${q.urgency}: ${q.question}`,\n ),\n )\n }\n if ((prior?.findings.length ?? 0) > 0) {\n lines.push(\n '',\n 'Analyst findings from the prior process:',\n ...(prior?.findings ?? []).map(\n (f) => `- ${f.analyst} on ${f.fromWorker}: ${safeJson(f.findings)}`,\n ),\n )\n }\n if ((prior?.continuations.length ?? 0) > 0) {\n const attempts = new Set(\n (prior?.deliveryEvidence ?? [])\n .filter((event) => event.type === 'delivery-attempt')\n .map((event) => event.attempt.receiptId),\n )\n const outcomes = new Map(\n (prior?.deliveryEvidence ?? [])\n .filter((event) => event.type === 'steer' || event.type === 'answer')\n .map((event) => [event.down.receiptId, event.down.outcome] as const),\n )\n lines.push(\n '',\n 'Authorized continuations committed by the prior process (evidence only; never replayed automatically):',\n ...(prior?.continuations ?? []).map((continuation) => {\n const outcome = outcomes.get(continuation.receiptId)\n const delivery =\n outcome ??\n (attempts.has(continuation.receiptId)\n ? 'unknown-after-crash'\n : 'not-attempted-before-crash')\n return `- receipt=${continuation.receiptId}, ${continuation.kind} → ${continuation.toWorker}, instruction=${continuation.instructionDigest}, delivery=${delivery}`\n }),\n )\n }\n}\n\n/** Run a work tool. A throw is data to the driver (it can recover next turn), not a crash — fold\n * the error back as a string result. null/undefined passes through (the caller treats it as \"not\n * handled\" and falls to the coordination dispatch). */\nasync function runExtraTool(\n execute: (name: string, args: Record<string, unknown>) => Promise<string | null | undefined>,\n name: string,\n args: Record<string, unknown>,\n): Promise<string | null | undefined> {\n try {\n return await execute(name, args)\n } catch (e) {\n return `error: ${e instanceof Error ? e.message : String(e)}`\n }\n}\n\nasync function runTool(tool: McpToolDescriptor, args: Record<string, unknown>): Promise<unknown> {\n try {\n return await tool.handler(args)\n } catch (e) {\n // A tool throw is data to the driver (it can recover), not a crash — fold it back.\n return { error: e instanceof Error ? e.message : String(e) }\n }\n}\n\n/** Keep-best finalize under the completion-oracle: return the highest-scoring DELIVERED child's\n * output (settled `done` AND `valid` — its deliverable check passed). Returns undefined when no\n * child delivered — an honest \"the driver produced nothing\", never a high-scoring result that\n * ran without passing its check (Foreman's 0/18 lesson). `valid` is the single delivery signal,\n * matching `defaultSelectWinner`'s valid-first rule; the oracle just doesn't fall back to an\n * unchecked best-effort. The same argmax as the `bestDelivered` finalizer (`pickBestDelivered`);\n * this direct form serves callers that hold a bare ledger + blob store. */\nexport async function finalizeBestDelivered(\n settled: ReadonlyArray<{ status: string; score?: number; valid?: boolean; outRef?: string }>,\n blobs: ResultBlobStore,\n): Promise<unknown> {\n const delivered = settled.filter((w) => w.status === 'done' && w.valid === true)\n const best = pickBestDelivered(delivered)\n if (best === undefined) return undefined\n return best.outRef ? await blobs.get(best.outRef) : undefined\n}\n\nfunction stringifyTask(task: unknown): string {\n return typeof task === 'string' ? task : safeJson(task)\n}\n\nfunction safeJson(v: unknown): string {\n try {\n return JSON.stringify(v) ?? String(v)\n } catch {\n return String(v)\n }\n}\n\nfunction errMessage(e: unknown): string {\n return e instanceof Error ? e.message : String(e)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,uBAA4C;CAC1D,OAAO,CAAC,uBAAuB,EAAE,aAAa,EAAE,CAAC,GAAG,oBAAoB,EAAE,WAAW,EAAE,CAAC,CAAC;AAC3F;;;AAIA,SAAgB,WAAW,QAAqB,OAA0B,CAAC,GAAe;CACxF,MAAM,YAAY,KAAK,aAAa,qBAAqB;CACzD,OAAO,OAAO,QAAQ,SAAS;EAC7B,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,SAAS,GAAoB;CACpC,IAAI;EACF,OAAO,KAAK,UAAU,CAAC,KAAK,OAAO,CAAC;CACtC,QAAQ;EACN,OAAO,OAAO,CAAC;CACjB;AACF;AAEA,SAAS,WAAW,GAAoB;CACtC,OAAO,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC;AAClD"}
1
+ {"version":3,"file":"coordination-driver-BeLF1j7n.js","names":[],"sources":["../src/runtime/supervise/detector-monitor.ts","../src/runtime/supervise/event-bus.ts","../src/mcp/tools/coordination.ts","../src/runtime/supervise/coordination-log.ts","../src/runtime/supervise/run-context.ts","../src/runtime/anytime.ts","../src/runtime/supervise/stop-rules.ts","../src/runtime/supervise/coordination-driver.ts"],"sourcesContent":["/**\n *\n * The ONLINE analyst: watch a `TraceSource` and fold each tool span through agent-eval's published\n * streaming detector kernel (`repeatedActionDetector`/`errorStreakDetector` — the SAME kernel the\n * control loop folds), firing `onSignal` the moment a worker loops or error-storms. Substrate-\n * agnostic: it consumes spans from any source (owned router/bridge loop OR a sandbox box session),\n * never the raw tool seam. Detection logic + the failure taxonomy live in agent-eval; not reimplemented.\n *\n * @experimental\n */\n\nimport {\n argHash,\n type DetectorSignal,\n errorStreakDetector,\n observeAll,\n repeatedActionDetector,\n type StreamingDetector,\n type ToolSpan,\n} from '@tangle-network/agent-eval'\nimport type { TraceSource } from './trace-source'\n\nexport interface WatchTraceOptions {\n /** The detectors to run online. Defaults to a stuck-loop + error-streak panel. */\n readonly detectors?: ReadonlyArray<StreamingDetector>\n /** Fired for each signal a detector raises — the seam that raises a `finding` on the bus. */\n readonly onSignal?: (signal: DetectorSignal, span: ToolSpan) => void | Promise<void>\n}\n\n/** The default online panel for a tool-call pipe: a worker repeating the same call, or hammering\n * consecutive errors. (No-progress needs a domain progress-probe, so it is opt-in, not default.)\n *\n * Coverage note: `repeated-action` works for EVERY harness (it needs only tool name + args, which\n * every adapter provides). `error-streak` needs per-call status — opencode carries it inline\n * (`state.status`, VALIDATED live), but claude-code/codex tool-call parts do NOT (their errors live\n * in separate result blocks not yet decoded), so error-streak is silent for those until result-block\n * decoding is added + live-validated. It is in the panel because it is correct where status exists. */\nexport function defaultToolDetectors(): StreamingDetector[] {\n return [repeatedActionDetector({ maxRepeated: 3 }), errorStreakDetector({ maxErrors: 3 })]\n}\n\n/** Subscribe to a `TraceSource` and run the streaming detectors over its live spans. Returns an\n * unsubscribe. A defensive `argHash` failure (circular args) never throws out of the side-channel. */\nexport function watchTrace(source: TraceSource, opts: WatchTraceOptions = {}): () => void {\n const detectors = opts.detectors ?? defaultToolDetectors()\n return source.onSpan((span) => {\n let fingerprint: string\n try {\n // Same fingerprint scheme as agent-eval's batch stuck-loop view: tool name + hashed args.\n fingerprint = `${span.toolName}|${argHash(span.args)}`\n } catch {\n fingerprint = `${span.toolName}|<unhashable>`\n }\n const signals = observeAll(detectors, {\n actionFingerprint: fingerprint,\n ...(span.status ? { status: span.status } : {}),\n label: span.toolName,\n })\n for (const s of signals) void opts.onSignal?.(s, span)\n })\n}\n","/**\n *\n * The child→parent message bus: the ONE pipe carrying every message a worker, sub-driver, or\n * analyst sends up to the driver — settled outputs, questions, and trace-analyst findings. It\n * unifies channels that were ad-hoc before (the settled-worker cursor, the ask-parent question\n * channel, and analyst results) into a single typed primitive with two lanes:\n *\n * - PASS-THROUGH (`subscribe`): every published event reaches subscribers immediately — the\n * express lane for online steering and live observation (a UI, a hook, the parent's box).\n * - STANDBY (`pull`): events also queue so the driver consumes them on its own cadence. The queue\n * is PRIORITY-ordered: a higher-`priority` event (a blocking question) is bumped ahead of\n * queued settles/findings so the driver sees it first; ties resolve FIFO by publish order.\n *\n * Observability is first-class (A++): every event is stamped with a monotonic `seq` and wall-clock\n * `at`, the full ordered `history()` is retained as current-process audit evidence, and `stats()`\n * exposes published/pulled counts by kind. Subscribers receive the stamped record, not a bare event.\n *\n * The interface is transport-agnostic on purpose. Same box → this in-process queue. Cross box →\n * the SAME publish/pull/subscribe surface backed by a durable mailbox on the parent's box (children\n * POST events with at-least-once retry; payloads are blob refs so the event stays small). Consumers\n * depend only on this interface, so distribution is a transport swap, never an architecture change.\n *\n * @experimental\n */\n\n/** Every bus event is a discriminated union member keyed by `type`. */\nexport interface BusEvent {\n readonly type: string\n}\n\n/** A published event stamped for ordering and observability. `seq` is the monotonic publish index;\n * `priority` drives pull order (higher = bumped ahead); `at` is the wall-clock publish time (ms). */\nexport interface BusRecord<E extends BusEvent> {\n readonly seq: number\n readonly at: number\n readonly priority: number\n readonly event: E\n}\n\nexport interface PublishOptions {\n /** Higher = pulled ahead of lower-priority queued events (default 0). A blocking question sets\n * this so it bumps to the front of the driver's inbox. */\n readonly priority?: number\n /** Whether the event enters the pull queue (default true). Set `false` for record-only events —\n * the parent→child down-leg (steer / answer / resume): they belong in `history()` and reach\n * `subscribe` observers, but the parent must never `pull` its own outbound message back. */\n readonly queue?: boolean\n}\n\nexport interface BusStats {\n readonly published: number\n readonly pulled: number\n /** Count published per event `type`. */\n readonly byKind: Readonly<Record<string, number>>\n}\n\n/** The child→parent coordination bus surface: publish, priority-ordered pull, pass-through subscribe, history, and stats.\n * @experimental In-process only — the durable cross-process mailbox this interface is designed\n * to admit is not implemented (docs/agent-managed-compute/README.md). */\nexport interface EventBus<E extends BusEvent> {\n /** Stamp the event, await every subscriber in order, then make it pull-visible. A subscriber\n * failure leaves the event invisible and retrying the SAME event object reuses the exact stamp.\n * This lets an awaited product observer commit its record before a supervisor can consume it. */\n publish(event: E, opts?: PublishOptions): Promise<BusRecord<E>>\n /** Remove and return the highest-priority QUEUED event whose type is in `kinds` (any if omitted),\n * ties broken FIFO by `seq`; `undefined` when nothing matches. */\n pull(kinds?: ReadonlyArray<E['type']>): E | undefined\n /** Register a pass-through handler; it receives the stamped record of every event published after\n * registration. Returns an unsubscribe fn. */\n subscribe(handler: (record: BusRecord<E>) => void | Promise<void>): () => void\n /** Count of queued, not-yet-pulled events (filtered by `kinds` when given). */\n pending(kinds?: ReadonlyArray<E['type']>): number\n /** The full ordered log of every event published in this process (audit evidence, not replay). */\n history(): ReadonlyArray<BusRecord<E>>\n /** Throughput counters for observability dashboards. */\n stats(): BusStats\n}\n\n/** Create the child→parent coordination bus: one typed pipe for settled outputs, questions, and analyst findings, with a priority-ordered pull queue and a pass-through subscribe lane.\n * @experimental In-process queue; durability is a transport swap that does not exist yet. */\nexport function createEventBus<E extends BusEvent>(now: () => number = Date.now): EventBus<E> {\n const queue: BusRecord<E>[] = []\n const log: BusRecord<E>[] = []\n const subscribers: Array<(record: BusRecord<E>) => void | Promise<void>> = []\n const byKind: Record<string, number> = {}\n // A failed publication is staged, not published. Coordination retains and retries the same event\n // object, so the exact BusRecord survives a lost acknowledgement and downstream idempotency keys\n // do not change between attempts.\n const staged = new WeakMap<object, BusRecord<E>>()\n let seq = 0\n let published = 0\n let pulled = 0\n\n const matches = (r: BusRecord<E>, kinds?: ReadonlyArray<E['type']>) =>\n !kinds || kinds.includes(r.event.type)\n\n // Index of the highest-priority matching record; ties resolve to the earliest `seq` (the queue is\n // maintained in publish order, so the first scan hit at the max priority is the oldest).\n const bestIndex = (kinds?: ReadonlyArray<E['type']>): number => {\n let best = -1\n let bestPriority = Number.NEGATIVE_INFINITY\n for (let i = 0; i < queue.length; i++) {\n const r = queue[i]\n if (!r || !matches(r, kinds)) continue\n if (r.priority > bestPriority) {\n best = i\n bestPriority = r.priority\n }\n }\n return best\n }\n\n return {\n async publish(event, opts) {\n const record =\n staged.get(event) ??\n ({ seq: seq++, at: now(), priority: opts?.priority ?? 0, event } satisfies BusRecord<E>)\n staged.set(event, record)\n // Sequential, not Promise.all: transaction observers must see causal order. Nothing enters\n // the pull queue or successful history until all observers acknowledge the record.\n for (const handler of subscribers) await handler(record)\n staged.delete(event)\n // Record-only events (the down-leg) skip the pull queue but still hit the log + subscribers.\n if (opts?.queue !== false) queue.push(record)\n log.push(record)\n published += 1\n byKind[event.type] = (byKind[event.type] ?? 0) + 1\n return record\n },\n pull(kinds) {\n const i = bestIndex(kinds)\n if (i < 0) return undefined\n pulled++\n return queue.splice(i, 1)[0]?.event\n },\n subscribe(handler) {\n subscribers.push(handler)\n return () => {\n const i = subscribers.indexOf(handler)\n if (i >= 0) subscribers.splice(i, 1)\n }\n },\n pending(kinds) {\n return kinds ? queue.filter((r) => matches(r, kinds)).length : queue.length\n },\n history() {\n return log\n },\n stats() {\n return { published, pulled, byKind: { ...byKind } }\n },\n }\n}\n","/**\n *\n * MCP binding for a live `Scope`. A sandbox driver gets the same small verbs\n * the in-process driver has: spawn, observe, await, steer, ask/answer, analyze,\n * and stop. Settled outputs remain Scope artifacts; product code can project\n * them into any UI/report envelope it needs.\n *\n * @experimental\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { AnalystFinding, TraceAnalysisStore } from '@tangle-network/agent-eval'\nimport {\n type AgentProfile,\n agentProfileSchema,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentExecutionRef,\n Budget,\n ExecutionBindingReceipt,\n Handle,\n NodeExecutionIdentity,\n ProfileMaterializationReceipt,\n ResultBlobStore,\n Scope,\n Settled,\n Spend,\n Agent as SuperviseAgent,\n WorkerTraceEvidence,\n} from '../../runtime'\nimport { assertValidBudget } from '../../runtime/supervise/budget'\nimport type { DeliverableSpec } from '../../runtime/supervise/completion-gate'\nimport { type WatchTraceOptions, watchTrace } from '../../runtime/supervise/detector-monitor'\nimport { freeSlots } from '../../runtime/supervise/dispatch'\nimport { type BusRecord, type BusStats, createEventBus } from '../../runtime/supervise/event-bus'\nimport { isLiveNodeStatus } from '../../runtime/supervise/node-status'\nimport {\n createPeerMailbox,\n type PeerMailbox,\n type PeerMailEvent,\n type PeerMailLimits,\n} from '../../runtime/supervise/peer-mail'\nimport type { WorkerProgress } from '../../runtime/supervise/progress'\nimport { detachedFrozen } from '../../runtime/supervise/snapshot'\nimport {\n parseWorkerToolTraceArtifact,\n workerTraceAnalysisStore,\n} from '../../runtime/supervise/trace-evidence'\nimport type { McpToolDescriptor } from '../server'\n\n/** A worker the driver has drained via `await_event`. */\nexport interface SettledWorker {\n readonly id: string\n readonly status: 'done' | 'down'\n /** Stable manager-scoped assignment, including deterministic unkeyed siblings. */\n readonly assignmentId?: string\n /** Exact profile/task/candidate identity authorized for this node. */\n readonly identity?: NodeExecutionIdentity\n /** Stable effective execution plan, or an explicit unknown receipt. */\n readonly materialization?: ProfileMaterializationReceipt\n /** Backend bindings for each attempt, in durable oldest-first order. */\n readonly executionBindings?: ReadonlyArray<ExecutionBindingReceipt>\n /** Conserved spend. Missing means unavailable; unknown accounting remains explicitly unknown. */\n readonly spent?: Spend\n readonly score?: number\n readonly valid?: boolean\n readonly outRef?: string\n readonly reason?: string\n /** Structured tool-call evidence, never the worker's final prose. */\n readonly trace: WorkerTraceEvidence\n /** True when projected from a prior process of the same durable run. */\n readonly resumed?: boolean\n /** Epoch ms from the durable terminal record — the resolution a progress-based stop rule needs\n * to answer \"how long since anything landed?\" without inventing a timestamp at read time. */\n readonly settledAt?: number\n}\n\nexport type QuestionLevel = 'worker' | 'driver' | 'loop'\nexport type QuestionUrgency = 'continue-without' | 'blocks-step' | 'blocks-run'\n\nexport interface QuestionOption {\n readonly label: string\n readonly tradeoff: string\n}\n\nexport interface Question {\n readonly id: string\n readonly from: string\n readonly level: QuestionLevel\n readonly question: string\n readonly reason: string\n readonly urgency: QuestionUrgency\n readonly options?: ReadonlyArray<QuestionOption>\n}\n\n/** Where a question this driver cannot answer goes next. `answer_question` accepts these and\n * nothing else, so the decision type states them and nothing else. */\nexport const questionEscalationTargets = ['parent', 'user'] as const\n\nexport type QuestionEscalationTarget = (typeof questionEscalationTargets)[number]\n\nconst isQuestionEscalationTarget = (value: unknown): value is QuestionEscalationTarget =>\n (questionEscalationTargets as ReadonlyArray<unknown>).includes(value)\n\nexport type QuestionDecision =\n | { readonly kind: 'answer'; readonly answer: string; readonly by: string }\n | { readonly kind: 'defer'; readonly reason: string }\n | {\n readonly kind: 'escalate'\n readonly to: QuestionEscalationTarget\n readonly reason: string\n }\n\nexport interface QuestionRecord extends Question {\n readonly status: 'open' | 'answered' | 'deferred' | 'escalated'\n readonly decision?: QuestionDecision\n readonly openedAt: number\n}\n\ntype QuestionInput = Omit<Question, 'id'> & { readonly id?: string }\nexport type QuestionPolicy = 'auto' | 'mustDecide' | 'bubble' | 'failClosed'\n\n/**\n * What one analyst lens may return.\n *\n * Two shapes, because two real producers exist and neither can be dropped. An eval-registry lens\n * returns validated `AnalystFinding`s — the schema every upstream consumer already reads. An\n * authored lens like `failuresAnalyst` returns a written brief for the driver and has no findings\n * to validate against. The union names both, so the boundary can no longer silently accept an\n * unvalidated shape (#630) while the authored lens keeps working.\n */\nexport type AnalystLensOutput = ReadonlyArray<AnalystFinding> | { readonly summary: string }\n\nexport interface AnalystRegistry {\n readonly kinds: ReadonlyArray<{ id: string; description: string; area: string }>\n readonly run: (kindId: string, trace: TraceAnalysisStore) => Promise<AnalystLensOutput>\n}\n\n/** A trace-analyst result re-entered as a message on the bus (the `finding` event kind). */\nexport interface AnalystFindingEvent {\n readonly fromWorker: string\n readonly analyst: string\n /** The analyst's result. ABSENT when the analyst returned `undefined` (no findings); any other\n * value is canonicalized to finite RFC 8785 JSON at publish (`canonicalFindingEvent`), so\n * digesting subscribers (the coordination-event id) never throw on analyst-shaped data. */\n readonly findings?: unknown\n}\n\n/** Producer-side cleanliness for the `finding` event. The findings payload is arbitrary analyst\n * output, the digest a subscriber computes (RFC 8785) throws on ANY `undefined` value — nested\n * included — and a throwing subscriber leaves the event invisible to EVERY subscriber. The\n * producer, not the digest, owns keeping the event canonical: an `undefined` payload is stripped\n * to key-absence, everything else is JSON round-tripped (nested `undefined` object values drop,\n * `undefined` array slots become `null`), and a payload JSON cannot represent at all (cycle,\n * BigInt, bare function) becomes a record OF that fact — degraded findings beat a vanished\n * event. */\nexport function canonicalFindingEvent(finding: AnalystFindingEvent): AnalystFindingEvent {\n if (finding.findings === undefined) {\n const { findings: _absent, ...present } = finding\n return present\n }\n try {\n // JSON.stringify returns undefined (not a string) for a bare function/symbol payload;\n // JSON.parse then throws, landing in the same non-canonical fallback as cycles and BigInt.\n return { ...finding, findings: JSON.parse(JSON.stringify(finding.findings)) as unknown }\n } catch (error) {\n return {\n ...finding,\n findings: { nonCanonicalFindings: error instanceof Error ? error.message : String(error) },\n }\n }\n}\n\n/**\n * One analyst-on-settle ROUTE: which lens runs (`kind`), over WHICH settled workers (`over`),\n * delivered to WHOM (`to`), wrapped in WHAT standing instruction (`directive`). The generalized\n * form of the bare-string entry — a string `k` is exactly `{ kind: k }`: every settle feeds the\n * lens and the findings go to the driver via the bus. This is the analyzes-edge of an agent\n * graph expressed at the coordination layer; the finding is ALWAYS also published on the bus\n * (the audit trail), routing adds delivery, never replaces the record.\n */\nexport interface AnalyzeOnSettleRoute {\n /** The analyst id: a lens id resolved against the `analysts` registry, or — when `agent` is\n * present — the AGENT analyst's stable identity carried on its finding/steer events (it need\n * not exist in any registry). */\n readonly kind: string\n /**\n * Make this analyst a tool-equipped AGENT instead of a registry lens: on each matching settle\n * the runtime spawns this profile as a WORKER through the SAME spawn machinery a driver spawn\n * uses (`Scope.spawn` + the run's `makeWorkerAgent` seam) — so its spend reserves from the\n * conserved pool, its node is journaled and traced like any worker, and a node-pinning seam\n * sees the spawn context marker (`WorkerSpawnContext.analyst`). Its task is `directive` plus\n * the settled worker's tool-trace evidence; its settle OUTPUT is the findings, published as a\n * `finding` event (same canonicalization) and delivered per `to` exactly like registry-analyst\n * findings. A settle that failed publishes `{ analystRunFailed }`; a spawn the pool or fences\n * refuse publishes `{ analystSpawnRefused }` — observable, never a silent drop. An agent\n * analyst's settlement never enters the settled-worker ledger, never feeds the finalizer, and\n * never re-fires the analyst-on-settle hook (no analyst-on-analyst cascade by construction).\n */\n readonly agent?: AgentProfile\n /** Deliver the findings to this live worker, named by its PROFILE NAME (the stable node\n * identity a graph pins) or its spawn label. Omit = the driver (bus only). Delivery goes\n * through the same authorization + steer machinery a driver-authored steer uses and is\n * recorded as a `steer` event carrying `analyst`, so a routed delivery is observable and a\n * failed one (`delivered: false`) is a recorded outcome, never a silent drop. */\n readonly to?: string\n /** Standing instruction wrapped around the findings on a routed delivery — what the recipient\n * should DO with the analysis. For an AGENT analyst (`agent` set) it is instead the analysis\n * directive handed to the agent as its task; the routed delivery then carries the bare\n * findings, because the directive was already consumed upstream. Omit = the bare findings\n * JSON (and, for an agent analyst, a task of evidence only). */\n readonly directive?: string\n /** Restrict which settled workers feed this lens, by profile name or spawn label. Omit =\n * every settled `done` worker. */\n readonly over?: ReadonlyArray<string>\n}\n\n/** Normalize the two spellings of an analyst-on-settle entry to the route form. */\nexport function normalizeAnalyzeOnSettle(\n entry: string | AnalyzeOnSettleRoute,\n): AnalyzeOnSettleRoute {\n return typeof entry === 'string' ? { kind: entry } : entry\n}\n\n/** How a spawn CONTINUES a node's prior work: `'fresh'` starts a brand-new session (the default,\n * and the only pre-continuity behavior); `'resume'` re-attaches to the node's most recent\n * SETTLED worker — a NEW live worker is spawned whose spawn context carries the prior worker's\n * identity ({@link WorkerResumeContext}), and the executor seam owns the actual session\n * re-attachment. */\nexport type ContinuityMode = 'fresh' | 'resume'\n\n/** The resume lineage a `'resume'` spawn hands the executor seam\n * ({@link WorkerSpawnContext.resume}). The kernel owns identity, ordering, ledger truth, and\n * spend continuity (the resumed worker reserves from the same conserved pool); the seam owns the\n * re-attachment itself — e.g. mapping `ofWorker` to a backend session id. */\nexport interface WorkerResumeContext {\n /** The prior SETTLED worker whose session the new worker continues. */\n readonly ofWorker: string\n /** 1-based position of the NEW worker in the node's continuity chain: a node spawned once and\n * resumed once hands the resumed worker `sequence: 2`. */\n readonly sequence: number\n}\n\n/** The exact result of one parent→child delivery attempt. */\nexport type DownMessageDeliveryOutcome =\n | 'delivered'\n | 'unknown-worker'\n | 'already-settled'\n | 'runtime-has-no-inbox'\n | 'scope-stopped'\n | 'runtime-error'\n\n/** A durable marker written after authorization and immediately before Runtime calls `Scope.send`.\n * If a process dies with this marker but no matching outcome, delivery is unknown and is never\n * replayed automatically. */\nexport interface DownMessageDeliveryAttempt {\n readonly receiptId: string\n readonly kind: 'steer' | 'answer'\n readonly toWorker: string\n readonly instructionDigest: string\n readonly interrupt: boolean\n readonly questionId?: string\n}\n\n/** A parent→child delivery result (the down-leg): recorded for observability, never pulled back by\n * the parent. `receiptId` and `instructionDigest` link it to the pre-delivery authorization receipt\n * and attempt marker. */\nexport interface DownMessageEvent {\n readonly receiptId: string\n readonly toWorker: string\n readonly instruction: string\n readonly instructionDigest: string\n readonly delivered: boolean\n readonly outcome: DownMessageDeliveryOutcome\n readonly error?: string\n}\n\n/** Durable authorization receipt written before a continuation reaches a worker. */\nexport interface ContinuationInstruction {\n readonly receiptId: string\n readonly kind: 'steer' | 'answer'\n readonly toWorker: string\n readonly instruction: string\n readonly instructionDigest: string\n readonly workerIdentity?: NodeExecutionIdentity\n readonly interrupt: boolean\n readonly questionId?: string\n}\n\n/** Detached continuation bytes and exact worker identity presented to product authorization before\n * Runtime records or delivers a steer/answer. */\nexport interface DownMessageAuthorizationInput {\n readonly kind: 'steer' | 'answer'\n readonly workerId: string\n readonly workerIdentity: NodeExecutionIdentity\n readonly instruction: string\n readonly interrupt: boolean\n readonly questionId?: string\n}\n\n/** Product-authorized continuation bytes. Returning a narrowed instruction replaces the proposed\n * bytes; throwing refuses delivery. */\nexport interface AuthorizedDownMessage {\n readonly instruction: string\n}\n\n/** Product decision over an exact continuation before it is durably recorded or delivered. */\nexport type AuthorizeDownMessage = (input: DownMessageAuthorizationInput) => AuthorizedDownMessage\n\n/** Every message on the one typed pipe. UP (child→parent): question / settled / finding — queued for\n * the driver to `pull`. An `instruction` is the pre-delivery authorization receipt and is retained\n * as evidence. DOWN (parent→child): steer / answer — record-only (history + subscribers), routed\n * to the child inbox. SIDEWAYS (child→sibling): mail — also record-only, and deliberately NOT\n * queued, so peer traffic audits through the parent without flooding the inbox it pulls from.\n * Receipts are never auto-delivered on restart. New kinds are additive. */\nexport type CoordinationEvent =\n | { readonly type: 'question'; readonly question: QuestionRecord }\n | { readonly type: 'settled'; readonly worker: SettledWorker }\n | { readonly type: 'finding'; readonly finding: AnalystFindingEvent }\n | {\n readonly type: 'steer'\n readonly down: DownMessageEvent\n /** Present when this steer DELIVERED an analyst's routed findings (an analyzes-edge\n * traversal), naming the lens — absent on an ordinary driver-authored steer. */\n readonly analyst?: string\n }\n | { readonly type: 'answer'; readonly down: DownMessageEvent; readonly questionId: string }\n | { readonly type: 'instruction'; readonly instruction: ContinuationInstruction }\n | { readonly type: 'delivery-attempt'; readonly attempt: DownMessageDeliveryAttempt }\n | { readonly type: 'mail'; readonly mail: PeerMailEvent }\n\n/** Immutable task, allocation, identity attribution, and semantic key supplied while a manager's\n * complete worker profile is prepared for one spawn. */\nexport interface WorkerSpawnContext {\n /** Stable assignment identity within this manager. A semantic key wins; otherwise Runtime mints\n * the manager's deterministic pre-factory spawn ordinal so identical unkeyed siblings stay\n * isolated and can recover by issuing the same assignments in the same order. */\n readonly assignmentId: string\n /** Trusted concrete manager node authorizing this spawn. Never accepted from model arguments. */\n readonly parentNodeId: string\n /** The exact allocation this node receives after the tool's optional override is merged. */\n readonly budget: Budget\n /** Detached, deeply immutable task bytes from this spawn request. */\n readonly task: unknown\n /** Exact trace label selected for this spawn. */\n readonly label: string\n /** Semantic restart key, when the manager supplied one. */\n readonly key?: string\n /** Trusted candidate/campaign attribution attached by product authorization. */\n readonly execution?: AgentExecutionRef\n /** Present (as the analyst id) ONLY when this spawn is an analyst-AGENT run initiated by the\n * runtime's analyst-on-settle hook ({@link AnalyzeOnSettleRoute.agent}) — authored by the\n * runtime, never accepted from a driver's tool arguments. A node-pinning `makeWorkerAgent`\n * reads it to admit the analyst node it would refuse as a driver-authored spawn. */\n readonly analyst?: string\n /** The EFFECTIVE continuity mode of this spawn — the spawn tool's per-call argument when given,\n * else the profile name's declared default ({@link CoordinationToolsOptions.continuityByProfile}),\n * else `'fresh'`. Absent only from producers that predate continuity — read absence as\n * `'fresh'`. */\n readonly continuity?: ContinuityMode\n /** Present iff `continuity === 'resume'`: the lineage the executor seam re-attaches with. */\n readonly resume?: WorkerResumeContext\n /**\n * The PEER MAIL capability endpoint minted for this exact spawn, when the run enabled peer mail\n * ({@link CoordinationToolsOptions.peerMail}). It serves `send_mail` / `read_mail` and nothing\n * else, and it speaks as this worker: the sender is bound to the capability, never passed as an\n * argument. Mount it on the worker the way `coordinationMcpUrl` is mounted on a driver.\n *\n * It arrives HERE, out of band, rather than being merged into the worker's `AgentProfile.mcp`,\n * for the same reason the driver's coordination URL does: the URL carries fresh random bytes per\n * process, so writing it into the profile would change the canonical profile digest every run and\n * a keyed re-spawn would then fail its identity check against the journal.\n */\n readonly peerMailUrl?: string\n}\n\nexport type MakeWorkerAgent = (\n profile: AgentProfile,\n context?: WorkerSpawnContext,\n) => SuperviseAgent<unknown, unknown>\n\nexport interface CoordinationToolsOptions {\n readonly scope: Scope<unknown>\n readonly blobs: ResultBlobStore\n readonly makeWorkerAgent: MakeWorkerAgent\n readonly perWorker: Budget\n /** Called once when this manager declares completion through `stop` or an accepted submission. */\n readonly onStop?: (reason: string | undefined) => void\n /**\n * The same independent completion check used for workers. When present, the driver receives a\n * `submit_result` tool and may finish work itself instead of being forced to delegate it. The\n * first passing submission is retained; a false or throwing check fails closed.\n */\n readonly deliverable?: DeliverableSpec<unknown>\n readonly analysts?: AnalystRegistry\n /** Event-first for source compatibility; the second argument is its exact bus ordering stamp. */\n readonly onEvent?: (\n event: CoordinationEvent,\n record: BusRecord<CoordinationEvent>,\n ) => void | Promise<void>\n /** Re-publish resumed settlements through the awaited observer before the driver starts. This is\n * the crash-window recovery path for product transactions; off preserves low-level legacy reads. */\n readonly replaySettlements?: boolean\n /** Authorize each continuation against the exact worker identity. The returned instruction is\n * detached, recorded durably through `onEvent`, and only then delivered. */\n readonly authorizeDownMessage?: AuthorizeDownMessage\n readonly questionPolicy?: QuestionPolicy\n /** Analyst lenses run AUTOMATICALLY when a worker settles `done` (the analyst-on-settle hook).\n * A bare string names a lens whose findings go to THE DRIVER: published as a `finding` event on\n * the bus — pass-through to subscribers and queued for `await_event`. An\n * {@link AnalyzeOnSettleRoute} generalizes the DESTINATION: findings can be delivered to a\n * named live WORKER (wrapped in the route's directive, through the same authorized steer\n * machinery a driver steer uses) instead of being hardwired to the spawning driver, and `over`\n * restricts which settled workers feed the lens. A route carrying `agent` generalizes the\n * ANALYST itself: a tool-equipped agent spawned as a worker whose settle output is the\n * findings (see {@link AnalyzeOnSettleRoute.agent}). Omit/empty = no auto-analysis (default;\n * the driver can still run lenses on demand via `run_analyst`). Lens routes require\n * `analysts`; agent routes do not. */\n readonly analyzeOnSettle?: ReadonlyArray<string | AnalyzeOnSettleRoute>\n /** Hard cap on how many workers may be LIVE (spawned but not yet settled) at once. `spawn_agent`\n * counts the scope's non-terminal nodes and fails closed (`error: 'max-live-workers'`) BEFORE\n * reserving from the pool when the cap is already met — a concurrency fence on top of the\n * conserved-budget fence (the pool bounds total work; this bounds simultaneous work, e.g. live\n * sandboxes/boxes). A tree-wide limit owned by `Scope` takes precedence when present; this field\n * is the local form for a caller-owned scope. Omit or `<= 0` = no local cap. */\n readonly maxLiveWorkers?: number\n /** Max wall-clock ms a single `await_event` call may block waiting on a live worker to settle\n * before it returns a non-error `{ pending: true, live }` snapshot and lets the caller re-poll.\n * The underlying `scope.next()` blocks for the WHOLE (multi-minute) worker run; over a remote MCP\n * transport that block outlives the client's per-request timeout, so an unbounded await surfaces\n * to the supervisor as a hard tool ERROR on every call — the exact failure that leaves it flying\n * blind. Bounding the wait converts that error into a re-pollable liveness signal. The background\n * drain keeps running, so a settlement that lands after the bound is published to the bus and\n * pulled by the next call — nothing is lost. Omit = {@link DEFAULT_AWAIT_EVENT_TIMEOUT_MS}; `<= 0`\n * restores the prior UNBOUNDED block (only safe for in-process drivers with no transport timeout). */\n readonly awaitTimeoutMs?: number\n /**\n * OPT-IN: run the ONLINE detector panel over each spawned worker's live tool trace and raise a\n * `finding` on the bus the moment a detector fires — so the driver learns \"this worker is\n * looping\" mid-run, from `await_event`, instead of at settle.\n *\n * This closes the `watchTrace` → `raiseFinding` wire whose own docstring already described it\n * (\"the seam an ONLINE detector uses to tell the driver 'this worker is looping/erroring' the\n * moment it happens\") but which nothing connected. Workers whose executor exposes no\n * `traceSource` are simply not watched; nothing fails.\n *\n * Omit = no online watching (the settle-time analysts are unaffected).\n */\n readonly watchWorkers?: WorkerWatchOptions\n /**\n * How long a worker may go without metered activity before `observe_agent` reports it as\n * `stalled`. A derived read at observation time, never a background watchdog — nothing is\n * killed or retried. Omit = the runtime default.\n */\n readonly stallAfterMs?: number\n /**\n * Questions carried over from a prior process of the SAME run (a durable coordination log a\n * resuming caller replays). Seeded into the question ledger verbatim — `list_questions` shows\n * them, the stop policy counts the still-blocking ones, and `answer_question` can decide them.\n * Omit/empty = fresh ledger (every run that is not a resume).\n */\n readonly priorQuestions?: ReadonlyArray<QuestionRecord>\n /**\n * Default continuity per PROFILE NAME (the stable node identity a graph pins). A name mapping\n * to `'resume'` makes its spawns re-attach to the node's most recent settled worker whenever\n * one exists — the node's FIRST spawn is effectively `'fresh'`, and a spawn while a prior\n * worker of the node is still LIVE fails closed (`resume-while-live`; steer is the live-worker\n * channel). The spawn tool's per-call `continuity` argument overrides the declared default in\n * either direction. Omit = every spawn is `'fresh'` (status quo). Resume lineage is\n * PROCESS-LOCAL (the same boundary as the analyst-run marker): workers settled by a prior\n * process of a durable run are not resume targets.\n */\n readonly continuityByProfile?: Readonly<Record<string, ContinuityMode>>\n /**\n * OPT-IN: give this manager's workers a bounded SIBLING channel (`../../runtime/supervise/\n * peer-mail`). Each spawn is minted a capability endpoint handed out on\n * {@link WorkerSpawnContext.peerMailUrl}; every attempt, delivered or refused, publishes a\n * `mail` event so the parent audits a channel it no longer relays. Omit = no peer channel and no\n * capability is minted (the status quo: a worker is reachable only by its parent).\n */\n readonly peerMail?: { readonly limits?: Partial<PeerMailLimits> }\n /**\n * OPT-IN async gate run on every spawn BEFORE an assignment is minted, budget is reserved, or\n * `Scope.spawn` is called — the one pre-journal point where a network question may be asked.\n *\n * `Scope.spawn` and `MakeWorkerAgent` are synchronous, so a check that needs the backend's\n * answer (does this bridge route the child's wire id; is it already at admission capacity)\n * cannot live there. Returning a {@link SpawnRefusal} refuses the spawn as a tool result: no\n * assignment, no reservation, no journal entry, no worker — and the refusal is counted on\n * {@link CoordinationTools.stats} so a gate that never refuses is visible as such.\n *\n * Returning `undefined` admits the spawn. A THROW is not a refusal: it propagates, because a\n * pre-flight that fails open would hand back exactly the silent admission it exists to stop.\n */\n readonly preflightSpawn?: SpawnPreflight\n /**\n * OPT-IN pre-journal PROFILE resolution: maps the profile a driver authored to the profile that\n * will actually run, before `preflightSpawn` asks the backend about it. A layer that pins\n * profiles by name (an agent graph) installs this so the gate judges the canonical profile —\n * its real model, tools and harness — never the `{ name }` stub the driver wrote. Synchronous,\n * throw-on-refusal, identity-free: it sees only the profile, never the assignment or budget,\n * because both are minted AFTER the pre-journal point. Omit = the authored profile is used.\n */\n readonly resolveSpawnProfile?: (profile: AgentProfile) => AgentProfile\n}\n\n/** Why a pre-flight refused a spawn. Each cause is a distinct, separately countable decision. */\nexport type SpawnRefusalCause = 'model-route' | 'bridge-full' | 'unmountable-tool'\n\n/** A pre-flight's refusal: the cause it decided on, and the operator-facing evidence for it. */\nexport interface SpawnRefusal {\n readonly cause: SpawnRefusalCause\n /** Names the exact thing that failed — the unrouted wire id, the admission numbers, the tool. */\n readonly detail: string\n}\n\n/** What a pre-flight sees: the authored child profile and the spawn it is being asked to admit. */\nexport interface SpawnPreflightContext {\n readonly label: string\n readonly key?: string\n readonly task: unknown\n}\n\n/** The gate `CoordinationToolsOptions.preflightSpawn` installs. */\nexport type SpawnPreflight = (\n profile: AgentProfile,\n context: SpawnPreflightContext,\n) => Promise<SpawnRefusal | undefined>\n\n/** Bus throughput plus the pre-flight's own refusal ledger. */\nexport interface CoordinationStats extends BusStats {\n /** One counter per refusal cause, present only when a pre-flight is installed. */\n readonly preflight?: Readonly<Record<SpawnRefusalCause, number>>\n}\n\n/** Every cause at zero — a pre-flight publishes its whole ledger from the first read. */\nfunction emptyPreflightCounts(): Record<SpawnRefusalCause, number> {\n return { 'model-route': 0, 'bridge-full': 0, 'unmountable-tool': 0 }\n}\n\n/** Online-detector wiring for spawned workers (`CoordinationToolsOptions.watchWorkers`). */\nexport interface WorkerWatchOptions {\n /** Detector panel; omit for the default stuck-loop + error-streak pair. */\n readonly detectors?: WatchTraceOptions['detectors']\n /** Raise at most this many findings per worker, so one pathological worker cannot flood the\n * driver's inbox with the same signal every span. Default 3; `<= 0` = unlimited. */\n readonly maxFindingsPerWorker?: number\n}\n\n/** Default ceiling for a single `await_event` block (ms). Chosen well under any reasonable remote\n * MCP client request timeout so the call returns a `pending` liveness snapshot instead of erroring;\n * the supervisor re-polls until the worker settles. */\nexport const DEFAULT_AWAIT_EVENT_TIMEOUT_MS = 15_000\n\n/**\n * The supervisor-side toolbox returned by {@link createCoordinationTools}: the MCP tool\n * descriptors a driver `AgentProfile` calls to spawn, steer, observe, and settle workers\n * over a live `Scope`, plus the typed accessors (`settled`/`questions`/`history`/`stats`/\n * `raiseFinding`) for the bidirectional coordination bus. This is the live, backend-of-your-\n * choice, steerable counterpart to the one-shot own-sandbox delegation MCP.\n */\nexport interface CoordinationTools {\n readonly tools: McpToolDescriptor[]\n /** Commit any resume-time event replay before a supervisor can reason or an MCP can listen. */\n ready(): Promise<void>\n isStopped(): boolean\n stopReason(): string | undefined\n /** The first result whose injected independent check passed, if the driver submitted one. */\n submittedResult(): { readonly result: unknown } | undefined\n settled(): ReadonlyArray<SettledWorker>\n questions(): ReadonlyArray<QuestionRecord>\n /** The full ordered log of every bus event — UP (settled / question / finding), authorized\n * instruction receipts, and DOWN delivery outcomes (steer / answer). Each record carries seq,\n * timestamp, and priority. A receipt is evidence and is never auto-delivered on restart. */\n history(): ReadonlyArray<BusRecord<CoordinationEvent>>\n /** Bus throughput counters (published / pulled / by-kind) for live dashboards, plus one\n * counter per {@link SpawnRefusalCause} the pre-flight refused. `preflight` is present\n * whenever `preflightSpawn` is installed, with every cause at 0 until one fires — a gate that\n * never refuses has to be readable as such. */\n stats(): CoordinationStats\n /** The run's peer-mail post office, present only when `peerMail` was enabled. The transport\n * layer stands the capability endpoint up over it; the parent reads `history()` for the audit\n * trail and calls `stopThread` to end a peer exchange. */\n readonly peerMail?: PeerMailbox\n /** Raise a `finding` on the bus from outside the settle hook — the seam an ONLINE detector\n * (mid-run, on the worker pipe) uses to tell the driver \"this worker is looping/erroring\" the\n * moment it happens, instead of only at settle. Queued for `await_event` + pass-through. */\n raiseFinding(finding: AnalystFindingEvent): Promise<void>\n /** Authorize, durably record, and attempt one external steer through the same down-leg used by\n * `steer_agent`. The returned outcome is exact and is never inferred from queue admission. */\n steerWorker(\n workerId: string,\n instruction: string,\n options?: { readonly interrupt?: boolean },\n ): Promise<DownMessageEvent>\n /**\n * Abort ONE live worker this manager spawned, through the worker's own per-child abort chain\n * (the scope cascades that abort into the worker's subtree and no sibling). `ref` resolves\n * workerId-first, then profile name, then spawn label, against LIVE workers only. Returns the\n * resolved identity, or `undefined` when no live worker matches — an already-settled or unknown\n * reference is never reported as aborted. The runtime cancel acknowledger is the intended\n * caller; the durable contract around it lives in `supervise/run-layout`.\n */\n abortWorker(\n ref: string,\n reason?: string,\n ): { readonly id: string; readonly label: string } | undefined\n /**\n * Post-loop drain: pull every ALREADY-settled, unpulled child into the ledger (publishing each\n * as a `settled` bus event for the audit trail) WITHOUT awaiting live children. The driver\n * calls this once its brain loop ends, so a delivered child the brain never awaited still\n * reaches `finalizeBestDelivered` — a gate-verified delivery must never be lost to the\n * driver's pull discipline. Analyst-on-settle hooks do NOT fire here (the driver has stopped;\n * nobody is left to read a finding, and analysts spend real compute). Returns the count.\n */\n drainResolved(): Promise<number>\n}\n\n/** The reserved coordination verb names — the complete set `createCoordinationTools` can emit\n * (the analyst pair is conditional but still reserved). A driver's extra WORK tools must not\n * collide with any of these, or it could no longer coordinate; callers validate eagerly against\n * this set so the conflict fails loud at construction, not buried in a swallowed `act()` throw. */\nexport const coordinationVerbNames = [\n 'spawn_agent',\n 'observe_agent',\n 'steer_agent',\n 'await_event',\n 'list_questions',\n 'answer_question',\n 'ask_parent',\n 'submit_result',\n 'stop',\n 'list_analysts',\n 'run_analyst',\n] as const\n\n/**\n * The `CoordinationEvent` kinds a driver may name in `await_event`. The pull queue carries the\n * UP-leg only: `steer` / `answer` / `instruction` / `delivery-attempt` are recorded `queue: false`\n * (history and subscribers, never pulled back), and `mail` is delivered to its addressee's inbox.\n *\n * Declared once because the tool advertises this list in its JSON Schema AND filters on it at\n * dispatch. Written twice, the two drift and the schema promises a kind the filter drops — a\n * driver then blocks on a queue that already holds its event.\n */\nconst awaitableEventKinds = ['settled', 'question', 'finding'] as const satisfies ReadonlyArray<\n CoordinationEvent['type']\n>\n\ntype AwaitableEventKind = (typeof awaitableEventKinds)[number]\n\nfunction isAwaitableEventKind(value: unknown): value is AwaitableEventKind {\n return (awaitableEventKinds as ReadonlyArray<unknown>).includes(value)\n}\n\nconst idArg = { type: 'string', description: 'The workerId returned by spawn_agent.' } as const\n\n/**\n * Strip zod's object-KEY CODEC artifact from a derived JSON Schema, at every depth.\n *\n * `z.record(z.string(), …)` converts to `propertyNames: { type: 'string', pattern:\n * '^u(?:[0-9a-f]{4})*$' }` — a marker of the lossy key round-trip, not a constraint anything\n * enforces: `agentProfileSchema.safeParse({ name: 'r', tools: { bash: true, Read: false } })`\n * succeeds with those plain keys. Published verbatim it reads to a model as \"every key must be a\n * run of hex quads\", and the model either emits hex-encoded garbage keys or drops the field —\n * on `tools`, `permissions`, `metadata`, `mcp`, `mcp.*.env`, and `model.metadata`, which is most\n * of what a parent actually configures.\n *\n * Every `propertyNames` in the canonical profile schema is this artifact (25 of 25 at Interface\n * 0.40), and the canonical schema constrains no key by pattern, so dropping the keyword outright\n * loses nothing real and cannot be defeated by zod changing the encoding's exact regex.\n *\n * Rebuilds rather than mutates: the canonical conversion output must stay untouched for callers\n * that compare against it.\n */\nconst stripKeyCodecArtifacts = (node: unknown): unknown => {\n if (Array.isArray(node)) return node.map(stripKeyCodecArtifacts)\n if (!node || typeof node !== 'object') return node\n return Object.fromEntries(\n Object.entries(node as Record<string, unknown>)\n .filter(([key]) => key !== 'propertyNames')\n .map(([key, value]) => [key, stripKeyCodecArtifacts(value)]),\n )\n}\n\n/** One field of the published child-profile shape: the canonical field it mirrors, the one-line\n * description a model can act on (what it is, what a child typically sets), and — for the two\n * fields whose canonical sub-tree dwarfs the rest of the tool surface — the BRIEF schema published\n * in place of that sub-tree. */\ninterface PublishedProfileField {\n readonly name: string\n readonly description: string\n readonly brief?: Record<string, unknown>\n}\n\n/** The canonical profile fields a spawning parent actually sets on a child, in the order a reader\n * needs them, each with the description published alongside it. Everything else stays legal to\n * pass — see {@link deriveSpawnProfileArg}.\n *\n * Why these eleven, with the measured numbers (serialized JSON bytes, Interface 0.40). The\n * canonical `properties` map is 10629 bytes, against 2424 bytes for every argument of every other\n * coordination tool COMBINED — publishing it whole makes one parameter four times the rest of the\n * surface a driver re-reads each turn. Of the seven omitted fields (tags, connections, subagents,\n * hooks, modes, confidential, extensions) none is something a parent hands a worker; `permissions`\n * (321 bytes) IS, so it is published — a child that must not touch the network or the filesystem\n * is fenced there and nowhere else. `mcp` (2663 bytes) and `resources` (3122 bytes) are the two a\n * parent is least likely to author inline and were together 85% of the published cost, so they\n * carry a brief shape plus a description naming the full form instead of the canonical sub-tree. */\nconst spawnProfileFields: readonly PublishedProfileField[] = [\n {\n name: 'name',\n description:\n 'Short identifier for this child, e.g. \"researcher\" or \"patch-writer\". A child normally ' +\n 'sets it to its role; it shows up in traces and worker labels.',\n },\n {\n name: 'description',\n description:\n 'One line saying what this child is for. Read by humans and by a parent listing its workers.',\n },\n {\n name: 'version',\n description:\n 'Optional version string for this profile, so two revisions of the same role are ' +\n 'distinguishable in evidence. A child usually omits it.',\n },\n {\n name: 'harness',\n description:\n 'Which coding backend runs the child. Omit to inherit the run default; set it only when ' +\n 'this child needs a specific backend (e.g. a long refactor on \"claude-code\").',\n },\n {\n name: 'model',\n description:\n 'Model routing: `default` model id, optional `small` for cheap sub-calls, `provider`, and ' +\n '`reasoningEffort`. A child typically sets `default` and `reasoningEffort` — raise effort ' +\n 'for a hard reasoning task, lower it for bulk mechanical work.',\n },\n {\n name: 'prompt',\n description:\n \"The child's standing instructions: `systemPrompt` (who it is and how it works) and \" +\n '`instructions` (durable rules). This is the role; the separate `task` argument carries ' +\n 'what to do right now. A child with no systemPrompt has no role — always set one.',\n },\n {\n name: 'tools',\n description:\n 'Per-tool on/off map keyed by tool name, e.g. `{ \"bash\": true, \"webfetch\": false }`. Omit ' +\n \"to inherit the backend's default tool set; set it to narrow a child to the tools its task \" +\n 'needs. Keys are plain tool names.',\n },\n {\n name: 'permissions',\n description:\n 'Per-tool permission decisions: each tool name maps to \"allow\", \"deny\", or \"ask\", or to a ' +\n 'nested map of finer-grained rules. This is where a parent fences a child it does not fully ' +\n 'trust — a read-only child denies write and network tools here, not in `tools`.',\n },\n {\n name: 'mcp',\n description:\n 'MCP tool servers to mount for the child, keyed by server name. Brief form: each value is ' +\n 'either `{ transport: \"stdio\", command, args?, env?, cwd? }` or ' +\n '`{ transport: \"sse\" | \"http\", url, headers? }`. A child normally sets this only when it ' +\n 'needs a tool server the task requires; the canonical AgentProfile schema carries the full ' +\n 'form (secret-ref values for env/headers, per-server metadata) and governs validation.',\n brief: { type: 'object', additionalProperties: { type: 'object' } },\n },\n {\n name: 'resources',\n description:\n 'Files, tools, skills, and agents materialized into the child workspace before it starts. ' +\n 'Brief form: `{ files?, tools?, skills?, agents? }`, each an array whose entries are ' +\n '`{ kind: \"inline\", name, content }` or `{ kind: \"github\", repository?, path, ref? }` ' +\n '(`files` entries wrap that as `{ path, resource, executable? }`). A child typically gets ' +\n '`files` for seed inputs and `skills` for a procedure it must follow; the canonical ' +\n 'AgentProfile schema carries the full form and governs validation.',\n brief: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'object' } },\n tools: { type: 'array', items: { type: 'object' } },\n skills: { type: 'array', items: { type: 'object' } },\n agents: { type: 'array', items: { type: 'object' } },\n },\n additionalProperties: true,\n },\n },\n {\n name: 'metadata',\n description:\n 'Free-form key/value bag carried with the profile (plain string keys). Use it for run ' +\n 'bookkeeping a reader will want later; it does not change how the child executes.',\n },\n]\n\n/**\n * Build the published shape of `spawn_agent`'s `profile` argument from the canonical\n * `agentProfileSchema` conversion's `properties` map, so it cannot drift from the profile the\n * runtime materializes.\n *\n * DEGRADES, never throws. A canonical field that is absent — renamed or removed upstream — is\n * simply omitted from the published shape, and a canonical schema that is no longer an object\n * publishes no properties at all. This function is reached from a statically-imported module, so a\n * throw here bricks `import '@tangle-network/agent-runtime/kernel'` for every consumer over an\n * upstream rename that costs them, at worst, one advisory field. The drift itself is still caught\n * loudly — as a test assertion in `tests/kernel/coordination.test.ts`, in CI, where it is our\n * problem rather than at a consumer's import, where it is theirs.\n *\n * Permissive on purpose: `additionalProperties: true` with no `required` list, so every canonical\n * field this shape omits stays legal to pass. This tool layer performs no profile validation.\n *\n * @internal exported for the drift and degradation tests; not part of the package's public API.\n */\nexport function deriveSpawnProfileArg(\n canonicalProperties: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n const published: Array<[string, unknown]> = []\n for (const field of spawnProfileFields) {\n const canonical = canonicalProperties?.[field.name]\n if (canonical === undefined) continue\n const shape = field.brief ?? (stripKeyCodecArtifacts(canonical) as Record<string, unknown>)\n published.push([field.name, { ...shape, description: field.description }])\n }\n return {\n type: 'object',\n description:\n 'The child agent profile to run — this is the shape the DEFAULT worker seam accepts; a run ' +\n 'wired with a custom makeWorkerAgent may accept a different one. The properties below are ' +\n 'derived from the canonical AgentProfile schema and reduced to what a spawning parent sets ' +\n '(`mcp` and `resources` in a brief form); every other canonical field — tags, connections, ' +\n 'subagents, hooks, modes, confidential, extensions — may still be passed. This tool does ' +\n 'not validate the profile: the canonical AgentProfile schema governs validation downstream.',\n properties: Object.fromEntries(published),\n additionalProperties: true,\n }\n}\n\n/** The canonical field names this module publishes, in published order — the drift test's input.\n *\n * @internal */\nexport const spawnProfileFieldNames: readonly string[] = spawnProfileFields.map((f) => f.name)\n\nlet spawnProfileArgCache: Record<string, unknown> | undefined\n\n/** The published `profile` shape, computed on FIRST tool-definition access and memoized — not at\n * module load. The conversion walks the whole canonical profile tree, and the strip walk rebuilds\n * it: 3.5ms on the first `createCoordinationTools`, 0.017ms on every later one (measured, Interface\n * 0.40, node 24). `src/runtime/index.ts` imports this module statically, so paying that at import\n * taxes every consumer of the kernel entrypoint — including the ones that never build a\n * coordination toolbox. The memo keeps it at once per process for the ones that do.\n *\n * Conversion choices. `io: 'input'` is the CALLER's view — pre-default, pre-transform — which is\n * what a spawning parent may pass, not what the runtime ends up holding. `unrepresentable: 'any'`\n * keeps the conversion total: the canonical schema contains transforms with no JSON Schema form,\n * and zod's default is to throw on them, which would leave the tool with no published shape. */\nfunction spawnProfileArg(): Record<string, unknown> {\n if (!spawnProfileArgCache) {\n const canonical = agentProfileSchema.toJSONSchema({\n io: 'input',\n target: 'draft-07',\n unrepresentable: 'any',\n })\n // Deep-frozen because ONE memoized object is handed to every coordination toolbox in the\n // process: an unfrozen shared schema lets one consumer's mutation corrupt every later one.\n spawnProfileArgCache = detachedFrozen(deriveSpawnProfileArg(canonical.properties))\n }\n return spawnProfileArgCache\n}\n\n/** Build the driver's MCP tools over a live scope. */\nexport function createCoordinationTools(opts: CoordinationToolsOptions): CoordinationTools {\n const deliverable = opts.deliverable\n let stopped = false\n let reason: string | undefined\n let stopNotified = false\n let submitted: { readonly result: unknown } | undefined\n let questionSeq = 0\n const ledger: SettledWorker[] = []\n const questions: QuestionRecord[] = [...(opts.priorQuestions ?? [])]\n const questionPolicy = opts.questionPolicy ?? 'auto'\n\n const notifyStop = (): void => {\n if (stopNotified) return\n stopNotified = true\n opts.onStop?.(reason)\n }\n\n // Keyed-assignment bookkeeping for the live-worker fence. `completedKeys` is every key this run\n // can already answer from committed work — seeded from the prior journal on a resume, extended as\n // keyed workers deliver in THIS process. A spawn under such a key starts nothing and occupies no\n // slot, so the fence must not hold it back. `keyByWorker` is what lets a settlement find its key.\n const completedKeys = new Set<string>()\n const keyByWorker = new Map<string, string>()\n // Worker id → the AUTHORED profile name it was spawned from. The stable identity an\n // `AnalyzeOnSettleRoute` names (`to`/`over`): labels are the driver's free-text choice, while\n // the profile name is what a graph pins a node by. Recorded at spawn, dropped never (a settled\n // source can still be matched by `over` after it is gone).\n const profileNameByWorker = new Map<string, string>()\n // Worker id → the live child Handle from its spawn. `Handle.abort` is the ONLY per-child abort\n // (its controller cascades to that child's subtree and no sibling), and the scope does not\n // re-expose it, so `abortWorker` must keep the handle from the spawn that minted it. Entries\n // are never deleted (liveness is re-checked against the view at abort time); the map is\n // bounded by the run's spawn count, like `profileNameByWorker`.\n const liveHandles = new Map<string, Handle<unknown>>()\n // `Scope` advances its node/cursor ordinals on resume, but assignment identity belongs to this\n // manager. Seed it independently from durable evidence so a restarted manager never calls new\n // work `ordinal:0` when a prior process already used that assignment. Use the maximum rather\n // than the number of rows: journals can contain gaps, keyed assignments, and legacy/custom ids.\n let unkeyedAssignmentOrdinal = nextUnkeyedAssignmentOrdinal(opts.scope)\n const preflightCounts = emptyPreflightCounts()\n for (const [key, prior] of opts.scope.resume?.keys ?? []) {\n if (prior.state === 'completed') completedKeys.add(key)\n }\n\n const nodeForWorker = (id: string) =>\n opts.scope.view.nodes.find((node) => node.id === id) ??\n opts.scope.resume?.view.nodes.find((node) => node.id === id)\n\n const projectSettled = (settled: Settled<unknown>, resumed = false): SettledWorker => {\n const node = nodeForWorker(settled.handle.id)\n const assignmentId = settled.handle.assignmentId ?? node?.assignmentId\n const identity = settled.handle.identity ?? node?.identity\n const materialization = settled.handle.materialization ?? node?.materialization\n const executionBindings = settled.handle.executionBindings ?? node?.executionBindings\n const settledAt = settled.settledAt ?? node?.settledAt\n const trace =\n settled.trace ??\n node?.trace ??\n ({\n status: 'unavailable',\n reason: 'legacy-settlement-without-trace-evidence',\n } as const)\n const common = {\n id: settled.handle.id,\n ...(assignmentId === undefined ? {} : { assignmentId }),\n ...(identity === undefined ? {} : { identity }),\n ...(materialization === undefined ? {} : { materialization }),\n ...(executionBindings === undefined ? {} : { executionBindings }),\n ...(settledAt === undefined ? {} : { settledAt }),\n trace,\n ...(resumed ? { resumed: true as const } : {}),\n }\n return detachedFrozen<SettledWorker>(\n settled.kind === 'done'\n ? {\n ...common,\n status: 'done',\n spent: settled.spent,\n ...(settled.verdict?.score === undefined ? {} : { score: settled.verdict.score }),\n ...(settled.verdict?.valid === undefined ? {} : { valid: settled.verdict.valid }),\n outRef: settled.outRef,\n }\n : {\n ...common,\n status: 'down',\n ...(node?.spent === undefined ? {} : { spent: node.spent }),\n reason: settled.reason,\n },\n )\n }\n\n // A resumed scope's replayed settlements enter the ledger AT CONSTRUCTION, so `settled()` — and\n // therefore the finalize that reads it — spans processes exactly as the journal does.\n const resumedWorkers: SettledWorker[] = []\n for (const s of opts.scope.resume?.settled ?? []) {\n const worker = projectSettled(s, true)\n resumedWorkers.push(worker)\n ledger.push(worker)\n }\n\n // The one child→parent pipe. Keep the event-first callback and also pass its exact stamp, so a\n // durable subscriber retains causal sequence, original timestamp, and priority.\n const bus = createEventBus<CoordinationEvent>()\n if (opts.onEvent) {\n const cb = opts.onEvent\n bus.subscribe((rec) => cb(rec.event, rec))\n }\n // A settlement can be durable in the spawn journal while the process dies before the product\n // observer acknowledges it. Opted-in high-level callers replay those events at least once. Keep\n // each frozen event object across an in-process retry so EventBus reuses its exact BusRecord.\n const resumeEvents = opts.replaySettlements\n ? resumedWorkers.map((worker) => detachedFrozen<CoordinationEvent>({ type: 'settled', worker }))\n : []\n let resumeEventIndex = 0\n let readyInFlight: Promise<void> | undefined\n const ready = (): Promise<void> => {\n if (resumeEventIndex >= resumeEvents.length) return Promise.resolve()\n if (readyInFlight) return readyInFlight\n readyInFlight = (async () => {\n while (resumeEventIndex < resumeEvents.length) {\n const event = resumeEvents[resumeEventIndex]\n if (!event) break\n await bus.publish(event)\n resumeEventIndex += 1\n }\n })().finally(() => {\n readyInFlight = undefined\n })\n return readyInFlight\n }\n\n // Urgency → bus priority: a blocking question is bumped ahead of queued settles/findings so the\n // driver sees it FIRST when it drains the inbox (and pass-through already delivered it the instant\n // it was raised). Non-blocking messages share priority 0 and resolve FIFO.\n const urgencyPriority = (u: QuestionUrgency): number =>\n u === 'blocks-run' ? 20 : u === 'blocks-step' ? 10 : 0\n\n const str = (v: unknown, field: string): string => {\n if (typeof v !== 'string' || v.length === 0)\n throw new Error(`coordination tools: \"${field}\" must be a non-empty string`)\n return v\n }\n const obj = (raw: unknown): Record<string, unknown> => {\n if (!raw || typeof raw !== 'object')\n throw new Error('coordination tools: arguments must be an object')\n return raw as Record<string, unknown>\n }\n // Parse a per-spawn `budget` override and merge it over the per-worker default (per field).\n // Fails loud on a non-object or a non-finite numeric field — a malformed budget must never\n // silently fall back to the default and run a sub-task on a ceiling nobody chose.\n const mergeBudget = (base: Budget, raw: unknown): Budget => {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw))\n throw new Error('coordination tools: \"budget\" must be an object')\n const o = raw as Record<string, unknown>\n const field = (name: keyof Budget): number | undefined => {\n const v = o[name]\n if (v === undefined) return undefined\n if (typeof v !== 'number' || !Number.isFinite(v))\n throw new Error(`coordination tools: \"budget.${name}\" must be a finite number`)\n return v\n }\n const maxIterations = field('maxIterations')\n const maxTokens = field('maxTokens')\n const maxUsd = field('maxUsd')\n const deadlineMs = field('deadlineMs')\n const merged: Budget = {\n maxIterations: maxIterations ?? base.maxIterations,\n maxTokens: maxTokens ?? base.maxTokens,\n ...((maxUsd ?? base.maxUsd) === undefined ? {} : { maxUsd: maxUsd ?? base.maxUsd }),\n ...((deadlineMs ?? base.deadlineMs) === undefined\n ? {}\n : { deadlineMs: deadlineMs ?? base.deadlineMs }),\n }\n assertValidBudget(merged, 'coordination tools: budget')\n return merged\n }\n const level = (v: unknown): Question['level'] => {\n if (v === 'worker' || v === 'driver' || v === 'loop') return v\n throw new Error('coordination tools: \"level\" must be worker, driver, or loop')\n }\n const urgency = (v: unknown): Question['urgency'] => {\n if (v === 'continue-without' || v === 'blocks-step' || v === 'blocks-run') return v\n throw new Error(\n 'coordination tools: \"urgency\" must be continue-without, blocks-step, or blocks-run',\n )\n }\n\n const commitSettled = (s: Settled<unknown>, w: SettledWorker): void => {\n // A keyed assignment that just delivered is complete for the rest of this run, so a later\n // spawn under the same key resolves for free instead of being held behind the live-worker\n // fence (it starts no worker, so it occupies no slot).\n const settledKey = keyByWorker.get(s.handle.id)\n if (settledKey !== undefined && s.kind === 'done') completedKeys.add(settledKey)\n ledger.push(w)\n // A settled worker's trace source is finished; drop the online subscription with it.\n unwatchWorker(w.id)\n }\n\n // `Scope.next()` is once-only, while an awaited observer may commit and lose its acknowledgement.\n // Retain the exact event until publication succeeds so the next await retries rather than losing\n // the settlement between the spawn journal and the product transaction. `analystRun` marks a\n // settlement that IS an analyst-agent's findings (see `analystRuns`), whose event is a `finding`.\n let pendingSettlement:\n | {\n readonly settled: Settled<unknown>\n readonly worker: SettledWorker\n readonly event: CoordinationEvent\n readonly analyze: boolean\n readonly analystRun?: AnalystRunInFlight\n }\n | undefined\n\n // Analyst-AGENT runs in flight (`AnalyzeOnSettleRoute.agent`): worker id → the route that\n // spawned it + the settled source worker whose evidence it analyzes. A member's settlement is a\n // FINDING, not a worker settle: it never enters the settled ledger, never feeds the finalizer,\n // and never re-fires the analyst-on-settle hook — so an analyst cannot cascade onto itself.\n interface AnalystRunInFlight {\n readonly route: AnalyzeOnSettleRoute\n readonly sourceWorker: string\n }\n // PROCESS-LOCAL by design: a durable-run RESUME does not repopulate this map, so an\n // analyst spawn from a PRIOR process settles as an ordinary worker on resume (it re-enters\n // the settled ledger instead of being intercepted as a finding). Journal-level marking of\n // analyst assignments is the fix; until then resume + analyst-node graphs do not compose.\n const analystRuns = new Map<string, AnalystRunInFlight>()\n let analystRunOrdinal = 0\n\n /** The `finding` event an analyst-agent settlement becomes: its settle OUTPUT is the findings\n * (a failed run publishes the failure as findings — degraded beats vanished). */\n const analystRunFinding = (\n run: AnalystRunInFlight,\n settled: Settled<unknown>,\n ): CoordinationEvent =>\n detachedFrozen<CoordinationEvent>({\n type: 'finding',\n finding: canonicalFindingEvent({\n fromWorker: run.sourceWorker,\n analyst: run.route.kind,\n findings: settled.kind === 'done' ? settled.out : { analystRunFailed: settled.reason },\n }),\n })\n\n /**\n * Spawn one analyst-AGENT run over a settled worker's evidence, through the SAME spawn\n * machinery a driver spawn uses (`scope.spawn` + `makeWorkerAgent`): the analyst's spend\n * reserves from the conserved pool, its node is journaled/traced like any worker, and a\n * node-pinning seam sees `context.analyst`. Its task is the route directive plus the settled\n * worker's persisted tool-trace spans. A refused spawn publishes a finding RECORDING the\n * refusal — observable, never silent — and must never take down the settlement path.\n */\n const spawnAnalystRun = async (\n route: AnalyzeOnSettleRoute,\n worker: SettledWorker,\n ): Promise<void> => {\n let spansText = ''\n let spanCount = 0\n if (worker.trace.status === 'available') {\n try {\n const raw = await opts.blobs.get(worker.trace.traceRef)\n const artifact = parseWorkerToolTraceArtifact(raw, worker.trace.traceRef)\n spanCount = artifact.spans.length\n spansText = safeJsonText(artifact.spans)\n } catch {\n spansText = '' // degraded evidence is stated below, never a thrown settle path\n }\n }\n const task = [\n ...(route.directive === undefined || route.directive.length === 0 ? [] : [route.directive]),\n `Evidence — settled worker '${worker.id}' tool trace (${spanCount} spans):`,\n spansText.length === 0 ? '(no tool spans available)' : spansText,\n ].join('\\n\\n')\n const assignmentId = `analyst:${route.kind}:o${analystRunOrdinal++}`\n const label = `analyst:${route.kind}`\n const context: WorkerSpawnContext = Object.freeze({\n assignmentId,\n parentNodeId: opts.scope.view.root,\n budget: opts.perWorker,\n task,\n label,\n analyst: route.kind,\n // An analyst run is always a brand-new session over settled evidence — never a resume.\n continuity: 'fresh' as const,\n })\n let refusal: string | undefined\n let spawnedId: string | undefined\n try {\n const res = opts.scope.spawn(\n () => opts.makeWorkerAgent(route.agent as AgentProfile, context),\n task,\n { budget: opts.perWorker, label, assignmentId },\n )\n if (res.ok) spawnedId = res.handle.id\n else refusal = String(res.reason)\n } catch (cause) {\n refusal = cause instanceof Error ? cause.message : String(cause)\n }\n if (spawnedId === undefined) {\n await bus.publish({\n type: 'finding',\n finding: canonicalFindingEvent({\n fromWorker: worker.id,\n analyst: route.kind,\n findings: { analystSpawnRefused: refusal ?? 'unknown' },\n }),\n })\n return\n }\n analystRuns.set(spawnedId, { route, sourceWorker: worker.id })\n watchWorker(spawnedId)\n }\n\n // The names an analyst route may know a worker by: its authored profile name (the stable node\n // identity) and its spawn label (the driver's free-text choice).\n const workerRouteNames = (workerId: string): Set<string> => {\n const names = new Set<string>()\n const profileName = profileNameByWorker.get(workerId)\n if (profileName !== undefined) names.add(profileName)\n const label = nodeForWorker(workerId)?.label\n if (label !== undefined) names.add(label)\n return names\n }\n\n /** The LIVE worker a route destination names, by profile name first, label second. */\n const liveWorkerIdNamed = (destination: string): string | undefined => {\n const live = opts.scope.view.nodes.filter((node) => isLiveNodeStatus(node.status))\n return (\n live.find((node) => profileNameByWorker.get(node.id) === destination)?.id ??\n live.find((node) => node.label === destination)?.id\n )\n }\n\n // ── Continuity: how a spawn continues a node's prior work ──\n // Node identity is the PROFILE NAME only (never the label): resume re-attaches to a specific\n // prior session, and the label is the driver's free-text choice. All three reads are\n // process-local by construction — `profileNameByWorker` records only this process's spawns —\n // which is the documented resume boundary (a prior process's workers are not resume targets).\n const liveWorkerForNode = (name: string): string | undefined =>\n opts.scope.view.nodes.find(\n (node) => isLiveNodeStatus(node.status) && profileNameByWorker.get(node.id) === name,\n )?.id\n const latestSettledWorkerForNode = (name: string): string | undefined => {\n for (let i = ledger.length - 1; i >= 0; i -= 1) {\n const worker = ledger[i] as SettledWorker\n if (profileNameByWorker.get(worker.id) === name) return worker.id\n }\n return undefined\n }\n const nodeSpawnCount = (name: string): number => {\n let count = 0\n for (const profileName of profileNameByWorker.values()) if (profileName === name) count += 1\n return count\n }\n const parseContinuity = (v: unknown): ContinuityMode | undefined => {\n if (v === undefined) return undefined\n if (v === 'fresh' || v === 'resume') return v\n throw new Error('coordination tools: \"continuity\" must be \"fresh\" or \"resume\"')\n }\n type ResolvedContinuity =\n | { readonly continuity: 'fresh' }\n | { readonly continuity: 'resume'; readonly resume: WorkerResumeContext }\n | { readonly error: string; readonly hint: string }\n /**\n * Resolve the EFFECTIVE continuity of one spawn: the per-call request wins, else the profile\n * name's declared default, else `'fresh'`. Every refusal is loud and actionable:\n * - an EXPLICIT `'resume'` with no settled prior worker refuses (`resume-no-prior`) — the\n * DECLARED default degrades to `'fresh'` instead, so a resume edge's first traversal is\n * simply the first spawn;\n * - resume while a prior worker of the node is still LIVE refuses (`resume-while-live`) —\n * that is what steer is for, and the error says so;\n * - resume under a semantic `key` refuses (`resume-with-key`) — a key makes an assignment\n * run-once, resume explicitly runs the node again.\n */\n const resolveContinuity = (\n requested: ContinuityMode | undefined,\n profileName: string | undefined,\n key: string | undefined,\n ): ResolvedContinuity => {\n const declared =\n profileName === undefined ? 'fresh' : (opts.continuityByProfile?.[profileName] ?? 'fresh')\n const wantsResume = requested === 'resume' || (requested === undefined && declared === 'resume')\n if (!wantsResume) return { continuity: 'fresh' }\n if (profileName === undefined || profileName.length === 0) {\n return {\n error: 'resume-unnamed-profile',\n hint:\n 'Resume targets a node by profile.name — the stable node identity — and this profile ' +\n 'has none. Name the profile, or spawn fresh.',\n }\n }\n if (key !== undefined) {\n return {\n error: 'resume-with-key',\n hint:\n 'A semantic key makes an assignment run-once (a completed key returns its committed ' +\n 'result instead of running again); resume explicitly runs the node AGAIN. Drop the ' +\n 'key to resume, or keep the key and spawn fresh.',\n }\n }\n const live = liveWorkerForNode(profileName)\n if (live !== undefined) {\n return {\n error: 'resume-while-live',\n hint:\n `Worker '${live}' on node '${profileName}' is still LIVE — resume re-attaches to a ` +\n 'SETTLED session. To redirect the live worker, use steer_agent (that is the ' +\n \"live-worker channel); to run a parallel sibling instead, pass continuity: 'fresh'.\",\n }\n }\n const prior = latestSettledWorkerForNode(profileName)\n if (prior === undefined) {\n // The DECLARED default asked for resume-when-possible; with nothing to resume this is the\n // node's effective first spawn. Only an explicit per-call demand fails loud here.\n if (requested === undefined) return { continuity: 'fresh' }\n return {\n error: 'resume-no-prior',\n hint:\n `Node '${profileName}' has no settled prior worker in this process to resume — ` +\n 'resume continues a FINISHED session. Spawn the node fresh first (omit continuity or ' +\n \"pass 'fresh').\",\n }\n }\n return {\n continuity: 'resume',\n resume: { ofWorker: prior, sequence: nodeSpawnCount(profileName) + 1 },\n }\n }\n\n /**\n * Deliver one routed analyst finding to its destination worker through the SAME authorized\n * steer machinery a driver steer uses, so the delivery is recorded (`steer` event carrying\n * `analyst`) and its outcome is a fact. No live destination ⇒ a record-only failed steer —\n * observable, never a silent drop. A throw here must not kill the settle path: failures are\n * recorded on the bus (a `steer` with `delivered: false`) before being swallowed, with ONE\n * narrow exception — a bus that refuses the `delivery-attempt` record itself leaves only the\n * `instruction` receipt (an attempt with no outcome = explicitly unknown, per\n * recordDeliveryAttempt's own contract).\n */\n const deliverRoutedFinding = async (\n route: AnalyzeOnSettleRoute,\n findings: AnalystLensOutput | unknown,\n ): Promise<void> => {\n const destination = route.to as string\n const text =\n route.directive === undefined || route.directive.length === 0\n ? safeJsonText(findings)\n : `${route.directive}\\n\\n${safeJsonText(findings)}`\n const targetId = liveWorkerIdNamed(destination)\n if (targetId === undefined) {\n await bus.publish(\n {\n type: 'steer',\n down: detachedFrozen({\n receiptId: randomUUID(),\n toWorker: destination,\n instruction: text,\n instructionDigest: canonicalCandidateDigest(text),\n delivered: false,\n outcome: 'unknown-worker' as const,\n }),\n analyst: route.kind,\n },\n { queue: false },\n )\n return\n }\n let instruction: ContinuationInstruction\n try {\n instruction = authorizeInstruction('steer', targetId, text, false)\n await recordInstruction(instruction)\n } catch (cause) {\n // NOTHING reached the bus for this failure (an authorization refusal, a target without\n // durable identity, a durable subscriber rejecting the instruction record) — record the\n // failed delivery now, in the same `steer` shape a failed attempt publishes, so a routed\n // finding is observable on EVERY failure path, never a silent drop.\n try {\n await sendDown(\n 'steer',\n detachedFrozen({\n receiptId: randomUUID(),\n toWorker: targetId,\n instruction: text,\n instructionDigest: canonicalCandidateDigest(text),\n delivered: false,\n outcome: 'runtime-error' as const,\n error: cause instanceof Error ? cause.message : String(cause),\n }),\n route.kind,\n )\n } catch {\n // The bus itself refused the failure record — there is nothing left to record ON, and a\n // routed finding must never take down the settlement path.\n }\n return\n }\n try {\n await attemptDelivery(\n instruction,\n { steer: instruction.instruction, interrupt: false },\n {\n analyst: route.kind,\n },\n )\n } catch {\n // `attemptDelivery` publishes the failed `steer` (delivered:false + outcome) BEFORE\n // rethrowing, so the failure is already on the bus — except when the bus refused the\n // `delivery-attempt` record itself, where only the `instruction` receipt lands (see the\n // docstring). A routed finding must never take down the settlement path.\n }\n }\n\n const flushPendingSettlement = async (): Promise<boolean> => {\n const pending = pendingSettlement\n if (!pending) return false\n await bus.publish(pending.event)\n // An analyst-AGENT settlement IS its finding (just published): it never enters the settled\n // ledger or the finalizer, and it re-fires no analyst hook. Its routed delivery goes through\n // the exact machinery a registry-analyst finding uses — with no wrap directive, because the\n // route's directive was already consumed as the analyst's task.\n if (pending.analystRun) {\n analystRuns.delete(pending.worker.id)\n unwatchWorker(pending.worker.id)\n pendingSettlement = undefined\n const { route } = pending.analystRun\n if (route.to !== undefined && pending.event.type === 'finding') {\n await deliverRoutedFinding(\n { kind: route.kind, to: route.to },\n pending.event.finding.findings,\n )\n }\n return true\n }\n commitSettled(pending.settled, pending.worker)\n pendingSettlement = undefined\n if (\n pending.analyze &&\n pending.worker.status === 'done' &&\n pending.worker.trace.status === 'available' &&\n opts.analyzeOnSettle?.length\n ) {\n const routes = opts.analyzeOnSettle.map(normalizeAnalyzeOnSettle)\n const sourceNames = workerRouteNames(pending.worker.id)\n const applicable = routes.filter(\n (route) => route.over === undefined || route.over.some((name) => sourceNames.has(name)),\n )\n // Registry lenses run in-process over the trace store; agent analysts spawn as workers.\n const lensRoutes = applicable.filter((route) => route.agent === undefined)\n const agentRoutes = applicable.filter((route) => route.agent !== undefined)\n if (lensRoutes.length > 0 && opts.analysts) {\n const trace = await workerTraceAnalysisStore(pending.worker.trace, opts.blobs)\n for (const route of lensRoutes) {\n const findings = await opts.analysts.run(route.kind, trace)\n // The finding ALWAYS lands on the bus — the audit trail and the driver's pullable copy —\n // whether or not the route also delivers it to a named worker.\n await bus.publish({\n type: 'finding',\n finding: canonicalFindingEvent({\n fromWorker: pending.worker.id,\n analyst: route.kind,\n findings,\n }),\n })\n if (route.to !== undefined) await deliverRoutedFinding(route, findings)\n }\n }\n for (const route of agentRoutes) await spawnAnalystRun(route, pending.worker)\n }\n return true\n }\n\n // Producer: drain exactly one settlement from the scope cursor onto the bus (a `settled` event),\n // then fire the analyst-on-settle hook — auto-run each configured lens over the worker's trace and\n // publish its result as a `finding`. Returns false when the cursor is idle (no live workers). The\n // cursor is a once-per-child source, so a settlement is produced at most once.\n const drainSettlement = async (): Promise<boolean> => {\n if (!pendingSettlement) {\n const settled = await opts.scope.next()\n if (!settled) return false\n const worker = projectSettled(settled)\n const run = analystRuns.get(settled.handle.id)\n pendingSettlement = run\n ? {\n settled,\n worker,\n event: analystRunFinding(run, settled),\n analyze: false,\n analystRun: run,\n }\n : {\n settled,\n worker,\n event: detachedFrozen<CoordinationEvent>({ type: 'settled', worker }),\n analyze: true,\n }\n }\n return flushPendingSettlement()\n }\n\n // Post-loop drain: every ALREADY-settled, unpulled child enters the ledger + audit trail. No\n // analyst-on-settle here — the driver has stopped, so a finding has no reader and an analyst\n // spawn would spend real compute for nothing. An analyst-agent run ALREADY in flight is not a\n // new spawn: its settlement still becomes its finding (the audit trail must not lose paid-for\n // findings), though a routed delivery will usually record `delivered:false` this late.\n const drainResolved = async (): Promise<number> => {\n let drained = 0\n for (;;) {\n if (!pendingSettlement) {\n const settled = await opts.scope.nextResolved()\n if (!settled) return drained\n const worker = projectSettled(settled)\n const run = analystRuns.get(settled.handle.id)\n pendingSettlement = run\n ? {\n settled,\n worker,\n event: analystRunFinding(run, settled),\n analyze: false,\n analystRun: run,\n }\n : {\n settled,\n worker,\n event: detachedFrozen<CoordinationEvent>({ type: 'settled', worker }),\n analyze: false,\n }\n }\n await flushPendingSettlement()\n drained += 1\n }\n }\n\n // The down-leg: record a parent→child message on the bus for the audit trail (history +\n // subscribers) WITHOUT enqueuing it — the parent must never pull its own outbound message back.\n // Overloaded so the `answer` kind REQUIRES a questionId (no silent `?? ''` fallback to mask a bug).\n function sendDown(type: 'steer', down: DownMessageEvent, analyst?: string): Promise<void>\n function sendDown(type: 'answer', down: DownMessageEvent, questionId: string): Promise<void>\n async function sendDown(\n type: 'steer' | 'answer',\n down: DownMessageEvent,\n questionIdOrAnalyst?: string,\n ): Promise<void> {\n await bus.publish(\n type === 'answer'\n ? { type, down, questionId: str(questionIdOrAnalyst, 'questionId') }\n : questionIdOrAnalyst !== undefined\n ? { type, down, analyst: questionIdOrAnalyst }\n : { type, down },\n { queue: false },\n )\n }\n\n const authorizeInstruction = (\n kind: 'steer' | 'answer',\n workerId: string,\n instruction: string,\n interrupt: boolean,\n questionId?: string,\n ): ContinuationInstruction => {\n const workerIdentity = opts.scope.view.nodes.find((node) => node.id === workerId)?.identity\n let authorizedInstruction = instruction\n if (opts.authorizeDownMessage) {\n if (workerIdentity === undefined) {\n throw new Error(\n `coordination tools: cannot authorize ${kind} for worker ${JSON.stringify(workerId)} without durable identity`,\n )\n }\n const decision = detachedFrozen(\n opts.authorizeDownMessage(\n detachedFrozen({\n kind,\n workerId,\n workerIdentity,\n instruction,\n interrupt,\n ...(questionId !== undefined ? { questionId } : {}),\n }),\n ),\n )\n if (\n typeof decision !== 'object' ||\n decision === null ||\n Array.isArray(decision) ||\n typeof decision.instruction !== 'string' ||\n decision.instruction.length === 0\n ) {\n throw new Error('coordination tools: authorizeDownMessage must return an instruction')\n }\n authorizedInstruction = decision.instruction\n }\n return detachedFrozen({\n receiptId: randomUUID(),\n kind,\n toWorker: workerId,\n instruction: authorizedInstruction,\n instructionDigest: canonicalCandidateDigest(authorizedInstruction),\n ...(workerIdentity !== undefined ? { workerIdentity } : {}),\n interrupt,\n ...(questionId !== undefined ? { questionId } : {}),\n })\n }\n\n /** Publish before `scope.send`: an awaited durable subscriber therefore commits the exact bytes\n * before the worker can observe them. */\n const recordInstruction = async (instruction: ContinuationInstruction): Promise<void> => {\n await bus.publish({ type: 'instruction', instruction }, { queue: false })\n }\n\n /** Commit delivery intent after the authorization receipt and before `Scope.send`. An attempt with\n * no matching outcome after a crash is explicitly unknown and must never be replayed. */\n const recordDeliveryAttempt = async (\n instruction: ContinuationInstruction,\n ): Promise<DownMessageDeliveryAttempt> => {\n const attempt = detachedFrozen({\n receiptId: instruction.receiptId,\n kind: instruction.kind,\n toWorker: instruction.toWorker,\n instructionDigest: instruction.instructionDigest,\n interrupt: instruction.interrupt,\n ...(instruction.questionId !== undefined ? { questionId: instruction.questionId } : {}),\n })\n await bus.publish({ type: 'delivery-attempt', attempt }, { queue: false })\n return attempt\n }\n\n const deliveryOutcome = (workerId: string, delivered: boolean): DownMessageDeliveryOutcome => {\n if (delivered) return 'delivered'\n if (opts.scope.signal.aborted) return 'scope-stopped'\n const node = opts.scope.view.nodes.find((candidate) => candidate.id === workerId)\n if (!node) return 'unknown-worker'\n if (!isLiveNodeStatus(node.status)) return 'already-settled'\n return 'runtime-has-no-inbox'\n }\n\n const attemptDelivery = async (\n instruction: ContinuationInstruction,\n message: unknown,\n origin?: { readonly analyst?: string },\n ): Promise<DownMessageEvent> => {\n await recordDeliveryAttempt(instruction)\n let delivered = false\n let outcome: DownMessageDeliveryOutcome\n let error: string | undefined\n try {\n delivered = opts.scope.send(instruction.toWorker, message)\n outcome = deliveryOutcome(instruction.toWorker, delivered)\n } catch (cause) {\n outcome = 'runtime-error'\n error = cause instanceof Error ? cause.message : String(cause)\n }\n const down = detachedFrozen({\n receiptId: instruction.receiptId,\n toWorker: instruction.toWorker,\n instruction: instruction.instruction,\n instructionDigest: instruction.instructionDigest,\n delivered,\n outcome,\n ...(error !== undefined ? { error } : {}),\n })\n if (instruction.kind === 'answer') {\n await sendDown('answer', down, str(instruction.questionId, 'questionId'))\n } else {\n await sendDown('steer', down, origin?.analyst)\n }\n if (error !== undefined) throw new Error(`coordination tools: delivery failed: ${error}`)\n return down\n }\n\n const steerWorker = async (\n workerId: string,\n instruction: string,\n options: { readonly interrupt?: boolean } = {},\n ): Promise<DownMessageEvent> => {\n const interrupt = options.interrupt === true\n const authorized = authorizeInstruction('steer', workerId, instruction, interrupt)\n await recordInstruction(authorized)\n return await attemptDelivery(authorized, {\n steer: authorized.instruction,\n interrupt,\n })\n }\n\n // Consumer projection: the wire shape the driver sees for a pulled bus event.\n const projectEvent = (ev: CoordinationEvent): Record<string, unknown> => {\n if (ev.type === 'settled') {\n const { id, status, ...evidence } = ev.worker\n return { type: 'settled', settled: id, status, ...evidence }\n }\n if (ev.type === 'question') return { type: 'question', question: ev.question }\n if (ev.type === 'finding') return { type: 'finding', ...ev.finding }\n if (ev.type === 'answer') return { type: 'answer', ...ev.down, questionId: ev.questionId }\n if (ev.type === 'instruction') return { type: 'instruction', ...ev.instruction }\n if (ev.type === 'delivery-attempt') return { type: 'delivery-attempt', ...ev.attempt }\n // Peer mail is sideways and record-only, so the driver never pulls it either. Projected\n // explicitly rather than through the `down` fallback below: a member with no `down` property\n // spread through that fallback would yield a bare `{ type }` and drop the whole payload.\n if (ev.type === 'mail') return { type: 'mail', ...ev.mail }\n // Down-leg `steer` is record-only (never queued), so the driver never pulls it; project\n // defensively for completeness.\n return { type: ev.type, ...ev.down }\n }\n\n // The sibling channel, when this run enabled it. Publishing is record-only (`queue: false`) for\n // the same reason a steer is: the parent audits and can stop a thread, but peer traffic must not\n // enter the queue the driver pulls from — a busy channel would otherwise starve `await_event` of\n // the settlements and questions it exists to deliver.\n const peerMail: PeerMailbox | undefined = opts.peerMail\n ? createPeerMailbox({\n scope: opts.scope,\n publish: (mail) =>\n bus.publish({ type: 'mail', mail }, { queue: false }).then(() => undefined),\n ...(opts.peerMail.limits ? { limits: opts.peerMail.limits } : {}),\n })\n : undefined\n\n const nextQuestionId = (from: string): string => {\n for (;;) {\n const id = `${from}:q${questionSeq++}`\n if (!questions.some((question) => question.id === id)) return id\n }\n }\n const normalizeQuestion = (q: QuestionInput, fallbackFrom: string): Question => {\n const from = str(q.from ?? fallbackFrom, 'from')\n return {\n id: typeof q.id === 'string' && q.id.length > 0 ? q.id : nextQuestionId(from),\n from,\n level: level(q.level),\n question: str(q.question, 'question'),\n reason: str(q.reason, 'reason'),\n ...(q.options ? { options: q.options } : {}),\n urgency: urgency(q.urgency),\n }\n }\n const addQuestion = (\n raw: QuestionInput,\n fallbackFrom: string,\n decision?: QuestionDecision,\n ): { question: QuestionRecord; added: boolean } => {\n const q = normalizeQuestion(raw, fallbackFrom)\n const existing = questions.find((x) => x.id === q.id)\n if (existing) return { question: existing, added: false }\n const effectiveDecision =\n decision ??\n (questionPolicy === 'bubble'\n ? ({\n kind: 'escalate',\n to: 'parent',\n reason: 'question policy bubbled to parent',\n } as const)\n : undefined)\n const status: QuestionRecord['status'] =\n effectiveDecision?.kind === 'answer'\n ? 'answered'\n : effectiveDecision?.kind === 'defer'\n ? 'deferred'\n : effectiveDecision?.kind === 'escalate'\n ? 'escalated'\n : 'open'\n const record: QuestionRecord = {\n ...q,\n status,\n openedAt: Date.now(),\n ...(effectiveDecision ? { decision: effectiveDecision } : {}),\n }\n questions.push(record)\n return { question: record, added: true }\n }\n const emitNewQuestion = async (record: {\n question: QuestionRecord\n added: boolean\n }): Promise<QuestionRecord> => {\n if (record.added)\n await bus.publish(\n { type: 'question', question: record.question },\n { priority: urgencyPriority(record.question.urgency) },\n )\n return record.question\n }\n const decideQuestion = (questionId: string, decision: QuestionDecision): QuestionRecord => {\n const idx = questions.findIndex((q) => q.id === questionId)\n if (idx < 0) throw new Error(`unknown questionId ${JSON.stringify(questionId)}`)\n const prior = questions[idx] as QuestionRecord\n const status: QuestionRecord['status'] =\n decision.kind === 'answer' ? 'answered' : decision.kind === 'defer' ? 'deferred' : 'escalated'\n const next: QuestionRecord = { ...prior, status, decision }\n questions[idx] = next\n return next\n }\n const blockingQuestionsForStop = (): QuestionRecord[] => {\n if (questionPolicy === 'auto' || questionPolicy === 'bubble') return []\n return questions.filter((q) => {\n const blocking = q.urgency === 'blocks-step' || q.urgency === 'blocks-run'\n if (!blocking) return false\n if (questionPolicy === 'mustDecide') return q.status === 'open'\n return q.status !== 'answered' && q.status !== 'deferred'\n })\n }\n\n // A supervised tree exposes one shared capacity reading; a caller-owned legacy scope falls back\n // to this toolbox's direct-child count. The shared reading is what prevents each nested manager\n // from multiplying the same cap independently.\n const maxLiveWorkers = opts.maxLiveWorkers\n const localLiveWorkerCount = (): number =>\n opts.scope.view.nodes.filter((n) => isLiveNodeStatus(n.status)).length\n const sharedWorkerCapacity = (): Scope<unknown>['workerCapacity'] | undefined => {\n const scope = opts.scope as Partial<Scope<unknown>>\n return scope.workerCapacity\n }\n const usesTreeWideLimit = (): boolean => {\n const capacity = sharedWorkerCapacity()\n return capacity !== undefined && capacity.freeSlots !== null\n }\n const liveWorkerCount = (): number =>\n usesTreeWideLimit()\n ? (sharedWorkerCapacity()?.live ?? localLiveWorkerCount())\n : localLiveWorkerCount()\n\n // A snapshot of every still-in-flight worker — the liveness signal a bounded `await_event`\n // returns when its wait elapses, so the supervisor can tell \"worker still running, keep waiting\"\n // apart from \"nothing is happening\" (the distinction it lost when the unbounded await erred out).\n const projectNodeEvidence = (\n node: Scope<unknown>['view']['nodes'][number],\n resumed = false,\n ): Record<string, unknown> => ({\n id: node.id,\n status: node.status,\n ...(node.assignmentId === undefined ? {} : { assignmentId: node.assignmentId }),\n ...(node.identity === undefined ? {} : { identity: node.identity }),\n ...(node.materialization === undefined ? {} : { materialization: node.materialization }),\n ...(node.executionBindings === undefined ? {} : { executionBindings: node.executionBindings }),\n spent: node.spent,\n ...(node.settledAt === undefined ? {} : { settledAt: node.settledAt }),\n ...(node.outRef === undefined ? {} : { outRef: node.outRef }),\n ...(node.trace === undefined ? {} : { trace: node.trace }),\n ...(resumed ? { resumed: true } : {}),\n })\n\n const liveSnapshot = (): Array<Record<string, unknown>> =>\n opts.scope.view.nodes\n .filter((n) => isLiveNodeStatus(n.status))\n .map((n) => projectNodeEvidence(n))\n\n // How many workers the driver could open RIGHT NOW without hitting the simultaneity fence, or\n // `null` when no cap is set (the conserved pool is then the only fence, so there is no finite\n // slot count). Without this the brain could see WHO is running but never that capacity was idle,\n // so filling N slots meant emitting N blind tool calls with no feedback telling it to — the\n // mechanical reason a 5-worker run peaked at 2 live workers. Policy (whether to fill) stays with\n // the driver; this is only the reading.\n const freeWorkerSlots = (): number | null =>\n usesTreeWideLimit()\n ? (sharedWorkerCapacity()?.freeSlots ?? null)\n : freeSlots(localLiveWorkerCount(), maxLiveWorkers)\n\n // The LIVE read of one worker. Guarded because `createCoordinationTools` is bound to a `Scope`\n // it did not construct — an older or hand-rolled scope may not implement `progress` at all, and\n // an observation must degrade to \"no progress available\", never throw at the driver.\n const readProgress = (id: string): WorkerProgress | undefined => {\n const scope = opts.scope as Partial<Scope<unknown>>\n if (typeof scope.progress !== 'function') return undefined\n try {\n return scope.progress(\n id,\n opts.stallAfterMs !== undefined ? { stallAfterMs: opts.stallAfterMs } : {},\n )\n } catch {\n return undefined\n }\n }\n\n // ONLINE detection: subscribe the streaming detector panel to a freshly-spawned worker's live\n // tool trace, and turn each signal into a `finding` the driver pulls from `await_event`. The\n // unsubscribe fires on the worker's settle (its trace source is dead from then on) and the\n // per-worker cap stops one looping worker from flooding the bus.\n const watchers = new Map<string, () => void>()\n const watchWorker = (id: string): void => {\n const watch = opts.watchWorkers\n if (!watch) return\n const scope = opts.scope as Partial<Scope<unknown>>\n if (typeof scope.traceSource !== 'function') return\n let source: ReturnType<NonNullable<Scope<unknown>['traceSource']>>\n try {\n source = scope.traceSource(id)\n } catch {\n return\n }\n if (!source) return\n const cap = watch.maxFindingsPerWorker ?? 3\n let raised = 0\n const unsub = watchTrace(source, {\n ...(watch.detectors ? { detectors: watch.detectors } : {}),\n onSignal: async (signal, span) => {\n if (cap > 0 && raised >= cap) return\n raised += 1\n await bus.publish({\n type: 'finding',\n // canonicalFindingEvent: `span.toolName` is optional — an undefined value anywhere in\n // the payload would throw in the digesting subscriber and vanish the event.\n finding: canonicalFindingEvent({\n fromWorker: id,\n analyst: `online:${signal.detector}`,\n findings: {\n detector: signal.detector,\n severity: signal.severity,\n reason: signal.reason,\n streak: signal.streak,\n ...(signal.failureClass ? { failureClass: signal.failureClass } : {}),\n toolName: span.toolName,\n at: span.endedAt,\n progress: readProgress(id),\n },\n }),\n })\n },\n })\n watchers.set(id, unsub)\n }\n const unwatchWorker = (id: string): void => {\n const unsub = watchers.get(id)\n if (!unsub) return\n watchers.delete(id)\n try {\n unsub()\n } catch {\n // an unsubscribe that throws must never break the settle path\n }\n }\n\n // The blocking `scope.next()` (via `drainSettlement`) waits on a LIVE worker for its whole run.\n // Keep at most ONE such drain in flight and let every concurrent `await_event` race THAT single\n // promise against a timeout — so a bounded call never starts a second unbounded block, and the\n // one drain still delivers the settlement (exactly-once via the scope cursor) whenever it lands.\n const awaitTimeoutMs = opts.awaitTimeoutMs ?? DEFAULT_AWAIT_EVENT_TIMEOUT_MS\n let inFlightDrain: Promise<boolean> | null = null\n const ensureDrain = (): Promise<boolean> => {\n if (!inFlightDrain)\n inFlightDrain = drainSettlement().finally(() => {\n inFlightDrain = null\n })\n return inFlightDrain\n }\n // Resolve `{ drained }` if the drain wins, or `undefined` if the bound elapses first. A `<= 0`\n // bound restores the prior unbounded block (no timer): the caller opted out of the fence.\n const raceDrainWithTimeout = async (\n drain: Promise<boolean>,\n ): Promise<{ drained: boolean } | undefined> => {\n if (awaitTimeoutMs <= 0) return { drained: await drain }\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), awaitTimeoutMs)\n // Never let this fence-timer alone keep the process alive (e.g. at teardown).\n if (typeof timer?.unref === 'function') timer.unref()\n })\n try {\n return await Promise.race([drain.then((drained) => ({ drained })), timeout])\n } finally {\n if (timer) clearTimeout(timer)\n }\n }\n\n const tools: McpToolDescriptor[] = [\n {\n name: 'spawn_agent',\n description:\n 'Start a worker the driver will drive. `profile` is the worker or another driver; ' +\n '`task` is what it should do. Reserves budget from the conserved pool and fails closed. ' +\n 'Pass an optional `budget` (per-field) to give a hard sub-task more than the default — it ' +\n 'merges over the per-worker default; the conserved pool is still the hard fence. When a ' +\n 'max-live-workers cap is set it also fails closed (`error: \"max-live-workers\"`) while that ' +\n 'many workers are still in flight — settle or steer one before spawning another. ' +\n 'Pass a `key` naming the assignment to make it run-once ACROSS restarts: a key that ' +\n 'already completed returns the finished result (`resumed: \"completed\"` — no work re-runs, ' +\n 'nothing is spent), a key whose prior attempt failed or was lost with a dead process ' +\n 'spawns fresh and says so (`resumed: \"retried\" | \"lost\"`), and a key still running is ' +\n 'refused (`error: \"duplicate-key\"`). ' +\n 'Returns `freeSlots`: how many MORE workers you can start right now (`null` = uncapped). ' +\n 'While `freeSlots > 0` there is idle capacity — call this again to fill it rather than ' +\n 'waiting; parallel workers finish the run sooner than one at a time.',\n inputSchema: {\n type: 'object',\n properties: {\n profile: spawnProfileArg(),\n task: { description: 'The task the worker should perform.' },\n label: { type: 'string', description: 'Optional trace label.' },\n key: {\n type: 'string',\n description:\n 'Optional semantic name for this assignment (e.g. \"summarize-ch3\"). The same key ' +\n 'never runs twice: completed keys return their committed result, even after a ' +\n 'coordinator restart.',\n },\n continuity: {\n type: 'string',\n enum: ['fresh', 'resume'],\n description:\n 'How this spawn continues the node\\'s prior work. \"fresh\" (the default) starts a ' +\n 'brand-new session. \"resume\" re-attaches to the node\\'s most recent SETTLED ' +\n 'worker: a NEW live worker is spawned whose session continues where that worker ' +\n 'stopped (the backend receives the prior workerId and the resume sequence). ' +\n 'Resume fails closed when the node has no settled prior worker ' +\n '(`error: \"resume-no-prior\"` — spawn it fresh first), while a prior worker of the ' +\n 'node is still live (`error: \"resume-while-live\"` — steer_agent is the ' +\n 'live-worker channel), and under a `key` (`error: \"resume-with-key\"` — keys are ' +\n \"run-once, resume runs again). Omit to use the run's declared default for this \" +\n 'profile name.',\n },\n budget: {\n type: 'object',\n description:\n 'Optional per-spawn budget that merges over the per-worker default (per field). ' +\n 'Only set the ceilings this sub-task needs raised; the conserved pool still fences.',\n properties: {\n maxIterations: { type: 'number', minimum: 0 },\n maxTokens: { type: 'number', minimum: 0 },\n maxUsd: { type: 'number', minimum: 0 },\n deadlineMs: { type: 'number', minimum: 0 },\n },\n },\n },\n required: ['profile', 'task'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const key = a.key === undefined ? undefined : str(a.key, 'key')\n // A key already proven complete — by the resumed journal or by a delivery earlier in this\n // run — resolves to committed work and starts no live worker, so the concurrency fence\n // does not apply to it.\n const keyCompleted = key !== undefined && completedKeys.has(key)\n // Concurrency fence FIRST — fail closed before reserving budget, so a rejected spawn never\n // touches the pool. The conserved pool bounds TOTAL work; this bounds SIMULTANEOUS work.\n if (\n !keyCompleted &&\n !usesTreeWideLimit() &&\n maxLiveWorkers !== undefined &&\n maxLiveWorkers > 0 &&\n liveWorkerCount() >= maxLiveWorkers\n )\n return Promise.resolve({\n error: 'max-live-workers' as const,\n live: liveWorkerCount(),\n freeSlots: freeWorkerSlots(),\n })\n const parsedProfile = agentProfileSchema.safeParse(a.profile)\n if (!parsedProfile.success) {\n return Promise.resolve({\n error: 'invalid-profile' as const,\n issues: parsedProfile.error.issues.map((issue) => ({\n path: issue.path.join('.'),\n message: issue.message,\n })),\n })\n }\n const profile = detachedFrozen(parsedProfile.data)\n // Continuity resolves BEFORE any assignment is minted or budget reserved, so a refused\n // resume touches nothing — same fail-closed discipline as the fences above.\n const continuity = resolveContinuity(parseContinuity(a.continuity), profile.name, key)\n if ('error' in continuity) {\n return Promise.resolve({\n error: continuity.error,\n hint: continuity.hint,\n live: liveWorkerCount(),\n freeSlots: freeWorkerSlots(),\n })\n }\n const task = detachedFrozen(a.task)\n const label = typeof a.label === 'string' ? a.label : 'worker'\n // The ONE pre-journal point that may ask the backend a question: everything below —\n // assignment, budget reservation, `Scope.spawn` — is synchronous and commits state.\n if (opts.preflightSpawn) {\n // The gate judges the profile that will RUN. A pinning layer resolves the authored stub\n // to its canonical profile here, so the backend is asked about the real model and tools.\n const preflightProfile = opts.resolveSpawnProfile\n ? detachedFrozen(opts.resolveSpawnProfile(profile))\n : profile\n const refusal = await opts.preflightSpawn(preflightProfile, {\n label,\n ...(key !== undefined ? { key } : {}),\n task,\n })\n if (refusal) {\n preflightCounts[refusal.cause] += 1\n return {\n error: 'preflight-refused' as const,\n cause: refusal.cause,\n detail: refusal.detail,\n live: liveWorkerCount(),\n freeSlots: freeWorkerSlots(),\n }\n }\n }\n const budget = Object.freeze(\n a.budget === undefined ? opts.perWorker : mergeBudget(opts.perWorker, a.budget),\n )\n const assignmentId =\n key !== undefined ? `key:${key}` : `ordinal:${unkeyedAssignmentOrdinal++}`\n // Minted BEFORE the worker exists, because the agent factory runs inside `scope.spawn` and\n // the node id is not known until after it. The capability is bound to the concrete worker\n // below, and sends nothing until then.\n const peerMailUrl = peerMail?.mintCapability(assignmentId)\n const context: WorkerSpawnContext = Object.freeze({\n assignmentId,\n parentNodeId: opts.scope.view.root,\n budget,\n task,\n label,\n ...(key !== undefined ? { key } : {}),\n continuity: continuity.continuity,\n ...(continuity.continuity === 'resume' ? { resume: continuity.resume } : {}),\n ...(peerMailUrl !== undefined ? { peerMailUrl } : {}),\n })\n const res = opts.scope.spawn(() => opts.makeWorkerAgent(profile, context), task, {\n budget,\n label,\n assignmentId,\n ...(key !== undefined ? { key } : {}),\n })\n // A keyed spawn that resolved to committed work: NOTHING ran — return the finished result\n // (it is already in the settled ledger, seeded from the resumed scope or recorded when the\n // cursor yielded it), so the driver folds it in without an await_event round-trip.\n if (res.ok && res.prior?.state === 'completed') {\n const s = res.prior.settled\n if (key !== undefined) completedKeys.add(key)\n const { id, status, resumed: _resumed, ...evidence } = projectSettled(s)\n return Promise.resolve({\n workerId: id,\n resumed: 'completed' as const,\n status,\n ...evidence,\n live: liveWorkerCount(),\n freeSlots: freeWorkerSlots(),\n })\n }\n if (res.ok) {\n watchWorker(res.handle.id)\n liveHandles.set(res.handle.id, res.handle)\n // The capability becomes a sender only now, when there is a concrete worker to speak as.\n peerMail?.bindCapability(assignmentId, res.handle.id)\n // Bind the new worker to its key so its settlement can mark the key complete.\n if (key !== undefined) keyByWorker.set(res.handle.id, key)\n if (typeof profile.name === 'string' && profile.name.length > 0) {\n profileNameByWorker.set(res.handle.id, profile.name)\n }\n }\n // A `completed` key returned above, so any prior still attached here is a real re-run:\n // `retried` (the prior attempt failed) or `lost` (it died in flight with its process).\n const priorHistory =\n res.ok && res.prior !== undefined && res.prior.state !== 'completed'\n ? {\n resumed: res.prior.state,\n priorWorkerId: res.prior.priorId,\n ...(res.prior.state === 'retried' ? { priorReason: res.prior.reason } : {}),\n }\n : {}\n // Report the REMAINING capacity alongside the spawn, so one tool call tells the driver\n // both \"it started\" and \"you can still open N more\" — the feedback that lets it fill\n // slots instead of opening one worker per turn. `null` = uncapped. A fresh spawn under a\n // key with a failed/lost prior attempt carries that history (`resumed`/`priorWorkerId`),\n // so a re-run is always explicit, never a silent duplicate.\n return Promise.resolve(\n res.ok\n ? {\n workerId: res.handle.id,\n assignmentId: res.handle.assignmentId ?? assignmentId,\n ...(res.handle.identity === undefined ? {} : { identity: res.handle.identity }),\n ...(res.handle.materialization === undefined\n ? {}\n : { materialization: res.handle.materialization }),\n ...(res.handle.executionBindings === undefined\n ? {}\n : { executionBindings: res.handle.executionBindings }),\n // The EFFECTIVE continuity of this spawn, with the resume lineage when it\n // re-attached — so the driver's transcript states how the node continued.\n continuity: continuity.continuity,\n ...(continuity.continuity === 'resume' ? { resume: continuity.resume } : {}),\n live: liveWorkerCount(),\n freeSlots: freeWorkerSlots(),\n ...priorHistory,\n }\n : {\n error: res.reason,\n // A refusal a driver can ACT on. `usd-unbudgeted` is the one rejection that no\n // retry can clear, so it says so: without this, a driver reads \"budget\" and walks\n // its request down until it gives up.\n ...(res.reason === 'usd-unbudgeted'\n ? {\n hint:\n \"This run's root budget declares no maxUsd, so a child budget naming maxUsd \" +\n 'can never be admitted — at any amount. Retrying with a smaller maxUsd will ' +\n 'fail identically. Spawn with a budget that omits maxUsd, or ask the caller ' +\n 'to give the run a root maxUsd.',\n }\n : {}),\n live: liveWorkerCount(),\n freeSlots: freeWorkerSlots(),\n },\n )\n },\n },\n {\n name: 'observe_agent',\n description:\n 'Inspect a worker WHILE IT RUNS, not only after it finishes: status, spend so far, and ' +\n '`progress` — how long since it last did anything (`idleMs`), whether that counts as ' +\n 'stalled, how many turns it has taken, the last tools/files it touched ' +\n '(`recentActivity`), what its executor CHANGED about the profile you gave it ' +\n '(`derived` — an MCP config it materialized, an extension it had to add), whether a ' +\n 'steer can even reach it (`steerable`), and how many ' +\n 'steers it has not yet read (`pendingMessages`). Returns the settled output artifact ' +\n 'once it exists. Use this BEFORE steer_agent: a steer is only worth sending when the ' +\n 'progress says the worker is on the wrong path or has stopped making any.',\n inputSchema: { type: 'object', properties: { workerId: idArg }, required: ['workerId'] },\n handler: async (raw) => {\n const id = str(obj(raw).workerId, 'workerId')\n const node = opts.scope.view.nodes.find((n) => n.id === id)\n if (!node) {\n // A worker from a PRIOR process of this run: not in the live nursery, but its committed\n // record is on the resumed view — observable like any settled worker, marked `resumed`.\n const resumed = opts.scope.resume?.view.nodes.find((n) => n.id === id)\n if (!resumed) return { error: `unknown workerId ${JSON.stringify(id)}` }\n const output = resumed.outRef ? await opts.blobs.get(resumed.outRef) : undefined\n return {\n ...projectNodeEvidence(resumed, true),\n outRef: resumed.outRef ?? null,\n output: output ?? null,\n progress: null,\n }\n }\n const output = node.outRef ? await opts.blobs.get(node.outRef) : undefined\n const progress = readProgress(id)\n return {\n ...projectNodeEvidence(node),\n outRef: node.outRef ?? null,\n output: output ?? null,\n progress: progress ?? null,\n }\n },\n },\n {\n name: 'steer_agent',\n description:\n 'Send a message DOWN to a still-LIVE worker (parent→child): a new instruction, a course ' +\n 'correction, or a continuation. The worker drains it at its next step boundary — and before ' +\n 'it may settle, so it cannot finish while a message it never read is pending. A worker that ' +\n 'already settled is gone (returns delivered:false) — spawn a fresh one instead.',\n inputSchema: {\n type: 'object',\n properties: {\n workerId: idArg,\n instruction: { type: 'string', description: 'What the worker should do next.' },\n interrupt: {\n type: 'boolean',\n description:\n 'true = forceful: abort the worker’s in-flight inference so it re-plans on the NEXT ' +\n 'turn (a tool already mid-execution finishes first; only the owned tool-loop honors this). ' +\n 'false/omitted = queued: it flushes at the next step boundary (and before it may settle).',\n },\n },\n required: ['workerId', 'instruction'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const workerId = str(a.workerId, 'workerId')\n const instruction = str(a.instruction, 'instruction')\n const delivery = await steerWorker(workerId, instruction, {\n interrupt: a.interrupt === true,\n })\n if (delivery.delivered) {\n return { delivered: true, progress: readProgress(workerId) ?? null }\n }\n return {\n delivered: false,\n reason: delivery.outcome,\n progress: readProgress(workerId) ?? null,\n }\n },\n },\n {\n name: 'await_event',\n description:\n 'Wait for and pull the next message a worker, sub-driver, or analyst sent up — the unified ' +\n \"inbox. An event is one of: a settled worker output ('settled'), a question needing your \" +\n \"answer ('question', from ask_parent / the worker's ask-user), or a trace-analyst finding \" +\n \"('finding', from analyze-on-settle). Pass kinds:['settled'] for just the next finished \" +\n 'worker; omit `kinds` to also receive questions and findings. Returns { idle: true } when ' +\n 'nothing is queued and no workers are live. If a worker is still running when the wait ' +\n 'elapses, returns { pending: true, live: [...] } (the workers still in flight) instead of ' +\n 'blocking indefinitely — call await_event again to keep waiting; the settlement is not lost. ' +\n 'Every reply carries `freeSlots`: how many more workers you can start right now (`null` = ' +\n 'uncapped). A settled worker frees its slot, so `freeSlots > 0` means capacity is sitting ' +\n 'idle — spawn into it before waiting again.',\n inputSchema: {\n type: 'object',\n properties: {\n kinds: {\n type: 'array',\n items: { type: 'string', enum: [...awaitableEventKinds] },\n description: 'Restrict to these event kinds (any if omitted).',\n },\n },\n },\n handler: async (raw) => {\n const k = obj(raw).kinds\n const kinds = Array.isArray(k) ? k.filter(isAwaitableEventKind) : undefined\n // Already-queued async messages (findings, questions) first — a fast, non-blocking pull.\n let ev = bus.pull(kinds)\n // Every return from this verb carries `freeSlots` — a settlement is exactly the moment\n // capacity frees up, so the answer travels with the event that freed it.\n if (ev) return { ...projectEvent(ev), freeSlots: freeWorkerSlots() }\n // Else drive the cursor to produce the next settlement — but BOUND the block. `scope.next()`\n // waits on a live worker for its entire (multi-minute) run; unbounded, that outlives a remote\n // MCP client's request timeout and surfaces as a hard tool error, leaving the supervisor with\n // no working \"wait for the worker\" primitive. Race the single in-flight drain against the\n // fence: if it settles in time, re-pull and return the event (or idle when the cursor is dry);\n // if the fence wins, return a non-error liveness snapshot the supervisor can re-poll on.\n const raced = await raceDrainWithTimeout(ensureDrain())\n if (raced === undefined)\n return { pending: true, live: liveSnapshot(), freeSlots: freeWorkerSlots() }\n ev = bus.pull(kinds)\n if (!ev) return { idle: !raced.drained, freeSlots: freeWorkerSlots() }\n return { ...projectEvent(ev), freeSlots: freeWorkerSlots() }\n },\n },\n {\n name: 'list_questions',\n description:\n 'List questions raised by workers, drivers, or analysts. Blocking stop behavior follows questionPolicy.',\n inputSchema: { type: 'object', properties: {} },\n handler: () => Promise.resolve({ questions }),\n },\n {\n name: 'answer_question',\n description: 'Record an answer, deferral, or escalation for a loop question.',\n inputSchema: {\n type: 'object',\n properties: {\n questionId: { type: 'string' },\n answer: { type: 'string' },\n by: { type: 'string', description: 'Node id or \"user\".' },\n deferReason: { type: 'string' },\n escalateTo: { type: 'string', enum: questionEscalationTargets },\n escalateReason: { type: 'string' },\n },\n required: ['questionId'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const questionId = str(a.questionId, 'questionId')\n if (typeof a.answer === 'string' && a.answer.length > 0) {\n const answer = a.answer\n const pendingQuestion = questions.find((question) => question.id === questionId)\n if (pendingQuestion === undefined) {\n throw new Error(`unknown questionId ${JSON.stringify(questionId)}`)\n }\n // Route the answer DOWN to the worker that asked, unparking it, and record the down-leg.\n // A blocking question parked the worker, so deliver forcefully — it should resume on the\n // answer immediately, not wait for its next step boundary.\n const interrupt =\n pendingQuestion.urgency === 'blocks-run' || pendingQuestion.urgency === 'blocks-step'\n const authorized = authorizeInstruction(\n 'answer',\n pendingQuestion.from,\n answer,\n interrupt,\n questionId,\n )\n await recordInstruction(authorized)\n const delivery = await attemptDelivery(authorized, {\n answer: authorized.instruction,\n questionId,\n interrupt,\n })\n // Authorization is evidence of allowed bytes, not proof the blocked worker received them.\n // Resolve the question only after the durable delivery outcome says the live inbox accepted\n // the answer. A refusal stays open both in this process and after replay.\n const question = delivery.delivered\n ? decideQuestion(questionId, {\n kind: 'answer',\n answer: authorized.instruction,\n by: typeof a.by === 'string' && a.by.length > 0 ? a.by : 'user',\n })\n : pendingQuestion\n // Surface `delivered` like steer_agent — the caller must see whether the answer actually\n // reached a live worker (false when it already settled or has no inbox).\n return {\n question,\n delivered: delivery.delivered,\n ...(delivery.delivered ? {} : { reason: delivery.outcome }),\n }\n }\n if (typeof a.deferReason === 'string' && a.deferReason.length > 0) {\n return Promise.resolve({\n question: decideQuestion(questionId, {\n kind: 'defer',\n reason: a.deferReason,\n }),\n })\n }\n if (typeof a.escalateTo === 'string' && a.escalateTo.length > 0) {\n if (!isQuestionEscalationTarget(a.escalateTo)) {\n throw new Error(\n `answer_question: escalateTo must be one of ${questionEscalationTargets.join(\n ', ',\n )}; received ${JSON.stringify(a.escalateTo)}`,\n )\n }\n const escalateReason =\n typeof a.escalateReason === 'string' && a.escalateReason.length > 0\n ? a.escalateReason\n : 'driver escalated'\n return Promise.resolve({\n question: decideQuestion(questionId, {\n kind: 'escalate',\n to: a.escalateTo,\n reason: escalateReason,\n }),\n })\n }\n throw new Error('answer_question: provide answer, deferReason, or escalateTo')\n },\n },\n {\n name: 'ask_parent',\n description: 'Raise a question to the parent driver/Pi/user when this driver cannot decide.',\n inputSchema: {\n type: 'object',\n properties: {\n from: { type: 'string' },\n level: { type: 'string', enum: ['worker', 'driver', 'loop'] },\n question: { type: 'string' },\n reason: { type: 'string' },\n urgency: { type: 'string', enum: ['continue-without', 'blocks-step', 'blocks-run'] },\n },\n required: ['from', 'level', 'question', 'reason', 'urgency'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const from = str(a.from, 'from')\n const q = await emitNewQuestion(\n addQuestion(\n {\n from,\n level: level(a.level),\n question: str(a.question, 'question'),\n reason: str(a.reason, 'reason'),\n urgency: urgency(a.urgency),\n },\n from,\n { kind: 'escalate', to: 'parent', reason: 'asked parent' },\n ),\n )\n return { question: q }\n },\n },\n ...(deliverable\n ? [\n {\n name: 'submit_result',\n description: [\n 'Submit the complete result to the injected independent check.',\n 'The first passing result is retained; stop work when accepted.',\n ...(deliverable.describe ? [`Expected result: ${deliverable.describe}`] : []),\n ].join(' '),\n inputSchema: {\n type: 'object',\n properties: {\n result: {\n description: 'The complete result in the form requested by the task.',\n },\n },\n required: ['result'],\n additionalProperties: false,\n },\n handler: async (raw: unknown) => {\n if (submitted) {\n return {\n accepted: true,\n retained: 'earlier-passing-result',\n stop: true,\n }\n }\n const a = obj(raw)\n if (!Object.hasOwn(a, 'result')) {\n throw new Error('submit_result: \"result\" is required')\n }\n\n // Copy once at intake so the value checked below is the exact value retained after\n // acceptance, even when this handler is called directly rather than through JSON-RPC.\n const result = structuredClone(a.result)\n let accepted = false\n try {\n accepted = (await deliverable.check(result)) === true\n } catch {\n accepted = false\n }\n if (!accepted) return { accepted: false, stop: false }\n // Two remote callers may submit concurrently. Whichever passing check completes\n // first owns the retained result; a later completion must never overwrite it.\n if (submitted) {\n return {\n accepted: true,\n retained: 'earlier-passing-result',\n stop: true,\n }\n }\n\n submitted = Object.freeze({ result })\n stopped = true\n reason = 'result-accepted'\n notifyStop()\n return { accepted: true, retained: 'this-result', stop: true }\n },\n } satisfies McpToolDescriptor,\n ]\n : []),\n {\n name: 'stop',\n description: 'Declare the run complete.',\n inputSchema: {\n type: 'object',\n properties: { reason: { type: 'string', description: 'Why you are stopping.' } },\n },\n handler: (raw) => {\n const blocking = blockingQuestionsForStop()\n if (blocking.length) {\n return Promise.resolve({\n stopped: false,\n error: 'unresolved-blocking-questions',\n questions: blocking,\n })\n }\n stopped = true\n const r = obj(raw).reason\n reason = typeof r === 'string' ? r : undefined\n notifyStop()\n return Promise.resolve({ stopped: true })\n },\n },\n ]\n\n if (opts.analysts) {\n tools.push({\n name: 'list_analysts',\n description: 'List trace-analyst lenses available to run over a settled worker.',\n inputSchema: { type: 'object', properties: {} },\n handler: () => Promise.resolve({ analysts: opts.analysts?.kinds }),\n })\n tools.push({\n name: 'run_analyst',\n description: 'Apply an analyst lens to a settled worker trace.',\n inputSchema: {\n type: 'object',\n properties: {\n kind: { type: 'string', description: 'The analyst kind id.' },\n workerId: idArg,\n },\n required: ['kind', 'workerId'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const id = str(a.workerId, 'workerId')\n const node = nodeForWorker(id)\n if (!node) return { error: `unknown workerId ${JSON.stringify(id)}` }\n if (isLiveNodeStatus(node.status)) {\n return { error: `worker ${JSON.stringify(id)} has not settled — no trace to analyze yet` }\n }\n const trace =\n ledger.find((worker) => worker.id === id)?.trace ??\n node.trace ??\n ({\n status: 'unavailable',\n reason: 'legacy-settlement-without-trace-evidence',\n } as const)\n let store: TraceAnalysisStore\n try {\n store = await workerTraceAnalysisStore(trace, opts.blobs)\n } catch (error) {\n return {\n error: error instanceof Error ? error.message : String(error),\n trace,\n }\n }\n return { findings: await opts.analysts?.run(str(a.kind, 'kind'), store) }\n },\n })\n }\n\n // Per-child abort by stable reference. Resolution order matches the steer destination rule\n // (profile name before label) with the exact workerId first; only LIVE workers resolve, so an\n // already-settled or unknown reference returns `undefined` instead of a false \"aborted\".\n const abortWorker = (\n ref: string,\n reason?: string,\n ): { readonly id: string; readonly label: string } | undefined => {\n const live = opts.scope.view.nodes.filter((node) => isLiveNodeStatus(node.status))\n const target =\n live.find((node) => node.id === ref) ??\n live.find((node) => profileNameByWorker.get(node.id) === ref) ??\n live.find((node) => node.label === ref)\n if (target === undefined) return undefined\n const handle = liveHandles.get(target.id)\n if (handle === undefined) return undefined\n handle.abort(reason)\n return { id: target.id, label: target.label }\n }\n\n return {\n tools,\n ready,\n history: () => bus.history(),\n raiseFinding: (finding) =>\n bus\n .publish({ type: 'finding', finding: canonicalFindingEvent(finding) })\n .then(() => undefined),\n steerWorker,\n stats: () =>\n opts.preflightSpawn === undefined\n ? bus.stats()\n : { ...bus.stats(), preflight: { ...preflightCounts } },\n isStopped: () => stopped,\n stopReason: () => reason,\n submittedResult: () => submitted,\n settled: () => ledger,\n questions: () => questions,\n drainResolved,\n abortWorker,\n ...(peerMail ? { peerMail } : {}),\n }\n}\n\nfunction nextUnkeyedAssignmentOrdinal(scope: Scope<unknown>): number {\n let next = 0\n const views = [scope.resume?.view, scope.view]\n for (const view of views) {\n if (view === undefined) continue\n for (const node of view.nodes) {\n const match = /^ordinal:(\\d+)$/.exec(node.assignmentId ?? '')\n if (match === null) continue\n const ordinal = Number(match[1])\n if (!Number.isSafeInteger(ordinal)) {\n throw new Error(\n `coordination: durable assignment id '${node.assignmentId}' exceeds the safe ordinal range`,\n )\n }\n next = Math.max(next, ordinal + 1)\n }\n }\n if (!Number.isSafeInteger(next)) {\n throw new Error('coordination: durable assignment ordinal space is exhausted')\n }\n return next\n}\n\n/** Stringify a findings payload for a routed delivery; never throws (a cyclic payload degrades to\n * its String form rather than killing the settle path). */\nfunction safeJsonText(value: unknown): string {\n if (typeof value === 'string') return value\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n","/**\n * Durable side-log for coordination evidence the spawn journal does not own: questions, analyst\n * findings, answer decisions, authorized continuation receipts, delivery-attempt markers, and\n * delivery outcomes. A durable run\n * (`supervise({ runDir })`) appends them as they publish and loads them on resume, so a restarted\n * coordinator retains the exact evidence produced by prior processes.\n *\n * Answer down-events also fold status on load: a question answered before the crash reloads as\n * `answered`, not as a re-blocking `open`. Settled events are skipped (the spawn journal is their\n * ledger). A receipt followed by an attempt but no outcome proves the process died in the delivery\n * window; that outcome remains unknown and no prior instruction is auto-delivered.\n *\n * JSONL, one fsynced record per event, keyed by `runId` — several runs may share one log file\n * exactly as they share one spawn-journal file.\n *\n * @experimental\n */\n\nimport {\n isNoEntError,\n parseCommittedJsonLines,\n prepareJsonlAppend,\n writeAllBytes,\n} from '../../durable/jsonl-file'\nimport type {\n AnalystFindingEvent,\n ContinuationInstruction,\n CoordinationEvent,\n QuestionRecord,\n} from '../../mcp/tools/coordination'\nimport type { BusRecord } from './event-bus'\nimport type { PeerMailEvent } from './peer-mail'\n\n/** Stable identity of the supervisor that owns one coordination stream. High-level supervision\n * derives it from the exact root/child execution identity plus its parent assignment. */\nexport type CoordinationOwnerId = string\n\n/** Durable delivery evidence retained in commit order. An attempt without a later event carrying\n * the same `receiptId` has an unknown outcome after a crash and is never replayed. */\nexport type CoordinationDeliveryEvidence = Extract<\n CoordinationEvent,\n { readonly type: 'delivery-attempt' | 'steer' | 'answer' }\n>\n\n/** Coordination evidence loaded from prior processes of one durable supervised run. */\nexport interface PriorCoordination {\n /** The owner filter used for this replay. Omitted only for the compatibility all-owner read. */\n readonly ownerId?: CoordinationOwnerId\n /** Every question the prior process raised, with answer-status folded in, raise order. */\n readonly questions: ReadonlyArray<QuestionRecord>\n /** Every analyst finding the prior process published, publish order. */\n readonly findings: ReadonlyArray<AnalystFindingEvent>\n /** Every authorized continuation, in commit order. These are evidence, never replayed to a new\n * worker automatically. */\n readonly continuations: ReadonlyArray<ContinuationInstruction>\n /** Delivery intent and result records in commit order, linked to receipts by `receiptId`. */\n readonly deliveryEvidence: ReadonlyArray<CoordinationDeliveryEvidence>\n /** Every peer-mail attempt the prior process made, delivered and refused alike, in commit order.\n * Evidence of what siblings told each other; never replayed into a new worker's inbox. */\n readonly mail: ReadonlyArray<PeerMailEvent>\n /** Exact source-bus stamps in durable append order. Bus `seq` restarts with each process; append\n * order remains the cross-process replay order. */\n readonly records: ReadonlyArray<BusRecord<CoordinationEvent>>\n}\n\n/** The durable coordination side-log seam. `append` records one bus event (kinds it does not\n * persist are ignored); `load` replays a run's prior records folded into `PriorCoordination`. */\nexport interface CoordinationLog {\n append(\n runId: string,\n record: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): Promise<void>\n load(runId: string, ownerId?: CoordinationOwnerId): Promise<PriorCoordination>\n}\n\ntype CoordinationLogRecord = {\n readonly runId: string\n readonly ownerId?: CoordinationOwnerId\n readonly seq: number\n readonly at: number\n readonly priority: number\n readonly event: CoordinationEvent\n}\n\ntype LegacyCoordinationLogRecord = {\n readonly runId: string\n readonly ownerId?: CoordinationOwnerId\n readonly at: string\n readonly event: CoordinationEvent\n}\n\n/** Persist prior context plus exact continuation authorization, attempt, and result evidence.\n * Settlements have their own journal. */\nfunction persisted(event: CoordinationEvent): boolean {\n return event.type !== 'settled'\n}\n\n/** FS-backed `CoordinationLog`: append-only JSONL, fsynced per record. */\nexport class FileCoordinationLog implements CoordinationLog {\n private appendTail: Promise<void> = Promise.resolve()\n\n constructor(private readonly path: string) {}\n\n async append(\n runId: string,\n record: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): Promise<void> {\n if (!persisted(record.event)) return\n const append = this.appendTail.then(() => this.appendRecord(runId, record, ownerId))\n this.appendTail = append.catch(() => undefined)\n return append\n }\n\n private async appendRecord(\n runId: string,\n busRecord: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): 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 record: CoordinationLogRecord = {\n runId,\n ...(ownerId !== undefined ? { ownerId } : {}),\n ...busRecord,\n }\n const needsSeparator = await prepareJsonlAppend(this.path)\n const fh = await fs.open(this.path, 'a')\n try {\n await writeAllBytes(fh, `${needsSeparator ? '\\n' : ''}${JSON.stringify(record)}\\n`)\n await fh.sync()\n } finally {\n await fh.close()\n }\n }\n\n async load(runId: string, ownerId?: CoordinationOwnerId): Promise<PriorCoordination> {\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 emptyPriorCoordination(ownerId)\n throw err\n }\n const byId = new Map<string, QuestionRecord>()\n const findings: AnalystFindingEvent[] = []\n const continuations: ContinuationInstruction[] = []\n const deliveryEvidence: CoordinationDeliveryEvidence[] = []\n const mail: PeerMailEvent[] = []\n const records: BusRecord<CoordinationEvent>[] = []\n let legacySeq = 0\n for (const stored of parseCommittedJsonLines<\n CoordinationLogRecord | LegacyCoordinationLogRecord\n >(text, this.path)) {\n if (stored.runId !== runId) continue\n // Omitting ownerId preserves the historical all-run read for direct consumers. Runtime always\n // supplies one, so root and nested supervisors never receive one another's evidence.\n if (ownerId !== undefined && stored.ownerId !== ownerId) continue\n const record: BusRecord<CoordinationEvent> =\n 'seq' in stored\n ? {\n seq: stored.seq,\n at: stored.at,\n priority: stored.priority,\n event: stored.event,\n }\n : {\n seq: legacySeq++,\n at: Date.parse(stored.at),\n priority: 0,\n event: stored.event,\n }\n records.push(record)\n const ev = record.event\n if (ev.type === 'delivery-attempt' || ev.type === 'steer' || ev.type === 'answer') {\n deliveryEvidence.push(ev)\n }\n if (ev.type === 'question') {\n byId.set(ev.question.id, ev.question)\n } else if (ev.type === 'finding') {\n findings.push(ev.finding)\n } else if (ev.type === 'answer') {\n // Only accepted delivery resolves a blocking question. Authorization and an attempted\n // refusal remain evidence, but cannot turn \"worker never received the answer\" into answered\n // state on replay. `by` is not on the wire; prior-run is the honest attribution.\n const prior = byId.get(ev.questionId)\n if (prior && ev.down.delivered) {\n byId.set(ev.questionId, {\n ...prior,\n status: 'answered',\n decision: { kind: 'answer', answer: ev.down.instruction, by: 'prior-run' },\n })\n }\n } else if (ev.type === 'instruction') {\n continuations.push(ev.instruction)\n } else if (ev.type === 'mail') {\n mail.push(ev.mail)\n }\n }\n return {\n ...(ownerId !== undefined ? { ownerId } : {}),\n questions: [...byId.values()],\n findings,\n continuations,\n deliveryEvidence,\n mail,\n records,\n }\n }\n}\n\nfunction emptyPriorCoordination(ownerId?: CoordinationOwnerId): PriorCoordination {\n return {\n ...(ownerId !== undefined ? { ownerId } : {}),\n questions: [],\n findings: [],\n continuations: [],\n deliveryEvidence: [],\n mail: [],\n records: [],\n }\n}\n","/**\n *\n * `createInMemoryRunContext` — the one-call bundle of the in-memory stores a\n * `createSupervisor().run(root, task, opts)` needs: a fresh `InMemorySpawnJournal`\n * (the event-sourced spawn log), a fresh `InMemoryResultBlobStore` (the\n * content-addressed `outRef` payload store the driver's `observe`/`finalize` reads\n * settled outputs through), and a fresh `createExecutorRegistry()` (the open\n * `AgentSpec → Executor` resolver).\n *\n * It exists to kill the boilerplate every offline/local supervised run repeats by\n * hand — three constructors threaded into `SupervisorOpts` — and to single-source the\n * ONE wiring invariant that is easy to get wrong: when the root is the recursive\n * `driverAgent` LLM-driver brain AND it may spawn DRIVER children (agents\n * driving agents), the registry MUST be wrapped with `withDriverExecutor` so a\n * `role: 'driver'` child resolves to the nested-scope executor — and that SAME blob\n * store MUST be the one passed to `driverAgent({ blobs })`, or the driver\n * reads from a different store than the scope writes to. Pass `{ withDriver: true }`\n * and reuse the returned `blobs` for both.\n *\n * The spread shape matches `SupervisorOpts` exactly, so the call site reads:\n * const run = createInMemoryRunContext()\n * await createSupervisor().run(root, task, { budget, runId, ...run })\n *\n * @experimental\n */\n\nimport {\n FileResultBlobStore,\n FileSpawnJournal,\n InMemoryResultBlobStore,\n InMemorySpawnJournal,\n} from '../../durable/spawn-journal'\nimport { type CoordinationLog, FileCoordinationLog } from './coordination-log'\nimport { withDriverExecutor } from './driver-executor'\nimport { createExecutorRegistry } from './runtime'\nimport type { ExecutorRegistry, ResultBlobStore, SpawnJournal } from './types'\n\n/** Options for a supervised run context. */\nexport interface InMemoryRunContextOptions {\n /**\n * Wrap the executor registry with `withDriverExecutor` so a spawned child marked\n * `role: 'driver'` resolves to the recursive driver-executor (agents driving agents\n * over a nested `Scope` on the same conserved pool). Leave `false` for a flat tree of\n * leaf workers. Default `false`.\n */\n readonly withDriver?: boolean\n}\n\n/**\n * The bundle of stores a supervised run needs, shaped to spread into `SupervisorOpts`.\n * The fields are exactly `SupervisorOpts`' `journal` / `blobs` / `executors`.\n */\nexport interface InMemoryRunContext {\n readonly journal: SpawnJournal\n readonly blobs: ResultBlobStore\n readonly executors: ExecutorRegistry\n /**\n * Present (and `true`) only on a DURABLE context (`createFileRunContext`), so spreading the\n * context into `SupervisorOpts` also opts the run into resume-first. An in-memory context\n * leaves it undefined: there is never a prior tree to resume, and the default stays fresh-run.\n */\n readonly resume?: boolean\n /**\n * Present only on a DURABLE context: the coordination side-log stores questions, analyst\n * findings, answer decisions, and authorized continuation receipts that the spawn journal does\n * not own. `supervise({ runDir })` appends them as they publish and loads them on resume.\n * Continuation receipts are evidence and are never auto-delivered to a replacement worker.\n * In-memory contexts have none: nothing outlives the process.\n */\n readonly coordinationLog?: CoordinationLog\n}\n\n/** The stores a supervised run needs, in-memory or file-backed. `InMemoryRunContext` is the\n * historical name for the same shape. */\nexport type RunContext = InMemoryRunContext\n\n/**\n * Build a fresh in-memory run context. Every call returns NEW stores (no shared global\n * state between runs), so two runs never cross-contaminate their journals/blobs.\n */\nexport function createInMemoryRunContext(opts: InMemoryRunContextOptions = {}): InMemoryRunContext {\n const base = createExecutorRegistry()\n return {\n journal: new InMemorySpawnJournal(),\n blobs: new InMemoryResultBlobStore(),\n executors: opts.withDriver ? withDriverExecutor(base) : base,\n }\n}\n\n/**\n * Build a DURABLE run context: the spawn journal and the result blobs are file-backed (fsynced\n * per append/write) under `dir`, and the context carries `resume: true` so spreading it into\n * `SupervisorOpts` makes the supervisor `loadTree`-first. A run that dies mid-flight therefore\n * resumes when it is re-run with the SAME `runId` and the SAME `dir`: the committed children come\n * back on `Scope.resume` (rehydrated by `replaySpawnTree`) instead of being re-executed.\n *\n * Layout: `${dir}/spawn-journal.jsonl` (one JSONL record per event), `${dir}/blobs/` (one\n * content-addressed JSON file per settled result), and `${dir}/coordination-log.jsonl`\n * (questions, findings, answer decisions, and authorized continuation receipts retained as\n * evidence). The directory is created on first write.\n *\n * Opt-in by construction — `createInMemoryRunContext()` is unchanged and stays the default, so no\n * existing consumer writes to disk or resumes unless it asks for this.\n */\nexport function createFileRunContext(\n dir: string,\n opts: InMemoryRunContextOptions = {},\n): RunContext {\n const base = createExecutorRegistry()\n return {\n journal: new FileSpawnJournal(`${dir}/spawn-journal.jsonl`),\n blobs: new FileResultBlobStore(`${dir}/blobs`),\n executors: opts.withDriver ? withDriverExecutor(base) : base,\n resume: true,\n coordinationLog: new FileCoordinationLog(`${dir}/coordination-log.jsonl`),\n }\n}\n","/**\n * anytimeReport — time-to-satisfactory-output metrics, derived entirely from the\n * waterfall's spans (no new instrumentation): per task, the best-so-far score after each\n * shot with its elapsed wall-clock and cumulative spend; per strategy, the standard\n * anytime-optimization metrics:\n *\n * TTT time-to-target — elapsed ms until best-so-far ≥ the target (per task; median\n * over tasks that reached it)\n * STT shots-to-target — attempts until best-so-far ≥ target\n * ERT expected running time (the COCO benchmarking convention): TOTAL time spent\n * across all tasks — including failures' full budgets — divided by the number of\n * tasks that reached the target. The honest \"how long per success, all-in\".\n * AUC the anytime curve's area (mean best-so-far score across the budget, per shot\n * index) — higher = climbs earlier.\n *\n * The \"satisfactory\" bar follows the COCO/BBOB convention: a SET of satisficing targets\n * (e.g. [0.5, 0.8, 1.0] on the normalized check score), each measured independently —\n * runtime-to-target per (task, target) pair — optionally overridden per task\n * (`targetFor`) when satisfaction is task-specific. Spans come from\n * `createWaterfallCollector().report()`; tasks are grouped by the supervisor runId\n * (`agentic:<strategy>:<taskId>`); shot spans are `shot:N` labels.\n */\nimport type { WaterfallSpan } from './waterfall'\n\nexport interface AnytimeTaskCurve {\n taskId: string\n strategy: string\n /** Best-so-far after each settled shot: elapsed ms from the task's first spawn,\n * cumulative usd, and the running max score. */\n points: Array<{ elapsedMs: number; cumUsd: number; best: number }>\n /** Per satisficing target (keyed by the target value as a string): the first point\n * where best ≥ target, or null when never reached within budget. */\n hits: Record<string, { ms: number; shots: number; usd: number } | null>\n}\n\nexport interface AnytimeStrategySummary {\n strategy: string\n /** The satisficing target this row summarizes. */\n target: number\n tasks: number\n reachedTarget: number\n /** Median time-to-target over the tasks that reached it (null when none did). */\n medianTttMs: number | null\n medianShotsToTarget: number | null\n /** COCO ERT: Σ all task wall-time (incl. failures) / #successes. Null when 0 succeed. */\n ertMs: number | null\n /** Same construction over dollars: Σ all spend / #successes. */\n erUsd: number | null\n /** Mean best-so-far score by shot index (the anytime curve, averaged over tasks). */\n curveByShot: number[]\n /** Area under the per-shot anytime curve, normalized to [0,1]. */\n auc: number\n}\n\nexport interface AnytimeReport {\n targets: number[]\n perTask: AnytimeTaskCurve[]\n /** One summary per (strategy, target) pair — the COCO-style multi-target view. */\n perStrategy: AnytimeStrategySummary[]\n}\n\n/**\n * The best-so-far fold — the ONE definition of \"how good was the run after k results\", shared by\n * the post-run anytime report below and by the LIVE progress-based stop rules\n * (`supervise/stop-rules.ts`). Given the observed objective per settled result in order, it returns\n * the running maximum. A result with no objective (`undefined` — it failed, or it was never\n * scored) carries the previous best forward rather than resetting it.\n *\n * It is extracted rather than duplicated on purpose: a stop rule that decides a run has plateaued\n * must agree, number for number, with the report that later says whether stopping was right.\n */\nexport function bestSoFar(values: ReadonlyArray<number | undefined>): number[] {\n const out: number[] = []\n let best = 0\n for (const v of values) {\n if (typeof v === 'number' && v > best) best = v\n out.push(best)\n }\n return out\n}\n\n/** Mean of a best-so-far curve — the anytime AUC when the curve is normalized to [0,1]. Higher =\n * the run climbed earlier. Shared with the stop rules so \"improving\" means one thing. */\nexport function areaUnderCurve(curve: ReadonlyArray<number>): number {\n if (curve.length === 0) return 0\n return curve.reduce((s, v) => s + v, 0) / curve.length\n}\n\n/**\n * How many trailing entries of a best-so-far curve are within `minDelta` of the curve's value\n * `window` steps back — i.e. the length of the current PLATEAU, in settles. `0` means the most\n * recent settle improved the best by more than `minDelta`.\n *\n * The plateau math the live stop rules read. Defined here, beside the report that measures whether\n * the plateau was real, so there is exactly one notion of \"not improving\".\n */\nexport function plateauLength(curve: ReadonlyArray<number>, minDelta: number): number {\n if (curve.length === 0) return 0\n const last = curve[curve.length - 1] as number\n let i = curve.length - 1\n while (i > 0 && last - (curve[i - 1] as number) <= minDelta) i -= 1\n return curve.length - 1 - i\n}\n\nconst median = (xs: number[]): number | null => {\n if (xs.length === 0) return null\n const s = [...xs].sort((a, b) => a - b)\n const mid = Math.floor(s.length / 2)\n return s.length % 2 === 1 ? (s[mid] as number) : ((s[mid - 1] as number) + (s[mid] as number)) / 2\n}\n\n/** Derive anytime metrics from waterfall spans. `targets` are the satisficing score\n * bars (default [1] = fully resolved; COCO-style multi-target: [0.5, 0.8, 1]);\n * `targetFor` overrides the bar per task (task-specific satisfaction) — when set, the\n * per-task bar replaces every entry of `targets` for that task. */\nexport function anytimeReport(\n spans: WaterfallSpan[],\n opts?: { targets?: number[]; targetFor?: (taskId: string) => number },\n): AnytimeReport {\n const targets = opts?.targets ?? [1]\n const byRun = new Map<string, WaterfallSpan[]>()\n for (const s of spans) {\n if (!s.label.startsWith('shot:')) continue\n const list = byRun.get(s.runId) ?? []\n list.push(s)\n byRun.set(s.runId, list)\n }\n\n const perTask: AnytimeTaskCurve[] = []\n for (const [runId, shots] of byRun) {\n const m = runId.match(/^agentic:(.+):(.+)$/)\n const strategy = m?.[1] ?? runId\n const taskId = m?.[2] ?? runId\n const ordered = [...shots].sort((a, b) => (a.endMs ?? a.startMs) - (b.endMs ?? b.startMs))\n const t0 = Math.min(...ordered.map((s) => s.startMs))\n const taskTargets = opts?.targetFor ? [opts.targetFor(taskId)] : targets\n // ONE best-so-far definition, shared with the live stop rules.\n const bests = bestSoFar(ordered.map((s) => (typeof s.score === 'number' ? s.score : undefined)))\n let cumUsd = 0\n const points: AnytimeTaskCurve['points'] = []\n const hits: AnytimeTaskCurve['hits'] = {}\n for (const t of taskTargets) hits[String(t)] = null\n for (const [i, s] of ordered.entries()) {\n cumUsd += s.usd\n const best = bests[i] as number\n const elapsedMs = (s.endMs ?? s.startMs) - t0\n points.push({ elapsedMs, cumUsd, best })\n for (const t of taskTargets) {\n if (hits[String(t)] === null && best >= t) {\n hits[String(t)] = { ms: elapsedMs, shots: points.length, usd: cumUsd }\n }\n }\n }\n perTask.push({ taskId, strategy, points, hits })\n }\n\n const byStrategy = new Map<string, AnytimeTaskCurve[]>()\n for (const t of perTask) {\n const list = byStrategy.get(t.strategy) ?? []\n list.push(t)\n byStrategy.set(t.strategy, list)\n }\n\n const perStrategy: AnytimeStrategySummary[] = []\n for (const [strategy, tasks] of byStrategy) {\n const totalMs = tasks.reduce((s, t) => s + (t.points[t.points.length - 1]?.elapsedMs ?? 0), 0)\n const totalUsd = tasks.reduce((s, t) => s + (t.points[t.points.length - 1]?.cumUsd ?? 0), 0)\n const maxShots = Math.max(0, ...tasks.map((t) => t.points.length))\n const curveByShot: number[] = []\n for (let i = 0; i < maxShots; i += 1) {\n // A task with fewer shots carries its final best forward (it stopped — its\n // best-so-far is what an operator would have at that point).\n const vals = tasks.map(\n (t) => (t.points[Math.min(i, t.points.length - 1)] as { best: number }).best,\n )\n curveByShot.push(vals.reduce((s, v) => s + v, 0) / vals.length)\n }\n const auc = areaUnderCurve(curveByShot)\n const summaryTargets = opts?.targetFor ? [Number.NaN] : targets\n for (const t of summaryTargets) {\n const key = (\n taskCurve: AnytimeTaskCurve,\n ): { ms: number; shots: number; usd: number } | null =>\n opts?.targetFor\n ? (Object.values(taskCurve.hits)[0] ?? null)\n : (taskCurve.hits[String(t)] ?? null)\n const reached = tasks.filter((x) => key(x) !== null)\n perStrategy.push({\n strategy,\n target: t,\n tasks: tasks.length,\n reachedTarget: reached.length,\n medianTttMs: median(reached.map((x) => (key(x) as { ms: number }).ms)),\n medianShotsToTarget: median(reached.map((x) => (key(x) as { shots: number }).shots)),\n ertMs: reached.length > 0 ? totalMs / reached.length : null,\n erUsd: reached.length > 0 ? totalUsd / reached.length : null,\n curveByShot,\n auc,\n })\n }\n }\n perStrategy.sort((a, b) => a.strategy.localeCompare(b.strategy) || a.target - b.target)\n return { targets, perTask, perStrategy }\n}\n\n/** One row per (strategy, satisficing target): the shareable time-to-satisfactory table. */\nexport function renderAnytimeTable(report: AnytimeReport): string {\n const lines = [\n `anytime metrics · satisficing targets [${report.targets.join(', ')}] · ERT = Σ all wall-time / #successes (COCO)`,\n 'strategy ≥tgt reach med-TTT med-shots ERT(all-in) $/success AUC curve',\n ]\n for (const s of report.perStrategy) {\n const curve = s.curveByShot.map((v) => '▁▂▃▄▅▆▇█'[Math.min(7, Math.floor(v * 8))]).join('')\n const tgt = Number.isNaN(s.target) ? 'task' : s.target.toFixed(2)\n lines.push(\n `${s.strategy.padEnd(19)} ${tgt.padStart(4)} ${String(s.reachedTarget).padStart(4)}/${String(s.tasks).padEnd(3)} ` +\n `${s.medianTttMs === null ? ' —' : `${(s.medianTttMs / 1000).toFixed(1).padStart(6)}s`} ` +\n `${s.medianShotsToTarget === null ? ' —' : String(s.medianShotsToTarget).padStart(5)} ` +\n `${s.ertMs === null ? ' —' : `${(s.ertMs / 1000).toFixed(1).padStart(9)}s`} ` +\n `${s.erUsd === null ? ' —' : `$${s.erUsd.toFixed(4)}`} ${s.auc.toFixed(2)} ${curve}`,\n )\n }\n return lines.join('\\n')\n}\n","/**\n *\n * PROGRESS-BASED STOP RULES — end a long-horizon run for the right reason.\n *\n * Every existing bound is a CEILING: iterations, tokens, dollars, an absolute deadline, a turn\n * cap. A ceiling answers \"may this run continue?\" and never \"is this run still getting anywhere?\".\n * So a supervision tree that stopped learning at settle 4 keeps buying workers until it hits a\n * wall — the run ends on exhaustion, and the operator cannot tell a run that finished from a run\n * that ran out.\n *\n * A stop rule reads the run's own PROGRESS and decides. Three signals feed it:\n * - the objective curve over settled work (best-so-far, from `anytime.ts` — see below),\n * - the LIVE worker feed (`WorkerProgress`: `idleMs`, `stalled`, `turns`, `tokens`),\n * - tree-level shape (how many are in flight, how many are waiting, when the last settle landed).\n *\n * ── Two boundaries this module holds deliberately ───────────────────────────────────────────────\n *\n * ENFORCEMENT lives here; THRESHOLDS do not. \"Stop after 5 settles with no improvement\" is a\n * judgment about a domain — how noisy its scores are, how expensive a worker is, how much a late\n * breakthrough is worth. That belongs to the caller (a loop, a bench, a product). Every rule below\n * takes its thresholds as required options with no hidden defaults for the numbers that decide;\n * the module ships the MECHANISM and refuses to ship the judgment.\n *\n * A stop rule can only ADD a stop, never remove one. The driver evaluates the hard ceilings\n * (`poolStarved`, `deadlinePassed`, abort, the driver's own stop) FIRST and independently; the\n * rule is consulted only when they all say \"continue\". So no rule can talk a run past its budget.\n *\n * ── What is reused, not re-derived ──────────────────────────────────────────────────────────────\n *\n * `anytime.ts` already computed best-so-far curves, their area, and plateau detection — but only\n * after a run was over, from waterfall spans. Rather than write a second copy for the live path,\n * `bestSoFar` / `areaUnderCurve` / `plateauLength` were extracted there and are imported here. A\n * stop rule that calls a run plateaued therefore agrees, number for number, with the report that\n * later judges whether stopping was right.\n *\n * @experimental\n */\n\nimport { ValidationError } from '../../errors'\nimport { areaUnderCurve, bestSoFar, plateauLength } from '../anytime'\nimport { isTerminalNodeStatus } from './node-status'\nimport type { WorkerProgress } from './progress'\nimport type { Scope, Settled } from './types'\n\n/** One settled unit of work, reduced to what a stop rule reads. `objective` is the run's own\n * quality signal (a verdict score, a test pass-rate, a judge rating); `undefined` = this\n * settlement produced no measurable objective (it failed, or nothing scored it). */\nexport interface ProgressSample {\n readonly id: string\n /** Epoch ms the settlement was observed. */\n readonly at: number\n readonly objective?: number\n /** True when the settlement passed its deliverable check — a scored-but-undelivered result is\n * not progress. */\n readonly delivered: boolean\n}\n\n/** The read-model a `StopRule` decides from — the run's progress, not its budget. */\nexport interface ProgressView {\n readonly now: number\n /** Settlements observed so far, in the order they landed. */\n readonly settles: number\n /** Of those, how many passed their deliverable check. */\n readonly delivered: number\n /** Best-so-far objective after each settlement (`anytime.bestSoFar`). */\n readonly curve: ReadonlyArray<number>\n /** The current best objective; `0` when nothing has scored. */\n readonly best: number\n /** Mean of the best-so-far curve — how EARLY the run climbed (`anytime.areaUnderCurve`). */\n readonly auc: number\n /** Epoch ms of the most recent settlement; `0` when none has landed. */\n readonly lastSettleAt: number\n /** Epoch ms of the most recent improvement in best-so-far; `0` when none. */\n readonly lastImprovementAt: number\n /** Settlements since the last improvement — `0` right after one improves. */\n readonly settlesSinceImprovement: number\n /** Live read of every non-terminal worker (the `Scope.progress` feed). Empty when the caller\n * supplied no scope. */\n readonly workers: ReadonlyArray<WorkerProgress>\n /** Nodes running or acquiring. */\n readonly inFlight: number\n /** Armed wait-state nodes — deliberately separate from `inFlight`: a tree whose only remaining\n * nodes are waits is NOT stalled, it is waiting on the world. */\n readonly waiting: number\n}\n\n/** A stop rule's answer. `reason` is required when stopping — a run that ends must be able to say\n * why in the result, and an unexplained early stop is indistinguishable from a bug. */\nexport type StopDecision =\n | { readonly stop: false }\n | { readonly stop: true; readonly reason: string }\n\n/** Evaluated from the progress feed, never from the budget. Pure and synchronous: it is called on\n * the driver's hot path, once per turn. */\nexport type StopRule = (view: ProgressView) => StopDecision\n\nconst CONTINUE: StopDecision = { stop: false }\n\n/** Accumulates settlements and materializes a `ProgressView`. Idempotent by settlement id, so a\n * caller may re-push its whole roster every turn (the driver does exactly that) without\n * double-counting or moving a recorded timestamp. */\nexport interface ProgressTracker {\n /** Record a settlement. A second call with the same `id` is ignored. Returns true when it was\n * new. */\n record(sample: ProgressSample): boolean\n /** Materialize the view. Pass the live `Scope` to include the worker feed and tree shape. */\n view(scope?: Scope<unknown>, opts?: { readonly stallAfterMs?: number }): ProgressView\n /** Evaluate a rule against the current view. */\n evaluate(\n rule: StopRule,\n scope?: Scope<unknown>,\n opts?: { readonly stallAfterMs?: number },\n ): StopDecision\n /** The samples recorded so far, in order. */\n samples(): ReadonlyArray<ProgressSample>\n}\n\nexport interface ProgressTrackerOptions {\n /** Clock for `view().now`. Defaults to `Date.now`. */\n readonly now?: () => number\n /** Treat a settlement that did NOT pass its deliverable check as having no objective. Default\n * true — \"scored 0.9 but never delivered\" is not progress, and counting it as progress is the\n * exact way a plateau rule gets talked out of firing. */\n readonly requireDelivered?: boolean\n /** How much the best-so-far must rise for a settlement to count as an IMPROVEMENT. Default 0\n * (any strict rise counts). Raise it to ignore score noise. */\n readonly minImprovement?: number\n}\n\n/** Build the settled-work ledger a `StopRule` decides from: record each settlement (idempotent by\n * id) and materialize a `ProgressView` combining the best-so-far curve with the live worker feed. */\nexport function createProgressTracker(opts: ProgressTrackerOptions = {}): ProgressTracker {\n const now = opts.now ?? Date.now\n const requireDelivered = opts.requireDelivered ?? true\n const minImprovement = opts.minImprovement ?? 0\n const seen = new Set<string>()\n const recorded: ProgressSample[] = []\n\n return {\n record(sample) {\n if (seen.has(sample.id)) return false\n seen.add(sample.id)\n recorded.push(sample)\n return true\n },\n samples: () => [...recorded],\n view(scope, viewOpts) {\n const objectives = recorded.map((s) =>\n requireDelivered && !s.delivered ? undefined : s.objective,\n )\n const curve = bestSoFar(objectives)\n const best = curve.length > 0 ? (curve[curve.length - 1] as number) : 0\n let lastImprovementAt = 0\n let lastImprovementIdx = -1\n let prev = 0\n for (const [i, value] of curve.entries()) {\n if (value - prev > minImprovement) {\n lastImprovementAt = (recorded[i] as ProgressSample).at\n lastImprovementIdx = i\n }\n prev = value\n }\n const treeView = scope?.view\n const workers: WorkerProgress[] = []\n if (scope && treeView) {\n for (const node of treeView.nodes) {\n if (isTerminalNodeStatus(node.status)) continue\n // A wait-state is not a worker. It produces no metered activity by design, so including\n // it here would make every waiting tree read as a fleet of stalled workers — the exact\n // false positive `allWorkersStalled` exists to avoid. It is counted in `waiting` instead.\n if (node.status === 'waiting') continue\n const p = scope.progress(\n node.id,\n viewOpts?.stallAfterMs !== undefined\n ? { now: now(), stallAfterMs: viewOpts.stallAfterMs }\n : { now: now() },\n )\n if (p) workers.push(p)\n }\n }\n return {\n now: now(),\n settles: recorded.length,\n delivered: recorded.filter((s) => s.delivered).length,\n curve,\n best,\n auc: areaUnderCurve(curve),\n lastSettleAt:\n recorded.length > 0 ? (recorded[recorded.length - 1] as ProgressSample).at : 0,\n lastImprovementAt,\n settlesSinceImprovement:\n lastImprovementIdx < 0 ? recorded.length : recorded.length - 1 - lastImprovementIdx,\n workers,\n inFlight: treeView?.inFlight ?? 0,\n waiting: treeView?.waiting ?? 0,\n }\n },\n evaluate(rule, scope, viewOpts) {\n return rule(this.view(scope, viewOpts))\n },\n }\n}\n\n/** Build a `ProgressSample` from a scope settlement. The objective is the verdict score and\n * `delivered` is the verdict's `valid` — the SAME single delivery signal `finalizeBestDelivered`\n * and `defaultSelectWinner` use, so \"progress\" and \"winner\" cannot disagree. */\nexport function sampleFromSettled(settled: Settled<unknown>, at: number): ProgressSample {\n if (settled.kind === 'down') {\n return { id: settled.handle.id, at, delivered: false }\n }\n return {\n id: settled.handle.id,\n at,\n ...(settled.verdict?.score !== undefined ? { objective: settled.verdict.score } : {}),\n delivered: settled.verdict?.valid === true,\n }\n}\n\n// ── The default rules ────────────────────────────────────────────────────────────────────────\n//\n// Each takes its thresholds as REQUIRED options. A default number here would be this module\n// deciding a domain's judgment for it — which is the boundary the header states.\n\nexport interface NoProgressForOptions {\n /** Stop when this many ms have passed since the last SETTLEMENT. Omit to not bound on time. */\n readonly ms?: number\n /** Stop when this many settlements have landed with no improvement in best-so-far. Omit to not\n * bound on settles. */\n readonly settles?: number\n /** Never stop before this many settlements have landed — the warm-up that stops a rule from\n * firing on an empty run. Default 1. */\n readonly minSettles?: number\n}\n\n/**\n * \"Nothing new has happened.\" Fires when the run has produced no new settled work for `ms`, or no\n * IMPROVEMENT over the last `settles` settlements.\n *\n * A tree whose only remaining nodes are armed WAITS is exempt from the time bound: a run waiting\n * on CI is not a run that stopped making progress, and killing it there would defeat mechanic C.\n */\nexport function noProgressFor(opts: NoProgressForOptions): StopRule {\n if (opts.ms === undefined && opts.settles === undefined) {\n throw new ValidationError('noProgressFor: set at least one of { ms, settles }')\n }\n if (opts.ms !== undefined && opts.ms <= 0) {\n throw new ValidationError('noProgressFor: ms must be > 0')\n }\n if (opts.settles !== undefined && opts.settles < 1) {\n throw new ValidationError('noProgressFor: settles must be >= 1')\n }\n const minSettles = opts.minSettles ?? 1\n return (v) => {\n if (v.settles < minSettles) return CONTINUE\n if (opts.settles !== undefined && v.settlesSinceImprovement >= opts.settles) {\n return {\n stop: true,\n reason: `no-progress: ${v.settlesSinceImprovement} settles with no improvement (limit ${opts.settles}), best=${v.best}`,\n }\n }\n if (opts.ms !== undefined && v.waiting === 0 && v.lastSettleAt > 0) {\n const idle = v.now - v.lastSettleAt\n if (idle >= opts.ms) {\n return {\n stop: true,\n reason: `no-progress: ${idle}ms since the last settlement (limit ${opts.ms}ms)`,\n }\n }\n }\n return CONTINUE\n }\n}\n\nexport interface PlateauOptions {\n /** How many trailing settlements to judge. The rule fires when the whole window failed to lift\n * the best-so-far by more than `minDelta`. */\n readonly window: number\n /** The rise that counts as an improvement — the domain's noise floor. `0` means any strict rise\n * counts. */\n readonly minDelta: number\n /** Never fire before this many settlements. Defaults to `window` (so the first decision is made\n * on a full window, not on a partial one). */\n readonly minSettles?: number\n}\n\n/**\n * \"The objective has stopped climbing.\" Fires when the best-so-far curve has risen by no more than\n * `minDelta` across the last `window` settlements.\n *\n * Built on `anytime.plateauLength` — the same plateau math the post-run anytime report uses, so a\n * rule that stops a run and a report that grades the decision cannot disagree about whether the\n * run was flat.\n */\nexport function plateau(opts: PlateauOptions): StopRule {\n if (!Number.isInteger(opts.window) || opts.window < 1) {\n throw new ValidationError('plateau: window must be a positive integer')\n }\n if (!Number.isFinite(opts.minDelta) || opts.minDelta < 0) {\n throw new ValidationError('plateau: minDelta must be >= 0')\n }\n const minSettles = opts.minSettles ?? opts.window\n return (v) => {\n if (v.settles < minSettles) return CONTINUE\n const flat = plateauLength(v.curve, opts.minDelta)\n if (flat >= opts.window) {\n return {\n stop: true,\n reason: `plateau: best-so-far rose <= ${opts.minDelta} over the last ${flat} settles (window ${opts.window}), best=${v.best}, auc=${v.auc.toFixed(3)}`,\n }\n }\n return CONTINUE\n }\n}\n\nexport interface AllWorkersStalledOptions {\n /** Require at least this many live workers before the rule can fire — one stalled worker in a\n * one-worker tree is a weaker signal than a whole fleet going quiet. Default 1. */\n readonly minWorkers?: number\n /** Idle time that counts as stalled, passed through to the live progress read. Omit = the\n * runtime default (`DEFAULT_STALL_AFTER_MS`). */\n readonly stallAfterMs?: number\n}\n\n/**\n * \"Everyone is stuck.\" Fires when every live worker reads `stalled` — no metered activity for\n * longer than the stall threshold — and none of the tree is merely waiting.\n *\n * `stalled` is a derived read at observation time, never a background watchdog; this rule only\n * reads it. A tree with armed waits never fires: waiting is not stalling.\n */\nexport function allWorkersStalled(opts: AllWorkersStalledOptions = {}): StopRule {\n const minWorkers = opts.minWorkers ?? 1\n return (v) => {\n if (v.waiting > 0) return CONTINUE\n if (v.workers.length < minWorkers) return CONTINUE\n if (!v.workers.every((w) => w.stalled)) return CONTINUE\n const worst = Math.max(...v.workers.map((w) => w.idleMs))\n return {\n stop: true,\n reason: `all-stalled: ${v.workers.length} live workers idle, worst ${worst}ms`,\n }\n }\n}\n\n/** Stop when ANY rule stops — the ordinary composition (each rule is a separate reason to end). */\nexport function anyOf(...rules: ReadonlyArray<StopRule>): StopRule {\n return (v) => {\n for (const rule of rules) {\n const d = rule(v)\n if (d.stop) return d\n }\n return CONTINUE\n }\n}\n\n/** Stop only when EVERY rule stops — for a conservative gate that needs corroboration. */\nexport function allOf(...rules: ReadonlyArray<StopRule>): StopRule {\n if (rules.length === 0) throw new ValidationError('allOf: needs at least one rule')\n return (v) => {\n const reasons: string[] = []\n for (const rule of rules) {\n const d = rule(v)\n if (!d.stop) return CONTINUE\n reasons.push(d.reason)\n }\n return { stop: true, reason: reasons.join(' AND ') }\n }\n}\n\n/** The settled-work ledger a stop evaluation folds — the shape both the router driver's\n * coordination tools and the harness arm's MCP handle expose. */\nexport interface SettledLedger {\n settled(): ReadonlyArray<{\n readonly id: string\n readonly status: 'done' | 'down'\n readonly score?: number\n readonly valid?: boolean\n readonly settledAt?: number\n }>\n}\n\n/**\n * Evaluate a rule against the run's settled work — the ONE evaluator both supervisor arms call.\n *\n * The router arm calls it before each driver inference turn; the harness arm calls it on each\n * worker settle. Ordering is the contract in both: the hard ceilings (`poolStarved`,\n * `deadlinePassed`, abort, the driver's own stop) are checked first and independently, so a stop\n * rule can only ever ADD a stop — it can never keep a run alive past a budget it has exhausted.\n *\n * Folding the whole roster each call is idempotent by worker id, so it costs O(settled) and never\n * double-counts. `settledAt` carries the instant the ledger recorded a settlement; `now()` is the\n * fallback resolution a per-turn guard has.\n */\nexport function progressStop(\n tracker: ProgressTracker,\n rule: StopRule,\n ledger: SettledLedger,\n scope: Scope<unknown>,\n now: () => number,\n stallAfterMs: number | undefined,\n): StopDecision {\n for (const w of ledger.settled()) {\n tracker.record({\n id: w.id,\n at: w.settledAt ?? now(),\n ...(w.score !== undefined ? { objective: w.score } : {}),\n delivered: w.status === 'done' && w.valid === true,\n })\n }\n return tracker.evaluate(rule, scope, stallAfterMs !== undefined ? { stallAfterMs } : undefined)\n}\n","/**\n *\n * `driverAgent` — the driver's BRAIN.\n *\n * The recursive driver-executor (`driver-executor.ts`) runs a driver `Agent.act` inside a\n * nested `Scope`; this is the intelligent `act`: it mounts the coordination MCP verbs\n * (`createCoordinationTools`) over that scope and runs an LLM tool-loop, so the driver\n * REASONS — spawn / observe / steer / await / stop — about how to drive its children,\n * instead of running a fixed script. Each turn: ask the driver LLM for tool calls, run them\n * against the live scope, fold the results back, repeat until the driver stops (no tool\n * calls) or the turn cap forces a keep-best finalize.\n *\n * Recursion composes through `makeWorkerAgent`: `spawn_agent` resolves a `profile` to a\n * worker LEAF or — when the profile is a driver — a `driverChild` wrapping ANOTHER\n * `driverAgent` over its own nested scope (see `driver-executor.ts`). So an agent\n * drives an agent that drives an agent, each an LLM tool-loop, all on one conserved-budget\n * tree.\n *\n * Two seams are INJECTED so the loop runs offline with no creds and stays decoupled:\n * - `brain` (`ToolLoopChat`) — one driver-LLM turn over the canonical tool-loop seam; a test\n * drives a scripted mock, production passes the router's tool-calling (`routerBrain`), a\n * sandboxed harness drives the verbs as MCP tools. The same seam every tool-loop uses.\n * - `systemPrompt` — the driver's stance (the agent-eval worker-driver prompt / the prompt\n * generator). Injected, never hardcoded — the prompt is a pluggable role.\n *\n * @experimental\n */\n\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { RuntimeRunStateError, ValidationError } from '../../errors'\nimport type { McpToolDescriptor } from '../../mcp/server'\nimport {\n type AnalystRegistry,\n type AnalyzeOnSettleRoute,\n type AuthorizeDownMessage,\n type ContinuityMode,\n type CoordinationEvent,\n coordinationVerbNames,\n createCoordinationTools,\n type DownMessageEvent,\n type MakeWorkerAgent,\n normalizeAnalyzeOnSettle,\n type SettledWorker,\n type SpawnPreflight,\n type WorkerWatchOptions,\n} from '../../mcp/tools/coordination'\nimport type { ToolSpec } from '../router-client'\nimport {\n runBrainLoop,\n type ToolLoopCallContext,\n type ToolLoopChat,\n type ToolLoopCompaction,\n type ToolLoopCompactionOptions,\n} from '../tool-loop'\nimport { chargedTokens, promptCacheTokenClasses, unmeteredSpend } from '../util'\nimport type { DeliverableSpec } from './completion-gate'\nimport type { PriorCoordination } from './coordination-log'\nimport type { BusRecord } from './event-bus'\nimport {\n bestDelivered,\n pickBestDelivered,\n runFinalizer,\n runTree,\n type SupervisorFinalizer,\n} from './finalizer'\nimport { createInbox, type Inbox } from './inbox'\nimport { providerAttemptEvidence } from './materialization'\nimport { isTerminalNodeStatus } from './node-status'\nimport {\n claimWorkerSteerDelivery,\n type RunCancellation,\n readRunCancellation,\n readRunCancelRequest,\n readWorkerCancellation,\n readWorkerCancelRequests,\n readWorkerSteerAcknowledgement,\n readWorkerSteerRequests,\n type WorkerCancellation,\n type WorkerCancelRequest,\n type WorkerSteerAcknowledgement,\n type WorkerSteerRequest,\n writeRunCancellation,\n writeWorkerCancellation,\n writeWorkerSteerAcknowledgement,\n} from './run-layout'\nimport { meterRuntimeOwnedProviderAttempt } from './scope'\nimport { createProgressTracker, progressStop, type StopRule } from './stop-rules'\nimport type {\n Agent,\n Budget,\n NodeSnapshot,\n ResultBlobStore,\n ResumedWork,\n Scope,\n Spend,\n TreeView,\n} from './types'\n\nexport interface DriverAgentOptions {\n readonly name: string\n /** The driver-LLM seam — ONE inference turn over the conversation + the coordination tool specs\n * (the canonical `ToolLoopChat`): a scripted mock offline, the router's tool-calling in\n * production, or a sandboxed harness. The same seam every tool-loop uses; no bespoke shape. */\n readonly brain: ToolLoopChat\n /** Profile-declared model for a production Router brain. When set, every turn must report this\n * exact provider-observed model before its output is accepted. Omitted by scripted test brains. */\n readonly expectedModel?: string\n /** Runtime-owned observation sink for the provider identity of each settled driver turn. */\n readonly onProviderModel?: (model: string | undefined) => void\n /** Shared blob store — `observe_agent` reads settled outputs through it. */\n readonly blobs: ResultBlobStore\n /** Resolve a spawned `profile` to a worker LEAF or a driver child (the recursion seam). */\n readonly makeWorkerAgent: MakeWorkerAgent\n readonly authorizeDownMessage?: AuthorizeDownMessage\n /** Per-child budget reserved from the conserved pool on each spawn. */\n readonly perWorker: Budget\n /** Independent completion check for work the driver performs itself. When present, the driver\n * receives `submit_result`; the first passing submission ends the loop and becomes the output. */\n readonly deliverable?: DeliverableSpec<unknown>\n /** Hard cap on simultaneously-LIVE workers — `spawn_agent` fails closed once this many are in\n * flight (a concurrency fence on top of the conserved-pool fence). Omit/`<= 0` = no cap. */\n readonly maxLiveWorkers?: number\n /** The analyst lenses available to the driver. Required for `analyzeOnSettle` (and `run_analyst`).\n * Unset → no analyst feed (status quo: the driver gets settled outputs, no findings). */\n readonly analysts?: AnalystRegistry\n /** Analyst kind ids run AUTOMATICALLY when a worker settles `done` — each result re-enters as a\n * `finding` the driver pulls and composes its next steer from. The UP-leg of the self-improving\n * loop. Omit/empty = no auto-analysis (status quo). Requires `analysts`. */\n readonly analyzeOnSettle?: ReadonlyArray<string | AnalyzeOnSettleRoute>\n /** Run the ONLINE detector panel over each worker's LIVE tool trace and raise a `finding` the\n * moment it loops/error-storms — mid-run evidence to steer on, not a settle-time post-mortem.\n * Omit = no online watching. */\n readonly watchWorkers?: WorkerWatchOptions\n /** Idle time after which `observe_agent` reports a worker as stalled (a derived read; nothing is\n * killed). Omit = the runtime default. */\n readonly stallAfterMs?: number\n /** Default continuity per worker PROFILE NAME — `'resume'` makes spawns of that name re-attach\n * to the node's latest settled worker (see\n * `CoordinationToolsOptions.continuityByProfile`); `spawn_agent`'s per-call `continuity`\n * argument overrides. Omit = every spawn fresh (status quo). */\n readonly continuityByProfile?: Readonly<Record<string, ContinuityMode>>\n /** OPT-IN async gate run before every spawn mints an assignment or reserves budget. See\n * `CoordinationToolsOptions.preflightSpawn`. */\n readonly preflightSpawn?: SpawnPreflight\n /** Pre-journal profile resolution for `preflightSpawn`; see\n * `CoordinationToolsOptions.resolveSpawnProfile`. */\n readonly resolveSpawnProfile?: (profile: AgentProfile) => AgentProfile\n /** The driver's stance — a string, or built from the task (the worker-driver prompt /\n * the generator). INJECTED so the prompt is a pluggable, optimizable role. */\n readonly systemPrompt: string | ((task: unknown) => string)\n /** Product-selected tools already bound to this exact supervisor node. The same descriptors are\n * served over MCP for external supervisors; this arm projects them into router ToolSpecs. */\n readonly nodeTools?: ReadonlyArray<McpToolDescriptor>\n /** WORK tools the driver may call DIRECTLY (alongside the coordination verbs) — so the driver is\n * not a pure manager but a full agent that can ACT (do simple work itself) OR SPAWN (delegate).\n * Each is a router tool spec; their names must not collide with the coordination verbs. Pair with\n * `executeExtraTool`. Unset → coordination-only (the prior behavior). */\n readonly extraTools?: ReadonlyArray<{\n readonly name: string\n readonly description?: string\n readonly parameters: Record<string, unknown>\n }>\n /** Runs an `extraTools` call. Returns a string result, or null/undefined to signal \"not handled\"\n * so the call falls through to the coordination dispatch. Required iff `extraTools` is set. */\n readonly executeExtraTool?: (\n name: string,\n args: Record<string, unknown>,\n ) => Promise<string | null | undefined>\n /** Max driver turns before the loop force-finalizes on the best settled child. Default 16.\n * `0` lifts the turn-COUNT cap: the loop is bounded instead by the conserved budget pool,\n * an absolute deadline, the driver's own stop, and abort (checked in-loop). A finite\n * anti-runaway tripwire still guards a degenerate driver that loops on a no-spawn tool. */\n readonly maxTurns?: number\n /** Injected clock for the in-loop absolute-deadline guard — keeps the deadline check\n * deterministic in tests. Defaults to `Date.now`. */\n readonly now?: () => number\n /**\n * PROGRESS-derived stop (mechanic D). Today a run ends on a ceiling — iterations, tokens,\n * dollars, deadline, turn cap — which answers \"may it continue?\" and never \"is it still getting\n * anywhere?\". A stop rule reads the run's own progress (best-so-far over settled work, time\n * since the last settle, the live worker feed) and ends a run that has stopped learning BEFORE\n * it exhausts a budget.\n *\n * Composes with, and can never override, the hard guards: `poolStarved` / `deadlinePassed` /\n * abort / the driver's own stop are evaluated first, so a rule can only ADD a stop.\n *\n * THRESHOLDS are the caller's judgment, not this module's — build the rule with\n * `plateau({window, minDelta})` / `noProgressFor({...})` / `allWorkersStalled({...})` from\n * `supervise/stop-rules`. Omit ⇒ ceilings only (unchanged behavior).\n */\n readonly stopRule?: StopRule\n /** Called once with the rule's reason when a `stopRule` ends the run — so a caller can record\n * WHY a run stopped early instead of inferring it from an unexhausted budget. */\n readonly onProgressStop?: (reason: string) => void\n /** Give the driver brain a chapter-lifecycle on its OWN context window. The LLM-brain front doors\n * lose to a dumb-Ralph respawn because the brain re-bills its whole coordination transcript every\n * turn — the same context overflow a single steered agent suffers, one level up. With this set,\n * once the brain's running conversation exceeds `thresholdTokens` it distills the accumulated\n * history to a compact progress note and continues fresh: the supervisor analog of respawning\n * against external tracking state, except the live `Scope` roster IS the durable state. Default\n * off (no behavior change). `distill` defaults to a self-summary authored by the brain combined\n * with the factual settled-worker roster; override to supply your own. */\n readonly compaction?: ToolLoopCompactionOptions\n /** Pass-through subscriber for every coordination bus event: settled/question/finding,\n * pre-delivery instruction receipts, and steer/answer delivery outcomes. A durable caller uses\n * this to append the coordination log. Omit = no observer. */\n readonly onEvent?: (\n event: CoordinationEvent,\n record: BusRecord<CoordinationEvent>,\n ) => void | Promise<void>\n /** Re-publish resume-time settlements through the awaited observer before the first brain turn. */\n readonly replaySettlements?: boolean\n /** Questions, findings, and authorized continuation receipts loaded from a prior process.\n * Questions seed the ledger (`list_questions`, blocking-stop policy); all three feed the resume\n * brief. Continuation receipts are evidence only and are never auto-delivered. Omit = fresh. */\n readonly priorCoordination?: PriorCoordination\n /** How the settled-worker ledger becomes the run's output. Default `bestDelivered` — the single\n * highest-scoring DELIVERED child (the exact keep-best every existing caller had). Runs under\n * the delivered-only invariant (`runFinalizer`): whatever the finalizer, an undelivered or\n * invalid child's output stays unreachable. */\n readonly finalizer?: SupervisorFinalizer\n /** Optional shared manager inbox used by a wrapper that must accept messages before async node\n * setup finishes. Ordinary callers omit it and the driver owns a fresh inbox. */\n readonly inbox?: Inbox\n /**\n * The durable run directory (`SuperviseOptions.runDir` / the `run-layout` event dir) this driver\n * ACKNOWLEDGES worker-scoped cancel requests from. Each turn the driver reads the layout's\n * cancellation inbox once, applies any request naming one of ITS OWN workers through that\n * worker's existing per-child abort (cascading to the worker's subtree and no sibling), and\n * writes the durable {@link WorkerCancellation} acknowledgement: `cancel_requested` when the\n * abort is issued, `cancelled` only when the worker reaches a terminal `down` on the settle\n * path, `not_live` when the worker is already gone — a missing worker never reads as success.\n * Which requests this driver OWNS is set by {@link controlScope}. Omit = no acknowledger\n * (in-memory runs keep in-process control via handles).\n */\n readonly controlDir?: string\n /**\n * Which cancel requests this driver's acknowledger owns when `controlDir` is set.\n *\n * `'run'` (the default, and the tree root's role): exact node ids of its OWN direct children,\n * plus every label/profile-name reference. `'subtree'` (a nested manager): exact direct-child\n * node ids ONLY — never labels or profile names, which can match workers under more than one\n * manager. Ownership makes each operation appliable by exactly ONE manager, so two acknowledgers\n * sharing one `controlDir` can never abort two workers for one operation or race on the\n * acknowledgement file. At the end of `act`, the owner writes an expiry record for each owned\n * request still open: `not_live` for one never applied, `unknown` for an abort whose settle the\n * run ended too soon to observe — so a reader can tell run-over from in-progress.\n */\n /** Called with this driver's coordination tool descriptors once they exist and before the brain\n * loop starts — the seam a node tool uses to call the same verbs in code\n * (`SupervisorToolInvocationContext.verbs`). */\n readonly onCoordinationTools?: (tools: ReadonlyArray<McpToolDescriptor>) => void\n readonly controlScope?: 'run' | 'subtree'\n /**\n * Abort the WHOLE run — the seam a run-scoped cancel request (`cancelRun`) is applied through.\n * Wired by `supervise()` to the run's ONE cascade controller (the attached root control), so a\n * run cancel takes the same path a caller's `RootHandle.abort` takes; there is no second\n * controller and no poller. Read only by the `'run'`-scoped manager with a `controlDir`; omit\n * and a run-scoped request stays unanswered.\n */\n readonly abortRun?: (reason: string) => void\n}\n\n/** The default chapter-close prompt: the brain summarizes its OWN progress for its future self before\n * the detailed history is dropped. Emphasis on PENDING work — the part a too-eager chapter-close\n * loses (the coding-burn counter-finding: closing after one fix leaves integration bugs uncircled). */\nconst distillInstruction =\n 'CONTEXT COMPACTION. Your detailed turn-by-turn history is about to be discarded to free your context window. Write a COMPLETE, compact handoff note for your future self so you can keep going without it. Cover: (1) what you have accomplished; (2) every worker you spawned and its current status/result; (3) what subtasks remain unfinished, failing, or unverified — be specific and exhaustive here, this is the part you must not lose; (4) your immediate next action. Do not call any tools; respond with the note only.'\n\n/** Factual ground truth for the digest — the live worker roster from Scope plus the delivered-result\n * ledger, independent of whatever the brain's prose summary captures. */\nfunction summarizeRoster(view: TreeView, settled: ReadonlyArray<SettledWorker>): string {\n if (view.nodes.length === 0) return 'Workers in current live scope: none yet.'\n const settledById = new Map(settled.map((w) => [w.id, w]))\n const lines = view.nodes.map((node) => formatRosterNode(node, settledById.get(node.id)))\n return `Workers in current live scope (ground truth from the run, ${view.nodes.length} total, ${view.inFlight} in flight):\\n${lines.join('\\n')}`\n}\n\nfunction formatRosterNode(node: NodeSnapshot, settled?: SettledWorker): string {\n const result =\n settled?.status === 'done'\n ? `, delivered=${settled.valid ?? false}${\n settled.score !== undefined ? `, score=${settled.score}` : ''\n }${settled.outRef ? `, outRef=${settled.outRef}` : ''}`\n : settled?.status === 'down'\n ? `, reason=${settled.reason ?? 'unknown'}`\n : node.outRef\n ? `, outRef=${node.outRef}`\n : ''\n return `- ${node.id}: ${node.status}, label=${node.label}, runtime=${node.runtime}${result}`\n}\n\n/** Spawn-progress is impossible: the pool can't afford another worker AND nothing is in flight to\n * await. A long-horizon driver bounded by the conserved pool stops here instead of spinning (the\n * in-loop budget guard the turn cap alone never provided). Checks BOTH conserved channels: tokens\n * (can't afford a worker) and usd (a usd-capped pool whose ceiling the driver's own metered\n * inference has drained — `meter` debits usd, so without this a huge-token/small-usd pool would\n * overspend usd up to the turn tripwire). */\nfunction poolStarved(scope: Scope<unknown>, perWorker: Budget): boolean {\n const b = scope.budget\n if (scope.view.inFlight > 0 || scope.view.waiting > 0) return false\n const tokenStarved = b.tokensLeft < perWorker.maxTokens\n const iterationStarved = b.iterationsLeft <= 0\n const usdStarved =\n b.usdCapped &&\n (b.usdLeft <= 0 || (perWorker.maxUsd !== undefined && b.usdLeft < perWorker.maxUsd))\n return tokenStarved || iterationStarved || usdStarved\n}\n\n/** The absolute wall-clock deadline (when the root set one) has passed. */\nfunction deadlinePassed(scope: Scope<unknown>, now: () => number): boolean {\n const b = scope.budget\n return b.deadlineMs > 0 && now() >= b.deadlineMs\n}\n\n/** The USD-denominated members of {@link PromptCacheUsage} — the schema, not a guess. Every\n * other known member (`readTokens`, `writeTokens`, `missTokens`) is a token COUNT. */\nconst PROMPT_CACHE_USD_FIELDS: ReadonlySet<string> = new Set(['readSavingsUsd'])\n\n/** Dollar amounts above this are provider nonsense, not evidence. The old all-integer rule\n * rejected them as a side effect; keeping an explicit ceiling preserves that protection\n * without pretending a dollar amount is an integer. */\nconst MAX_PROMPT_CACHE_USD = 1_000_000\n\n/**\n * Validate provider-reported prompt-cache evidence.\n *\n * Prompt-cache carries two kinds of number and they obey different rules: token COUNTS are\n * integers, and USD amounts are fractional by nature. Applying the count rule to a dollar\n * field refuses every provider that reports cache savings in dollars — a healthy router\n * response carrying `readSavingsUsd: 0.0034` failed the driver outright before this split.\n *\n * Classification is schema-first: a field named in {@link PromptCacheUsage} is validated by\n * what that member IS. `promptCache` is an open record (the sandbox path forwards provider\n * fields verbatim), so an unknown field falls back to the `usd` name-suffix convention —\n * documented here as the contract a provider must follow to report dollars.\n *\n * Returns the refusal, or `undefined` when the evidence is acceptable.\n */\nexport function validateDriverPromptCache(\n promptCache: Readonly<Record<string, number | string>> | undefined,\n): ValidationError | undefined {\n for (const [field, value] of Object.entries(promptCache ?? {})) {\n if (typeof value !== 'number') continue\n const isUsdField = PROMPT_CACHE_USD_FIELDS.has(field) || /usd$/i.test(field)\n if (isUsdField) {\n if (!Number.isFinite(value) || value < 0 || value > MAX_PROMPT_CACHE_USD) {\n return new ValidationError(\n `driverAgent: prompt-cache field ${JSON.stringify(field)} must be a non-negative finite number of dollars`,\n )\n }\n continue\n }\n if (!Number.isSafeInteger(value) || value < 0) {\n return new ValidationError(\n `driverAgent: prompt-cache field ${JSON.stringify(field)} must be a non-negative safe integer`,\n )\n }\n }\n return undefined\n}\n\n/** The journal file `createFileRunContext` writes inside the run directory. The acknowledger\n * reads it as EVIDENCE for the terminated-descendants set — the nested trees of a cancelled\n * lead journal their terminal records there before the lead settles into this scope. */\nconst SPAWN_JOURNAL_FILE = 'spawn-journal.jsonl'\n\ninterface CancelAcknowledgerDeps {\n readonly dir: string\n readonly coord: {\n settled(): ReadonlyArray<SettledWorker>\n abortWorker(\n ref: string,\n reason?: string,\n ): { readonly id: string; readonly label: string } | undefined\n }\n readonly scope: Scope<unknown>\n readonly now: () => number\n /** This manager's own node id (`scope.view.root`) — the parent every owned node id hangs off. */\n readonly ownerId: string\n /** `'run'` also owns label/profile-name references (the tree root's role); `'subtree'` owns\n * exact direct-child node ids only. See `DriverAgentOptions.controlScope`. */\n readonly controlScope: 'run' | 'subtree'\n /** Abort the WHOLE run through the one cascade controller it already has. Present only on the\n * `'run'`-scoped manager, and only when the caller wired a root control; without it a\n * run-scoped cancel request is not this manager's to apply. */\n readonly abortRun?: (reason: string) => void\n}\n\ninterface SteerAcknowledgerDeps {\n readonly dir: string\n readonly coord: {\n steerWorker(\n workerId: string,\n instruction: string,\n options?: { readonly interrupt?: boolean },\n ): Promise<DownMessageEvent>\n }\n readonly now: () => number\n readonly ownerId: string\n}\n\n/**\n * Apply externally admitted steers once from the owning manager's turn loop.\n *\n * The `unknown` acknowledgement lands before authorization or delivery. A crash after that write\n * can lose this steer, but a restarted manager never delivers it again. This is the same\n * at-most-once crash boundary as coordination instruction receipts: no duplicate instruction is\n * safer than replaying a mutation whose first delivery may already have succeeded.\n */\nexport function createSteerAcknowledger(deps: SteerAcknowledgerDeps): {\n pass(phase: 'turn' | 'final'): Promise<void>\n} {\n const iso = () => new Date(deps.now()).toISOString()\n const directChildId = (ref: string): boolean =>\n ref.startsWith(`${deps.ownerId}:s`) && /^s\\d+$/.test(ref.slice(deps.ownerId.length + 1))\n\n const base = (\n request: WorkerSteerRequest,\n ): Omit<WorkerSteerAcknowledgement, 'effect' | 'observedAt' | 'detail'> => ({\n schemaVersion: 1,\n operationId: request.operationId,\n requestDigest: request.requestDigest,\n worker: request.worker,\n requestedAt: request.at,\n })\n\n return {\n async pass(phase): Promise<void> {\n for (const request of readWorkerSteerRequests(deps.dir)) {\n if (!directChildId(request.worker)) continue\n if (readWorkerSteerAcknowledgement(deps.dir, request.operationId) !== undefined) continue\n if (phase === 'final') {\n writeWorkerSteerAcknowledgement(deps.dir, {\n ...base(request),\n effect: 'not_live',\n observedAt: iso(),\n detail: 'run ended before the steer was applied',\n })\n continue\n }\n const claimed = claimWorkerSteerDelivery(deps.dir, {\n ...base(request),\n effect: 'unknown',\n observedAt: iso(),\n detail: 'delivery admitted; outcome not yet known',\n })\n if (!claimed) continue\n try {\n const outcome = await deps.coord.steerWorker(request.worker, request.message, {\n interrupt: request.interrupt,\n })\n const effect: WorkerSteerAcknowledgement['effect'] = outcome.delivered\n ? 'delivered'\n : outcome.outcome === 'runtime-has-no-inbox'\n ? 'unsupported'\n : outcome.outcome === 'unknown-worker' ||\n outcome.outcome === 'already-settled' ||\n outcome.outcome === 'scope-stopped'\n ? 'not_live'\n : 'unknown'\n writeWorkerSteerAcknowledgement(deps.dir, {\n ...base(request),\n effect,\n observedAt: iso(),\n detail: steerAcknowledgementDetail(outcome),\n })\n } catch (error) {\n void error\n writeWorkerSteerAcknowledgement(deps.dir, {\n ...base(request),\n effect: 'unknown',\n observedAt: iso(),\n detail: 'delivery outcome is unknown after a runtime error',\n })\n }\n }\n },\n }\n}\n\nfunction steerAcknowledgementDetail(outcome: DownMessageEvent): string {\n switch (outcome.outcome) {\n case 'delivered':\n return 'the owning manager delivered the steer to the exact live worker'\n case 'runtime-has-no-inbox':\n return 'the exact worker does not expose a steer inbox'\n case 'unknown-worker':\n return 'the owning manager does not know the exact worker'\n case 'already-settled':\n return 'the exact worker settled before delivery'\n case 'scope-stopped':\n return 'the owning manager stopped before delivery'\n case 'runtime-error':\n return 'delivery outcome is unknown after a runtime error'\n }\n}\n\n/**\n * The worker-cancel ACKNOWLEDGER — the runtime-side half of `run-layout`'s `cancelWorker`\n * contract, run from the coordination driver's turn loop (one cancellation-inbox read per turn,\n * no new process, no poller, no extra lifetime). Every manager with a `controlDir` mounts one;\n * OWNERSHIP keeps them from colliding: a request naming a node id is owned by the manager whose\n * own id is that node's parent, and a label/profile-name reference is owned by the `'run'`-scoped\n * (root) manager only — so exactly one acknowledger can ever apply one operation.\n *\n * Two-phase, honestly reported: `cancel_requested` is written the moment a live worker's abort is\n * issued (through the per-child abort chain the scope already owns, so siblings are untouched);\n * `cancelled` is written only when that worker's settlement is DELIVERED on the settle path with\n * a terminal `down`, and then the record names every subtree node id proven terminated. A worker\n * that already settled — or that settles `done` despite the abort — records `not_live`; a\n * reference matching nothing this manager owns stays pending (`cancelWorker` reports it\n * `unknown`). No path reports success for a missing worker.\n *\n * Expiry is run end, not a clock: `finish()` (after the final post-drain pass) writes `not_live`\n * for every owned request never applied and `unknown` for an issued abort whose settle the run\n * ended too soon to observe. A pending request can therefore never outlive its run and abort a\n * future spawn that happens to reuse a label.\n *\n * Idempotency is a lookup, in-process and across processes: an operation with a durable\n * acknowledgement is returned as-is and never re-applied.\n */\nexport function createCancelAcknowledger(deps: CancelAcknowledgerDeps): {\n /** `'turn'` = a driver turn boundary (the only phase that APPLIES a request); `'final'` = the\n * post-drain pass, which only reconciles records the run already wrote. */\n pass(phase: 'turn' | 'final'): void\n finish(): void\n} {\n const tracked = new Map<string, WorkerCancellation>()\n // The run-scoped operation this manager has already applied, so its abort is issued once.\n let runTracked: RunCancellation | undefined\n // The abort-issue instant per operation (the `observedAt` written on its `cancel_requested`\n // record) — the terminated-set window survives the record moving to `cancelled`.\n const abortIssuedAt = new Map<string, string>()\n const iso = () => new Date(deps.now()).toISOString()\n\n const write = (record: WorkerCancellation): void => {\n writeWorkerCancellation(deps.dir, record)\n tracked.set(record.operationId, record)\n }\n\n /** `ref` is exactly one of THIS manager's direct-child node ids (`${ownerId}:s<seq>`). */\n const directChildId = (ref: string): boolean =>\n ref.startsWith(`${deps.ownerId}:s`) && /^s\\d+$/.test(ref.slice(deps.ownerId.length + 1))\n\n /** Whether this acknowledger owns `ref`. A node id deeper in this subtree belongs to the nested\n * manager that parents it; anything that is not a node id under this manager is a\n * label/profile-name reference, owned by the `'run'`-scoped manager alone. */\n const owned = (ref: string): boolean => {\n if (directChildId(ref)) return true\n if (deps.controlScope !== 'run') return false\n return !ref.startsWith(`${deps.ownerId}:`) && ref !== deps.ownerId\n }\n\n // Terminal knowledge of one node, visible only once its settlement was DELIVERED (the ledger\n // row, or the view status `finalizeSettlement` stamps on the pull). 'down' = it died.\n const deliveredTerminal = (id: string): 'down' | 'done' | undefined => {\n const row = deps.coord.settled().find((w) => w.id === id)\n if (row !== undefined) return row.status\n const node = deps.scope.view.nodes.find((n) => n.id === id)\n if (node === undefined) return undefined\n if (node.status === 'done') return 'done'\n if (node.status === 'failed' || node.status === 'cancelled') return 'down'\n return undefined\n }\n\n const apply = (request: WorkerCancelRequest): void => {\n const aborted = deps.coord.abortWorker(request.worker, request.reason ?? 'cancel requested')\n const base = {\n operationId: request.operationId,\n worker: request.worker,\n requestedAt: request.at,\n observedAt: iso(),\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n }\n if (aborted !== undefined) {\n abortIssuedAt.set(request.operationId, base.observedAt)\n write({\n ...base,\n effect: 'cancel_requested',\n workerId: aborted.id,\n detail: `abort issued to live worker '${aborted.label}' (${aborted.id}); termination not yet proven`,\n terminated: [],\n })\n return\n }\n // Not live. A reference that matches a node whose settlement was already delivered is\n // answered `not_live`; a reference matching nothing stays pending — never a success either\n // way, and a worker that appears later can still be cancelled by a later pass.\n const settledNode = deps.scope.view.nodes.find(\n (n) =>\n (n.id === request.worker || n.label === request.worker) && isTerminalNodeStatus(n.status),\n )\n const goneId = settledNode?.id ?? deps.coord.settled().find((w) => w.id === request.worker)?.id\n if (goneId !== undefined) {\n write({\n ...base,\n effect: 'not_live',\n workerId: goneId,\n detail: `worker '${goneId}' had already settled before this operation was applied`,\n terminated: [],\n })\n }\n }\n\n /** The proven-terminated set for one record: the worker plus every subtree id with a terminal\n * journal record at/after the abort was issued. Union with what the record already names, so\n * the set only ever grows (a late teardown journal adds; nothing removes). */\n const provenTerminated = (record: WorkerCancellation, workerId: string): string[] => {\n const since = abortIssuedAt.get(record.operationId) ?? record.observedAt\n const ids = new Set<string>([\n ...record.terminated,\n workerId,\n ...terminatedDescendants(deps.dir, workerId, since),\n ])\n return [...ids].sort()\n }\n\n const reconcile = (record: WorkerCancellation): void => {\n const workerId = record.workerId\n if (workerId === undefined) return\n const terminal = deliveredTerminal(workerId)\n if (terminal === undefined) return\n if (terminal === 'down') {\n write({\n ...record,\n effect: 'cancelled',\n observedAt: iso(),\n terminated: provenTerminated(record, workerId),\n detail: `worker '${workerId}' reached a terminal down state on the settle path`,\n })\n return\n }\n // The worker finished `done` despite the abort request — its result stands, so this\n // operation terminated nothing and must not read as a successful cancellation.\n write({\n ...record,\n effect: 'not_live',\n observedAt: iso(),\n terminated: [],\n detail: `worker '${workerId}' settled done despite the abort request; nothing was terminated`,\n })\n }\n\n /** Re-scan a `cancelled` record while the manager still turns: a descendant whose teardown\n * journals after the lead's settle joins the set on a later pass instead of being lost. Only\n * a grown set is re-written; the window needs the in-process abort instant, so a record a\n * PRIOR process closed stays as that process proved it. */\n const regrow = (record: WorkerCancellation): void => {\n const workerId = record.workerId\n if (workerId === undefined || !abortIssuedAt.has(record.operationId)) return\n const terminated = provenTerminated(record, workerId)\n if (terminated.length > record.terminated.length) {\n write({ ...record, observedAt: iso(), terminated })\n }\n }\n\n /**\n * The RUN-scoped request: seen once, `cancel_requested` written the moment the run's cascading\n * abort is issued through the one controller the run already has. The `supervise()` settle path\n * records what the run then actually did — this manager cannot observe its own tree's terminal\n * state from inside `act`.\n *\n * Applied only at a TURN boundary, never on the final post-drain pass: by then the driver has\n * finished and drained, so a root abort could only void work that is already delivered. A\n * request that arrives that late expires in `finish()` instead — it terminated nothing.\n */\n const passRun = (): void => {\n if (deps.controlScope !== 'run' || deps.abortRun === undefined) return\n const request = readRunCancelRequest(deps.dir)\n if (request === undefined) return\n if (runTracked !== undefined) return\n const prior = readRunCancellation(deps.dir, request.operationId)\n if (prior !== undefined) {\n runTracked = prior\n return\n }\n const record: RunCancellation = {\n operationId: request.operationId,\n effect: 'cancel_requested',\n requestedAt: request.at,\n observedAt: iso(),\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n detail: 'root abort issued to the whole run; termination not yet proven',\n }\n writeRunCancellation(deps.dir, record)\n runTracked = record\n deps.abortRun(request.reason ?? 'run cancel requested')\n }\n\n const pass = (phase: 'turn' | 'final'): void => {\n if (phase === 'turn') passRun()\n for (const request of readWorkerCancelRequests(deps.dir)) {\n if (!owned(request.worker)) continue\n let record = tracked.get(request.operationId)\n if (record === undefined) {\n // Cross-process idempotency: an acknowledgement a prior process wrote wins over\n // re-applying the operation.\n record = readWorkerCancellation(deps.dir, request.operationId)\n if (record !== undefined) tracked.set(request.operationId, record)\n }\n if (record === undefined) {\n apply(request)\n continue\n }\n if (record.effect === 'cancel_requested') reconcile(record)\n else if (record.effect === 'cancelled') regrow(record)\n }\n }\n\n return {\n pass,\n finish(): void {\n const runRequest =\n deps.controlScope === 'run' && deps.abortRun !== undefined\n ? readRunCancelRequest(deps.dir)\n : undefined\n if (\n runRequest !== undefined &&\n readRunCancellation(deps.dir, runRequest.operationId) === undefined\n ) {\n // The request landed after the last turn boundary. The run is over, so it terminated\n // nothing — recording it here keeps a reader from seeing an operation that never resolves.\n writeRunCancellation(deps.dir, {\n operationId: runRequest.operationId,\n effect: 'not_live',\n requestedAt: runRequest.at,\n observedAt: iso(),\n ...(runRequest.reason === undefined ? {} : { reason: runRequest.reason }),\n detail: 'run ended before the request was applied',\n })\n }\n for (const request of readWorkerCancelRequests(deps.dir)) {\n if (!owned(request.worker)) continue\n const record =\n tracked.get(request.operationId) ?? readWorkerCancellation(deps.dir, request.operationId)\n if (record === undefined) {\n // Never applied and the run is over: the request expires as `not_live` so it cannot\n // linger and abort a future spawn that matches by label — and never reads as success.\n write({\n operationId: request.operationId,\n worker: request.worker,\n effect: 'not_live',\n requestedAt: request.at,\n observedAt: iso(),\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n detail: 'run ended before the request was applied',\n terminated: [],\n })\n continue\n }\n if (record.effect === 'cancel_requested') {\n // The abort went out but act is returning before the settle path could prove the\n // termination. `unknown` is the honest terminal: not in progress, never a success.\n write({\n ...record,\n effect: 'unknown',\n observedAt: iso(),\n detail: 'abort issued; run ended before termination was observed',\n })\n }\n }\n },\n }\n}\n\n/**\n * Subtree node ids with a terminal `down`/`cancelled` journal record at or after `sinceIso` —\n * the abort-issue instant (the acknowledger's own `observedAt` on the `cancel_requested` record,\n * runtime clock), never the client's `requestedAt` — read from the durable spawn journal beside\n * the run layout. The set is proven at acknowledgement time and is approximate about post-abort\n * causation: a descendant that died of its OWN cause after the abort was issued is\n * indistinguishable from the cascade and may be included; one whose teardown journals late joins\n * on a later acknowledger pass; a teardown journal still absent when the run ends is absent from\n * the set. Ids are hierarchical (`parent:sN`), so `${nodeId}:` prefixes exactly the subtree.\n * Tolerant of a missing or partially-written journal: evidence that cannot be read names fewer\n * nodes, never wrong ones.\n */\nfunction terminatedDescendants(dir: string, nodeId: string, sinceIso: string): string[] {\n let raw: string\n try {\n raw = readFileSync(join(dir, SPAWN_JOURNAL_FILE), 'utf8')\n } catch {\n return []\n }\n const prefix = `${nodeId}:`\n const ids = new Set<string>()\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n let parsed: { kind?: unknown; event?: Record<string, unknown> }\n try {\n parsed = JSON.parse(trimmed) as { kind?: unknown; event?: Record<string, unknown> }\n } catch {\n continue\n }\n if (parsed.kind !== 'event' || parsed.event === undefined) continue\n const event = parsed.event\n const died = (event.kind === 'settled' && event.status === 'down') || event.kind === 'cancelled'\n if (!died) continue\n if (typeof event.id !== 'string' || !event.id.startsWith(prefix)) continue\n if (typeof event.at !== 'string' || event.at < sinceIso) continue\n ids.add(event.id)\n }\n return [...ids].sort()\n}\n\n/**\n * Build the intelligent recursive driver. Its `act` is the LLM tool-loop; spawn it as a\n * `driverChild` (`driver-executor.ts`) to run it inside a nested scope, recursively.\n */\nexport function driverAgent(opts: DriverAgentOptions): Agent<unknown, unknown> {\n if (typeof opts.brain !== 'function') {\n throw new ValidationError('driverAgent: opts.brain must be a function')\n }\n // Fail loud on a half-wired work-tool seam: extra tool specs with no executor (or an executor\n // with no specs the model can see) is a silent no-op the house rules forbid.\n if ((opts.extraTools?.length ?? 0) > 0 && typeof opts.executeExtraTool !== 'function') {\n throw new ValidationError(\n 'driverAgent: extraTools requires executeExtraTool (how to run a work-tool call)',\n )\n }\n // Fail loud on a half-wired analyst seam (matches the extraTools pattern): analyze-on-settle with no\n // lens registry is a silent no-op the house rules forbid — the driver would get no findings, no error.\n // Only LENS routes resolve against the registry; an agent route carries its own analyst profile.\n if (\n (opts.analyzeOnSettle ?? [])\n .map(normalizeAnalyzeOnSettle)\n .some((route) => route.agent === undefined) &&\n !opts.analysts\n ) {\n throw new ValidationError(\n 'driverAgent: analyzeOnSettle requires analysts (the lens registry the kinds resolve against)',\n )\n }\n // A work tool that shadows a coordination verb would leave the driver unable to coordinate.\n // Validate against the reserved verb set HERE (construction), so the conflict fails loud — not\n // buried inside act() where the supervisor would swallow the throw into a quiet no-winner.\n const reserved = new Set<string>(coordinationVerbNames)\n for (const tool of opts.nodeTools ?? []) {\n if (reserved.has(tool.name)) {\n throw new ValidationError(\n `driverAgent: node tool \"${tool.name}\" collides with a coordination verb or another node tool`,\n )\n }\n reserved.add(tool.name)\n }\n for (const t of opts.extraTools ?? []) {\n if (reserved.has(t.name)) {\n throw new ValidationError(\n `driverAgent: extra work tool \"${t.name}\" collides with a coordination verb or node tool`,\n )\n }\n reserved.add(t.name)\n }\n // Fail loud on a nonsensical cap: a negative maxTurns would silently run zero turns and\n // finalize an empty no-winner — a silent zero the house rules forbid.\n if (opts.maxTurns !== undefined && opts.maxTurns < 0) {\n throw new ValidationError(\n 'driverAgent: maxTurns must be >= 0 (0 lifts the turn cap; bounds become the conserved pool + deadline + abort)',\n )\n }\n // maxTurns=0 lifts the turn-count cap exactly. The conserved pool, deadline, abort, and explicit\n // stop remain the caller-visible bounds; Runtime does not substitute a hidden sentinel.\n const maxTurns = opts.maxTurns ?? 16\n const now = opts.now ?? Date.now\n const inbox = opts.inbox ?? createInbox()\n\n return {\n name: opts.name,\n deliver(message): boolean {\n return inbox.deliver(message)\n },\n async act(task, scope: Scope<unknown>): Promise<unknown> {\n const coord = createCoordinationTools({\n scope,\n blobs: opts.blobs,\n makeWorkerAgent: opts.makeWorkerAgent,\n ...(opts.authorizeDownMessage ? { authorizeDownMessage: opts.authorizeDownMessage } : {}),\n perWorker: opts.perWorker,\n ...(opts.deliverable ? { deliverable: opts.deliverable } : {}),\n ...(opts.maxLiveWorkers !== undefined ? { maxLiveWorkers: opts.maxLiveWorkers } : {}),\n ...(opts.analysts ? { analysts: opts.analysts } : {}),\n ...(opts.analyzeOnSettle ? { analyzeOnSettle: opts.analyzeOnSettle } : {}),\n ...(opts.watchWorkers ? { watchWorkers: opts.watchWorkers } : {}),\n ...(opts.stallAfterMs !== undefined ? { stallAfterMs: opts.stallAfterMs } : {}),\n ...(opts.continuityByProfile ? { continuityByProfile: opts.continuityByProfile } : {}),\n ...(opts.preflightSpawn ? { preflightSpawn: opts.preflightSpawn } : {}),\n ...(opts.resolveSpawnProfile ? { resolveSpawnProfile: opts.resolveSpawnProfile } : {}),\n ...(opts.onEvent ? { onEvent: opts.onEvent } : {}),\n ...(opts.replaySettlements ? { replaySettlements: true } : {}),\n ...(opts.priorCoordination?.questions.length\n ? { priorQuestions: opts.priorCoordination.questions }\n : {}),\n })\n await coord.ready()\n // Before the first brain turn: a node tool invoked on turn one must already be able to call\n // these verbs.\n opts.onCoordinationTools?.(coord.tools)\n // The worker-cancel acknowledger, mounted only for a durable run that named its layout dir.\n // It runs inside this existing turn loop — the one place that already runs every turn and\n // already holds the child handles — so external cancellation needs no second lifetime.\n const acknowledger =\n opts.controlDir === undefined\n ? undefined\n : createCancelAcknowledger({\n dir: opts.controlDir,\n coord,\n scope,\n now,\n ownerId: scope.view.root,\n controlScope: opts.controlScope ?? 'run',\n ...(opts.abortRun ? { abortRun: opts.abortRun } : {}),\n })\n const steerAcknowledger =\n opts.controlDir === undefined\n ? undefined\n : createSteerAcknowledger({\n dir: opts.controlDir,\n coord,\n now,\n ownerId: scope.view.root,\n })\n // Resume-first: re-establish the prior process's supervision state BEFORE the first brain\n // turn — its armed-but-never-woken waits become live again on their ORIGINAL deadlines\n // (they settle through the same cursor `await_event` drains). Fail loud on a wait that\n // cannot be re-armed: silently dropping supervision state is worse than stopping.\n for (const w of scope.resume?.waits ?? []) {\n const rearmed = scope.wait(w.spec, { label: w.label })\n if (!rearmed.ok) {\n throw new RuntimeRunStateError(\n `driverAgent: cannot re-arm resumed wait '${w.label}' (${rearmed.reason})`,\n )\n }\n }\n const byName = new Map<string, McpToolDescriptor>(\n [...coord.tools, ...(opts.nodeTools ?? [])].map((t) => [t.name, t]),\n )\n const toolSpecs: ToolSpec[] = [\n ...coord.tools.map((t) => ({\n type: 'function' as const,\n function: { name: t.name, description: t.description, parameters: t.inputSchema },\n })),\n ...(opts.nodeTools ?? []).map((t) => ({\n type: 'function' as const,\n function: { name: t.name, description: t.description, parameters: t.inputSchema },\n })),\n // Work tools the driver calls DIRECTLY — so it can ACT, not only delegate.\n ...(opts.extraTools ?? []).map((t) => ({\n type: 'function' as const,\n function: { name: t.name, description: t.description, parameters: t.parameters },\n })),\n ]\n const system =\n typeof opts.systemPrompt === 'function' ? opts.systemPrompt(task) : opts.systemPrompt\n\n // Built only when a rule is configured, so a run without one allocates and evaluates nothing.\n const tracker = opts.stopRule ? createProgressTracker({ now }) : undefined\n let progressStopReason: string | undefined\n\n // Meter the driver's OWN inference on EVERY turn into the conserved pool — the largest single\n // token consumer in the loop, and what makes maxTurns=0 genuinely bounded (a thinking driver\n // drains the pool → poolStarved). Driver turns never consume the child-iteration budget;\n // failed inference stays visible through unknown token/USD channels and journal detail.\n //\n // There is deliberately no branch that skips `scope.meter`. A turn whose brain reported no\n // usage is metered as an UNKNOWN turn (`tokensKnown: false`), not omitted: omitting it let the\n // pool and the journal record a turn that ran as a turn that cost nothing, which is the one\n // thing this package forbids — a missing measurement is never zero. The unknown turn debits\n // the zero it actually knows and permanently marks `pool.readout().tokensKnown` false, so a\n // reader of `tokensLeft` can see the balance is a ceiling rather than a measurement. A\n // scripted/mock turn takes this path too, so offline equal-k still debits exactly zero tokens.\n let driverTurn = 0\n let driverCall = 0\n const meteredBrain = async (\n messages: ReadonlyArray<Record<string, unknown>>,\n tools: ReadonlyArray<ToolSpec>,\n detail: Record<string, unknown>,\n ) => {\n let res: Awaited<ReturnType<typeof opts.brain>>\n const call = driverCall\n driverCall += 1\n const callContext: ToolLoopCallContext = Object.freeze({\n signal: scope.signal,\n callId: `${scope.view.root}:brain:${crypto.randomUUID()}`,\n correlationId: scope.view.root,\n })\n try {\n res = await opts.brain(messages, tools, callContext)\n } catch (error) {\n // Calling the brain is the provider-attempt boundary. A rejection after that boundary\n // carries no trusted served identity, so preserve an empty attempt for root settlement.\n opts.onProviderModel?.(undefined)\n await meterRuntimeOwnedProviderAttempt(\n scope,\n unmeteredSpend(0),\n providerAttemptEvidence(undefined),\n {\n driver: opts.name,\n inferenceFailed: true,\n call,\n callId: callContext.callId,\n correlationId: callContext.correlationId,\n ...detail,\n },\n )\n throw error\n }\n let evidenceError: ValidationError | undefined\n opts.onProviderModel?.(res.model)\n if (opts.expectedModel !== undefined) {\n if (res.model === undefined) {\n evidenceError = new ValidationError(\n `driverAgent: Router response omitted model identity; expected ${JSON.stringify(opts.expectedModel)}`,\n )\n } else if (res.model !== opts.expectedModel) {\n evidenceError = new ValidationError(\n `driverAgent: Router response reported model ${JSON.stringify(res.model)}; expected ${JSON.stringify(opts.expectedModel)}`,\n )\n }\n }\n if (\n res.transportAttempts !== undefined &&\n (!Number.isSafeInteger(res.transportAttempts) || res.transportAttempts < 1)\n ) {\n evidenceError = new ValidationError(\n 'driverAgent: transportAttempts must be a positive safe integer when reported',\n )\n }\n evidenceError = validateDriverPromptCache(res.promptCache) ?? evidenceError\n const trustedCost =\n res.costProvenance === 'provider-receipt' || res.costProvenance === 'billing-receipt'\n const cacheUsage = promptCacheTokenClasses(res.usage?.input, res.promptCache)\n const turnSpend: Spend = {\n iterations: 0,\n tokens: {\n input: res.usage?.input ?? 0,\n output: res.usage?.output ?? 0,\n ...cacheUsage,\n },\n ...(res.usage === undefined ? { tokensKnown: false } : {}),\n usd: trustedCost ? (res.costUsd ?? 0) : 0,\n ...(trustedCost && res.costUsd !== undefined ? {} : { usdKnown: false }),\n ms: 0,\n }\n await meterRuntimeOwnedProviderAttempt(\n scope,\n turnSpend,\n providerAttemptEvidence(res.model),\n {\n driver: opts.name,\n call,\n callId: callContext.callId,\n correlationId: callContext.correlationId,\n toolCalls: (res.toolCalls ?? []).map((c) => c.name),\n ...(res.model !== undefined ? { model: res.model } : {}),\n ...(res.transportAttempts !== undefined\n ? { transportAttempts: res.transportAttempts }\n : {}),\n ...(res.usage?.reasoning !== undefined ? { reasoningTokens: res.usage.reasoning } : {}),\n ...(res.promptCache !== undefined ? { promptCache: res.promptCache } : {}),\n // The streamed transport says explicitly when it finished with no usage chunk (a broken\n // `include_usage` contract), which is a different fact from a brain that never reports\n // usage at all. Recorded on the turn so the journal distinguishes them.\n ...(res.usageUnknown === true ? { streamUsageMissing: true } : {}),\n ...(res.costProvenance === 'catalog-estimate' ? { estimatedCostUsd: res.costUsd } : {}),\n ...detail,\n },\n )\n if (evidenceError !== undefined) throw evidenceError\n return res\n }\n const chat: ToolLoopChat = async (messages, tools) => {\n const turn = driverTurn\n const res = await meteredBrain(messages, tools, {\n kind: 'driver-inference',\n turn,\n })\n driverTurn += 1\n return res\n }\n\n // Chapter-close on the brain's own window. The default distiller pairs the factual settled-worker\n // roster (from the live scope) with a brain-authored progress note; the brain call runs through\n // the metered `chat`, so the one-time O(history) distill cost debits the conserved pool like any\n // turn. It replaces the per-turn O(history) re-billing it removes.\n const compaction: ToolLoopCompaction | undefined = opts.compaction\n ? {\n thresholdTokens: opts.compaction.thresholdTokens,\n distill:\n opts.compaction.distill ??\n (async (msgs) => {\n const roster = summarizeRoster(scope.view, coord.settled())\n try {\n const res = await meteredBrain(\n [...msgs, { role: 'user', content: distillInstruction }],\n [],\n { kind: 'driver-compaction', compactingTurn: driverTurn },\n )\n const narrative = (res.content ?? '').trim()\n return narrative ? `${roster}\\n\\n## Progress notes\\n${narrative}` : roster\n } catch (e) {\n return `${roster}\\n\\n## Progress notes\\nSummary unavailable: ${errMessage(e)}`\n }\n }),\n ...(opts.compaction.onCompact ? { onCompact: opts.compaction.onCompact } : {}),\n ...(opts.compaction.preserveHead !== undefined\n ? { preserveHead: opts.compaction.preserveHead }\n : {}),\n ...(opts.compaction.estimateTokens\n ? { estimateTokens: opts.compaction.estimateTokens }\n : {}),\n }\n : undefined\n\n await runBrainLoop({\n chat,\n tools: toolSpecs,\n ...(compaction ? { compaction } : {}),\n execute: async (name, args) => {\n // WORK FIRST: a work tool the driver runs itself (act). A non-null return is handled here;\n // null/undefined means \"not mine\" → fall through to the coordination dispatch (spawn/await/…).\n if (opts.executeExtraTool) {\n const worked = await runExtraTool(opts.executeExtraTool, name, args)\n if (worked !== null && worked !== undefined) return worked\n }\n const tool = byName.get(name)\n const result = tool ? await runTool(tool, args) : { error: `unknown tool: ${name}` }\n return safeJson(result)\n },\n initialMessages: [\n { role: 'system', content: system },\n { role: 'user', content: stringifyTask(task) },\n // The resume brief: on a resumed run the brain's FIRST context already carries the\n // committed settlements, the key states, the re-armed waits, carried-over questions/\n // findings, and the spend the run already paid — so it continues from the unresolved\n // work instead of re-planning (and re-paying) from scratch.\n ...(scope.resume\n ? [{ role: 'user', content: resumeBrief(scope.resume, opts.priorCoordination) }]\n : hasPriorCoordination(opts.priorCoordination)\n ? [\n {\n role: 'user',\n content: priorCoordinationBrief(opts.priorCoordination as PriorCoordination),\n },\n ]\n : []),\n ],\n maxTurns,\n // The conserved-pool + deadline + external-stop bound (what maxTurns=0 relies on): a driver\n // that can no longer spawn (pool starved) or has run past the deadline stops here instead of\n // burning turns. Checked before each inference turn.\n hooks: {\n beforeTurn: async (_turn, messages) => {\n await steerAcknowledger?.pass('turn')\n acknowledger?.pass('turn')\n const pending = inbox.drain()\n if (pending.length > 0) {\n messages.push({ role: 'user', content: inbox.fold(pending) })\n }\n },\n stopBefore: () => {\n // HARD CEILINGS FIRST, and independently — a progress rule may never keep a run alive\n // past one, so they are not folded into the same expression.\n if (\n coord.isStopped() ||\n scope.signal.aborted ||\n poolStarved(scope, opts.perWorker) ||\n deadlinePassed(scope, now)\n ) {\n return true\n }\n if (!opts.stopRule || !tracker) return false\n const decision = progressStop(\n tracker,\n opts.stopRule,\n coord,\n scope,\n now,\n opts.stallAfterMs,\n )\n if (!decision.stop) return false\n // `stopBefore` is a predicate the loop may consult more than once; the callback is a\n // one-shot notification, so it fires on the FIRST stop only.\n if (progressStopReason === undefined) {\n progressStopReason = decision.reason\n opts.onProgressStop?.(decision.reason)\n }\n return true\n },\n },\n })\n // Drain every already-settled child the brain never pulled — a gate-verified delivery must\n // never be lost to the driver's pull discipline (e.g. a brain that spawned and stopped\n // without awaiting). Non-blocking: live children are the supervisor's to tear down.\n await coord.drainResolved()\n // Final acknowledgement pass over the drained ledger, so a cancellation whose worker\n // settled after the last turn's pass still records its terminal effect before act returns.\n // Then expiry: run end closes every owned request that is still open (`not_live` never\n // applied, `unknown` issued-but-unproven) — a reader can tell run-over from in-progress,\n // and no pending request survives to abort a future spawn that matches by label.\n await steerAcknowledger?.pass('final')\n acknowledger?.pass('final')\n acknowledger?.finish()\n // Direct work is eligible only through `submit_result`, after the same injected independent\n // check workers face. Raw driver prose remains ineligible. The first passing submission wins;\n // otherwise finalize over delivered children as before.\n const submitted = coord.submittedResult()\n if (submitted) return submitted.result\n return runFinalizer(opts.finalizer ?? bestDelivered, {\n settled: coord.settled(),\n blobs: opts.blobs,\n tree: runTree(scope),\n budget: scope.budget,\n })\n },\n }\n}\n\n/**\n * The factual context a resumed driver starts from — everything the durable stores prove about\n * the prior process(es): committed settlements, per-key states (completed / lost / failed),\n * re-armed waits, carried-over questions/findings/continuation receipts, and spend already paid.\n * Injected as the brain's first user-context on a resumed run so it continues from unresolved work;\n * old continuation receipts are evidence and are never auto-delivered.\n */\nfunction resumeBrief(resume: ResumedWork<unknown>, prior?: PriorCoordination): string {\n const lines: string[] = [\n 'RESUME: this run continues a prior coordinator process. Its committed work is restored',\n 'below and already counts toward the deliverable — do NOT redo it. Continue from the',\n 'unresolved work only.',\n '',\n `Committed workers (${resume.settled.length}):`,\n ]\n if (resume.settled.length === 0) lines.push('- none')\n for (const s of resume.settled) {\n lines.push(\n s.kind === 'done'\n ? `- ${s.handle.id} (${s.handle.label}): done, score=${s.verdict?.score ?? 0}, valid=${\n s.verdict?.valid ?? false\n }, outRef=${s.outRef}`\n : `- ${s.handle.id} (${s.handle.label}): down, reason=${s.reason}`,\n )\n }\n const byState = (state: 'completed' | 'in-doubt' | 'down') =>\n [...resume.keys].filter(([, v]) => v.state === state)\n const completed = byState('completed')\n const lost = byState('in-doubt')\n const failed = byState('down')\n if (completed.length > 0) {\n lines.push(\n '',\n 'COMPLETED keys — spawn_agent with the same key returns the finished result, spending nothing:',\n ...completed.map(([k, v]) => `- ${k} → ${v.id} (${v.label})`),\n )\n }\n if (lost.length > 0) {\n lines.push(\n '',\n 'Keys LOST in flight with the prior process — this is the unresolved work; spawn_agent with the same key starts a fresh attempt:',\n ...lost.map(([k, v]) => `- ${k} (prior attempt ${v.id}, ${v.label})`),\n )\n }\n if (failed.length > 0) {\n lines.push(\n '',\n 'Keys whose prior attempt FAILED (settled down) — spawn_agent with the same key retries:',\n ...failed.map(([k, v]) => `- ${k} (prior attempt ${v.id}, ${v.label})`),\n )\n }\n if (resume.waits.length > 0) {\n lines.push(\n '',\n 'Pending waits RE-ARMED on their original deadlines (they settle through await_event):',\n ...resume.waits.map((w) => `- ${w.label} (${w.spec.kind})`),\n )\n }\n appendPriorCoordination(lines, prior)\n const spent = resume.priorSpend\n lines.push(\n '',\n 'Budget the run ALREADY spent before this process (it counts toward the run total):',\n // `charged` is what the token cap debited: newly-presented tokens, not the rolled-up prompt\n // total, which counts a cached prefix again on every turn that reads it. A driver told the\n // rolled-up number would read a cache-heavy resume as near-exhaustion of a cap it has barely\n // touched.\n `- child work: tokens charged=${chargedTokens(spent.childWork.tokens)} (in=${spent.childWork.tokens.input} out=${spent.childWork.tokens.output}), usd=${spent.childWork.usd}, iterations=${spent.childWork.iterations}`,\n `- driver inference: tokens charged=${chargedTokens(spent.driverInference.tokens)} (in=${spent.driverInference.tokens.input} out=${spent.driverInference.tokens.output}), usd=${spent.driverInference.usd}`,\n )\n return lines.join('\\n')\n}\n\nfunction hasPriorCoordination(prior?: PriorCoordination): boolean {\n return (\n prior !== undefined &&\n (prior.questions.length > 0 ||\n prior.findings.length > 0 ||\n prior.continuations.length > 0 ||\n prior.deliveryEvidence.length > 0)\n )\n}\n\nfunction priorCoordinationBrief(prior: PriorCoordination): string {\n const lines = [\n 'PRIOR COORDINATION EVIDENCE: this logical supervisor ran in an earlier process.',\n 'Use the evidence below as context. Never auto-deliver an old continuation; issue a new',\n 'authorized instruction only when current live state still warrants it.',\n ]\n appendPriorCoordination(lines, prior)\n return lines.join('\\n')\n}\n\nfunction appendPriorCoordination(lines: string[], prior?: PriorCoordination): void {\n const openQuestions = (prior?.questions ?? []).filter(\n (q) => q.status === 'open' || q.status === 'escalated',\n )\n if (openQuestions.length > 0) {\n lines.push(\n '',\n 'Questions carried over, still undecided (answer_question decides them; list_questions shows all):',\n ...openQuestions.map(\n (q) => `- [${q.id}] from=${q.from}, urgency=${q.urgency}: ${q.question}`,\n ),\n )\n }\n if ((prior?.findings.length ?? 0) > 0) {\n lines.push(\n '',\n 'Analyst findings from the prior process:',\n ...(prior?.findings ?? []).map(\n (f) => `- ${f.analyst} on ${f.fromWorker}: ${safeJson(f.findings)}`,\n ),\n )\n }\n if ((prior?.continuations.length ?? 0) > 0) {\n const attempts = new Set(\n (prior?.deliveryEvidence ?? [])\n .filter((event) => event.type === 'delivery-attempt')\n .map((event) => event.attempt.receiptId),\n )\n const outcomes = new Map(\n (prior?.deliveryEvidence ?? [])\n .filter((event) => event.type === 'steer' || event.type === 'answer')\n .map((event) => [event.down.receiptId, event.down.outcome] as const),\n )\n lines.push(\n '',\n 'Authorized continuations committed by the prior process (evidence only; never replayed automatically):',\n ...(prior?.continuations ?? []).map((continuation) => {\n const outcome = outcomes.get(continuation.receiptId)\n const delivery =\n outcome ??\n (attempts.has(continuation.receiptId)\n ? 'unknown-after-crash'\n : 'not-attempted-before-crash')\n return `- receipt=${continuation.receiptId}, ${continuation.kind} → ${continuation.toWorker}, instruction=${continuation.instructionDigest}, delivery=${delivery}`\n }),\n )\n }\n}\n\n/** Run a work tool. A throw is data to the driver (it can recover next turn), not a crash — fold\n * the error back as a string result. null/undefined passes through (the caller treats it as \"not\n * handled\" and falls to the coordination dispatch). */\nasync function runExtraTool(\n execute: (name: string, args: Record<string, unknown>) => Promise<string | null | undefined>,\n name: string,\n args: Record<string, unknown>,\n): Promise<string | null | undefined> {\n try {\n return await execute(name, args)\n } catch (e) {\n return `error: ${e instanceof Error ? e.message : String(e)}`\n }\n}\n\nasync function runTool(tool: McpToolDescriptor, args: Record<string, unknown>): Promise<unknown> {\n try {\n return await tool.handler(args)\n } catch (e) {\n // A tool throw is data to the driver (it can recover), not a crash — fold it back.\n return { error: e instanceof Error ? e.message : String(e) }\n }\n}\n\n/** Keep-best finalize under the completion-oracle: return the highest-scoring DELIVERED child's\n * output (settled `done` AND `valid` — its deliverable check passed). Returns undefined when no\n * child delivered — an honest \"the driver produced nothing\", never a high-scoring result that\n * ran without passing its check (Foreman's 0/18 lesson). `valid` is the single delivery signal,\n * matching `defaultSelectWinner`'s valid-first rule; the oracle just doesn't fall back to an\n * unchecked best-effort. The same argmax as the `bestDelivered` finalizer (`pickBestDelivered`);\n * this direct form serves callers that hold a bare ledger + blob store. */\nexport async function finalizeBestDelivered(\n settled: ReadonlyArray<{ status: string; score?: number; valid?: boolean; outRef?: string }>,\n blobs: ResultBlobStore,\n): Promise<unknown> {\n const delivered = settled.filter((w) => w.status === 'done' && w.valid === true)\n const best = pickBestDelivered(delivered)\n if (best === undefined) return undefined\n return best.outRef ? await blobs.get(best.outRef) : undefined\n}\n\nfunction stringifyTask(task: unknown): string {\n return typeof task === 'string' ? task : safeJson(task)\n}\n\nfunction safeJson(v: unknown): string {\n try {\n return JSON.stringify(v) ?? String(v)\n } catch {\n return String(v)\n }\n}\n\nfunction errMessage(e: unknown): string {\n return e instanceof Error ? e.message : String(e)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,uBAA4C;CAC1D,OAAO,CAAC,uBAAuB,EAAE,aAAa,EAAE,CAAC,GAAG,oBAAoB,EAAE,WAAW,EAAE,CAAC,CAAC;AAC3F;;;AAIA,SAAgB,WAAW,QAAqB,OAA0B,CAAC,GAAe;CACxF,MAAM,YAAY,KAAK,aAAa,qBAAqB;CACzD,OAAO,OAAO,QAAQ,SAAS;EAC7B,IAAI;EACJ,IAAI;GAEF,cAAc,GAAG,KAAK,SAAS,GAAG,QAAQ,KAAK,IAAI;EACrD,QAAQ;GACN,cAAc,GAAG,KAAK,SAAS;EACjC;EACA,MAAM,UAAU,WAAW,WAAW;GACpC,mBAAmB;GACnB,GAAI,KAAK,SAAS,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC;GAC7C,OAAO,KAAK;EACd,CAAC;EACD,KAAK,MAAM,KAAK,SAAS,KAAU,WAAW,GAAG,IAAI;CACvD,CAAC;AACH;;;;;ACoBA,SAAgB,eAAmC,MAAoB,KAAK,KAAkB;CAC5F,MAAM,QAAwB,CAAC;CAC/B,MAAM,MAAsB,CAAC;CAC7B,MAAM,cAAqE,CAAC;CAC5E,MAAM,SAAiC,CAAC;CAIxC,MAAM,yBAAS,IAAI,QAA8B;CACjD,IAAI,MAAM;CACV,IAAI,YAAY;CAChB,IAAI,SAAS;CAEb,MAAM,WAAW,GAAi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