@tangle-network/agent-runtime 2.3.8 → 2.3.11

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 (94) hide show
  1. package/dist/{activation-Cks1h3Nw.d.ts → activation-B8dLwJj6.d.ts} +2 -2
  2. package/dist/{activation-CDPbi8JA.js → activation-BzNeFJDB.js} +4 -4
  3. package/dist/{activation-CDPbi8JA.js.map → activation-BzNeFJDB.js.map} +1 -1
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +3 -3
  6. package/dist/{bundle-PDYNXIEf.js → bundle-DhV73H6U.js} +2 -2
  7. package/dist/{bundle-PDYNXIEf.js.map → bundle-DhV73H6U.js.map} +1 -1
  8. package/dist/candidate-execution/index.js +4 -4
  9. package/dist/{coordination-manager-DNrb7zMg.js → coordination-manager-BluavEgY.js} +42 -152
  10. package/dist/coordination-manager-BluavEgY.js.map +1 -0
  11. package/dist/{coordination-map-routing-CUvwHAtv.js → coordination-map-routing-BllzcZov.js} +5 -2
  12. package/dist/coordination-map-routing-BllzcZov.js.map +1 -0
  13. package/dist/{delegate-CHdWyLz9.js → delegate-CYWL0MrO.js} +2 -2
  14. package/dist/{delegate-CHdWyLz9.js.map → delegate-CYWL0MrO.js.map} +1 -1
  15. package/dist/durable-file-DstVeHcj.js.map +1 -1
  16. package/dist/durable.d.ts +1 -1
  17. package/dist/durable.js +42 -202
  18. package/dist/durable.js.map +1 -1
  19. package/dist/{graph-oOdDpXFH.js → graph-ByNMeS0j.js} +8 -13
  20. package/dist/graph-ByNMeS0j.js.map +1 -0
  21. package/dist/{graph-registry-72DlMnUl.js → graph-registry-D6y6zffC.js} +2 -2
  22. package/dist/{graph-registry-72DlMnUl.js.map → graph-registry-D6y6zffC.js.map} +1 -1
  23. package/dist/{graph-registry-CAX15LO6.js → graph-registry-rV9mwxQO.js} +1 -1
  24. package/dist/{improve-BCjhWbVk.js → improve-D9A79N5a.js} +7 -7
  25. package/dist/{improve-BCjhWbVk.js.map → improve-D9A79N5a.js.map} +1 -1
  26. package/dist/index.d.ts +3 -3
  27. package/dist/index.js +10 -11
  28. package/dist/index.js.map +1 -1
  29. package/dist/intelligence.d.ts +2 -2
  30. package/dist/intelligence.js +7 -6
  31. package/dist/intelligence.js.map +1 -1
  32. package/dist/kernel.d.ts +1 -1
  33. package/dist/kernel.js +12 -12
  34. package/dist/{loop-runner-Bkvx4Saw.d.ts → loop-runner-D9fuOb69.d.ts} +2 -2
  35. package/dist/{loop-runner-Cy1K7f-A.js → loop-runner-DiMfhI_z.js} +2 -2
  36. package/dist/{loop-runner-Cy1K7f-A.js.map → loop-runner-DiMfhI_z.js.map} +1 -1
  37. package/dist/loop-runner-bin.d.ts +1 -1
  38. package/dist/loop-runner-bin.js +1 -1
  39. package/dist/mcp/bin.js +3 -3
  40. package/dist/mcp/index.d.ts +1 -1
  41. package/dist/mcp/index.js +6 -5
  42. package/dist/mcp/index.js.map +1 -1
  43. package/dist/{prepare-Bv6X2Wnx.js → prepare-DrHOZFJy.js} +3 -4
  44. package/dist/{prepare-Bv6X2Wnx.js.map → prepare-DrHOZFJy.js.map} +1 -1
  45. package/dist/{profile-Dir2A1_2.js → profile-BzzmKuIX.js} +3 -2
  46. package/dist/{profile-Dir2A1_2.js.map → profile-BzzmKuIX.js.map} +1 -1
  47. package/dist/profiles.d.ts +1 -1
  48. package/dist/{provision-supervisor-Pd95wA1X.js → provision-supervisor-DP5U58V4.js} +13 -5
  49. package/dist/provision-supervisor-DP5U58V4.js.map +1 -0
  50. package/dist/{run-cancellation-CzQZUlHr.js → run-cancellation-BxoFCpJ_.js} +208 -5
  51. package/dist/run-cancellation-BxoFCpJ_.js.map +1 -0
  52. package/dist/{runtime-CWZ9q7lU.js → runtime-DS5AgACg.js} +15 -16
  53. package/dist/{runtime-CWZ9q7lU.js.map → runtime-DS5AgACg.js.map} +1 -1
  54. package/dist/sandbox-profile-compat-DxegoIK5.js +65 -0
  55. package/dist/sandbox-profile-compat-DxegoIK5.js.map +1 -0
  56. package/dist/scope-DRaBilEX.js +16734 -0
  57. package/dist/scope-DRaBilEX.js.map +1 -0
  58. package/dist/{search-executor-CMPbMvpr.js → search-executor-DLo_9jUv.js} +4 -5
  59. package/dist/{search-executor-CMPbMvpr.js.map → search-executor-DLo_9jUv.js.map} +1 -1
  60. package/dist/{server-DyTbsg7n.js → server-DfHV4ajw.js} +4 -4
  61. package/dist/{server-DyTbsg7n.js.map → server-DfHV4ajw.js.map} +1 -1
  62. package/dist/{structural-rollout-BUqZsIhX.js → structural-rollout-BIjjZ_XX.js} +4 -5
  63. package/dist/{structural-rollout-BUqZsIhX.js.map → structural-rollout-BIjjZ_XX.js.map} +1 -1
  64. package/dist/{supervise-D1eYde7p.js → supervise-6BCQ73Xa.js} +34 -136
  65. package/dist/supervise-6BCQ73Xa.js.map +1 -0
  66. package/dist/{supervision-discovery-DmDWHwLu.js → supervision-discovery-Da5zebY2.js} +130 -5
  67. package/dist/supervision-discovery-Da5zebY2.js.map +1 -0
  68. package/dist/{supervisor-B8beIEqH.js → supervisor-3JHXy3tz.js} +7336 -19680
  69. package/dist/supervisor-3JHXy3tz.js.map +1 -0
  70. package/dist/testing.d.ts +1 -1
  71. package/dist/testing.js +13 -13
  72. package/dist/{top-web-CUDlOKu0.js → top-web-DK6lTMHG.js} +89 -64
  73. package/dist/top-web-DK6lTMHG.js.map +1 -0
  74. package/dist/tui/bin.js +3 -3
  75. package/dist/tui/index.d.ts +14 -8
  76. package/dist/tui/index.js +2 -2
  77. package/dist/{types-DzS0kBeK.d.ts → types-S3RbyJ4x.d.ts} +51 -65
  78. package/dist/{sandbox-profile-compat-DRiz9kME.js → workspace-streams-Dep2L6XD.js} +617 -57
  79. package/dist/workspace-streams-Dep2L6XD.js.map +1 -0
  80. package/package.json +2 -2
  81. package/dist/coordination-manager-DNrb7zMg.js.map +0 -1
  82. package/dist/coordination-map-routing-CUvwHAtv.js.map +0 -1
  83. package/dist/graph-oOdDpXFH.js.map +0 -1
  84. package/dist/provision-supervisor-Pd95wA1X.js.map +0 -1
  85. package/dist/root-stream-Bsh5WFcg.js +0 -4252
  86. package/dist/root-stream-Bsh5WFcg.js.map +0 -1
  87. package/dist/run-cancellation-CzQZUlHr.js.map +0 -1
  88. package/dist/sandbox-profile-compat-DRiz9kME.js.map +0 -1
  89. package/dist/supervise-D1eYde7p.js.map +0 -1
  90. package/dist/supervision-discovery-DmDWHwLu.js.map +0 -1
  91. package/dist/supervisor-B8beIEqH.js.map +0 -1
  92. package/dist/top-web-CUDlOKu0.js.map +0 -1
  93. package/dist/util-BX20UJ9X.js +0 -624
  94. package/dist/util-BX20UJ9X.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"coordination-map-routing-CUvwHAtv.js","names":[],"sources":["../src/mcp/tools/coordination-json.ts","../src/mcp/tools/coordination-runtime-spawn.ts","../src/mcp/tools/coordination-map-routing.ts"],"sourcesContent":["/** 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). */\nexport function 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","import { errMessage } from '../../runtime/supervise/error-message'\nimport type { SpawnAdmission } from './coordination-contracts'\n\n/** What a keyed runtime spawn (a flow's entry or route, a map's item or join) became. */\nexport type RuntimeSpawnOutcome =\n /** `committed`: the key's done settlement is already on disk, so nothing ran and the caller\n * settles that result itself; no settlement drain will ever carry it. */\n | { readonly workerId: string; readonly committed: boolean }\n /** The key and its one replacement both have a prior worker started without a terminal receipt. */\n | { readonly inDoubt: true }\n | { readonly refused: string }\n\n/**\n * Admit one keyed runtime spawn. A key whose prior worker is in doubt (started in a dead process\n * with no terminal receipt) is re-admitted once under `<key>#2`, the replacement key the\n * `spawn_worker` contract names; a replacement that is in doubt too is reported, never retried.\n */\nexport async function admitRuntimeSpawn(\n admitSpawn: (input: SpawnAdmission) => Promise<unknown>,\n input: SpawnAdmission & { readonly key: string },\n): Promise<RuntimeSpawnOutcome> {\n for (const key of [input.key, `${input.key}#2`]) {\n let response: unknown\n try {\n response = await admitSpawn({ ...input, key })\n } catch (error) {\n return { refused: errMessage(error) }\n }\n const started = response as Partial<\n Record<'workerId' | 'resumed' | 'error' | 'reason', unknown>\n >\n if (typeof started.workerId === 'string') {\n return { workerId: started.workerId, committed: started.resumed === 'completed' }\n }\n if (started.error !== 'in-doubt') {\n return { refused: typeof started.reason === 'string' ? started.reason : 'spawn refused' }\n }\n }\n return { inDoubt: true }\n}\n","import type { AgentProfile } from '@tangle-network/agent-interface'\nimport type { Scope, Settled } from '../../runtime'\nimport { errMessage } from '../../runtime/supervise/error-message'\nimport type { EventBus } from '../../runtime/supervise/event-bus'\nimport { detachedFrozen } from '../../runtime/supervise/snapshot'\nimport type {\n CoordinationToolsOptions,\n SettledWorker,\n SpawnAdmission,\n} from './coordination-contracts'\nimport type { CoordinationEvent } from './coordination-events'\nimport { safeJsonText } from './coordination-json'\nimport type { MapOnSettleRoute, MapTraversalEvent } from './coordination-map-contracts'\nimport { admitRuntimeSpawn } from './coordination-runtime-spawn'\n\ninterface MapExpansion {\n readonly route: MapOnSettleRoute\n readonly sourceWorker: string\n /** The source node's 1-based done-settle count: its spawns' keys are\n * `map:<edge>#<expansion>:<index>` and `map:<edge>#<expansion>:join`. */\n readonly expansion: number\n readonly items: ReadonlyArray<unknown>\n readonly settlements: Array<WorkerSettlement | undefined>\n /** The next index to start. */\n next: number\n inFlight: number\n /** Set by a failed item under all-or-refuse: no further item starts. */\n stopped: boolean\n finished: boolean\n}\n\ninterface MapMember {\n readonly expansion: MapExpansion\n readonly role: 'item' | 'join'\n readonly index?: number\n readonly bytes: number\n}\n\ntype MapDeps = {\n readonly opts: CoordinationToolsOptions\n readonly bus: EventBus<CoordinationEvent>\n readonly admitSpawn: (input: SpawnAdmission) => Promise<unknown>\n /** The node a worker of this manager runs, by profile name. */\n readonly nodeOf: (workerId: string) => string | undefined\n /** Run a committed spawn's journaled settle through the live settle path. */\n readonly settleCommitted: (workerId: string, node: string) => Promise<void>\n /** End a flow whose map spawn is in doubt twice, at the node and source worker named. */\n readonly endInDoubt: (node: string, source: string) => Promise<void>\n}\n\n/** The map state one manager owns; every function below reads and writes it by reference. */\ntype MapState = MapDeps & {\n readonly mapRoutes: ReadonlyArray<MapOnSettleRoute>\n readonly mapMembers: Map<string, MapMember>\n readonly liveExpansions: Map<string, number>\n}\n\n// ── Map routes: fan-out over a run-time list, then one join ──\n// A map's items and its join are runtime spawns, like analyst runs: each takes the admission a\n// `spawn_worker` call takes, so the pool, the pre-flight and the pinning authority judge it, and\n// no manager turn is spent starting it.\nexport function createMapRouting(deps: MapDeps) {\n const state: MapState = {\n ...deps,\n mapRoutes: deps.opts.mapOnSettle ?? [],\n mapMembers: new Map(),\n liveExpansions: new Map(),\n }\n return {\n isItem: (workerId: string) => state.mapMembers.get(workerId)?.role === 'item',\n settleMapMember: settleMapMember.bind(null, state),\n expandMaps: expandMaps.bind(null, state),\n runMapStep: runMapStep.bind(null, state),\n }\n}\n\nexport const textBytes = (value: unknown): number => Buffer.byteLength(safeJsonText(value), 'utf8')\n\nasync function publishMap(\n { bus }: MapState,\n event: MapTraversalEvent,\n wake = false,\n): Promise<void> {\n const record = detachedFrozen<CoordinationEvent>({ type: 'map', map: event })\n if (wake) await bus.publish(record)\n else await bus.publish(record, { queue: false })\n}\n\n// The run's worker-slot bound, or undefined when only the pool bounds concurrency.\nfunction workerSlotBound({ opts }: MapState): number | undefined {\n const capacity = (opts.scope as Partial<Scope<unknown>>).workerCapacity\n if (capacity === undefined || capacity.freeSlots === null) return undefined\n return capacity.working + capacity.freeSlots\n}\n\n// A started spawn is a map member until it settles. A committed one (its key's done settlement\n// is on disk from a prior process) settles at once through the live settle path, so a restarted\n// manager re-expanding a map runs only the items with no done settlement, then the join once.\n// A spawn in doubt twice is refused, and ends a flow.\nasync function startMapSpawn(\n state: MapState,\n expansion: MapExpansion,\n role: 'item' | 'join',\n profile: AgentProfile,\n task: unknown,\n index: number | undefined,\n): Promise<{ readonly workerId: string } | { readonly refused: string }> {\n const { opts } = state\n const { route } = expansion\n const name = typeof profile.name === 'string' && profile.name.length > 0 ? profile.name : 'worker'\n const spawned = await admitRuntimeSpawn(state.admitSpawn, {\n profile,\n args: {\n label: index === undefined ? name : `${name}#${index}`,\n ...(role === 'item' && route.itemBudget !== undefined ? { budget: route.itemBudget } : {}),\n },\n task,\n key: `map:${route.edge}#${expansion.expansion}:${index ?? 'join'}`,\n continuity: { continuity: 'fresh' },\n successorOf: undefined,\n preflightProfile: () =>\n opts.resolveSpawnProfile ? detachedFrozen(opts.resolveSpawnProfile(profile)) : profile,\n resourcesFromPath: [],\n defaultLabel: name,\n map: Object.freeze({ edge: route.edge, role, ...(index === undefined ? {} : { index }) }),\n })\n if ('inDoubt' in spawned) {\n await state.endInDoubt(name, expansion.sourceWorker)\n return { refused: `in-doubt:${name}` }\n }\n if ('refused' in spawned) return spawned\n state.mapMembers.set(spawned.workerId, {\n expansion,\n role,\n ...(index === undefined ? {} : { index }),\n bytes: textBytes(task),\n })\n if (role === 'item') expansion.inFlight += 1\n if (spawned.committed) await state.settleCommitted(spawned.workerId, name)\n return { workerId: spawned.workerId }\n}\n\n// A graph item starts the way `run_graph` starts a graph: the run prepares the same root profile.\nasync function mapItemProfile(\n { opts }: MapState,\n route: MapOnSettleRoute,\n): Promise<{ readonly profile: AgentProfile } | { readonly refused: string }> {\n if ('profile' in route.item) return { profile: route.item.profile }\n if (!opts.graphs) {\n return { refused: 'a graph item starts through run_graph, which this manager does not serve' }\n }\n const prepared = await opts.graphs.prepare({ graph: route.item.graph })\n return prepared.ok ? { profile: detachedFrozen(prepared.profile) } : { refused: prepared.reason }\n}\n\n/** Record an item that never ran, and tell the manager. */\nasync function recordUnstartedItem(\n state: MapState,\n expansion: MapExpansion,\n index: number,\n reason: string,\n): Promise<void> {\n expansion.settlements[index] = { outcome: 'unpropagated', reason }\n await publishMap(state, {\n edge: expansion.route.edge,\n phase: 'item',\n outcome: 'unpropagated',\n sourceWorker: expansion.sourceWorker,\n index,\n bytes: 0,\n reason,\n })\n}\n\nasync function startMapItem(\n state: MapState,\n expansion: MapExpansion,\n index: number,\n): Promise<void> {\n const { route } = expansion\n const resolved = await mapItemProfile(state, route)\n const started =\n 'refused' in resolved\n ? resolved\n : await startMapSpawn(\n state,\n expansion,\n 'item',\n resolved.profile,\n expansion.items[index],\n index,\n )\n if ('workerId' in started) return\n if (route.onItemFailure === 'all-or-refuse') expansion.stopped = true\n await recordUnstartedItem(state, expansion, index, `item spawn refused: ${started.refused}`)\n}\n\n// Start items until the concurrency cap is reached, the list is exhausted, or all-or-refuse\n// stopped the map; once nothing is in flight, the map finishes.\nasync function pumpMap(state: MapState, expansion: MapExpansion): Promise<void> {\n const { route, items } = expansion\n while (\n !expansion.stopped &&\n expansion.inFlight < route.concurrency &&\n expansion.next < items.length\n ) {\n const index = expansion.next\n expansion.next += 1\n await startMapItem(state, expansion, index)\n }\n if (expansion.inFlight === 0) await finishMap(state, expansion)\n}\n\n// Every item settled or was never started: record the unstarted ones, then start the join with\n// the ordered results, or refuse it. `closed` names why a manager that already stopped does not\n// run the join; nobody would read it.\nasync function finishMap(state: MapState, expansion: MapExpansion, closed?: string): Promise<void> {\n if (expansion.finished) return\n expansion.finished = true\n const { route, items, sourceWorker } = expansion\n for (let index = expansion.next; index < items.length; index += 1) {\n const reason = closed ?? 'not started: all-or-refuse stopped this map after an item failed'\n await recordUnstartedItem(state, expansion, index, reason)\n }\n expansion.next = items.length\n const { results, failures } = collectJoinInputs(expansion)\n const refusal =\n closed ??\n (route.onItemFailure === 'all-or-refuse' && failures.length > 0\n ? `all-or-refuse: ${failures.length} of ${items.length} items did not deliver (${failures\n .map((failure) => `#${failure.index} ${failure.outcome}: ${failure.reason}`)\n .join('; ')}); the join did not run`\n : undefined)\n if (refusal !== undefined) {\n // No settlement follows a refused join, so this event is what wakes the manager.\n await publishMap(\n state,\n {\n edge: route.edge,\n phase: 'join',\n outcome: 'unpropagated',\n sourceWorker,\n bytes: 0,\n reason: refusal,\n },\n closed === undefined,\n )\n return\n }\n const task = { map: route.edge, source: sourceWorker, items: items.length, results, failures }\n const started = await startMapSpawn(state, expansion, 'join', route.join, task, undefined)\n if ('refused' in started) {\n await publishMap(\n state,\n {\n edge: route.edge,\n phase: 'join',\n outcome: 'unpropagated',\n sourceWorker,\n bytes: 0,\n reason: `join spawn refused: ${started.refused}`,\n },\n true,\n )\n }\n // A started join is recorded when it settles; its outcome is not known before.\n}\n\n/** Split an expansion's settlements into the delivered results and the failures, in item order. */\nfunction collectJoinInputs(expansion: MapExpansion) {\n const results: Array<{ index: number; item: unknown; result: unknown }> = []\n const failures: Array<{ index: number; item: unknown; outcome: string; reason: string }> = []\n expansion.items.forEach((item, index) => {\n const settlement = expansion.settlements[index]\n if (settlement?.outcome === 'delivered') {\n results.push({ index, item, result: settlement.result })\n } else {\n failures.push({\n index,\n item,\n outcome: settlement?.outcome ?? 'unpropagated',\n reason: settlement?.reason ?? 'never settled',\n })\n }\n })\n return { results, failures }\n}\n\n// A map item or join settled. `advance` is false once the manager stopped: no further item or\n// join starts, and what never started is recorded as such.\nasync function settleMapMember(\n state: MapState,\n settled: Settled<unknown>,\n worker: SettledWorker,\n advance: boolean,\n): Promise<void> {\n const member = state.mapMembers.get(worker.id)\n if (member === undefined) return\n state.mapMembers.delete(worker.id)\n const { expansion, role, index, bytes } = member\n const settlement = workerSettlement(settled, worker)\n await publishMap(state, {\n edge: expansion.route.edge,\n phase: role,\n outcome: settlement.outcome,\n sourceWorker: expansion.sourceWorker,\n ...(index === undefined ? {} : { index }),\n workerId: worker.id,\n bytes,\n ...(settlement.reason === undefined ? {} : { reason: settlement.reason }),\n })\n if (role === 'join' || index === undefined) return\n expansion.inFlight -= 1\n expansion.settlements[index] = settlement\n if (settlement.outcome !== 'delivered' && expansion.route.onItemFailure === 'all-or-refuse') {\n expansion.stopped = true\n }\n if (advance) await pumpMap(state, expansion)\n else if (expansion.inFlight === 0) {\n await finishMap(state, expansion, 'not started: the manager stopped before this map finished')\n }\n}\n\n// The expansion number of a source's done settle. A settle a prior process committed keeps the\n// number it had there (its rank among the resumed done settles of that node), so a replay\n// re-derives the keys that process journaled. A new settle counts on past every prior settle and\n// every journaled expansion: a root-driven graph replays no prior settle, and its driver may\n// label a worker other than by its node.\nfunction expansionOf(state: MapState, source: string, workerId: string): number {\n const resume = state.opts.scope.resume\n const labels = new Map(resume?.view.nodes.map((node) => [node.id, node.label]) ?? [])\n const prior = (resume?.settled ?? [])\n .filter((s) => s.kind === 'done' && labels.get(s.handle.id) === source)\n .map((s) => s.handle.id)\n const rank = prior.indexOf(workerId)\n if (rank >= 0) return rank + 1\n let journaled = 0\n for (const route of state.mapRoutes) {\n if (route.from !== source) continue\n const prefix = `key:map:${route.edge}#`\n for (const node of resume?.view.nodes ?? []) {\n if (!node.assignmentId?.startsWith(prefix)) continue\n const n = Number.parseInt(node.assignmentId.slice(prefix.length), 10)\n if (Number.isSafeInteger(n)) journaled = Math.max(journaled, n)\n }\n }\n const live = (state.liveExpansions.get(source) ?? 0) + 1\n state.liveExpansions.set(source, live)\n return Math.max(prior.length, journaled) + live\n}\n\n/** The list a map expands over, or the reason no item runs. */\nfunction resolveMapItems(\n state: MapState,\n out: unknown,\n route: MapOnSettleRoute,\n): { readonly items: ReadonlyArray<unknown> } | { readonly refusal: string } {\n const selected = resolveJsonPointer(out, route.pointer)\n if (!selected.found) {\n return {\n refusal: `pointer ${JSON.stringify(route.pointer)} does not resolve in the source result: ${selected.reason}; no item ran`,\n }\n }\n const items = selected.value\n if (!Array.isArray(items)) {\n return {\n refusal: `pointer ${JSON.stringify(route.pointer)} resolves to ${items === null ? 'null' : typeof items}, not an array; no item ran`,\n }\n }\n if (items.length > route.maxItems) {\n return {\n refusal: `max-items-exceeded: the list holds ${items.length} items and this map admits at most ${route.maxItems}; no item ran`,\n }\n }\n const slots = workerSlotBound(state)\n if (slots !== undefined && route.concurrency > slots) {\n return {\n refusal: `concurrency-unsatisfiable: concurrency ${route.concurrency} exceeds this run's ${slots} worker slots, so the cap could never be honored; no item ran`,\n }\n }\n return { items }\n}\n\n// A source settled `done`: expand every map that names it.\nasync function expandMaps(\n state: MapState,\n settled: Settled<unknown>,\n worker: SettledWorker,\n): Promise<void> {\n const { mapRoutes } = state\n if (settled.kind !== 'done' || mapRoutes.length === 0) return\n const name = state.nodeOf(worker.id)\n if (name === undefined || !mapRoutes.some((route) => route.from === name)) return\n const expansion = expansionOf(state, name, worker.id)\n for (const route of mapRoutes) {\n if (route.from !== name) continue\n const resolved = resolveMapItems(state, settled.out, route)\n if ('refusal' in resolved) {\n await publishMap(\n state,\n {\n edge: route.edge,\n phase: 'expand',\n outcome: 'unpropagated',\n sourceWorker: worker.id,\n bytes: 0,\n reason: resolved.refusal,\n },\n true,\n )\n continue\n }\n const { items } = resolved\n await publishMap(state, {\n edge: route.edge,\n phase: 'expand',\n outcome: items.length === 0 ? 'empty' : 'delivered',\n sourceWorker: worker.id,\n bytes: textBytes(items),\n items: items.length,\n ...(items.length === 0 ? { reason: 'the list is empty; the join runs with no results' } : {}),\n })\n await pumpMap(state, {\n route,\n sourceWorker: worker.id,\n expansion,\n items: detachedFrozen(items),\n settlements: [],\n next: 0,\n inFlight: 0,\n stopped: false,\n finished: false,\n })\n }\n}\n\n// Map steps run on the settlement path, which must never be taken down by them.\nasync function runMapStep(\n { opts }: MapState,\n step: () => Promise<void>,\n worker: SettledWorker,\n): Promise<void> {\n try {\n await step()\n } catch (error) {\n console.error('Runtime map step failed', {\n managerId: opts.scope.view.root,\n worker: worker.id,\n error: errMessage(error),\n })\n }\n}\n\n/** What one settle delivered. A settle is usable (`delivered`) when it settled `done`, its\n * deliverable check did not reject it, and its result is defined; maps and routes both read\n * results through this one rule. */\ninterface WorkerSettlement {\n readonly outcome: 'delivered' | 'empty' | 'failed' | 'unpropagated'\n readonly result?: unknown\n readonly reason?: string\n}\n\nexport function workerSettlement(\n settled: Settled<unknown>,\n worker: SettledWorker,\n): WorkerSettlement {\n if (settled.kind !== 'done' || worker.status !== 'done') {\n return { outcome: 'failed', reason: worker.status === 'down' ? worker.reason : 'down' }\n }\n if (worker.valid === false) {\n return { outcome: 'failed', reason: 'its deliverable check rejected the result' }\n }\n if (settled.out === undefined) return { outcome: 'empty', reason: 'it settled with no result' }\n return { outcome: 'delivered', result: settled.out }\n}\n\n/** Resolve an RFC 6901 JSON pointer (`''` is the whole document). */\nexport function resolveJsonPointer(\n document: unknown,\n pointer: string,\n):\n | { readonly found: true; readonly value: unknown }\n | { readonly found: false; readonly reason: string } {\n if (pointer === '') return { found: true, value: document }\n if (!pointer.startsWith('/')) {\n return { found: false, reason: 'a JSON pointer is empty or starts with \"/\"' }\n }\n let value = document\n for (const raw of pointer.slice(1).split('/')) {\n const token = raw.replaceAll('~1', '/').replaceAll('~0', '~')\n if (Array.isArray(value)) {\n if (!/^(0|[1-9]\\d*)$/.test(token) || Number(token) >= value.length) {\n return {\n found: false,\n reason: `no index ${JSON.stringify(token)} in an array of ${value.length}`,\n }\n }\n value = value[Number(token)]\n } else if (typeof value === 'object' && value !== null && Object.hasOwn(value, token)) {\n value = (value as Record<string, unknown>)[token]\n } else {\n return { found: false, reason: `no member ${JSON.stringify(token)}` }\n }\n }\n return { found: true, value }\n}\n"],"mappings":";;;;AAEA,SAAgB,aAAa,OAAwB;CACnD,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,IAAI;EACF,OAAO,KAAK,UAAU,KAAK,KAAK,OAAO,KAAK;CAC9C,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;AACF;;;;;;;ACQA,eAAsB,kBACpB,YACA,OAC8B;CAC9B,KAAK,MAAM,OAAO,CAAC,MAAM,KAAK,GAAG,MAAM,IAAI,GAAG,GAAG;EAC/C,IAAI;EACJ,IAAI;GACF,WAAW,MAAM,WAAW;IAAE,GAAG;IAAO;GAAI,CAAC;EAC/C,SAAS,OAAO;GACd,OA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CAAI;AACrD;;AAGA,SAAgB,mBACd,UACA,SAGqD;CACrD,IAAI,YAAY,IAAI,OAAO;EAAE,OAAO;EAAM,OAAO;CAAS;CAC1D,IAAI,CAAC,QAAQ,WAAW,GAAG,GACzB,OAAO;EAAE,OAAO;EAAO,QAAQ;CAA6C;CAE9E,IAAI,QAAQ;CACZ,KAAK,MAAM,OAAO,QAAQ,MAAM,CAAC,CAAC,CAAC,MAAM,GAAG,GAAG;EAC7C,MAAM,QAAQ,IAAI,WAAW,MAAM,GAAG,CAAC,CAAC,WAAW,MAAM,GAAG;EAC5D,IAAI,MAAM,QAAQ,KAAK,GAAG;GACxB,IAAI,CAAC,iBAAiB,KAAK,KAAK,KAAK,OAAO,KAAK,KAAK,MAAM,QAC1D,OAAO;IACL,OAAO;IACP,QAAQ,YAAY,KAAK,UAAU,KAAK,EAAE,kBAAkB,MAAM;GACpE;GAEF,QAAQ,MAAM,OAAO,KAAK;EAC5B,OAAO,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAO,OAAO,OAAO,KAAK,GAClF,QAAS,MAAkC;OAE3C,OAAO;GAAE,OAAO;GAAO,QAAQ,aAAa,KAAK,UAAU,KAAK;EAAI;CAExE;CACA,OAAO;EAAE,OAAO;EAAM;CAAM;AAC9B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"graph-oOdDpXFH.js","names":[],"sources":["../src/runtime/supervise/graph-backend.ts","../src/runtime/supervise/stored-graph-check.ts","../src/runtime/supervise/graph.ts"],"sourcesContent":["import { ValidationError } from '../../errors'\nimport type { RunGraphOptions } from './graph'\n\n/** Graph nodes share the same resumable Bridge transport as Braid. Hosts own its lifecycle. */\nexport function graphExecutionOptions(options: RunGraphOptions): RunGraphOptions {\n if (options.makeLeafAgent) return options\n const backend = options.backend\n if (backend)\n return backend.backend === 'bridge'\n ? { ...options, backend: { ...backend, outputFormat: 'json' } }\n : options\n const bridgeUrl = process.env.CLI_BRIDGE_URL\n const bridgeBearer = process.env.BRIDGE_BEARER ?? process.env.CLI_BRIDGE_BEARER\n if (!bridgeUrl || !bridgeBearer)\n throw new ValidationError(\n 'runGraph: start CLI Bridge and supply backend: { backend: \"bridge\", bridgeUrl, bridgeBearer, cwd }, or configure CLI_BRIDGE_URL and BRIDGE_BEARER',\n )\n return {\n ...options,\n backend: {\n backend: 'bridge',\n bridgeUrl,\n bridgeBearer,\n cwd: process.cwd(),\n outputFormat: 'json',\n },\n }\n}\n","import { mkdirSync, realpathSync } from 'node:fs'\nimport { isAbsolute, join, relative } from 'node:path'\nimport { contentAddress } from '../../durable/content-address'\nimport {\n appendCommittedJsonLine,\n readCommittedJsonLines,\n withJsonlFileLock,\n} from '../../durable/jsonl-file'\nimport { ValidationError } from '../../errors'\nimport { defaultRunCommand } from '../../mcp/worktree-harness'\nimport type { CompletionCheckContext } from './completion-gate'\nimport type { AgentGraph, RunGraphOptions } from './graph'\n\n/** An environment-owned check command, run outside the agent's conversation. */\nexport interface GraphCommandCheck {\n readonly command: string\n readonly timeoutMs?: number\n}\n\nexport interface GraphFromStoredOptions {\n readonly trigger?: Readonly<Record<string, unknown>>\n readonly checks?: Readonly<Record<string, AgentGraph['deliverable']['check'] | GraphCommandCheck>>\n}\n\ninterface CommandCheckReceipt {\n readonly version: 1\n readonly key: string\n readonly binding: string\n readonly checkDigest: string\n readonly nodeName: string\n readonly nodeId: string\n readonly attemptId: string\n readonly outputDigest: string\n readonly exitCode: number | null\n readonly output: string\n readonly outputTruncated: boolean\n readonly nativeValid: boolean\n readonly valid: boolean\n}\n\n/** Driver-owned journal identity. Worker output never supplies any part of this authority. */\nfunction receiptKey(receipt: Omit<CommandCheckReceipt, 'key'>): string {\n return contentAddress({\n binding: receipt.binding,\n checkDigest: receipt.checkDigest,\n nodeName: receipt.nodeName,\n nodeId: receipt.nodeId,\n attemptId: receipt.attemptId,\n outputDigest: receipt.outputDigest,\n })\n}\n\nfunction isReceipt(value: unknown): value is CommandCheckReceipt {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false\n const row = value as Record<string, unknown>\n if (\n row.version !== 1 ||\n ![\n 'key',\n 'binding',\n 'checkDigest',\n 'nodeName',\n 'nodeId',\n 'attemptId',\n 'outputDigest',\n 'output',\n ].every((key) => typeof row[key] === 'string') ||\n !row.nodeName ||\n !row.nodeId ||\n !row.attemptId ||\n !(row.exitCode === null || Number.isSafeInteger(row.exitCode)) ||\n typeof row.outputTruncated !== 'boolean' ||\n typeof row.nativeValid !== 'boolean' ||\n typeof row.valid !== 'boolean'\n )\n return false\n const receipt = value as CommandCheckReceipt\n return (\n receipt.key === receiptKey(receipt) &&\n receipt.valid === (receipt.exitCode === 0 && receipt.nativeValid)\n )\n}\n\nfunction within(directory: string, path: string): boolean {\n const offset = relative(directory, path)\n return offset === '' || (!isAbsolute(offset) && offset !== '..' && !offset.startsWith('../'))\n}\n\n/** Lower a named check onto the local workspace, with evidence in the driver's durable state.\n * The run directory has the same trust boundary as RunContext journals: keep it outside the\n * worker workspace and do not mount it into the worker. A remote Bridge cannot run a host check.\n * Provider validators are refused because their context does not identify the admitted node.\n */\nexport function bindGraphCommand(\n graph: AgentGraph,\n options: RunGraphOptions,\n): { graph: AgentGraph; options: RunGraphOptions } {\n const { command: definition, ...deliverable } = graph.deliverable\n if (!definition) return { graph, options }\n const { command, timeoutMs = 60_000 } = definition\n if (!command.trim() || !Number.isSafeInteger(timeoutMs) || timeoutMs <= 0)\n throw new ValidationError(\n 'graphFromStored: command check needs a command and positive timeoutMs',\n )\n const backend = options.backend\n if (options.makeLeafAgent || !backend)\n throw new ValidationError('runGraph: command checks require an explicit execution backend')\n const workspace =\n backend.backend === 'bridge'\n ? backend.cwd\n : backend.backend === 'cli-in-place'\n ? backend.workspacePath\n : undefined\n if (\n !workspace ||\n (backend.backend === 'bridge' &&\n !['localhost', '127.0.0.1', '[::1]'].includes(new URL(backend.bridgeUrl).hostname))\n )\n throw new ValidationError(\n 'runGraph: command checks require a loopback Bridge or local CLI workspace; provider node binding is unsupported',\n )\n if (!options.runDir)\n throw new ValidationError(\n 'runGraph: command checks require a driver-owned runDir outside the workspace',\n )\n const cwd = realpathSync(workspace)\n mkdirSync(options.runDir, { recursive: true })\n const runDir = realpathSync(options.runDir)\n if (within(cwd, runDir))\n throw new ValidationError('runGraph: command check runDir must be outside the worker workspace')\n const file = join(runDir, 'command-checks.jsonl')\n const checkDigest = contentAddress({ command, timeoutMs, cwd })\n const binding = contentAddress({\n graph: { ...graph, deliverable: { ...deliverable, check: undefined } },\n runId: options.runId ?? options.runContext?.runId,\n checkDigest,\n })\n const nodeNames = new Set(graph.nodes.map((node) => node.id))\n\n // The map is supplied by Runtime's flow finalizer. It contains terminal graph node IDs and\n // outputs, never receipt metadata. Every match must come from this run's driver journal.\n const checkFinal = async (out: unknown): Promise<boolean> => {\n if (!out || typeof out !== 'object' || Array.isArray(out)) return false\n const entries = Object.entries(out)\n if (entries.length === 0 || entries.some(([name]) => !nodeNames.has(name))) return false\n return withJsonlFileLock(file, async (canonicalPath) => {\n if (within(cwd, canonicalPath)) return false\n const latest = new Map<string, CommandCheckReceipt>()\n for await (const raw of readCommittedJsonLines<unknown>(canonicalPath, {\n allowMissing: true,\n })) {\n if (!isReceipt(raw)) return false\n if (raw.binding !== binding || raw.checkDigest !== checkDigest) continue\n latest.set(contentAddress([raw.nodeName, raw.outputDigest]), raw)\n }\n return entries.every(\n ([name, output]) =>\n latest.get(contentAddress([name, contentAddress(output)]))?.valid === true,\n )\n })\n }\n\n const checkLeaf = async (out: unknown, context: CompletionCheckContext): Promise<boolean> => {\n const node = context.node\n const nodeName = context.profile.name\n if (!node || !node.nodeId || !node.attemptId || !nodeName || !nodeNames.has(nodeName))\n return false\n // Always execute for a fresh leaf. A prior success, even for identical output, never skips\n // this check. gateFactoryOnDeliverable deduplicates only one invocation's exact artifact.\n const outputDigest = contentAddress(out)\n let result: { exitCode: number | null; output: string }\n try {\n result = await defaultRunCommand({ command, cwd, timeoutMs, signal: context.signal })\n } catch (error) {\n // An unavailable check invalidates an earlier identical output too; it cannot inherit\n // a prior success just because the current command did not reach a normal exit.\n result = { exitCode: null, output: error instanceof Error ? error.message : String(error) }\n }\n const bytes = Buffer.from(result.output)\n const limit = 64 * 1024\n const receipt: Omit<CommandCheckReceipt, 'key'> = {\n version: 1,\n binding,\n checkDigest,\n nodeName,\n nodeId: node.nodeId,\n attemptId: node.attemptId,\n outputDigest,\n exitCode: result.exitCode,\n output: bytes.subarray(0, limit).toString('utf8'),\n outputTruncated: bytes.length > limit,\n nativeValid: context.originalVerdict?.valid !== false,\n valid: result.exitCode === 0 && context.originalVerdict?.valid !== false,\n }\n await withJsonlFileLock(file, async (canonicalPath) => {\n if (within(cwd, canonicalPath))\n throw new ValidationError(\n 'runGraph: command receipt journal resolves inside worker workspace',\n )\n await appendCommittedJsonLine(canonicalPath, { ...receipt, key: receiptKey(receipt) })\n })\n return receipt.valid\n }\n return {\n graph: {\n ...graph,\n deliverable: {\n ...deliverable,\n check: (out, context) =>\n context === undefined ? checkFinal(out) : checkLeaf(out, context),\n },\n },\n options,\n }\n}\n","/**\n *\n * `runGraph` — agent graphs: profiles as nodes, registry-backed prompt directives as edges.\n *\n * A topology is PLAIN DATA an agent can author in a few lines: nodes are canonical\n * `AgentProfile`s (the ONLY way a node is described — no role-builder functions), edges are typed\n * values carrying versioned {@link PromptHandle} directives, `deliverable` (termination) and\n * `budget` (one conserved pool) are mandatory. Driver↔worker is the two-node cyclic instance;\n * \"agent 3 analyzes 1 and 2 and reports to 1\" is ONE edge, not a framework.\n *\n * NOT A SECOND SCHEDULER. `runGraph` is an interpretation layer over what already runs:\n * `supervise()` is the execution core — the same `supervisorAgent`/`driverAgent` machinery,\n * backend-derived worker path (authorized, classified, recursive), conserved-pool budget, and\n * deliverable-gated settlement every\n * supervised run uses. (`runAgentRounds` is deliberately NOT the substrate here.) What the graph\n * layer ADDS is exactly what a bespoke driver loop never\n * had:\n *\n * 1. **Node pinning** — a spawn names a node (`profile.name` = node id) and the node's canonical\n * profile is what runs; a driver cannot smuggle capabilities into a worker it did not define.\n * 2. **Observable edges** — every delegates/analyzes/maps/routes traversal lands in an EDGE LEDGER\n * (`delivered | stripped | empty | unpropagated | failed`, with byte counts), in memory on\n * the result AND as `edge` events in the run journal. The motivating incident: a filter\n * silently replaced 1,700-char steering with 241 chars of boilerplate for three rounds and\n * NO artifact said so — an unobservable edge cannot be trusted and its directive cannot be\n * optimized.\n * 3. **Directives as data** — edge text lives in the prompt registry (`<surface>/v<n>`), so every\n * edge is a versioned optimization target, never prose hardcoded in a builder function.\n * 4. **Per-edge traversal caps** — the cyclic-graph backstop. A delegates edge whose cap is\n * exhausted REFUSES further traversals (fail loud), so a cycle cannot spin the pool dry.\n * 5. **Continuity as data** — a delegates edge may declare `continuity: 'resume'`, so each spawn\n * after the node's first re-attaches to its latest SETTLED session (the spawn context hands\n * the executor seam `resume: { ofWorker, sequence }`; the kernel keeps identity, ordering,\n * ledger truth, and the one conserved pool). Every ledger row states how its hop continued:\n * `'fresh' | 'resume'` for spawns, `'steer'` for mid-run deliveries — fresh respawns, session\n * resumes, and live steers are all plain data, each a ledgered fact.\n * 6. **Fan-out over a run-time list** — a `maps` edge takes the array a JSON pointer selects in a\n * node's settled result and runs one item per element, then hands the ordered results to a\n * join node. The runtime spawns every item and the join when the source settles, so the\n * driver spends no model turn on them; each item is a spawn through the same authorized path,\n * reserving from the same conserved pool, and every expansion, item and join is a ledger row.\n * 7. **Flow graphs** — with `entry` set, no node is a root: Runtime spawns the entries and fires\n * `routes` edges on each settle (`graph-flow.ts`), so a fixed order, a branch, a bounded repair\n * loop and a stop rule are graph data. The root manager is Runtime's own and never calls a\n * model; every entry and route spawn takes the same authorized path a map item takes.\n *\n * ORACLES ARE ENVIRONMENT, NEVER WORKERS. Graders/verifiers must not be spawnable in the graph —\n * a delegates edge to them leaks the rubric. An `analyzes` edge names its analyst in one of two\n * forms: a LENS id from the environment's registry (a pure function over trace evidence), or the\n * id of a graph NODE — a tool-equipped analyst AGENT spawned on each matching settle with the\n * node's pinned profile, whose settle output IS the findings. Either way the oracle doctrine\n * holds: an analyst node can never be a delegates target (refused loudly), so no driver can hand\n * it work, and an id living in both the registry and the nodes is refused as ambiguous.\n *\n * @experimental\n */\n\nimport { resolve } from 'node:path'\nimport { type AgentProfile, canonicalCandidateDigest } from '@tangle-network/agent-interface'\nimport { ConfigError, ValidationError } from '../../errors'\nimport type { AnalystRegistry } from '../../mcp/tools/coordination-analysts'\nimport type { MakeWorkerAgent } from '../../mcp/tools/coordination-contracts'\nimport type { MapItemFailurePolicy } from '../../mcp/tools/coordination-map-contracts'\nimport type { ContinuityMode } from '../../mcp/tools/coordination-messages'\nimport type {\n GateDecision,\n GateDecisionRecord,\n GateRequest,\n RouteGate,\n RouteWhen,\n} from '../../mcp/tools/coordination-route-contracts'\nimport { composeRuntimeHooks, type RuntimeHooks } from '../../runtime-hooks'\nimport { harnessRunsAgent } from '../harness-role'\nimport type { ToolLoopChat } from '../tool-loop'\nimport type { DeliverableSpec } from './completion-gate'\nimport { runtimeFlowBrain } from './flow-brain'\nimport { graphExecutionOptions } from './graph-backend'\nimport {\n createFlowRun,\n flowRootProfile,\n flowRouteDeliverable,\n GraphRouteError,\n journaledGateDecider,\n routeFlowOf,\n validateFlowGraph,\n} from './graph-flow'\nimport { createGraphOverlay } from './graph-overlay'\nimport {\n graphRootProfile,\n type RootValidatedGraph,\n type ValidatedGraph,\n validateGraphTopology,\n} from './graph-topology'\nimport { kernelPromptRegistry, type PromptHandle, type PromptRegistry } from './prompt-registry'\nimport { createFileRunContext, createInMemoryRunContext, withRunContext } from './run-context'\nimport { bindGraphCommand, type GraphCommandCheck } from './stored-graph-check'\nimport {\n profileGuidanceComposer,\n type SuperviseOptions,\n supervise,\n superviseWithTestBrain,\n} from './supervise'\nimport type { Budget, NodeId, ResultBlobStore, SpawnJournal, SupervisedResult } from './types'\n\nexport type { MapItemFailurePolicy } from '../../mcp/tools/coordination-map-contracts'\nexport type {\n GateDecision,\n GateRequest,\n JsonScalar,\n RouteGate as GraphGate,\n RouteMatch,\n RouteWhen,\n} from '../../mcp/tools/coordination-route-contracts'\nexport { GraphRouteError } from './graph-flow'\nexport { defaultEdgeTraversalCap } from './graph-topology'\n\n// ── The algebra ────────────────────────────────────────────────────────────────\n\n/** A graph node: an id and a canonical `AgentProfile`. The profile is the ONLY way a node is\n * described — its `prompt.systemPrompt` is the standing role (the 0.117 canonical resolution;\n * never a legacy top-level-only reduction), its tools/mcp/resources are its capabilities. */\nexport interface GraphNode {\n readonly id: NodeId\n readonly profile: AgentProfile\n}\n\nexport type GraphEdge =\n /** Work flows down. The delegation directive is DATA → versionable, sweepable, optimizable.\n * Each spawn of `to` by `from` — and each mid-run steer from `from` to a live `to` worker —\n * is one traversal. */\n | {\n readonly kind: 'delegates'\n readonly from: NodeId\n readonly to: NodeId\n readonly directive: PromptHandle\n /** Cyclic-graph backstop: traversals beyond this REFUSE (fail loud). Default\n * {@link defaultEdgeTraversalCap}. */\n readonly maxTraversals?: number\n /** Default continuity for this edge's SPAWN traversals. `'resume'` makes every spawn after\n * the node's first re-attach to its most recent SETTLED worker: a NEW live worker whose\n * spawn context carries `resume: { ofWorker, sequence }` for the executor seam, spending\n * from the same conserved pool — the node's first spawn is effectively `'fresh'`, and a\n * spawn while a prior worker is still live refuses loudly (steer is the live channel).\n * The driver's per-call `spawn_worker` `continuity` argument overrides either way. Omit =\n * `'fresh'` (today's behavior, byte-identical). Caps count resumes exactly like fresh\n * spawns. */\n readonly continuity?: ContinuityMode\n }\n /** Findings flow anywhere: an analyst over N nodes' settled traces, delivered to ONE node.\n * With a LENS analyst the directive wraps the findings for the recipient; with a NODE analyst\n * the directive is the analyst agent's task and the findings are its settle output. */\n | {\n readonly kind: 'analyzes'\n /** The analyst REFERENCE, in one of two forms: a lens id resolved against\n * `RunGraphOptions.analysts` (environment), or the id of a graph NODE with no delegates\n * edge pointing at it — then each matching settle spawns that node's pinned profile as a\n * tool-equipped analyst WORKER (same spawn machinery, conserved budget, trace join) whose\n * task is this edge's directive plus the settled worker's trace evidence and whose settle\n * output is the findings. An id that is both a node and a registry lens is refused. */\n readonly analyst: string\n readonly over: ReadonlyArray<NodeId>\n readonly to: NodeId\n readonly directive: PromptHandle\n /** Observability cap: traversals beyond this are LEDGERED as exhausted (`unpropagated`).\n * Only delegates caps refuse traversal — they are what close the spawn cycle. */\n readonly maxTraversals?: number\n }\n /**\n * Fan-out over a list that exists only at run time, then one join. When `from` settles `done`,\n * the array at `pointer` in its result is expanded: each element becomes the TASK of one item\n * run, at most `concurrency` at a time, and once every item settled the `join` node runs with\n * `{ map, source, items, results: [{ index, item, result }], failures: [{ index, item, outcome,\n * reason }] }`, results in item order. The runtime spawns the items and the join (`from`'s\n * driver spends no turn on them) through the same authorized spawn path a delegates spawn\n * takes: each item reserves its budget from the one conserved pool and is pinned to the edge's\n * profile, so an item's content can never choose what runs.\n *\n * An item is either the node `to` (its pinned profile plus this edge's directive) or the nested\n * `graph`, started per item exactly as `run_graph` starts a graph. Refusals are loud and\n * ledgered, and the driver is woken with them: a pointer that does not resolve to an array, more\n * elements than `maxItems`, or a `concurrency` the run's worker-slot bound can never honor.\n * `concurrency` otherwise THROTTLES (items wait for a free place); it never refuses an item.\n *\n * An edge rather than a node-level spec, because every kernel invariant a map must keep already\n * attaches to edge traversal: pinning admits only the edge's item and join nodes (the spawn\n * context carries a runtime-authored `map` marker), each item is admitted like a spawn and\n * reserves from the conserved pool, each item settles under its own deliverable check, and each\n * expansion, item and join is a ledger row with its journal twin. Topology stays static; only the\n * traversal count is dynamic, so validation and the one-node-one-profile rule are unchanged.\n */\n | {\n readonly kind: 'maps'\n /** The source node: a delegates target, or the join of another maps edge. Each of its `done`\n * settles expands the map once. */\n readonly from: NodeId\n /** RFC 6901 JSON pointer into `from`'s settled result (`''` is the whole result). */\n readonly pointer: string\n /** The item node, run once per element with the element as its task. Exactly one of `to`\n * and `graph`. Reachable only through this edge: never a delegates target. */\n readonly to?: NodeId\n /** A graph run per element as one subtask, through the `run_graph` path. */\n readonly graph?: GraphTopology\n /** Receives the ordered results once every item settled. Reachable only through this edge. */\n readonly join: NodeId\n /** The item directive, appended to the item node's instructions per traversal. */\n readonly directive: PromptHandle\n /** Lists longer than this are refused before any item runs. */\n readonly maxItems: number\n /** How many items run at once. */\n readonly concurrency: number\n readonly onItemFailure: MapItemFailurePolicy\n /** Each item's budget, merged over the per-worker default as `spawn_worker`'s `budget` is. */\n readonly itemBudget?: Partial<Budget>\n }\n /**\n * A route in a flow graph (one with `entry`): Runtime traverses it when `from` settles, so no\n * root decides the order, the branch, the repair loop or the stop. On each usable settle of\n * `from` its outgoing routes edges are tried in declaration order and the first whose `when`\n * holds fires; an edge without `when` is the default branch and comes last. A node target is\n * spawned with `{ from: { node, result }, evidence: { [id]: latest usable result } }` (a join's\n * target with `{ from: { nodes }, evidence }`, see below) and the directive appended to its pinned instructions; `{ stop }` ends the run with no winner and\n * `GraphResult.stopped`; `{ finish }` makes this settle part of the run's output.\n *\n * A fork lists two or more nodes in `to`: one traversal spawns each of them at once, each under\n * its own key `route:<edge id>#<traversal>:<node>`. A join lists two or more nodes in `from`: it\n * fires once every member has settled usably since it last fired, and the target's task is\n * `{ from: { nodes: <members in declared order> }, evidence }` with each member's latest result\n * in `evidence`, so it does not depend on which member settled last and a resumed run derives the\n * same task. A routes edge that spawns a node with a settled worker in this flow (a back edge)\n * names that node's latest settled worker as the spawn's `successorOf`. A join carries no `when`, and it is the only routes edge\n * leaving each of its members. A route into a node that still has a running worker throws\n * {@link GraphRouteError} with reason `target-live`: converging branches use a join.\n */\n | {\n readonly kind: 'routes'\n readonly from: NodeId | ReadonlyArray<NodeId>\n readonly to:\n | NodeId\n | ReadonlyArray<NodeId>\n | { readonly stop: string }\n | { readonly finish: string }\n readonly directive: PromptHandle\n /** Absent on the default edge and on every join. A match reads `from` unless it names a node\n * in `evidence`. */\n readonly when?: RouteWhen\n /** Nodes whose latest usable result rides the target's task. */\n readonly evidence?: ReadonlyArray<NodeId>\n /** Traversals beyond this are skipped (ledgered `unpropagated`) and matching continues with\n * the next edge. Default {@link defaultEdgeTraversalCap}. Every routes cycle, each subcycle\n * included, must cross an edge that sets it. */\n readonly maxTraversals?: number\n /** `'resume'` re-attaches each spawn of the target to its latest settled session. Omit =\n * `'fresh'`. */\n readonly continuity?: ContinuityMode\n }\n\n/** A topology without the run's own budget and deliverable: the form a `maps` edge runs per item,\n * as `run_graph` runs it. With `entry` it is a flow graph. Inside a maps item, the item value is\n * the task of every entry whose task is the placeholder `{ item: true }`; a down settle inside the item ends\n * that item only, and the maps edge's `onItemFailure` decides the join. */\nexport interface GraphTopology {\n readonly nodes: ReadonlyArray<GraphNode>\n readonly edges: ReadonlyArray<GraphEdge>\n readonly entry?: AgentGraph['entry']\n /** Refused here: a maps item's graph and a `run_graph` subtask have no `decideGate`. */\n readonly gates?: AgentGraph['gates']\n}\n\nexport interface AgentGraph {\n /** Preserve fully bound literal data when serializing a hydrated graph. */\n readonly triggerBindings?: readonly []\n readonly nodes: ReadonlyArray<GraphNode>\n readonly edges: ReadonlyArray<GraphEdge>\n /** Termination is mandatory, not optional: the independent completion oracle. */\n readonly deliverable: DeliverableSpec<unknown> & {\n readonly checkRef?: string\n readonly command?: GraphCommandCheck\n readonly when?: RouteWhen\n }\n /** One conserved pool across the whole graph — cycles without conservation never terminate. */\n readonly budget: Budget\n /** Setting it makes this a FLOW graph: Runtime spawns every entry at once, each with its task,\n * and traverses `routes` edges itself. No node is a root and no caller brain runs; the run's\n * output is `{ [node]: latest usable result }` over its terminal nodes and `finish` sources,\n * judged by `deliverable`. A stored route check (`checkRef: 'route'`) may also name a\n * non-terminal node: its condition reads that node's latest delivered output, while the output\n * stays terminal-only. */\n readonly entry?: ReadonlyArray<{ readonly node: NodeId; readonly task: unknown }>\n /** Flow-graph vertices that are not agents: a routes edge into one awaits\n * `RunGraphOptions.decideGate`, and one edge per choice leaves it, matching\n * `{ pointer: '/choice', equals: <choice> }`. A `finish` leaving a gate outputs\n * `{ [gate]: { choice, by } }`. */\n readonly gates?: ReadonlyArray<RouteGate>\n}\n\n// ── The edge ledger ────────────────────────────────────────────────────────────\n\n/** `failed` is a maps item or join that ran and settled without a usable result (down, or\n * rejected by its deliverable check); a traversal that never reached a worker is `unpropagated`. */\nexport type EdgeDeliveryOutcome = 'delivered' | 'stripped' | 'empty' | 'unpropagated' | 'failed'\n\n/** How one ledgered hop CONTINUED: a spawn traversal stamps its effective spawn mode\n * (`'fresh'` | `'resume'`), and every mid-run delivery into an already-live recipient — a\n * driver steer leg and every analyzes delivery (routed steer or driver-destined finding) —\n * stamps `'steer'`. Zero ambiguity: every row carries exactly one of the three. */\nexport type TraversalContinuity = ContinuityMode | 'steer'\n\n/** One recorded edge traversal — the in-memory row; the journal twin is the `edge` SpawnEvent. */\nexport interface EdgeTraversal {\n /** Stable edge id: `delegates:<from>-><to>`, `analyzes:<analyst>:<over…>-><to>`,\n * `maps:<from>-><to | graph>-><join>`, `routes:<from>#<ordinal>-><to | stop:<reason> |\n * finish:<reason>>`, or `routes:entry-><node>` for an entry. */\n readonly edge: string\n readonly kind: 'delegates' | 'analyzes' | 'maps' | 'routes'\n readonly from: string\n readonly to: string\n /** The resolved directive reference (`<surface>/v<n>`). */\n readonly directive: string\n /** 1-based per-edge ordinal. */\n readonly traversal: number\n readonly outcome: EdgeDeliveryOutcome\n /** How this hop continued — see {@link TraversalContinuity}. */\n readonly continuity: TraversalContinuity\n /** Bytes of directive + payload that actually crossed the edge. */\n readonly bytes: number\n readonly reason?: string\n /** The concrete worker node id, once known. A maps expansion names the source worker. */\n readonly workerId?: string\n /** Present on maps rows: the expansion of the source's list, one item by its index, or the\n * join. */\n readonly map?: { readonly phase: 'expand' | 'item' | 'join'; readonly index?: number }\n /** Present on a gate's decision row (`gate:<id>`, `traversal` = visit): who decided, and what. */\n readonly gate?: GateDecisionRecord\n}\n\n/** A delegates edge exhausted its traversal cap and the run produced no winner: the cap, not the\n * task, ended it. Carries the full evidence so failing loud loses nothing. */\nexport class GraphEdgeCapError extends Error {\n readonly exhaustedEdges: ReadonlyArray<string>\n readonly ledger: ReadonlyArray<EdgeTraversal>\n readonly result: SupervisedResult<unknown>\n constructor(\n exhaustedEdges: ReadonlyArray<string>,\n ledger: ReadonlyArray<EdgeTraversal>,\n result: SupervisedResult<unknown>,\n ) {\n super(\n `runGraph: edge traversal cap exhausted on ${exhaustedEdges.join(', ')} and the run ` +\n 'delivered no winner — the cap (the cyclic-graph backstop), not the task, ended this run. ' +\n 'Raise maxTraversals on the edge or fix the cycle; the full edge ledger and the ' +\n 'supervised result ride on this error.',\n )\n this.name = 'GraphEdgeCapError'\n this.exhaustedEdges = exhaustedEdges\n this.ledger = ledger\n this.result = result\n }\n}\n\n// ── Options / result ───────────────────────────────────────────────────────────\n\n/**\n * Every `SuperviseOptions` key, partitioned by what `runGraph` does with it.\n *\n * `runGraph` starts one `supervise()` run, so every option that run honors is a graph option too\n * unless the graph itself owns the value. This used to be an opt-in list written by hand, and the\n * hand lost: 25 of 49 keys never reached `supervise()` from a graph, including `childSettleGraceMs`\n * (a root-driver failure tore down children that had ALREADY computed the deliverable) and\n * `driverRetry` (agent-runtime#963). Each absence was discovered by losing a run.\n *\n * The four lists below must cover `keyof SuperviseOptions` exactly. `everySuperviseOptionIsClassified`\n * below fails to COMPILE, naming the offender, when a key belongs to none of them — so the next\n * option added to `supervise()` cannot go missing here silently. It has to be classified, and\n * classifying it as forwarded is one word.\n */\n\n/** The graph derives these from the `AgentGraph` itself; a caller value would be overwritten. */\nconst GRAPH_OWNED_SUPERVISE_OPTIONS = [\n 'rootDriverFromBackend',\n 'resolveSpawnProfile',\n 'budget',\n 'deliverable',\n 'makeWorkerAgent',\n 'onCoordinationEvent',\n 'analyzeOnSettle',\n 'mapOnSettle',\n // A flow graph's entries and routes edges; its runtime-owned root runs them.\n 'routeFlow',\n 'continuityByProfile',\n // A graph pins every node and its delegation edges; a node never gains spawn rights it lacks.\n 'inheritSpawnRights',\n] as const\n\n/** Caller-facing on `RunGraphOptions`, but the graph wraps or defaults the value before it goes in:\n * `hooks` composes with the graph's own spawn-binding hook, `authorizeMessage` is wrapped so a\n * narrowed instruction ledgers `stripped`, `authorizeSpawn` runs AFTER the graph has pinned the\n * node (so a product sees the canonical profile, never the driver's stub), `makeLeafAgent` is the\n * caller's leaf override slotted under the graph's pinning, `analysts` rides only with analyze\n * routes, and `journal`/`blobs`/`runId` get graph defaults. */\nconst GRAPH_TRANSFORMED_SUPERVISE_OPTIONS = [\n 'hooks',\n 'authorizeMessage',\n 'authorizeSpawn',\n 'makeLeafAgent',\n 'analysts',\n 'journal',\n 'blobs',\n 'runId',\n // Replays a journaled decision before asking the caller.\n 'decideGate',\n] as const\n\n/** Not reachable from a graph, with the reason. `registry` is a NAME COLLISION, not a policy:\n * `RunGraphOptions.registry` is the directive `PromptRegistry` and `SuperviseOptions.registry` is\n * the `SuperviseRegistry` name→value table. Two different types under one name; the graph's wins.\n * Giving the supervise one a graph channel means renaming a public option, so it is recorded here\n * rather than silently dropped. */\nconst GRAPH_REFUSED_SUPERVISE_OPTIONS = ['registry'] as const\n\n/**\n * Forwarded to the root `supervise()` VERBATIM. Everything not owned, transformed, or refused\n * above belongs here — the default is \"a graph honors it\", not \"someone remembered to add it\".\n */\nconst GRAPH_FORWARDED_SUPERVISE_OPTIONS = [\n 'parking',\n 'backend',\n // Forwarded: composes guidance into the root and into profiles a manager authors. The graph also\n // composes each PINNED node profile, because pinning replaces the composed `{ name }` stub.\n 'profileGuidance',\n // Forwarded, not graph-owned: a graph pins WHICH nodes run, never who answers a question one of\n // them raises. Without it a graph run's `ask_parent` would always report `no-parent` even when\n // the caller wired an inbox.\n 'escalateQuestion',\n 'rootHandle',\n 'signal',\n 'execution',\n 'resolveDeliverable',\n 'coordination',\n 'peerMail',\n 'peerAudit',\n 'traceTools',\n 'driverBackend',\n 'profileSecurity',\n 'authorizeSpawn',\n 'router',\n 'driveHarness',\n 'selectSeat',\n 'driverRetry',\n 'onDriverAttempt',\n 'workerRetry',\n 'onWorkerRetry',\n 'continuation',\n 'childSettleGraceMs',\n 'teardownConfirmMs',\n 'retainedAtSettlement',\n 'resolveDriveHarness',\n 'driveHarnessMaterialization',\n 'resolveSupervisorTools',\n 'extraTools',\n 'executeExtraTool',\n 'recoverExecutor',\n 'perWorker',\n 'reservationPolicy',\n 'deadlineCheckIn',\n 'budgetStopHoldMs',\n 'workerSlots',\n 'watchWorkers',\n 'stallAfterMs',\n 'wake',\n 'runDir',\n 'resume',\n 'segment',\n 'runContext',\n 'steerDir',\n 'stopRule',\n 'onProgressStop',\n 'maxDepth',\n 'maxTurns',\n 'compaction',\n 'now',\n 'allowedModels',\n 'finalizer',\n 'otel',\n // Forwarded: the registry a manager's `run_graph` resolves stored graphs against. A node of this\n // graph cannot start another graph (pinning refuses it), so it matters to no node here.\n 'graphRegistry',\n] as const\n\ntype ClassifiedSuperviseOption =\n | (typeof GRAPH_OWNED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_TRANSFORMED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_REFUSED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]\n\n/**\n * Every key `RunGraphOptions` accepts, as data: the forwarded and transformed `SuperviseOptions`\n * keys, the name-colliding `registry`, and the graph's own `brain`. `GRAPH_OWNED_SUPERVISE_OPTIONS`\n * is deliberately absent — a caller value for one of those is overwritten by the graph, so it is\n * refused by name rather than discarded.\n *\n * The assignment below fails to COMPILE, naming the key, when `RunGraphOptions` declares something\n * this list does not carry.\n */\nconst runGraphOptionKeys = [\n ...GRAPH_FORWARDED_SUPERVISE_OPTIONS,\n ...GRAPH_TRANSFORMED_SUPERVISE_OPTIONS,\n ...GRAPH_REFUSED_SUPERVISE_OPTIONS,\n 'brain',\n] as const\n\ntype UnlistedRunGraphOption = Exclude<keyof RunGraphOptions, (typeof runGraphOptionKeys)[number]>\nconst everyRunGraphOptionIsListed: UnlistedRunGraphOption extends never\n ? true\n : UnlistedRunGraphOption = true\nvoid everyRunGraphOptionIsListed\n\nconst runGraphOptionKeySet: ReadonlySet<string> = new Set<string>(runGraphOptionKeys)\nconst graphOwnedOptionKeySet: ReadonlySet<string> = new Set<string>(GRAPH_OWNED_SUPERVISE_OPTIONS)\n\n/**\n * Refuse an option key the graph would not read, naming it and saying which kind it is.\n *\n * A graph-owned key is the sharper case: it type-checks against a widened `SuperviseOptions`\n * value, the graph derives its own value and overwrites the caller's, the run succeeds, and the\n * capability the caller asked for is not there. The rename of the leaf seam from `makeWorkerAgent`\n * to `makeLeafAgent` is the shape of the failure — the old name stayed a valid `SuperviseOptions`\n * key AND a graph-owned one, so a caller that kept passing it got a run with no leaf override and\n * no complaint.\n */\nfunction assertRunGraphOptionKeys(opts: RunGraphOptions): void {\n const graphOwned: string[] = []\n const unknown: string[] = []\n for (const key of Object.keys(opts)) {\n if (runGraphOptionKeySet.has(key)) continue\n if (graphOwnedOptionKeySet.has(key)) graphOwned.push(key)\n else unknown.push(key)\n }\n if (graphOwned.length > 0) {\n throw new ConfigError(\n `runGraph: ${graphOwned.sort().join(', ')} — the graph derives this from the AgentGraph ` +\n 'itself, so a caller value is overwritten and the capability it asks for would silently ' +\n 'be absent',\n )\n }\n if (unknown.length > 0) {\n throw new ConfigError(\n `runGraph: unknown option ${unknown.sort().join(', ')} — no reader consults that name, so ` +\n 'the value would be discarded and the capability it asks for would silently be absent',\n )\n }\n}\n\n/** A `SuperviseOptions` key in none of the four lists makes this assignment fail, and the compiler\n * error names the key. Classify it — `GRAPH_FORWARDED_SUPERVISE_OPTIONS` is usually the answer. */\ntype UnclassifiedSuperviseOption = Exclude<keyof SuperviseOptions, ClassifiedSuperviseOption>\nconst everySuperviseOptionIsClassified: UnclassifiedSuperviseOption extends never\n ? true\n : UnclassifiedSuperviseOption = true\nvoid everySuperviseOptionIsClassified\n\n/** `backend` and `driverBackend` keep graph-specific documentation below.\n *\n * Do not inherit and redeclare them through an indexed access type.\n * TypeScript 7 correctly treats `SuperviseOptions['backend']` as including `undefined`, which makes\n * that redeclaration wider than the exact optional property inherited from `SuperviseOptions`.\n */\ntype GraphInheritedSuperviseOption = Exclude<\n (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number],\n 'backend' | 'driverBackend'\n>\n\n/** Copy every forwarded option the caller actually set. Absent stays absent: `supervise()` and the\n * graph must not disagree about what \"unset\" means. */\nfunction forwardedSuperviseOptions(\n opts: RunGraphOptions,\n): Pick<SuperviseOptions, (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]> {\n const forwarded: Record<string, unknown> = {}\n for (const key of GRAPH_FORWARDED_SUPERVISE_OPTIONS) {\n const value = (opts as Record<string, unknown>)[key]\n if (value !== undefined) forwarded[key] = value\n }\n return forwarded as Pick<SuperviseOptions, (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]>\n}\n\n/**\n * Options for one `runGraph` run.\n *\n * Extends every forwarded `SuperviseOptions` key, so a graph honors what a `supervise()` run\n * honors WITHOUT anyone restating it here. Only the graph-specific members and the ones whose\n * graph semantics differ are declared below; everything else inherits its type AND its\n * documentation from `SuperviseOptions`, which is the one owner of both.\n */\nexport interface RunGraphOptions extends Pick<SuperviseOptions, GraphInheritedSuperviseOption> {\n /** WHERE worker nodes run — the executor backend. Provide this OR `makeLeafAgent`. Forwarded to\n * `supervise()`, which derives every authorized leaf from it. A node that declares\n * `agent_runtime_coordination_spawn_worker` becomes a nested supervisor instead, whose own\n * leaves are derived the same way. */\n readonly backend?: Exclude<SuperviseOptions['backend'], undefined>\n /** WHERE the ROOT node's harness brain runs — forwarded to `supervise()` verbatim (see\n * `SuperviseOptions.driverBackend`). Needed when the root node's profile declares an external\n * harness (`codex`, `claude-code`, `opencode`): that root is driven by the harness, not by the\n * router brain, and automatic execution supports a local `bridge`. Unlike `supervise()`, this\n * does NOT default to `backend`: a graph's `backend` places WORKER nodes, so the root driver\n * is selected only by this field. Omit = no harness driver, which is correct for a root whose\n * `profile.harness` is omitted or `cli-base` (that root runs on the router brain). */\n readonly driverBackend?: Exclude<SuperviseOptions['driverBackend'], undefined>\n /** Leaf-execution override (offline tests / advanced). `runGraph` still owns node pinning,\n * directive delivery, and the edge ledger AROUND this seam — only the leaf `act` is yours.\n * Slots INSIDE the kernel's authorized path (`SuperviseOptions.makeLeafAgent`), so a node that\n * declares the spawn tool still becomes a nested supervisor even under an offline leaf. */\n readonly makeLeafAgent?: MakeWorkerAgent\n /** The ROOT driver's inference seam — a caller-owned `ToolLoopChat` that makes every root\n * model call. Use it when the root's decisions must be caller-owned orchestration (a\n * deterministic conversation driver, a persona loop with its own LLM calls) rather than a\n * router-derived model call. The graph machinery around the seam is unchanged: node pinning,\n * directive delivery, the edge ledger, and the journal twin all run the same shipped path,\n * and the root profile keeps prompt control (`prompt-control-execution` materialization —\n * `systemPrompt`/`instructions` still apply). What moves to the caller with the brain:\n * model selection and provider-identity validation (`expectedModel` cannot be enforced on a\n * call the runtime did not place) and per-turn usage reporting (a brain that reports no\n * usage meters nothing into the pool). Omit = the router brain derived from the root\n * profile — the unchanged default. Mutually exclusive with `driverBackend`, and refused\n * when the root profile declares an external harness (that root is driven BY the harness). */\n readonly brain?: ToolLoopChat\n /** Caller-side runtime hooks (telemetry, policy, product extensions). Composed AFTER the\n * graph's own spawn-binding hook on the SAME event stream — the graph never swallows the\n * seam supervise() exposes. */\n readonly hooks?: RuntimeHooks\n /** The analyst lens registry `analyzes` edges resolve against. ENVIRONMENT — needed only for\n * lens analysts; an analyzes edge naming a graph NODE as its analyst needs no registry. */\n readonly analysts?: AnalystRegistry\n /** Answers a flow gate while the process holds the run; the wait counts against its deadline.\n * ENVIRONMENT, like `analysts`; required when the graph declares gates. */\n readonly decideGate?: (request: GateRequest) => Promise<GateDecision>\n /** Directive registry. Default: the seeded kernel registry (`kernelPromptRegistry()`).\n *\n * NOT `SuperviseOptions.registry`, which is the `SuperviseRegistry` name→value table for\n * code-valued options. The two share a name and nothing else, and this one wins here — see\n * `GRAPH_REFUSED_SUPERVISE_OPTIONS`. */\n readonly registry?: PromptRegistry\n /** The run journal the edge ledger and every spawn/settle ride. Default: in-memory. */\n readonly journal?: SpawnJournal\n readonly blobs?: ResultBlobStore\n readonly runId?: string\n /** Product authority over every steer/answer instruction (the filter seam). `runGraph` observes\n * what it CHANGES: a narrowed instruction ledgers its steer traversal as `stripped`. */\n readonly authorizeMessage?: SuperviseOptions['authorizeMessage']\n}\n\nexport interface GraphResult<Out = unknown> {\n readonly result: SupervisedResult<Out>\n /** Every edge traversal, in occurrence order — the observable-edge contract. */\n readonly ledger: ReadonlyArray<EdgeTraversal>\n /** Edge ids whose traversal cap was hit — analyzes exhaustion included (observable here, never\n * a refusal). A DELEGATES cap paired with a `no-winner` result THROWS\n * ({@link GraphEdgeCapError}) instead of returning: only delegates caps refuse spawns, so only\n * they can have ended the run. A LIFECYCLE no-winner (`aborted` / `budget-exhausted`) returns\n * normally even with an exhausted delegates cap — the abort or the pool, not the cap, ended\n * that run, and the exhaustion stays observable here. */\n readonly exhaustedEdges: ReadonlyArray<string>\n readonly runId: string\n /** Why a flow graph ended early: a `stop` edge fired (`edge` names it), or a flow node settled\n * down (no `edge`; `reason` is `down: <worker reason>`) or, where a route was needed, without a\n * usable result (no `edge`; `reason` is `unusable: <why>`). Live flow workers are aborted. */\n readonly stopped?: {\n readonly edge?: string\n readonly at: NodeId\n readonly workerId: string\n readonly reason: string\n }\n}\n\n/** `RunGraphOptions` with the brain REQUIRED — the shape the `/testing` entry's\n * `runGraphWithTestBrain` keeps accepting now that `brain` is a production option. */\nexport interface RunGraphTestOptions extends RunGraphOptions {\n readonly brain: ToolLoopChat\n}\n\n// ── Validation ─────────────────────────────────────────────────────────────────\n\n/** Validate the graph and resolve every directive BEFORE any compute is spent — an invalid\n * topology or an unknown directive is a configuration fault, never a mid-run surprise. */\nfunction validateGraph(\n graph: AgentGraph,\n registry: PromptRegistry,\n analysts: AnalystRegistry | undefined,\n): ValidatedGraph {\n if (graph.entry === undefined) {\n if (!Array.isArray(graph.nodes) || graph.nodes.length === 0) {\n throw new ValidationError('runGraph: graph.nodes must be a non-empty array')\n }\n if (!Array.isArray(graph.edges) || graph.edges.length === 0) {\n throw new ValidationError('runGraph: graph.edges must be a non-empty array')\n }\n }\n if (typeof graph.deliverable?.check !== 'function') {\n throw new ValidationError('runGraph: graph.deliverable is mandatory (termination oracle)')\n }\n if (typeof graph.budget !== 'object' || graph.budget === null) {\n throw new ValidationError('runGraph: graph.budget is mandatory (the conserved pool)')\n }\n if (graph.entry !== undefined) return validateFlowGraph(graph, registry, analysts)\n if (graph.gates !== undefined)\n throw new ValidationError('runGraph: graph.gates needs graph.entry')\n return validateGraphTopology(graph.nodes, graph.edges, registry, analysts)\n}\n\n// ── The runner ─────────────────────────────────────────────────────────────────\n\n/**\n * Execute an {@link AgentGraph}. A flow graph (`entry` set) runs from its entries and routes edges\n * under a runtime-owned root that places no model call. Otherwise the root node becomes the\n * supervisor (`supervise()` — the execution core), each worker node is spawnable BY NODE ID\n * (`spawn_worker` with `profile: { name: '<node id>' }`; the node's canonical profile is pinned by\n * the graph), each\n * delegates directive is appended to the worker profile's `prompt.instructions` per traversal,\n * and each analyzes edge becomes an analyst-on-settle route with a real DESTINATION. Every\n * traversal is ledgered and journaled.\n */\nexport function runGraph(graph: AgentGraph, opts: RunGraphOptions): Promise<GraphResult> {\n const { brain, ...runtimeOptions } = graphExecutionOptions(opts)\n return superviseAgentGraph(graph, runtimeOptions, brain)\n}\n\n/** Alias for graph tests written before `RunGraphOptions.brain` was production. The production\n * entry accepts the same shape; this wrapper only keeps the `/testing` import path working. */\nexport function runGraphWithTestBrain(\n graph: AgentGraph,\n opts: RunGraphTestOptions,\n): Promise<GraphResult> {\n const { brain, ...runtimeOptions } = opts\n return superviseAgentGraph(graph, runtimeOptions, brain)\n}\n\n/**\n * The graph supervise run, as its own entry: the engine's `run-graph` preset node executes exactly\n * this, so the preset and `runGraph` are the same code path by construction (agent-runtime#982).\n */\n/**\n * Every refusal a graph earns before any compute, in one place: the authoring contract. `runGraph`\n * calls it FIRST so a malformed graph throws synchronously, exactly as it did before the engine\n * preset (agent-runtime#982) moved execution behind a promise.\n */\nexport function assertRunGraphAuthoring(\n graph: AgentGraph,\n opts: RunGraphOptions,\n brain?: ToolLoopChat,\n): ReturnType<typeof validateGraph> {\n assertRunGraphOptionKeys(opts)\n const registry = opts.registry ?? kernelPromptRegistry()\n const validated = validateGraph(graph, registry, opts.analysts)\n const requireLeaves = (): void => {\n if (!opts.backend && !opts.makeLeafAgent) {\n throw new ValidationError(\n 'runGraph: provide opts.backend (where nodes run) or opts.makeLeafAgent',\n )\n }\n }\n if (validated.flow !== undefined) {\n // A flow's root is Runtime's own: nothing a caller sets for a root manager has a reader.\n const rootOptions = [\n ...(brain ? ['brain'] : []),\n ...(['driverBackend', 'finalizer', 'maxTurns', 'compaction'] as const).filter(\n (key) => opts[key] !== undefined,\n ),\n ]\n if (rootOptions.length > 0) {\n throw new ValidationError(\n `runGraph: ${rootOptions.join(', ')} with graph.entry — a flow graph has no root ` +\n 'manager: Runtime spawns its entries and traverses its routes edges, and the graph ' +\n \"owns the run's output\",\n )\n }\n if ((graph.gates?.length ?? 0) > 0 && opts.decideGate === undefined) {\n throw new ValidationError('runGraph: graph.gates needs opts.decideGate to answer them')\n }\n requireLeaves()\n return validated\n }\n const { root } = validated as RootValidatedGraph\n // A caller brain and a harness driver are two answers to WHO makes the root's calls: refuse the\n // contradiction before any compute, and refuse a harness-driven root outright — the harness IS\n // that root's brain, so a supplied one would be silently ignored downstream.\n if (brain && opts.driverBackend) {\n throw new ValidationError(\n 'runGraph: brain and driverBackend are mutually exclusive — a caller brain makes the root model calls, a driverBackend places a harness that makes its own',\n )\n }\n if (brain && harnessRunsAgent(root.profile.harness)) {\n throw new ValidationError(\n `runGraph: root node '${root.id}' declares harness '${root.profile.harness}', so the harness drives it — a caller brain applies only to a router-brained root (profile.harness omitted or 'cli-base')`,\n )\n }\n requireLeaves()\n return validated\n}\n\nexport function superviseAgentGraph(\n graph: AgentGraph,\n opts: RunGraphOptions,\n brain?: ToolLoopChat,\n): Promise<GraphResult> {\n if (graph.deliverable.command !== undefined) {\n const bound = bindGraphCommand(graph, opts)\n return superviseAgentGraph(bound.graph, bound.options, brain)\n }\n const registry = opts.registry ?? kernelPromptRegistry()\n if (opts.runContext?.acquire !== undefined) {\n return withRunContext(opts.runContext, opts.signal, (runContext, signal) =>\n superviseAgentGraph(\n graph,\n {\n ...opts,\n runContext,\n ...(signal === undefined ? {} : { signal }),\n },\n brain,\n ),\n )\n }\n const validated = assertRunGraphAuthoring(graph, opts, brain)\n // A flow graph: Runtime schedules its nodes, and its root manager is Runtime's own.\n const flow = validated.flow === undefined ? undefined : createFlowRun()\n const context =\n opts.runContext ??\n (opts.runDir === undefined\n ? createInMemoryRunContext()\n : createFileRunContext(resolve(opts.runDir)))\n const journal = opts.journal ?? context.journal\n const blobs = opts.blobs ?? context.blobs\n const runId =\n opts.runId ??\n opts.runContext?.runId ??\n `graph-${canonicalCandidateDigest(graph.nodes.map((n) => n.id)).slice('sha256:'.length, 'sha256:'.length + 12)}`\n const now = opts.now ?? Date.now\n\n // The graph layer: node pinning, analyst routes, continuity defaults and the edge ledger. A\n // `run_graph` subtask builds the same overlay around its nested manager.\n // `profileGuidance` composes the profile a manager authors, but a graph then swaps that\n // `{ name }` stub for the pinned node profile. Compose the pinned profile too, so every node\n // that runs carries its harness and model guidance. Composition is idempotent.\n const guidance = profileGuidanceComposer(opts.profileGuidance)\n const overlay = createGraphOverlay(validated, {\n registry,\n journal,\n runId,\n now,\n ...(guidance ? { guidance } : {}),\n ...(opts.authorizeSpawn ? { authorizeSpawn: opts.authorizeSpawn } : {}),\n })\n // Always present: the kernel refuses steer/answer whenever spawn authorization is on (the\n // graph's pinning IS spawn authorization), so a graph with no caller filter passes instructions\n // through unchanged rather than losing its steer channel. Only a caller filter can strip.\n const callerAuthorizeMessage = opts.authorizeMessage\n const authorizeMessage = overlay.observeMessages<\n Parameters<NonNullable<SuperviseOptions['authorizeMessage']>>[0]\n >((input) =>\n callerAuthorizeMessage ? callerAuthorizeMessage(input) : { instruction: input.instruction },\n )\n\n // ── Spawn-hook: bind ledger rows to concrete worker ids, then journal them ──\n const graphHooks: RuntimeHooks = {\n onEvent: (event) => {\n if (event.target !== 'agent.spawn' || event.phase !== 'after') return\n const payload = event.payload as { childId?: unknown; assignmentId?: unknown } | undefined\n if (typeof payload?.childId !== 'string' || typeof payload.assignmentId !== 'string') return\n return overlay.bindSpawn(event.parentId, payload.assignmentId, payload.childId)\n },\n }\n const hooks = composeRuntimeHooks(graphHooks, opts.hooks)\n const rootProfile =\n flow === undefined\n ? graphRootProfile(validated as RootValidatedGraph, registry)\n : flowRootProfile\n const rootBrain = flow === undefined ? brain : runtimeFlowBrain()\n const task =\n flow === undefined\n ? graphTask(graph, (validated as RootValidatedGraph).root)\n : (graph.deliverable.describe ?? 'Runtime runs this flow graph from its entries.')\n\n // Every configuration fault above throws SYNCHRONOUSLY (matching `supervise()`'s own\n // contract); only the run itself is asynchronous.\n const start = async (): Promise<GraphResult> => {\n const superviseOptions = {\n // The backend also drives seat-bearing flow nodes, which use the managed driver lifecycle.\n // A flow's root keeps Runtime's deterministic brain; deriving its child driver adds no root\n // inference. Rooted graphs keep driverBackend explicit rather than inheriting backend.\n ...forwardedSuperviseOptions(opts),\n rootDriverFromBackend: flow !== undefined,\n // Graph-owned values come after the spread: the graph, not the caller, decides these.\n budget: graph.budget,\n deliverable:\n flow !== undefined && graph.deliverable.checkRef === 'route'\n ? flowRouteDeliverable(graph.deliverable, flow)\n : graph.deliverable,\n authorizeSpawn: overlay.authorizeSpawn,\n resolveSpawnProfile: overlay.resolveSpawnProfile,\n inheritSpawnRights: false,\n ...(opts.makeLeafAgent ? { makeLeafAgent: opts.makeLeafAgent } : {}),\n journal,\n blobs,\n runId,\n hooks,\n onCoordinationEvent: async (\n context: { readonly depth: number },\n _eventId: unknown,\n record: { readonly event: Parameters<typeof overlay.onCoordinationEvent>[0] },\n ) => {\n // A route event belongs to the flow of the manager that published it: a flow inside a\n // maps item or a run_graph subtask ledgers and concludes its own.\n if (record.event.type === 'route' && context.depth !== 0) return\n overlay.onCoordinationEvent(record.event)\n flow?.observe(record.event)\n },\n // Lens routes resolve against the registry; agent routes carry their own analyst profile,\n // so a graph whose only analysts are nodes needs no registry at all.\n ...(overlay.routes.length > 0\n ? {\n analyzeOnSettle: overlay.routes,\n ...(opts.analysts ? { analysts: opts.analysts } : {}),\n }\n : {}),\n ...(overlay.maps.length > 0 ? { mapOnSettle: overlay.maps } : {}),\n ...(Object.keys(overlay.continuityByProfile).length > 0\n ? { continuityByProfile: overlay.continuityByProfile }\n : {}),\n // A flow root's wake batches nothing for a decision, so it ends its turn on the first event.\n ...(flow === undefined\n ? {}\n : {\n routeFlow: routeFlowOf(validated),\n ...(opts.decideGate && {\n decideGate: journaledGateDecider(opts.decideGate, journal, runId),\n }),\n finalizer: flow.finalizer,\n wake: { debounceMs: 0, ...opts.wake },\n }),\n authorizeMessage,\n } satisfies SuperviseOptions\n // The flow root reaches supervise through the same brain seam a caller brain takes.\n const supervised =\n rootBrain === undefined\n ? await supervise(rootProfile, task, superviseOptions)\n : await superviseWithTestBrain(rootProfile, task, { ...superviseOptions, brain: rootBrain })\n\n const { ledger, exhaustedEdges, exhaustedDelegates } = await overlay.settle()\n const concluded = flow?.conclude(supervised)\n if (concluded?.kind === 'unrouted') {\n throw new GraphRouteError(concluded.unrouted, ledger, supervised)\n }\n const result = concluded?.result ?? supervised\n const stopped = concluded?.stopped\n // A LIFECYCLE ending (caller abort, exhausted budget, deadline) is its own complete explanation: the\n // cap did not end that run even when it was exhausted along the way, and blaming it would\n // misattribute the ending (and turn a caller-initiated abort into a throw). The exhaustion\n // stays observable in `exhaustedEdges` either way.\n const lifecycleEnded =\n result.kind === 'no-winner' &&\n (result.reason === 'aborted' ||\n result.reason === 'cancelled' ||\n result.reason === 'budget-exhausted' ||\n result.reason === 'deadline')\n if (result.kind !== 'winner' && !lifecycleEnded && exhaustedDelegates.length > 0) {\n // Fail LOUD: the backstop, not the task, ended this run. The evidence rides on the error.\n // Only DELEGATES caps refuse spawns, so only they can be the cause named here.\n throw new GraphEdgeCapError(exhaustedDelegates, ledger, result)\n }\n return { result, ledger, exhaustedEdges, runId, ...(stopped ? { stopped } : {}) }\n }\n\n return start()\n}\n\n/** The root task: the graph's own framing. The deliverable (mandatory) is the termination; the\n * task names what the topology exists to produce. */\nfunction graphTask(graph: AgentGraph, root: GraphNode): string {\n const describe = graph.deliverable.describe\n return (\n describe ?? `Deliver the graph's deliverable by driving your worker nodes (root: '${root.id}').`\n )\n}\n"],"mappings":";;;;;;;;;;;;;AAIA,SAAgB,sBAAsB,SAA2C;CAC/E,IAAI,QAAQ,eAAe,OAAO;CAClC,MAAM,UAAU,QAAQ;CACxB,IAAI,SACF,OAAO,QAAQ,YAAY,WACvB;EAAE,GAAG;EAAS,SAAS;GAAE,GAAG;GAAS,cAAc;EAAO;CAAE,IAC5D;CACN,MAAM,YAAY,QAAQ,IAAI;CAC9B,MAAM,eAAe,QAAQ,IAAI,iBAAiB,QAAQ,IAAI;CAC9D,IAAI,CAAC,aAAa,CAAC,cACjB,MAAM,IAAI,gBACR,qJACF;CACF,OAAO;EACL,GAAG;EACH,SAAS;GACP,SAAS;GACT;GACA;GACA,KAAK,QAAQ,IAAI;GACjB,cAAc;EAChB;CACF;AACF;;;ACcA,SAAS,WAAW,SAAmD;CACrE,OAAO,eAAe;EACpB,SAAS,QAAQ;EACjB,aAAa,QAAQ;EACrB,UAAU,QAAQ;EAClB,QAAQ,QAAQ;EAChB,WAAW,QAAQ;EACnB,cAAc,QAAQ;CACxB,CAAC;AACH;AAEA,SAAS,UAAU,OAA8C;CAC/D,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG,OAAO;CACxE,MAAM,MAAM;CACZ,IACE,IAAI,YAAY,KAChB,CAAC;EACC;EACA;EACA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BAAuB,aAAa,MAAM;GAAE,GAAG;GAAkB,OAAO;EAAU,CAAC;EAE/F,MAAM,EAAE,QAAQ,gBAAgB,uBAAuB,MAAM,QAAQ,OAAO;EAC5E,MAAM,YAAY,MAAM,SAAS,UAAU;EAC3C,IAAI,WAAW,SAAS,YACtB,MAAM,IAAI,gBAAgB,UAAU,UAAU,QAAQ,UAAU;EAElE,MAAM,SAAS,WAAW,UAAU;EACpC,MAAM,UAAU,WAAW;EAK3B,MAAM,iBACJ,OAAO,SAAS,gBACf,OAAO,WAAW,aACjB,OAAO,WAAW,eAClB,OAAO,WAAW,sBAClB,OAAO,WAAW;EACtB,IAAI,OAAO,SAAS,YAAY,CAAC,kBAAkB,mBAAmB,SAAS,GAG7E,MAAM,IAAI,kBAAkB,oBAAoB,QAAQ,MAAM;EAEhE,OAAO;GAAE;GAAQ;GAAQ;GAAgB;GAAO,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;EAAG;CAClF;CAEA,OAAO,MAAM;AACf;;;AAIA,SAAS,UAAU,OAAmB,MAAyB;CAE7D,OADiB,MAAM,YAAY,YAErB,wEAAwE,KAAK,GAAG;AAEhG"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"provision-supervisor-Pd95wA1X.js","names":[],"sources":["../src/runtime/retained-interactive-control.ts","../src/runtime/supervise/interactive-executor.ts","../src/runtime/supervise/interactive-worker.ts","../src/runtime/supervise/provision-supervisor.ts"],"sourcesContent":["import type { AgentInteractiveSessionControlClaim } from '@tangle-network/agent-interface'\nimport {\n agentInteractiveSessionControlClaimRequestDigest,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type { RetainedInteractiveRunHandle } from './retained-interactive-types'\nimport { abortError } from './util'\n\nconst MAX_GENERATION_CONFLICTS = 8\n\n/** Input for acquiring write authority over one exact interactive process. @stable */\nexport interface ClaimRetainedInteractiveControlOptions {\n readonly handle: RetainedInteractiveRunHandle\n readonly holderId: string\n /** Last known provider generation. Zero discovers the current generation safely. */\n readonly expectedGeneration?: number\n readonly signal?: AbortSignal\n}\n\n/**\n * Acquire provider-issued write authority without reading authority from status.\n *\n * A new coordinator starts at generation zero. If another claim already exists,\n * the provider returns its public generation and this helper retries one new\n * compare-and-swap operation. Every generation has a deterministic operation\n * identifier, so retrying after an ambiguous response cannot create two claims.\n * @stable\n */\nexport async function claimRetainedInteractiveControl(\n options: ClaimRetainedInteractiveControlOptions,\n): Promise<AgentInteractiveSessionControlClaim> {\n const expected = options.expectedGeneration ?? 0\n if (!Number.isSafeInteger(expected) || expected < 0) {\n throw new Error('interactive control expectedGeneration must be a non-negative integer')\n }\n\n let generation = expected\n for (let conflict = 0; conflict <= MAX_GENERATION_CONFLICTS; conflict += 1) {\n if (options.signal?.aborted) throw abortError(options.signal.reason)\n const material = {\n operationId: controlClaimOperationId(options.handle, options.holderId, generation),\n ref: options.handle.ref,\n holderId: options.holderId,\n expectedGeneration: generation,\n }\n const acknowledgement = await options.handle.claimControl(\n {\n ...material,\n requestDigest: agentInteractiveSessionControlClaimRequestDigest(material),\n },\n options.signal === undefined ? undefined : { signal: options.signal },\n )\n if (acknowledgement.status === 'accepted' || acknowledgement.status === 'replayed') {\n const control = acknowledgement.control\n if (control === undefined) {\n throw new Error('provider accepted interactive control without returning its claim')\n }\n if (Date.parse(control.expiresAt) <= Date.now()) {\n throw new Error('provider returned an expired interactive control claim')\n }\n return control\n }\n if (\n acknowledgement.status !== 'conflict' ||\n acknowledgement.conflictReason !== 'generation_mismatch'\n ) {\n throw new Error(\n acknowledgement.status === 'unknown'\n ? 'interactive control claim outcome is unknown; retry the same acquisition'\n : 'interactive control claim operation conflicts with different request material',\n )\n }\n const current = acknowledgement.currentGeneration\n if (current === undefined || current <= generation) {\n throw new Error('provider returned a non-advancing interactive control generation')\n }\n generation = current\n }\n throw new Error('interactive control changed too often to acquire safely')\n}\n\nfunction controlClaimOperationId(\n handle: RetainedInteractiveRunHandle,\n holderId: string,\n expectedGeneration: number,\n): string {\n const digest = canonicalCandidateDigest({\n kind: 'retained-interactive-control-claim.v1',\n ref: handle.ref,\n holderId,\n expectedGeneration,\n })\n return `interactive-claim-${digest.slice('sha256:'.length, 'sha256:'.length + 40)}`\n}\n","/**\n * The executor behind one interactive worker: starts the provider's retained interactive process,\n * polls it to exit, relays steers as prompts, and stops and releases it exactly once.\n */\n\nimport {\n type AgentInteractiveSessionPromptCommand,\n type AgentInteractiveSessionStatus,\n type AgentInteractiveSessionStopAcknowledgement,\n type AgentInteractiveSessionStopCommand,\n type AgentProfile,\n agentInteractiveSessionPromptRequestDigest,\n agentInteractiveSessionStopRequestDigest,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironment,\n AgentEnvironmentProvider,\n} from '@tangle-network/agent-interface/environment-provider'\nimport { contentAddress } from '../../durable/content-address'\nimport type { WorkerSpawnContext } from '../../mcp/tools/coordination-contracts'\nimport { startRetainedInteractiveRun } from '../retained-interactive'\nimport { claimRetainedInteractiveControl } from '../retained-interactive-control'\nimport { destroyInteractiveEnvironment, environmentGone } from '../retained-interactive-lifecycle'\nimport type { RetainedInteractiveRunHandle } from '../retained-interactive-types'\nimport { retainedCreateMaterial } from '../retained-run-intent'\nimport type { RetainedInteractiveAdmission } from '../retained-run-types'\nimport { sleep } from '../util'\nimport { linkAbort, signalAbortError } from './abortable'\nimport { createInbox, failPendingAfter } from './inbox'\nimport type { InteractiveAdmissionWriter } from './interactive-admission'\nimport type {\n InteractiveWorkerEnvironment,\n InteractiveWorkerOptions,\n InteractiveWorkerResult,\n} from './interactive-worker'\nimport {\n attestRuntimeOwnedPendingExecutor,\n finalizeRuntimeOwnedPendingExecutor,\n newExecutionAttemptId,\n} from './materialization'\nimport { concreteProfileModel } from './model-policy'\nimport { detachedSnapshot } from './snapshot'\nimport { taskToPrompt } from './task-prompt'\nimport type {\n Executor,\n ExecutorCancellation,\n ExecutorResult,\n HeldEnvironment,\n Runtime,\n Spend,\n UsageEvent,\n WorkerInteractiveSession,\n} from './types'\n\nconst INTERACTIVE_TEARDOWN_TIMEOUT_MS = 30_000\n\nexport interface InteractiveExecutorInput {\n readonly provider: AgentEnvironmentProvider\n readonly profile: AgentProfile\n readonly context?: WorkerSpawnContext\n readonly environment?: InteractiveWorkerEnvironment\n readonly environmentKey: string\n readonly interactiveKey: (task: unknown) => string\n readonly holderId: (task: unknown) => string\n readonly initialPrompt?: InteractiveWorkerOptions['initialPrompt']\n readonly cwd?: string\n readonly cols?: number\n readonly rows?: number\n readonly runtime: Runtime\n readonly pollIntervalMs?: number\n readonly destroyEnvironmentOnTeardown?: boolean\n readonly executionAttemptId?: string\n readonly nodeId?: string\n readonly admission: InteractiveAdmissionWriter\n}\n\n/** The one record an interactive executor reads and writes across start, poll, steer, stop and teardown. */\ninterface InteractiveRun {\n readonly input: InteractiveExecutorInput\n readonly attemptId: string\n readonly localController: AbortController\n readonly inbox: ReturnType<typeof createInbox>\n readonly planned: PlannedDeclaration\n readonly stopOperations: Map<string, Promise<ExecutorCancellation>>\n readonly memoryAdmissions: Map<string, RetainedInteractiveAdmission>\n readonly ready: Promise<WorkerInteractiveSession>\n readonly resolveReady: (session: WorkerInteractiveSession) => void\n executor: Executor<InteractiveWorkerResult>\n handle: RetainedInteractiveRunHandle | undefined\n createdEnvironment: AgentEnvironment | undefined\n environmentId: string | undefined\n artifact: ExecutorResult<InteractiveWorkerResult> | undefined\n activeLink: ReturnType<typeof linkAbort> | undefined\n startPromise: Promise<RetainedInteractiveRunHandle> | undefined\n executeStarted: boolean\n teardownComplete: boolean\n teardownPromise: Promise<{ destroyed: boolean }> | undefined\n flushChain: Promise<void>\n controlError: unknown\n}\n\ntype PlannedDeclaration = ReturnType<typeof plannedDeclarationOf>\n\nconst descriptorOf = (input: InteractiveExecutorInput) =>\n ({\n kind: 'interactive-session',\n provider: input.provider.name,\n transport: 'agent-environment',\n }) as const\n\nfunction plannedDeclarationOf(input: InteractiveExecutorInput) {\n const declaredEnvironment = input.environment\n ? retainedCreateMaterial({\n ...input.environment,\n profile: input.profile,\n idempotencyKey: input.environmentKey,\n })\n : null\n const profileModel = concreteProfileModel(input.profile)\n return {\n effectiveProfile: input.profile,\n backend: input.provider.name,\n model: profileModel\n ? { status: 'known' as const, id: profileModel }\n : { status: 'unknown' as const, reason: 'provider selected the model' },\n execution: { kind: 'interactive-session', id: input.nodeId ?? input.environmentKey },\n materializer: 'retained-interactive-provider',\n plan: {\n kind: 'retained-interactive-provider',\n provider: input.provider.name,\n environment: declaredEnvironment,\n environmentIdempotencyKey: input.environmentKey,\n destroyEnvironmentOnTeardown: input.destroyEnvironmentOnTeardown !== false,\n },\n }\n}\n\nexport function interactiveExecutor(\n input: InteractiveExecutorInput,\n): Executor<InteractiveWorkerResult> {\n const attemptId =\n input.executionAttemptId ?? newExecutionAttemptId(input.nodeId ?? input.environmentKey)\n let resolveReady!: (session: WorkerInteractiveSession) => void\n const ready = new Promise<WorkerInteractiveSession>((resolve) => {\n resolveReady = resolve\n })\n const run: InteractiveRun = {\n input,\n attemptId,\n localController: new AbortController(),\n inbox: createInbox(),\n planned: plannedDeclarationOf(input),\n stopOperations: new Map(),\n memoryAdmissions: new Map(),\n ready,\n resolveReady,\n executor: undefined as unknown as Executor<InteractiveWorkerResult>,\n handle: undefined,\n createdEnvironment: undefined,\n environmentId: undefined,\n artifact: undefined,\n activeLink: undefined,\n startPromise: undefined,\n executeStarted: false,\n teardownComplete: false,\n teardownPromise: undefined,\n flushChain: Promise.resolve(),\n controlError: undefined,\n }\n run.executor = interactiveSurface(run)\n attestRuntimeOwnedPendingExecutor(run.executor, input.runtime, run.planned, {\n attemptId,\n binding: {\n provider: input.provider.name,\n environmentIdempotencyKey: input.environmentKey,\n nodeId: input.nodeId ?? null,\n },\n descriptor: descriptorOf(input),\n })\n return run.executor\n}\n\nfunction interactiveSurface(run: InteractiveRun): Executor<InteractiveWorkerResult> {\n const { input } = run\n return {\n runtime: input.runtime,\n teardownTimeoutMs: INTERACTIVE_TEARDOWN_TIMEOUT_MS,\n execute(task, signal): AsyncIterable<UsageEvent> {\n if (run.executeStarted || run.teardownComplete || run.teardownPromise !== undefined) {\n throw new Error('workerFromInteractiveProvider: execute() may only be called once')\n }\n run.executeStarted = true\n run.startPromise = startInteractive(run, task, signal)\n return failPendingAfter(run.inbox, runInteractive(run, signal))\n },\n deliver(message: unknown): boolean {\n if (run.teardownComplete || run.teardownPromise !== undefined) return false\n const accepted = run.inbox.deliver(message)\n if (accepted) void flushInbox(run)\n return accepted\n },\n interactive(): WorkerInteractiveSession {\n return run.handle\n ? { status: 'available', handle: run.handle }\n : { status: 'unavailable', reason: 'interactive-session-not-started' }\n },\n interactiveReady(): Promise<WorkerInteractiveSession> {\n return run.ready\n },\n async cancel(request): Promise<ExecutorCancellation> {\n const existing = run.stopOperations.get(request.operationId)\n if (existing) return existing\n const operation = stopInteractive(run, request.operationId, request.reason, request.signal)\n const tracked = operation.then((result) => {\n if (\n result.status === 'unknown' &&\n run.stopOperations.get(request.operationId) === tracked\n ) {\n run.stopOperations.delete(request.operationId)\n }\n return result\n })\n run.stopOperations.set(request.operationId, tracked)\n return tracked\n },\n teardown(grace): Promise<{ destroyed: boolean }> {\n void grace\n if (run.teardownComplete) return Promise.resolve({ destroyed: true })\n if (run.teardownPromise !== undefined) return run.teardownPromise\n const pending = teardownInteractive(run)\n run.teardownPromise = pending.then(\n (result) => {\n run.teardownComplete = true\n return result\n },\n (error) => {\n run.teardownPromise = undefined\n throw error\n },\n )\n return run.teardownPromise\n },\n heldEnvironments(): ReadonlyArray<HeldEnvironment> {\n if (run.teardownComplete || input.destroyEnvironmentOnTeardown === false) return []\n const held =\n run.createdEnvironment?.id ?? run.environmentId ?? run.handle?.ref.run.environmentId\n return held === undefined ? [] : [{ provider: input.provider.name, environmentId: held }]\n },\n resultArtifact(): ExecutorResult<InteractiveWorkerResult> {\n if (!run.artifact) {\n throw new Error(\n 'workerFromInteractiveProvider: resultArtifact() read before execution settled',\n )\n }\n return run.artifact\n },\n }\n}\n\nfunction initialPromptFor(input: InteractiveExecutorInput, task: unknown): string {\n const initialPrompt =\n typeof input.initialPrompt === 'function'\n ? input.initialPrompt(task, {\n provider: input.provider.name,\n profile: input.profile,\n ...(input.context === undefined ? {} : { context: input.context }),\n task,\n ...(input.nodeId === undefined ? {} : { nodeId: input.nodeId }),\n })\n : (input.initialPrompt ?? taskToPrompt(task))\n if (typeof initialPrompt !== 'string') {\n throw new Error('workerFromInteractiveProvider: initialPrompt must return a string')\n }\n return initialPrompt\n}\n\n/** Keep each admission phase's first snapshot in memory and refuse a retry that changes it. */\nasync function recordAdmission(\n run: InteractiveRun,\n admission: RetainedInteractiveAdmission,\n): Promise<void> {\n run.environmentId =\n admission.phase === 'interactive_environment' ? admission.environmentId : run.environmentId\n const existing = run.memoryAdmissions.get(admission.phase)\n if (existing !== undefined) {\n if (canonicalCandidateDigest(existing) !== canonicalCandidateDigest(admission)) {\n throw new Error(`interactive admission phase '${admission.phase}' changed across retry`)\n }\n } else {\n run.memoryAdmissions.set(admission.phase, detachedSnapshot(admission, 'interactive admission'))\n }\n await run.input.admission(admission)\n}\n\nasync function startInteractive(\n run: InteractiveRun,\n task: unknown,\n signal: AbortSignal,\n): Promise<RetainedInteractiveRunHandle> {\n const { input } = run\n try {\n run.activeLink = linkAbort(signal, run.localController.signal)\n const initialPrompt = initialPromptFor(input, task)\n const interactiveIdempotencyKey = input.interactiveKey(task)\n const started = await startRetainedInteractiveRun({\n provider: {\n ...input.provider,\n async create(environmentInput): Promise<AgentEnvironment> {\n const environment = await input.provider.create!(environmentInput)\n run.createdEnvironment = environment\n return environment\n },\n },\n environment: {\n ...(input.environment ?? {}),\n profile: input.profile,\n idempotencyKey: input.environmentKey,\n },\n interactiveIdempotencyKey,\n ...(initialPrompt.length === 0 ? {} : { initialPrompt }),\n ...(input.cwd === undefined ? {} : { cwd: input.cwd }),\n ...(input.cols === undefined ? {} : { cols: input.cols }),\n ...(input.rows === undefined ? {} : { rows: input.rows }),\n onAdmission: (admission) => recordAdmission(run, admission),\n signal: run.activeLink.signal,\n })\n finalizeRuntimeOwnedPendingExecutor(\n run.executor,\n {\n ...run.planned,\n execution: { kind: 'interactive-session', id: started.ref.run.executionId },\n plan: {\n ...run.planned.plan,\n environmentId: started.ref.run.environmentId,\n interactiveIdempotencyKey,\n },\n },\n {\n attemptId: run.attemptId,\n binding: {\n provider: input.provider.name,\n ref: started.ref,\n environmentId: started.ref.run.environmentId,\n },\n descriptor: descriptorOf(input),\n },\n )\n run.handle = started\n run.resolveReady({ status: 'available', handle: started })\n void flushInbox(run)\n return started\n } catch (error) {\n run.resolveReady({ status: 'unavailable', reason: unavailableReason(error) })\n run.activeLink?.release()\n throw error\n }\n}\n\nasync function* runInteractive(\n run: InteractiveRun,\n signal: AbortSignal,\n): AsyncIterable<UsageEvent> {\n const { input, localController } = run\n const startedAt = Date.now()\n try {\n const current = await run.startPromise\n if (current === undefined) {\n throw new Error('workerFromInteractiveProvider: interactive start did not begin')\n }\n yield { kind: 'iteration' }\n // Native TUI sessions do not expose a complete turn receipt. These zero counters are an\n // observed floor and the explicit false markers keep the run's accounting honest.\n yield { kind: 'tokens', input: 0, output: 0, tokensKnown: false }\n yield { kind: 'cost', usd: 0, usdKnown: false, provenance: 'uncaptured' }\n let status: AgentInteractiveSessionStatus | undefined\n for (;;) {\n if (signal.aborted || localController.signal.aborted) {\n throw signalAbortError(\n signal.aborted ? signal : localController.signal,\n 'interactive execution aborted',\n )\n }\n status = await current.status({ signal: run.activeLink?.signal })\n await run.flushChain\n if (run.controlError !== undefined) throw controlErrorValue(run.controlError)\n if (status.state !== 'running') break\n await sleep(input.pollIntervalMs ?? 100, run.activeLink?.signal)\n }\n const finished = status\n const output: InteractiveWorkerResult = {\n provider: input.provider.name,\n environmentId: current.ref.run.environmentId,\n sessionId: current.ref.run.sessionId,\n executionId: current.ref.run.executionId,\n state: finished?.state === 'exited' ? 'exited' : 'unknown',\n ref: current.ref,\n ...(finished?.state === 'exited' && finished.reason ? { reason: finished.reason } : {}),\n ...(finished?.state === 'exited' && finished.exitCode !== undefined\n ? { exitCode: finished.exitCode }\n : {}),\n ...(finished?.state === 'exited' && finished.exitSignal !== undefined\n ? { exitSignal: finished.exitSignal }\n : {}),\n }\n const spent: Spend = {\n iterations: 1,\n tokens: { input: 0, output: 0 },\n tokensKnown: false,\n usd: 0,\n usdKnown: false,\n ms: Date.now() - startedAt,\n }\n run.artifact = {\n outRef: contentAddress(output),\n out: output,\n spent,\n }\n } finally {\n run.activeLink?.release()\n }\n}\n\nasync function flushInbox(run: InteractiveRun): Promise<void> {\n run.flushChain = run.flushChain.then(async () => {\n const handle = run.handle\n if (!handle) return\n const lease = run.inbox.take()\n try {\n const messages = lease.messages\n if (messages.length === 0) return\n const prompt = run.inbox.fold(messages)\n const operationId = `interactive-prompt-${canonicalCandidateDigest({\n ref: handle.ref,\n prompt,\n }).slice('sha256:'.length)}`\n const control = await claimRetainedInteractiveControl({\n handle,\n holderId: run.input.holderId(undefined),\n })\n const material = {\n operationId,\n ref: handle.ref,\n control,\n prompt,\n }\n const command: AgentInteractiveSessionPromptCommand = {\n ...material,\n requestDigest: agentInteractiveSessionPromptRequestDigest(material),\n }\n await handle.sendPrompt(command)\n for (const message of messages) lease.commit(operationId, message.id)\n } catch (error) {\n lease.release()\n run.controlError ??= error\n }\n })\n await run.flushChain\n}\n\nasync function stopInteractive(\n run: InteractiveRun,\n operationId: string,\n reason?: string,\n signal?: AbortSignal,\n): Promise<ExecutorCancellation> {\n const observedAt = new Date().toISOString()\n const handle = run.handle\n if (!handle) {\n run.localController.abort(reason ?? 'interactive cancellation requested')\n return {\n status: 'unknown',\n effect: 'cancel_requested',\n observedAt,\n detail: 'interactive process has not published a provider reference',\n }\n }\n try {\n const control = await claimRetainedInteractiveControl({\n handle,\n holderId: run.input.holderId(undefined),\n signal,\n })\n const material = { operationId, ref: handle.ref, control }\n const command: AgentInteractiveSessionStopCommand = {\n ...material,\n requestDigest: agentInteractiveSessionStopRequestDigest(material),\n }\n const acknowledgement = await handle.stop(\n command,\n signal === undefined ? undefined : { signal },\n )\n run.localController.abort(reason ?? 'interactive cancellation requested')\n return cancellationFromAcknowledgement(acknowledgement, observedAt)\n } catch (error) {\n run.localController.abort(reason ?? 'interactive cancellation requested')\n return {\n status: 'unknown',\n effect: 'cancel_requested',\n observedAt,\n detail: error instanceof Error ? error.message : String(error),\n evidence: { operationId },\n }\n }\n}\n\nasync function teardownInteractive(run: InteractiveRun): Promise<{ destroyed: boolean }> {\n run.localController.abort('interactive worker teardown')\n run.activeLink?.release()\n await run.startPromise?.catch(() => undefined)\n if (run.handle) {\n const status = await safeStatus(run.handle)\n if (status?.state === 'running') {\n const operationId = `interactive-teardown-${canonicalCandidateDigest(run.handle.ref).slice(\n 'sha256:'.length,\n )}`\n const cancellation = await stopInteractive(run, operationId, 'interactive worker teardown')\n if (cancellation.status === 'rejected' || cancellation.status === 'unknown') {\n throw new Error(cancellation.detail ?? 'interactive teardown was not acknowledged')\n }\n }\n }\n await destroyEnvironment(run)\n return { destroyed: true }\n}\n\nasync function destroyEnvironment(run: InteractiveRun): Promise<void> {\n const { input } = run\n if (input.destroyEnvironmentOnTeardown === false) return\n if (run.createdEnvironment !== undefined) {\n await destroyConfirmed(input.provider, run.createdEnvironment)\n return\n }\n if (!input.provider.get) return\n // The exact provider reference is durable and remains available even when the admission\n // callback was interrupted after the environment was created. Use it as the cleanup identity\n // so an aborted provider signal cannot turn a real environment into an unconfirmed leak.\n const cleanupEnvironmentId = run.environmentId ?? run.handle?.ref.run.environmentId\n if (!cleanupEnvironmentId) return\n const environment = await input.provider.get(cleanupEnvironmentId)\n if (environment !== undefined && environment !== null) {\n await destroyConfirmed(input.provider, environment)\n }\n}\n\nasync function destroyConfirmed(\n provider: AgentEnvironmentProvider,\n environment: AgentEnvironment,\n): Promise<void> {\n try {\n await destroyInteractiveEnvironment(environment)\n } catch (error) {\n // A delete whose answer was lost fails not-found on every later attempt; the provider's\n // lookup confirming the environment gone is the destroy's confirmation.\n if (!(await environmentGone(provider, environment.id))) throw error\n }\n}\n\nfunction unavailableReason(\n error: unknown,\n): 'provider-has-no-interactive-contract' | 'interactive-binding-stale' {\n const message = error instanceof Error ? error.message : String(error)\n return message.includes('interactive') || message.includes('Interactive')\n ? 'provider-has-no-interactive-contract'\n : 'interactive-binding-stale'\n}\n\nfunction cancellationFromAcknowledgement(\n acknowledgement: AgentInteractiveSessionStopAcknowledgement,\n observedAt: string,\n): ExecutorCancellation {\n const status =\n acknowledgement.status === 'accepted' || acknowledgement.status === 'replayed'\n ? 'accepted'\n : acknowledgement.status === 'conflict'\n ? 'rejected'\n : 'unknown'\n const effect =\n acknowledgement.effect === 'stopped'\n ? 'cancelled'\n : acknowledgement.effect === 'not_live'\n ? 'not_live'\n : acknowledgement.effect === 'stop_requested'\n ? 'cancel_requested'\n : 'unknown'\n return {\n status,\n effect,\n observedAt,\n ...(acknowledgement.message === undefined ? {} : { detail: acknowledgement.message }),\n evidence: {\n operationId: acknowledgement.operationId,\n requestDigest: acknowledgement.requestDigest,\n providerStatus: acknowledgement.status,\n providerEffect: acknowledgement.effect,\n },\n }\n}\n\nfunction controlErrorValue(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error))\n}\n\nasync function safeStatus(\n handle: RetainedInteractiveRunHandle,\n): Promise<AgentInteractiveSessionStatus | undefined> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), 100)\n timer.unref?.()\n })\n try {\n // A provider environment created with the worker's abort signal may reject or hang all\n // subsequent calls after the scope begins teardown. Keep status best-effort and let the fresh\n // environment lookup below prove release without spending the teardown acknowledgement window\n // on a stale connection.\n return await Promise.race([handle.status(), timeout])\n } catch {\n return undefined\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n }\n}\n","/**\n * Runtime-owned worker seam for a provider's native interactive coding-agent process. It composes\n * the retained-interactive lifecycle, adding no second stream, replay buffer, session id or\n * cancellation protocol: the provider owns process state; Scope owns the worker, journal, budget\n * and local control inbox.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n type AgentInteractiveSessionRef,\n type AgentProfile,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironmentProvider,\n CreateAgentEnvironmentInput,\n} from '@tangle-network/agent-interface/environment-provider'\nimport type { MakeWorkerAgent, WorkerSpawnContext } from '../../mcp/tools/coordination-contracts'\nimport type { RetainedInteractiveAdmission } from '../retained-run-types'\nimport { executableAgentProfileSnapshot } from './executable-spec'\nimport {\n type InteractiveAdmissionWriter,\n interactiveAdmissionSeamKey,\n} from './interactive-admission'\nimport { interactiveExecutor } from './interactive-executor'\nimport { detachedSnapshot } from './snapshot'\nimport type { Agent, AgentSpec, Executor, ExecutorContext, Runtime } from './types'\n\n/** Environment fields supplied to every interactive worker after Runtime adds the exact profile. */\nexport type InteractiveWorkerEnvironment = Omit<\n CreateAgentEnvironmentInput,\n 'profile' | 'idempotencyKey' | 'signal'\n>\n\n/** Native interactive worker output. Provider usage is intentionally not fabricated. */\nexport interface InteractiveWorkerResult {\n readonly provider: string\n readonly environmentId: string\n readonly sessionId: string\n readonly executionId: string\n readonly state: 'exited' | 'unknown'\n readonly ref: AgentInteractiveSessionRef\n readonly reason?: string\n readonly exitCode?: number\n readonly exitSignal?: string\n}\n\n/** Configuration shared by every worker produced by `workerFromInteractiveProvider`. */\nexport interface InteractiveWorkerOptions {\n /** Provider create fields. Runtime supplies `profile`, the two idempotency keys, and `signal`. */\n readonly environment?: InteractiveWorkerEnvironment\n /** Stable environment identity override. Defaults to a digest of the exact worker assignment. */\n readonly environmentIdempotencyKey?: (input: InteractiveWorkerKeyInput) => string\n /** Stable interactive-session identity override. Defaults to a digest of assignment and task. */\n readonly interactiveIdempotencyKey?: (input: InteractiveWorkerKeyInput) => string\n /** Provider holder id used only while the worker sends a steer or stop command. */\n readonly holderId?: string | ((input: InteractiveWorkerKeyInput) => string)\n /** Initial prompt override. The exact worker task is the default prompt. */\n readonly initialPrompt?: string | ((task: unknown, input: InteractiveWorkerKeyInput) => string)\n readonly cwd?: string\n readonly cols?: number\n readonly rows?: number\n /** Runtime tag written into tree snapshots. Defaults to the provider name. */\n readonly runtime?: Runtime\n /** Poll delay used while waiting for the provider's native process to exit. */\n readonly pollIntervalMs?: number\n /** Destroy the provider environment after the process is terminal. Defaults to true. */\n readonly destroyEnvironmentOnTeardown?: boolean\n}\n\n/** Stable input available to key and holder functions. */\nexport interface InteractiveWorkerKeyInput {\n readonly provider: string\n readonly profile: AgentProfile\n readonly context?: WorkerSpawnContext\n readonly task?: unknown\n readonly nodeId?: string\n}\n\n/**\n * Build a `MakeWorkerAgent` that starts one provider-owned native TUI per worker. A Scope supplies\n * the durable admission hook and node attempt; the worker exposes `interactiveReady`, so the exact\n * provider reference is written before another process can attach, and `attachWorker` reconnects\n * it through the provider's public `get`/interactive contract.\n */\nexport function workerFromInteractiveProvider(\n provider: AgentEnvironmentProvider,\n options: InteractiveWorkerOptions = {},\n): MakeWorkerAgent {\n if (!provider.name.trim())\n throw new Error('workerFromInteractiveProvider: provider.name required')\n if (!provider.get) {\n throw new Error(\n `workerFromInteractiveProvider(${provider.name}): provider.get is required for reconnect`,\n )\n }\n const capturedEnvironment = options.environment\n ? (structuredClone(options.environment) as InteractiveWorkerEnvironment)\n : undefined\n const unscopedNamespace = randomUUID()\n let unscopedOrdinal = 0\n const runtime = options.runtime ?? (provider.name as Runtime)\n\n return (rawProfile, spawnContext) => {\n const profile = executableAgentProfileSnapshot(\n rawProfile,\n `workerFromInteractiveProvider(${provider.name})`,\n )\n const input: InteractiveWorkerKeyInput = {\n provider: provider.name,\n profile,\n ...(spawnContext === undefined ? {} : { context: spawnContext }),\n }\n const assignmentId =\n spawnContext?.assignmentId ?? `unscoped:${unscopedNamespace}:${unscopedOrdinal++}`\n const baseInput = { ...input, nodeId: spawnContext?.parentNodeId }\n const environmentKey = stableKey(\n options.environmentIdempotencyKey?.({ ...baseInput }) ??\n derivedKey('supervised-interactive-environment', {\n provider: provider.name,\n assignmentId,\n parentNodeId: spawnContext?.parentNodeId,\n profile,\n }),\n 'environment idempotency key',\n )\n const name = profile.name ?? 'interactive-worker'\n\n const executorFactory = (\n spec: AgentSpec,\n ctx: ExecutorContext,\n ): Executor<InteractiveWorkerResult> =>\n interactiveExecutor({\n provider,\n profile: spec.profile,\n context: spawnContext,\n environment: capturedEnvironment,\n environmentKey,\n interactiveKey: (task: unknown) =>\n stableKey(\n options.interactiveIdempotencyKey?.({\n ...baseInput,\n task,\n }) ??\n derivedKey('supervised-interactive-session', {\n provider: provider.name,\n assignmentId,\n parentNodeId: spawnContext?.parentNodeId,\n profile: spec.profile,\n task,\n }),\n 'interactive idempotency key',\n ),\n holderId: (task: unknown) => {\n const selected =\n typeof options.holderId === 'function'\n ? options.holderId({ ...baseInput, task })\n : options.holderId\n return stableKey(\n selected ??\n `runtime-interactive-worker:${canonicalCandidateDigest({\n provider: provider.name,\n assignmentId,\n })}`,\n 'interactive holder id',\n )\n },\n initialPrompt: options.initialPrompt,\n cwd: options.cwd,\n cols: options.cols,\n rows: options.rows,\n runtime,\n pollIntervalMs: options.pollIntervalMs,\n destroyEnvironmentOnTeardown: options.destroyEnvironmentOnTeardown,\n executionAttemptId: ctx.node?.attemptId,\n nodeId: ctx.node?.nodeId,\n admission: admissionWriter(ctx, provider.name, ctx.node?.nodeId),\n })\n\n const spec: AgentSpec = {\n profile,\n harness: null,\n executorFactory,\n ...(spawnContext?.execution ? { execution: spawnContext.execution } : {}),\n }\n return {\n name,\n act: async () => {\n throw new Error(\n 'workerFromInteractiveProvider: interactive workers execute through executorSpec',\n )\n },\n executorSpec: spec,\n } as Agent<unknown, InteractiveWorkerResult> & { executorSpec: AgentSpec }\n }\n}\n\nfunction admissionWriter(\n ctx: ExecutorContext,\n provider: string,\n workerId: string | undefined,\n): InteractiveAdmissionWriter {\n const candidate = ctx.seams[interactiveAdmissionSeamKey]\n if (typeof candidate === 'function') {\n return async (admission) => {\n await (candidate as (value: RetainedInteractiveAdmission) => Promise<void>)(admission)\n }\n }\n // In-memory runs still need a real hook because retained-start refuses an omitted hook. The\n // durable Scope path always supplies the Runtime-owned writer above; this fallback is explicit\n // and process-local, never mistaken for restart evidence.\n const records = new Map<string, RetainedInteractiveAdmission>()\n return async (admission) => {\n const prior = records.get(admission.phase)\n if (prior && canonicalCandidateDigest(prior) !== canonicalCandidateDigest(admission)) {\n throw new Error(\n `worker ${workerId ?? '(unscoped)'} provider ${provider} admission changed in memory`,\n )\n }\n records.set(admission.phase, detachedSnapshot(admission, 'interactive admission'))\n }\n}\n\nfunction derivedKey(kind: string, value: unknown): string {\n return `${kind}-${canonicalCandidateDigest(value).slice('sha256:'.length)}`\n}\n\nfunction stableKey(value: string, label: string): string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new Error(`${label} must be a non-empty string`)\n }\n const key = value.trim()\n if (key.length > 256) throw new Error(`${label} must not exceed 256 bytes`)\n return key\n}\n","/**\n * Public one-call composition for a durable Runtime supervisor proof run.\n *\n * This is intentionally a thin owner of existing Runtime primitives. The supervisor owns the\n * root abort channel and join barrier, Scope owns worker admission and lifecycle, and the provider\n * owns the environment and interactive process. External clients receive identifiers and opaque\n * handles; they do not receive a second supervisor protocol or a copy of provider state.\n *\n * @experimental\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { mkdirSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { dirname, join, resolve } from 'node:path'\nimport {\n type AgentProfile,\n agentProfileSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironmentCapabilities,\n AgentEnvironmentProvider,\n} from '@tangle-network/agent-interface/environment-provider'\nimport type { McpToolDescriptor } from '../../mcp/server'\nimport { createCoordinationTools } from '../../mcp/tools/coordination-manager'\nimport { sleep } from '../util'\nimport { armDeadlineTimer } from './deadline'\nimport { createCancelAcknowledger, createSteerAcknowledger } from './driver-control-acknowledgers'\nimport { writeAtomicDurableFile } from './durable-file'\nimport {\n type InteractiveWorkerEnvironment,\n workerFromInteractiveProvider,\n} from './interactive-worker'\nimport { createFileRunContext } from './run-context'\nimport { supervisorRunDir } from './run-layout'\nimport { createRootHandle, createSupervisor } from './supervisor'\nimport type { Agent, Budget, Scope, SpawnEvent, SupervisedResult } from './types'\nimport { readWorkerInteractiveBinding } from './worker-interactive'\n\nconst DEFAULT_POLL_MS = 25\nconst ROOT_MAX_ITERATIONS = 100\nconst ROOT_MAX_TOKENS = 100_000\nconst WORKER_MAX_ITERATIONS = 25\nconst WORKER_MAX_TOKENS = 25_000\n\n/** Caller-supplied environment provider for one supervisor run. */\nexport interface ProvisionSupervisorConnection {\n /** A constructed provider that owns exact-profile admission and environment reconnection. */\n readonly provider: AgentEnvironmentProvider\n}\n\n/** Input to the public Runtime supervisor provisioner. */\nexport interface ProvisionSupervisorRequest {\n readonly invocationId: string\n /** Caller-owned task assigned to the first interactive worker. */\n readonly task: string\n /** Canonical profile assigned to the first interactive worker. */\n readonly profile: AgentProfile\n /** Generic provider create fields forwarded to the interactive worker. */\n readonly workerEnvironment?: InteractiveWorkerEnvironment\n /** Root directory for Runtime-owned `.agent/supervisor` state. */\n readonly workspaceDir?: string\n /** Maximum wall-clock time for the complete supervisor lifecycle, including cleanup. Omit for no lifecycle deadline. */\n readonly timeoutMs?: number\n /** Poll cadence for lifecycle/control readiness. */\n readonly pollMs?: number\n /** Constructed provider for one execution connection. */\n readonly connection: ProvisionSupervisorConnection\n}\n\n/** Exact owner-scoped cleanup receipt returned after Runtime releases the run resources. */\nexport interface SupervisorCleanupReceipt {\n readonly status: 'completed'\n readonly rootDir: string\n readonly supervisorId: string\n readonly workerId: string\n readonly supervisorStatus: string\n readonly workerStatus: 'running' | 'done' | 'down' | 'cancelled'\n readonly resourcesReleased: true\n readonly remainingResources: readonly []\n}\n\n/** Handles for one Runtime-owned supervisor and its first interactive worker. */\nexport interface ProvisionedSupervisor {\n readonly rootDir: string\n readonly supervisorId: string\n readonly workerId: string\n /** Provider source for `attachWorker`; omitted only when resolution did not produce one. */\n readonly providers?: AgentEnvironmentProvider\n /** Capability-derived terminal takeover requirement. */\n readonly terminalTakeover: 'required' | 'unsupported' | 'unspecified'\n cleanup(): Promise<SupervisorCleanupReceipt>\n}\n\nclass SupervisorProvisionUnavailableError extends Error {\n readonly unavailable = true as const\n\n constructor(message: string, cause?: unknown) {\n super(message, cause === undefined ? undefined : { cause })\n this.name = 'SupervisorProvisionUnavailableError'\n }\n}\n\ninterface MutableState {\n readonly id: string\n status: string\n readonly task: string\n readonly workspaceDir: string\n readonly budget: number\n readonly workerModel?: string\n readonly startedAt: string\n completedAt?: string\n}\n\ninterface Deferred<T> {\n readonly promise: Promise<T>\n resolve(value: T): void\n reject(error: unknown): void\n readonly settled: () => boolean\n}\n\n/**\n * Provision one real provider-backed worker and keep its owning manager alive for controls.\n *\n * The root manager does not use a model. It runs the same coordination tools used by a driver in a\n * small deterministic loop, so durable steer and cancel requests are acknowledged by the owning\n * Runtime turn loop and never by a test-only shortcut. The caller owns profile, task, and provider\n * connection selection; Runtime does not infer them from process environment variables.\n */\nexport async function provisionSupervisor(\n request: ProvisionSupervisorRequest,\n): Promise<ProvisionedSupervisor> {\n const input = normalizeRequest(request)\n const provider = resolveProvider(input)\n const capabilities = await readCapabilities(provider)\n const terminalTakeover = terminalCapability(capabilities)\n const profile = input.profile\n const rootDir = resolve(input.workspaceDir ?? makeWorkspaceDir())\n mkdirSync(rootDir, { recursive: true })\n const supervisorId = supervisorIdFor(input.invocationId)\n const eventDir = supervisorRunDir(rootDir, supervisorId)\n const statePath = join(eventDir, 'state.json')\n mkdirSync(dirname(eventDir), { recursive: true })\n try {\n // The run directory is the cross-process invocation lock. A non-recursive mkdir closes the\n // duplicate-start race before any journal or provider resource is created.\n mkdirSync(eventDir)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EEXIST') {\n throw unavailable(\n `Runtime supervisor '${supervisorId}' already exists at '${eventDir}'; use a new invocationId`,\n )\n }\n throw error\n }\n\n const context = createFileRunContext(eventDir)\n const startedAtMs = Date.now()\n const state: MutableState = {\n id: supervisorId,\n status: 'running',\n task: input.task,\n workspaceDir: rootDir,\n budget: ROOT_MAX_TOKENS,\n ...(profile.model?.default === undefined ? {} : { workerModel: profile.model.default }),\n startedAt: new Date(startedAtMs).toISOString(),\n }\n writeState(statePath, state)\n\n const rootHandle = createRootHandle<unknown>()\n const supervisor = createSupervisor<unknown, unknown>()\n supervisor.attach(rootHandle)\n const workerSpawned = deferred<string>()\n const workerRunning = deferred<void>()\n const workerProfile = profile\n const workerEnvironment = {\n ...(input.workerEnvironment ?? {}),\n metadata: {\n ...(input.workerEnvironment?.metadata ?? {}),\n runtime: 'agent-runtime',\n invocationId: input.invocationId,\n },\n name: input.workerEnvironment?.name ?? `runtime-${supervisorId}`,\n }\n const makeWorkerAgent = workerFromInteractiveProvider(provider, {\n environment: workerEnvironment,\n pollIntervalMs: input.pollMs,\n destroyEnvironmentOnTeardown: true,\n })\n\n const rootAgent: Agent<unknown, unknown> = {\n name: 'runtime-supervisor-root',\n async act(_task: unknown, scope: Scope<unknown>): Promise<unknown> {\n const coord = createCoordinationTools({\n scope,\n blobs: context.blobs,\n makeWorkerAgent,\n perWorker: workerBudget(),\n })\n await coord.ready()\n const spawn = findTool(coord.tools, 'spawn_worker')\n const result = await spawn.handler({\n profile: workerProfile,\n task: input.task,\n label: 'interactive-worker',\n })\n const childId = workerIdFromSpawn(result)\n workerSpawned.resolve(childId)\n\n for (;;) {\n const child = scope.view.nodes.find((node) => node.id === childId)\n if (child?.status === 'running') break\n if (\n child === undefined ||\n child.status === 'done' ||\n child.status === 'failed' ||\n child.status === 'cancelled'\n ) {\n throw new Error(`Runtime supervisor worker '${childId}' ended before becoming live`)\n }\n await delay(input.pollMs)\n }\n workerRunning.resolve()\n\n const steerAcknowledger = createSteerAcknowledger({\n dir: eventDir,\n coord,\n now: Date.now,\n ownerId: scope.view.root,\n })\n const cancelAcknowledger = createCancelAcknowledger({\n dir: eventDir,\n coord,\n scope,\n now: Date.now,\n ownerId: scope.view.root,\n controlScope: 'run',\n })\n try {\n while (true) {\n await steerAcknowledger.pass('turn')\n cancelAcknowledger.pass('turn')\n // The wake owns the single scope cursor drain. Calling `scope.next()` directly here\n // would bypass the coordination ledger and make a real cancellation look unknown. Its\n // heartbeat bounds each pass so control requests are observed while the worker runs.\n const wake = await coord.awaitWake({\n attempt: 1,\n signal: scope.signal,\n heartbeatMs: input.pollMs,\n debounceMs: 0,\n })\n if (wake?.events.some((event) => event.type === 'settled')) {\n await steerAcknowledger.pass('final')\n cancelAcknowledger.pass('final')\n return undefined\n }\n if (wake === undefined) {\n throw new Error(`Runtime supervisor worker '${childId}' ended without a settlement`)\n }\n }\n } finally {\n // The final pass closes requests that landed after the last turn. It is idempotent with the\n // normal path and prevents an admitted operation from remaining open after root teardown.\n await steerAcknowledger.pass('final')\n cancelAcknowledger.pass('final')\n cancelAcknowledger.finish()\n }\n },\n }\n const runBudget = rootBudget(input.timeoutMs)\n let runResult: SupervisedResult<unknown> | undefined\n let runError: unknown\n let runSettled = false\n const runPromise = supervisor\n .run(rootAgent, input.task, {\n budget: runBudget,\n rootIdentity: {\n profileDigest: canonicalAgentProfileDigest(profile),\n taskDigest: canonicalCandidateDigest(input.task),\n },\n runId: supervisorId,\n ...context,\n interactiveBindingDir: eventDir,\n maxDepth: 1,\n workerSlots: 1,\n })\n .then(\n (result) => {\n runResult = result\n runSettled = true\n updateStateFromResult(state, result)\n writeState(statePath, state)\n return result\n },\n (error) => {\n runError = error\n runSettled = true\n state.status = 'down'\n state.completedAt = new Date().toISOString()\n writeState(statePath, state)\n throw error\n },\n )\n void runPromise.catch(() => undefined)\n\n let workerId: string\n try {\n workerId = await waitForWorkerSpawn(workerSpawned.promise, runPromise, input.timeoutMs)\n await waitForWorkerRunning(workerRunning.promise, runPromise, input.timeoutMs)\n if (terminalTakeover === 'required') {\n await waitForInteractiveBinding(eventDir, workerId, runPromise, input.timeoutMs, input.pollMs)\n }\n } catch (error) {\n if (!runSettled) {\n try {\n rootHandle.abort('supervisor provisioning failed')\n } catch {\n // The supervisor may have released the handle between the state read and this abort.\n }\n }\n await runPromise.catch(() => undefined)\n throw error\n }\n\n let cleanupPromise: Promise<SupervisorCleanupReceipt> | undefined\n const cleanup = async (): Promise<SupervisorCleanupReceipt> => {\n cleanupPromise ??= (async () => {\n if (!runSettled) {\n try {\n rootHandle.abort('supervisor cleanup')\n } catch {\n // A concurrent run completion already released the handle.\n }\n }\n const result = await runPromise.catch((error) => {\n runError = error\n return undefined\n })\n if (result !== undefined) runResult = result\n if (runError !== undefined) throw runError\n const finalEvents = await waitForWorkerTerminal(\n context.journal,\n supervisorId,\n workerId,\n input.timeoutMs,\n input.pollMs,\n )\n const workerStatus = workerStatusFromEvents(finalEvents, workerId)\n if (workerStatus === 'running') {\n throw new Error(`Runtime supervisor worker '${workerId}' did not reach a terminal state`)\n }\n if (runResult?.teardownUnconfirmed?.length) {\n const environments = runResult.teardownUnconfirmed.flatMap((node) =>\n (node.environments ?? []).map(\n (environment) => `${environment.provider}:${environment.environmentId}`,\n ),\n )\n throw new Error(\n `Runtime supervisor cleanup could not confirm ${runResult.teardownUnconfirmed.length} resource(s) released${\n environments.length > 0 ? `; environments still held: ${environments.join(', ')}` : ''\n }`,\n )\n }\n const supervisorStatus = state.status\n state.completedAt ??= new Date().toISOString()\n writeState(statePath, state)\n return Object.freeze({\n status: 'completed' as const,\n rootDir,\n supervisorId,\n workerId,\n supervisorStatus,\n workerStatus,\n resourcesReleased: true as const,\n remainingResources: Object.freeze([]) as readonly [],\n })\n })()\n return cleanupPromise\n }\n\n return Object.freeze({\n rootDir,\n supervisorId,\n workerId,\n providers: provider,\n terminalTakeover,\n cleanup,\n })\n}\n\nfunction normalizeRequest(request: ProvisionSupervisorRequest): ProvisionSupervisorRequest & {\n readonly invocationId: string\n readonly task: string\n readonly timeoutMs: number | undefined\n readonly pollMs: number\n readonly profile: AgentProfile\n readonly connection: ProvisionSupervisorConnection\n} {\n const invocationId = request.invocationId.trim()\n if (!invocationId) throw new SupervisorProvisionUnavailableError('invocationId is required')\n const task = request.task.trim()\n if (!task) throw new SupervisorProvisionUnavailableError('task is required')\n const profile = resolveProfile(request.profile)\n if (request.connection === undefined) {\n throw new SupervisorProvisionUnavailableError('provider connection is required')\n }\n const timeoutMs =\n request.timeoutMs === undefined ? undefined : positiveNumber(request.timeoutMs, 'timeoutMs')\n const pollMs = positiveNumber(request.pollMs ?? DEFAULT_POLL_MS, 'pollMs')\n return { ...request, invocationId, task, timeoutMs, pollMs, profile }\n}\n\nfunction positiveNumber(value: number, name: string): number {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new SupervisorProvisionUnavailableError(`${name} must be a positive safe integer`)\n }\n return value\n}\n\nfunction makeWorkspaceDir(): string {\n return join(tmpdir(), `agent-runtime-supervisor-${randomUUID()}`)\n}\n\nfunction supervisorIdFor(invocationId: string): string {\n const digest = canonicalCandidateDigest({ kind: 'runtime-supervisor', invocationId })\n return `runtime-supervisor-${digest.slice('sha256:'.length)}`\n}\n\n/** A caller-supplied deadline covers the complete supervisor lifecycle from run start through cleanup. */\nfunction rootBudget(timeoutMs: number | undefined): Budget {\n return {\n maxIterations: ROOT_MAX_ITERATIONS,\n maxTokens: ROOT_MAX_TOKENS,\n ...(timeoutMs === undefined ? {} : { deadlineMs: timeoutMs }),\n }\n}\n\nfunction workerBudget(): Budget {\n return {\n maxIterations: WORKER_MAX_ITERATIONS,\n maxTokens: WORKER_MAX_TOKENS,\n }\n}\n\nfunction resolveProfile(profile: AgentProfile): AgentProfile {\n const parsed = agentProfileSchema.safeParse(profile)\n if (!parsed.success) {\n throw unavailable(\n `Runtime supervisor profile is invalid: ${parsed.error.issues\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join('; ')}`,\n )\n }\n return parsed.data\n}\n\nfunction resolveProvider(request: ProvisionSupervisorRequest): AgentEnvironmentProvider {\n const provider = request.connection?.provider\n if (provider === undefined) {\n throw unavailable('Runtime supervisor requires connection.provider')\n }\n return requireReconnectProvider(provider)\n}\n\nfunction requireReconnectProvider(provider: AgentEnvironmentProvider): AgentEnvironmentProvider {\n if (!provider.name.trim()) throw unavailable('Runtime supervisor provider has no name')\n if (typeof provider.get !== 'function') {\n throw unavailable(\n `Runtime supervisor provider '${provider.name}' cannot reconnect environments`,\n )\n }\n return provider\n}\n\nasync function readCapabilities(\n provider: AgentEnvironmentProvider,\n): Promise<AgentEnvironmentCapabilities> {\n try {\n return await provider.capabilities()\n } catch (error) {\n throw unavailable(`Runtime supervisor could not read '${provider.name}' capabilities`, error)\n }\n}\n\nfunction terminalCapability(\n capabilities: AgentEnvironmentCapabilities,\n): 'required' | 'unsupported' | 'unspecified' {\n const interactive = capabilities.interactiveAgent\n if (interactive === undefined) return 'unsupported'\n const complete = [\n interactive.start,\n interactive.control,\n interactive.status,\n interactive.attach,\n interactive.reattach,\n interactive.sendPrompt,\n interactive.input,\n interactive.resize,\n interactive.stop,\n ].every((value) => value === true)\n return complete ? 'required' : 'unsupported'\n}\n\nfunction findTool(tools: readonly McpToolDescriptor[], name: string): McpToolDescriptor {\n const tool = tools.find((candidate) => candidate.name === name)\n if (tool === undefined)\n throw new Error(`Runtime supervisor coordination tool '${name}' is missing`)\n return tool\n}\n\nfunction workerIdFromSpawn(value: unknown): string {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('Runtime supervisor spawn did not return a worker id')\n }\n const workerId = (value as { workerId?: unknown }).workerId\n if (typeof workerId !== 'string' || !workerId.trim()) {\n throw new Error('Runtime supervisor spawn did not return a worker id')\n }\n return workerId\n}\n\nasync function waitForWorkerSpawn(\n worker: Promise<string>,\n run: Promise<SupervisedResult<unknown>>,\n timeoutMs: number | undefined,\n): Promise<string> {\n return await withTimeout(\n Promise.race([\n worker,\n run.then(() => {\n throw new Error('Runtime supervisor ended before it spawned a worker')\n }),\n ]),\n timeoutMs,\n 'worker spawn',\n )\n}\n\nasync function waitForWorkerRunning(\n running: Promise<void>,\n run: Promise<SupervisedResult<unknown>>,\n timeoutMs: number | undefined,\n): Promise<void> {\n await withTimeout(\n Promise.race([\n running,\n run.then(() => {\n throw new Error('Runtime supervisor ended before the worker became live')\n }),\n ]),\n timeoutMs,\n 'worker readiness',\n )\n}\n\nasync function waitForInteractiveBinding(\n eventDir: string,\n workerId: string,\n run: Promise<SupervisedResult<unknown>>,\n timeoutMs: number | undefined,\n pollMs: number,\n): Promise<void> {\n await withTimeout(\n pollUntil(\n async () => {\n const binding = readWorkerInteractiveBinding(eventDir, workerId)\n if (binding?.status === 'available') return true\n if (binding?.status === 'unavailable') {\n throw unavailable(`Runtime worker '${workerId}' could not publish an interactive binding`)\n }\n return false\n },\n run,\n pollMs,\n ),\n timeoutMs,\n 'interactive terminal binding',\n )\n}\n\nasync function pollUntil(\n read: () => Promise<boolean> | boolean,\n run: Promise<SupervisedResult<unknown>>,\n pollMs: number,\n): Promise<void> {\n for (;;) {\n if (await read()) return\n await Promise.race([\n delay(pollMs),\n run.then(() => {\n throw new Error('Runtime supervisor ended before readiness was observed')\n }),\n ])\n }\n}\n\nasync function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number | undefined,\n label: string,\n): Promise<T> {\n if (timeoutMs === undefined) return await promise\n let clearTimer: (() => void) | undefined\n const timeout = new Promise<never>((_resolve, reject) => {\n clearTimer = armDeadlineTimer(timeoutMs, () =>\n reject(unavailable(`Runtime supervisor timed out waiting for ${label}`)),\n )\n })\n try {\n return await Promise.race([promise, timeout])\n } finally {\n clearTimer?.()\n }\n}\n\nfunction delay(ms: number, keepAlive = false): Promise<void> {\n return sleep(ms, undefined, keepAlive)\n}\n\nfunction updateStateFromResult(state: MutableState, result: SupervisedResult<unknown>): void {\n state.status =\n result.kind === 'winner' ? 'done' : result.reason === 'cancelled' ? 'cancelled' : 'down'\n state.completedAt = new Date().toISOString()\n}\n\nfunction workerStatusFromEvents(\n events: readonly SpawnEvent[],\n workerId: string,\n): SupervisorCleanupReceipt['workerStatus'] {\n let status: SupervisorCleanupReceipt['workerStatus'] = 'running'\n let terminal = false\n for (const event of events) {\n if (event.id !== workerId) continue\n if (terminal) continue\n if (event.kind === 'spawned' || event.kind === 'progress') status = 'running'\n else if (event.kind === 'settled') {\n status = event.status === 'done' ? 'done' : 'down'\n terminal = true\n } else if (event.kind === 'cancelled') {\n status = 'cancelled'\n terminal = true\n }\n }\n return status\n}\n\nasync function waitForWorkerTerminal(\n journal: import('./types').SpawnJournal,\n root: string,\n workerId: string,\n timeoutMs: number | undefined,\n pollMs: number,\n): Promise<SpawnEvent[]> {\n const deadline = timeoutMs === undefined ? undefined : Date.now() + timeoutMs\n for (;;) {\n const events = await journal.loadTree(root)\n if (events !== undefined && workerStatusFromEvents(events, workerId) !== 'running') {\n return events\n }\n if (deadline !== undefined && Date.now() >= deadline) {\n throw unavailable(`Runtime supervisor timed out waiting for worker '${workerId}' to settle`)\n }\n // Cleanup is an explicit lifecycle operation. Keep this bounded poll referenced so a caller\n // awaiting cleanup cannot have Node exit while the provider is still committing the terminal\n // worker event.\n await delay(pollMs, true)\n }\n}\n\nfunction deferred<T>(): Deferred<T> {\n let done = false\n let resolveValue!: (value: T) => void\n let rejectValue!: (error: unknown) => void\n const promise = new Promise<T>((resolvePromise, rejectPromise) => {\n resolveValue = (value) => {\n if (done) return\n done = true\n resolvePromise(value)\n }\n rejectValue = (error) => {\n if (done) return\n done = true\n rejectPromise(error)\n }\n })\n return {\n promise,\n resolve: resolveValue,\n reject: rejectValue,\n settled: () => done,\n }\n}\n\nfunction unavailable(message: string, cause?: unknown): SupervisorProvisionUnavailableError {\n return new SupervisorProvisionUnavailableError(message, cause)\n}\n\nfunction writeState(path: string, state: MutableState): void {\n mkdirSync(dirname(path), { recursive: true })\n writeAtomicDurableFile(path, `${JSON.stringify(state)}\\n`, { mode: 0o600 })\n}\n"],"mappings":";;;;;;;;;;;;;AAQA,MAAM,2BAA2B;;;;;;;;;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