@tangle-network/agent-runtime 9.0.16 → 10.0.1

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 (93) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/dist/{activation-DgT20fzX.js → activation-C_BenzIu.js} +2 -2
  3. package/dist/{activation-DgT20fzX.js.map → activation-C_BenzIu.js.map} +1 -1
  4. package/dist/{activation-y6NAn3sW.d.ts → activation-s6dGGify.d.ts} +7 -8
  5. package/dist/agent.d.ts +1 -1
  6. package/dist/agent.js +3 -3
  7. package/dist/candidate-execution/index.d.ts +3 -0
  8. package/dist/candidate-execution/index.js +10 -3
  9. package/dist/candidate-execution/index.js.map +1 -1
  10. package/dist/{delegate-Cmu5OF3M.js → delegate-BOren4c7.js} +2 -2
  11. package/dist/{delegate-Cmu5OF3M.js.map → delegate-BOren4c7.js.map} +1 -1
  12. package/dist/{coordination-manager-CFtnSLPw.js → driver-control-acknowledgers-ByKwAgCI.js} +1062 -1042
  13. package/dist/driver-control-acknowledgers-ByKwAgCI.js.map +1 -0
  14. package/dist/durable.d.ts +5 -5
  15. package/dist/durable.js +13 -13
  16. package/dist/durable.js.map +1 -1
  17. package/dist/{failure-cause-WifbY42M.js → failure-cause-DoCCGLDH.js} +42 -18
  18. package/dist/failure-cause-DoCCGLDH.js.map +1 -0
  19. package/dist/{graph-DqtIiS94.js → graph-BXONYT1o.js} +8 -8
  20. package/dist/{graph-DqtIiS94.js.map → graph-BXONYT1o.js.map} +1 -1
  21. package/dist/{graph-registry-B_1C7qye.js → graph-registry-DxhlgHdA.js} +1 -1
  22. package/dist/{graph-registry-BbZN5deo.js → graph-registry-j9t9J0KT.js} +11 -12
  23. package/dist/{graph-registry-BbZN5deo.js.map → graph-registry-j9t9J0KT.js.map} +1 -1
  24. package/dist/{improve-B0vNv6e7.js → improve-CS2GIF5O.js} +42 -26
  25. package/dist/{improve-B0vNv6e7.js.map → improve-CS2GIF5O.js.map} +1 -1
  26. package/dist/index.d.ts +38 -6
  27. package/dist/index.js +59 -20
  28. package/dist/index.js.map +1 -1
  29. package/dist/intelligence.d.ts +93 -63
  30. package/dist/intelligence.js +166 -73
  31. package/dist/intelligence.js.map +1 -1
  32. package/dist/kernel.d.ts +3 -3
  33. package/dist/kernel.js +16 -15
  34. package/dist/{loop-runner-CfMOsISJ.d.ts → loop-runner-C0B3PexH.d.ts} +2 -2
  35. package/dist/loop-runner-bin.d.ts +1 -1
  36. package/dist/loop-runner-bin.js +1 -1
  37. package/dist/{loop-runner-BvVdDdZC.js → loop-runner-ftyZP4st.js} +2 -2
  38. package/dist/{loop-runner-BvVdDdZC.js.map → loop-runner-ftyZP4st.js.map} +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 +7 -7
  42. package/dist/mcp/memory-bin.js +1 -1
  43. package/dist/{model-policy-CZwhXp8O.js → model-policy-CqDuBTq-.js} +12 -2
  44. package/dist/model-policy-CqDuBTq-.js.map +1 -0
  45. package/dist/{prepare-Cw4ZaN01.js → prepare-DT-ibRsm.js} +2 -2
  46. package/dist/{prepare-Cw4ZaN01.js.map → prepare-DT-ibRsm.js.map} +1 -1
  47. package/dist/profiles.d.ts +1 -1
  48. package/dist/profiles.js +1 -1
  49. package/dist/{provision-supervisor-BjKluSKl.js → provision-supervisor-CauovUHn.js} +6 -6
  50. package/dist/{provision-supervisor-BjKluSKl.js.map → provision-supervisor-CauovUHn.js.map} +1 -1
  51. package/dist/{run-cancellation-BvGEEwRG.js → run-cancellation-NMNVuYiO.js} +2 -2
  52. package/dist/{run-cancellation-BvGEEwRG.js.map → run-cancellation-NMNVuYiO.js.map} +1 -1
  53. package/dist/{run-state-Dd_AjWd6.js → run-state-COyIVOVb.js} +5 -5
  54. package/dist/{run-state-Dd_AjWd6.js.map → run-state-COyIVOVb.js.map} +1 -1
  55. package/dist/{runtime-7VEM9muH.js → runtime-DYaRDLKn.js} +191 -24
  56. package/dist/runtime-DYaRDLKn.js.map +1 -0
  57. package/dist/{search-executor-Dqtm1fOC.js → search-executor-Drd_N9YO.js} +5 -5
  58. package/dist/{search-executor-Dqtm1fOC.js.map → search-executor-Drd_N9YO.js.map} +1 -1
  59. package/dist/{server-B8Kmit_v.js → server-Dk9B1WFf.js} +4 -4
  60. package/dist/{server-B8Kmit_v.js.map → server-Dk9B1WFf.js.map} +1 -1
  61. package/dist/{settle-record-BvH2-Ao5.js → settle-record-YdkkHzqw.js} +2 -2
  62. package/dist/{settle-record-BvH2-Ao5.js.map → settle-record-YdkkHzqw.js.map} +1 -1
  63. package/dist/{structural-rollout-CYc8PE2N.js → structural-rollout-DbZAkHTq.js} +5 -5
  64. package/dist/{structural-rollout-CYc8PE2N.js.map → structural-rollout-DbZAkHTq.js.map} +1 -1
  65. package/dist/{supervise-BayNu7qZ.js → supervise-B5hb0my3.js} +2426 -2336
  66. package/dist/supervise-B5hb0my3.js.map +1 -0
  67. package/dist/{supervision-discovery-Ca4QO4rG.js → supervision-discovery-ChkTxilL.js} +3 -3
  68. package/dist/{supervision-discovery-Ca4QO4rG.js.map → supervision-discovery-ChkTxilL.js.map} +1 -1
  69. package/dist/{supervisor-Bx21Hy27.js → supervisor-DpwcTrTh.js} +437 -75
  70. package/dist/supervisor-DpwcTrTh.js.map +1 -0
  71. package/dist/{supervisor-accounting-StDNW1YT.js → supervisor-accounting-QiXnF-EW.js} +541 -344
  72. package/dist/supervisor-accounting-QiXnF-EW.js.map +1 -0
  73. package/dist/testing.d.ts +1 -1
  74. package/dist/testing.js +11 -11
  75. package/dist/{tool-server-CirrqFlr.js → tool-server-DQCdu3am.js} +2 -2
  76. package/dist/{tool-server-CirrqFlr.js.map → tool-server-DQCdu3am.js.map} +1 -1
  77. package/dist/{top-web-Cg7ywIkF.js → top-web-E85Fk8pH.js} +6 -6
  78. package/dist/{top-web-Cg7ywIkF.js.map → top-web-E85Fk8pH.js.map} +1 -1
  79. package/dist/tui/bin.js +3 -3
  80. package/dist/tui/index.d.ts +1 -1
  81. package/dist/tui/index.js +2 -2
  82. package/dist/{types-_j53efrk.d.ts → types-dv295cpm.d.ts} +9907 -9784
  83. package/dist/{workspace-streams-BakRr-Pl.js → workspace-streams-C7PGLAUd.js} +3 -3
  84. package/dist/workspace-streams-C7PGLAUd.js.map +1 -0
  85. package/package.json +8 -7
  86. package/dist/coordination-manager-CFtnSLPw.js.map +0 -1
  87. package/dist/failure-cause-WifbY42M.js.map +0 -1
  88. package/dist/model-policy-CZwhXp8O.js.map +0 -1
  89. package/dist/runtime-7VEM9muH.js.map +0 -1
  90. package/dist/supervise-BayNu7qZ.js.map +0 -1
  91. package/dist/supervisor-Bx21Hy27.js.map +0 -1
  92. package/dist/supervisor-accounting-StDNW1YT.js.map +0 -1
  93. package/dist/workspace-streams-BakRr-Pl.js.map +0 -1
@@ -1,10 +1,10 @@
1
- import { E as writeWorkerCancellation, F as parseWorkerToolTraceArtifact, I as workerTraceAnalysisStore, K as spawnJournalRecordEvents, O as writeWorkerSteerAcknowledgement, Rt as runtimeGraphMetadataKey, S as workerCancelRequestsFile, St as resolveSpawnResourcePaths, T as workerSteerRequestsDir, W as FileSpawnJournal, _ as readWorkerSteerAcknowledgement, an as FileResultBlobStore, d as claimWorkerSteerDelivery, g as readWorkerCancellation, h as readWorkerCancelRequests, it as meterRuntimeOwnedAccounting, mr as isTerminalNodeStatus, pr as isLiveNodeStatus, v as readWorkerSteerRequests } from "./supervisor-accounting-StDNW1YT.js";
1
+ import { Ct as resolveSpawnResourcePaths, E as writeWorkerCancellation, F as parseWorkerToolTraceArtifact, Ht as runtimeGraphMetadataKey, I as workerTraceAnalysisStore, K as spawnJournalRecordEvents, O as writeWorkerSteerAcknowledgement, S as workerCancelRequestsFile, T as workerSteerRequestsDir, W as FileSpawnJournal, _ as readWorkerSteerAcknowledgement, at as meterRuntimeOwnedAccounting, d as claimWorkerSteerDelivery, g as readWorkerCancellation, h as readWorkerCancelRequests, ln as FileResultBlobStore, v as readWorkerSteerRequests, vr as isLiveNodeStatus, yr as isTerminalNodeStatus } from "./supervisor-accounting-QiXnF-EW.js";
2
2
  import { m as ValidationError } from "./errors-DG8yufqX.js";
3
- import { N as contentAddress, o as settlementFailureCause, tt as assertValidBudget } from "./failure-cause-WifbY42M.js";
3
+ import { M as contentAddress, a as settlementFailureCause, nt as assertValidBudget } from "./failure-cause-DoCCGLDH.js";
4
4
  import { a as errMessage, f as resolveRedactor, t as detachedFrozen } from "./snapshot-BKI_w3JD.js";
5
- import { X as INBOX_RECEIPT_KEY, _t as CheckUnavailableError, b as InMemorySpawnJournal, rt as createPeerMailbox, v as withDriverExecutor, x as createExecutorRegistry, y as InMemoryResultBlobStore } from "./supervisor-Bx21Hy27.js";
5
+ import { Z as INBOX_RECEIPT_KEY, b as InMemorySpawnJournal, it as createPeerMailbox, v as withDriverExecutor, vt as CheckUnavailableError, x as createExecutorRegistry, y as InMemoryResultBlobStore } from "./supervisor-DpwcTrTh.js";
6
6
  import { i as checkVerdictOf, o as failedItems } from "./continuation-CZaeHEzQ.js";
7
- import { c as writeRunCancellation, i as readRunCancellation, r as readRunCancelRequest, t as applyRunCancellation, v as FileCoordinationLog } from "./run-cancellation-BvGEEwRG.js";
7
+ import { c as writeRunCancellation, i as readRunCancellation, r as readRunCancelRequest, t as applyRunCancellation, v as FileCoordinationLog } from "./run-cancellation-NMNVuYiO.js";
8
8
  import { a as admitRuntimeSpawn, i as workerSettlement, n as resolveJsonPointer, o as safeJsonText, r as textBytes, t as createMapRouting } from "./coordination-map-routing-XZXTlCmn.js";
9
9
  import { ResourceRequestSchema, agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest } from "@tangle-network/agent-interface";
10
10
  import { argHash, errorStreakDetector, observeAll, repeatedActionDetector } from "@tangle-network/agent-eval";
@@ -87,82 +87,92 @@ function createFileRunContext(dir, opts = {}) {
87
87
  coordinationLog: new FileCoordinationLog(`${dir}/coordination-log.jsonl`)
88
88
  };
89
89
  }
90
- // src/mcp/tools/coordination-events.ts
91
- /** Default and maximum bounds for one {@link CoordinationTools} journal read. The defaults are
92
- * sized for a driver turn (a page a model can read and still have room to act on); the maxima
93
- * bound what a single tool result may cost even when the caller asks for everything. */
94
- const JOURNAL_READ_BOUNDS = Object.freeze({
95
- defaultLimit: 50,
96
- maxLimit: 500,
97
- defaultMaxBytes: 16384,
98
- maxMaxBytes: 262144
99
- });
100
- /** Every `CoordinationEvent` kind `read_journal` can return — the tool advertises this list in its
101
- * JSON Schema AND filters on it, so the schema cannot promise a kind the filter drops. */
102
- const journalEventKinds = [
103
- "question",
104
- "settled",
105
- "finding",
106
- "submission",
107
- "steer",
108
- "answer",
109
- "instruction",
110
- "delivery-attempt",
111
- "mail",
112
- "escalation",
113
- "analyst-defined",
114
- "analyst-assignment",
115
- "acknowledgement",
116
- "tool-outcome",
117
- "tool-timing",
118
- "lead-message",
119
- "map",
120
- "route"
121
- ];
122
- /** The reserved coordination verb names — the complete set `createCoordinationTools` can emit
123
- * (the analyst pair is conditional but still reserved). A driver's extra WORK tools must not
124
- * collide with any of these, or it could no longer coordinate; callers validate eagerly against
125
- * this set so the conflict fails loud at construction, not buried in a swallowed `act()` throw.
126
- *
127
- * Every name here must also stay clear of the tools a coding harness publishes NATIVELY
128
- * (`harnessNativeToolNames`, `mcp/harness-native-tools`). A harness prefixes an MCP tool with its
129
- * server name, so the two never collide on the wire — but a driver reads a BARE word out of a
130
- * prompt, and a bare word that the harness also publishes resolves to the harness's own tool.
131
- * The spawn verb is `spawn_worker` for that reason: the runtime's vocabulary for the spawned
132
- * thing is a worker (`workerId`, `workerSlots`, the per-worker budget), and no known harness
133
- * publishes that name. `tests/kernel/harness-native-tools.test.ts` holds the set clear. */
134
- const coordinationVerbNames = [
135
- "spawn_worker",
136
- "cancel_worker",
137
- "observe_agent",
138
- "steer_agent",
139
- "list_questions",
140
- "answer_question",
141
- "ask_parent",
142
- "submit_result",
143
- "stop",
144
- "report_blocked",
145
- "read_continuation",
146
- "read_journal",
147
- "list_analysts",
148
- "run_analyst",
149
- "define_analyst",
150
- "run_graph"
151
- ];
152
- /**
153
- * The `CoordinationEvent` kinds that wake a waiting manager. The queue carries the UP-leg only:
154
- * `steer` / `answer` / `instruction` / `delivery-attempt` are recorded `queue: false` (history and
155
- * subscribers, never delivered back), and `mail` is delivered to its addressee's inbox. A
156
- * `question` on this bus is the manager's own `ask_parent`, already escalated: it never wakes the
157
- * asker, whose answer arrives as a `lead-message`.
158
- */
159
- const wakeEventKinds = [
160
- "settled",
161
- "finding",
162
- "tool-outcome",
163
- "lead-message",
164
- "map"
165
- ];
90
+ // src/runtime/supervise/event-bus.ts
91
+ /** Create the child→parent coordination bus: one typed pipe for settled outputs, questions, and analyst findings, with a priority-ordered pull queue and a pass-through subscribe lane.
92
+ * @experimental In-process queue; durability is a transport swap that does not exist yet. */
93
+ function createEventBus(now = Date.now) {
94
+ const queue = [];
95
+ const log = [];
96
+ const subscribers = [];
97
+ const queuedHandlers = [];
98
+ const byKind = {};
99
+ const staged = /* @__PURE__ */ new WeakMap();
100
+ let seq = 0;
101
+ let published = 0;
102
+ let pulled = 0;
103
+ const matches = (r, kinds) => !kinds || kinds.includes(r.event.type);
104
+ const bestIndex = (kinds) => {
105
+ let best = -1;
106
+ let bestPriority = Number.NEGATIVE_INFINITY;
107
+ for (let i = 0; i < queue.length; i++) {
108
+ const r = queue[i];
109
+ if (!r || !matches(r, kinds)) continue;
110
+ if (r.priority > bestPriority) {
111
+ best = i;
112
+ bestPriority = r.priority;
113
+ }
114
+ }
115
+ return best;
116
+ };
117
+ const pullAt = (i) => {
118
+ if (i < 0) return void 0;
119
+ pulled++;
120
+ return queue.splice(i, 1)[0];
121
+ };
122
+ const pullRecord = (kinds) => pullAt(bestIndex(kinds));
123
+ return {
124
+ async publish(event, opts) {
125
+ const record = staged.get(event) ?? {
126
+ seq: seq++,
127
+ at: now(),
128
+ priority: opts?.priority ?? 0,
129
+ event
130
+ };
131
+ staged.set(event, record);
132
+ for (const handler of subscribers) await handler(record);
133
+ staged.delete(event);
134
+ if (opts?.queue !== false) queue.push(record);
135
+ log.push(record);
136
+ published += 1;
137
+ byKind[event.type] = (byKind[event.type] ?? 0) + 1;
138
+ if (opts?.queue !== false) for (const handler of [...queuedHandlers]) handler(record);
139
+ return record;
140
+ },
141
+ pull: (kinds) => pullRecord(kinds)?.event,
142
+ pullRecord,
143
+ take: (seq) => pullAt(queue.findIndex((r) => r.seq === seq)),
144
+ queued(kinds) {
145
+ return queue.filter((r) => matches(r, kinds));
146
+ },
147
+ subscribe(handler) {
148
+ subscribers.push(handler);
149
+ return () => {
150
+ const i = subscribers.indexOf(handler);
151
+ if (i >= 0) subscribers.splice(i, 1);
152
+ };
153
+ },
154
+ onQueued(handler) {
155
+ queuedHandlers.push(handler);
156
+ return () => {
157
+ const i = queuedHandlers.indexOf(handler);
158
+ if (i >= 0) queuedHandlers.splice(i, 1);
159
+ };
160
+ },
161
+ pending(kinds) {
162
+ return kinds ? queue.filter((r) => matches(r, kinds)).length : queue.length;
163
+ },
164
+ history() {
165
+ return log;
166
+ },
167
+ stats() {
168
+ return {
169
+ published,
170
+ pulled,
171
+ byKind: { ...byKind }
172
+ };
173
+ }
174
+ };
175
+ }
166
176
  // src/mcp/tools/coordination-analysts.ts
167
177
  /**
168
178
  * The trace-tool sets a DEFINED analyst may ask for — the exact group names agent-eval's
@@ -382,735 +392,139 @@ function normalizeAnalyzeOnSettle(entry) {
382
392
  if (route.statuses !== void 0 && (!Array.isArray(route.statuses) || route.statuses.length === 0 || route.statuses.some((status) => status !== "done" && status !== "down"))) throw new TypeError("analyzeOnSettle.statuses must contain done or down");
383
393
  return route;
384
394
  }
385
- // src/mcp/tools/coordination-budget.ts
386
- /** Each channel spent beyond its budget, as spent of budget: `tokens 235,857 of 42,000` or
387
- * `deadline 3,857 s of 2,400 s`. */
388
- function budgetOverspendText(violation) {
389
- const count = (value) => value.toLocaleString("en-US");
390
- return violation.overspent.map((entry) => entry.channel === "deadline" ? `deadline ${count(Math.round(entry.spent / 1e3))} s of ${count(Math.round(entry.reserved / 1e3))} s` : `${entry.channel} ${count(entry.spent)} of ${count(entry.reserved)}`).join("; ");
391
- }
392
- /** What a manager can do with a keyed worker its budget stopped. */
393
- const BUDGET_STOP_NEXT = "spawn_worker with the same key and a larger budget continues this session where it stopped; cancel_worker releases it";
394
- /** Every cause at zero — a pre-flight publishes its whole ledger from the first read. */
395
- function emptyPreflightCounts() {
395
+ // src/mcp/tools/coordination-analysis.ts
396
+ function createCoordinationAnalysis(deps) {
397
+ const { opts } = deps;
398
+ const analysisRoutes = (opts.analyzeOnSettle ?? []).map(normalizeAnalyzeOnSettle);
399
+ const analystAssignments = loadAnalystAssignments(opts);
400
+ const analystRuns = /* @__PURE__ */ new Map();
401
+ const state = {
402
+ ...deps,
403
+ analysisRoutes,
404
+ analystAssignments,
405
+ analystRuns,
406
+ flushedAnalystRuns: /* @__PURE__ */ new Set(),
407
+ definedAnalysts: [...opts.priorAnalystDefinitions ?? []],
408
+ maxDefinedAnalysts: opts.maxDefinedAnalysts ?? ANALYST_DEFINITION_BOUNDS.maxDefinitionsPerManager,
409
+ analystRunOrdinal: nextAnalystRunOrdinal(analystAssignments),
410
+ finishing: false,
411
+ managerAnalysis: void 0
412
+ };
413
+ recoverAnalystRuns(opts, analystAssignments, analystRuns);
396
414
  return {
397
- "model-route": 0,
398
- "bridge-full": 0,
399
- "unmountable-tool": 0,
400
- "unprovisionable-profile": 0
415
+ analysisRoutes: state.analysisRoutes,
416
+ analystRuns,
417
+ flushedAnalystRuns: state.flushedAnalystRuns,
418
+ analystRunFinding,
419
+ spawnAnalystRun: spawnAnalystRun.bind(null, state),
420
+ deliverRoutedFinding: deliverRoutedFinding.bind(null, state),
421
+ analystRunContext: analystRunContext.bind(null, opts),
422
+ finishAnalysis: finishAnalysis.bind(null, state),
423
+ definedAnalysts: state.definedAnalysts,
424
+ analystMenu: analystMenu.bind(null, state),
425
+ defineAnalyst: defineAnalyst.bind(null, state),
426
+ isFinishing: () => state.finishing
401
427
  };
402
428
  }
403
- /** The optional per-spawn budget `spawn_worker` and `run_graph` take. */
404
- const spawnBudgetArg = {
405
- type: "object",
406
- description: "Optional per-spawn budget that merges over the per-worker default (per field). Only set the ceilings this sub-task needs raised; the conserved pool still fences.",
407
- properties: {
408
- maxIterations: {
409
- type: "number",
410
- minimum: 0
411
- },
412
- maxTokens: {
413
- type: "number",
414
- minimum: 0
415
- },
416
- maxUsd: {
417
- type: "number",
418
- minimum: 0
419
- },
420
- deadlineMs: {
421
- type: "number",
422
- minimum: 0
423
- },
424
- resources: {
425
- type: "object",
426
- additionalProperties: {
427
- type: "object",
428
- properties: {
429
- unit: {
430
- type: "string",
431
- minLength: 1
432
- },
433
- limit: {
434
- type: "integer",
435
- minimum: 0,
436
- maximum: Number.MAX_SAFE_INTEGER
437
- }
438
- },
439
- required: ["unit", "limit"]
440
- }
441
- }
429
+ /** The durable analyst assignments of a prior process, refusing two that disagree on one id. */
430
+ function loadAnalystAssignments(opts) {
431
+ const analystAssignments = /* @__PURE__ */ new Map();
432
+ for (const record of opts.priorJournal ?? []) {
433
+ if (record.event.type !== "analyst-assignment") continue;
434
+ const assignment = record.event.assignment;
435
+ const prior = analystAssignments.get(assignment.assignmentId);
436
+ if (prior && canonicalCandidateDigest(prior) !== canonicalCandidateDigest(assignment)) throw new Error(`coordination: conflicting analyst assignment '${assignment.assignmentId}'`);
437
+ analystAssignments.set(assignment.assignmentId, detachedFrozen(assignment));
442
438
  }
443
- };
444
- function budgetField(channel) {
445
- return channel.startsWith("resource:") ? `resources.${channel.slice(9)}.limit` : BUDGET_FIELD[channel];
439
+ return analystAssignments;
446
440
  }
447
- /** One clause per short channel. Iterations can be requested at exactly `free`: a driver's own
448
- * turns charge none. Tokens and dollars cannot: the driver's next turn is metered from the same
449
- * pool before its retry reaches admission, so the clause says to leave room. */
450
- function shortfallClause(shortfall) {
451
- const { channel, requested, free } = shortfall;
452
- const field = budgetField(channel);
453
- if (shortfall.closedByUnknownSpend === true) return `${channel} is closed: work with unmeasured ${channel} usage ran under the run's enforced limit, so this run admits no further spawn at any budget`;
454
- const asked = `this spawn asked for budget.${field} ${requested}`;
455
- const held = shortfall.held ?? 0;
456
- const most = free + held;
457
- if (most === 0) return `${channel} has nothing free and none held by your running workers (${asked})`;
458
- const room = held > 0 ? `${free} free now and ${held} held by your running workers, which a spawn waits for` : `${free} free${channel === "iterations" || channel.startsWith("resource:") ? "" : " right now"}`;
459
- if (channel === "iterations" || channel.startsWith("resource:")) return `${channel} has ${room} (${asked}); budget.${field} at most ${most} fits`;
460
- return `${channel} has ${room} (${asked}); your own turns draw ${channel} from this same pool before a retry is admitted, so ask for well under ${most}`;
441
+ function nextAnalystRunOrdinal(analystAssignments) {
442
+ let analystRunOrdinal = 0;
443
+ for (const assignment of analystAssignments.values()) {
444
+ const ordinal = Number(/:o(\d+)$/.exec(assignment.assignmentId)?.[1]);
445
+ if (!Number.isSafeInteger(ordinal) || ordinal < 0 || ordinal === Number.MAX_SAFE_INTEGER) throw new Error(`coordination: invalid analyst assignment '${assignment.assignmentId}'`);
446
+ analystRunOrdinal = Math.max(analystRunOrdinal, ordinal + 1);
447
+ }
448
+ return analystRunOrdinal;
461
449
  }
462
- /**
463
- * The reason text `spawn_worker` returns for a refused spawn. Every rejection kind names its own
464
- * cause: a live-worker cap, a depth limit, or a key collision is not an empty budget, and telling a
465
- * driver "no allocation left" for those sends it after the wrong fix. A `budget-exhausted` refusal
466
- * names every channel that did not fit and the amounts, so the driver can size its next request.
467
- */
468
- function spawnRefusalReason(reason, shortfalls, pinned) {
469
- switch (reason) {
470
- case "usd-unbudgeted": return pinned.usdUnbudgeted;
471
- case "in-doubt": return pinned.inDoubt;
472
- case "scope-settled": return pinned.scopeSettled;
473
- case "scope-aborted": return "this run stopped admitting work (it was cancelled, passed its deadline, or too many children went down); no further worker can start";
474
- case "depth-exceeded": return "this spawn would exceed the run's maxDepth; a worker at the deepest level cannot start children of its own";
475
- case "duplicate-key": return "a worker under this key is still live; wait for it to settle, or use a different key for different work";
476
- case "key-conflict": return "this key is already recorded for a different profile or task in this run's journal; use a new key for different work";
477
- case "invalid-identity": return "a keyed spawn needs a complete execution identity to journal, and this profile and task did not produce one; spawn again without a key";
478
- case "budget-exhausted":
479
- if (shortfalls === void 0 || shortfalls.length === 0) return "the conserved pool refused this spawn (budget-exhausted): the run's remaining budget cannot cover this worker's budget";
480
- if (shortfalls.some((shortfall) => shortfall.closedByUnknownSpend === true)) return `the run pool refused this spawn: ${shortfallClause(shortfalls.find((shortfall) => shortfall.closedByUnknownSpend === true))}; the caller must re-run with a measurable or larger root budget`;
481
- return `the run pool refused this spawn: ${shortfalls.map(shortfallClause).join("; ")}; or ask the caller for a larger root budget`;
450
+ /** Re-attach every analyst node a prior process journaled to its durable assignment. */
451
+ function recoverAnalystRuns(opts, analystAssignments, analystRuns) {
452
+ for (const node of [...opts.scope.resume?.view.nodes ?? [], ...opts.scope.view.nodes]) {
453
+ if (node.parent !== opts.scope.view.root || !node.assignmentId?.startsWith("analyst:")) continue;
454
+ const assignment = analystAssignments.get(node.assignmentId);
455
+ if (!assignment) throw new Error(`coordination: analyst assignment '${node.assignmentId}' has no durable source record; refusing to treat its review as a worker result`);
456
+ if (node.identity && (node.identity.profileDigest !== assignment.profileDigest || node.identity.taskDigest !== assignment.taskDigest)) throw new Error(`coordination: analyst assignment '${node.assignmentId}' conflicts with its journaled execution identity`);
457
+ analystRuns.set(node.id, {
458
+ route: {
459
+ kind: assignment.kind,
460
+ ...assignment.to === void 0 ? {} : { to: assignment.to }
461
+ },
462
+ sourceWorker: assignment.sourceWorker,
463
+ assignmentId: assignment.assignmentId
464
+ });
482
465
  }
483
466
  }
484
- const BUDGET_FIELD = {
485
- tokens: "maxTokens",
486
- iterations: "maxIterations",
487
- usd: "maxUsd"
488
- };
489
- // src/runtime/supervise/driver-control-acknowledgers.ts
490
- const SPAWN_JOURNAL_FILE = "spawn-journal.jsonl";
491
- function appendedLines(tail) {
492
- let size;
467
+ const analystRunFinding = (run, settled) => detachedFrozen({
468
+ type: "finding",
469
+ finding: canonicalFindingEvent({
470
+ fromWorker: run.sourceWorker,
471
+ analyst: run.route.kind,
472
+ analystWorkerId: settled.handle.id,
473
+ assignmentId: run.assignmentId,
474
+ findings: settled.kind === "done" ? settled.out : { analystRunFailed: settled.reason }
475
+ })
476
+ });
477
+ /** The settled worker's persisted tool-trace spans; degraded evidence reads as empty, never a throw. */
478
+ async function readTraceSpans(opts, worker) {
479
+ if (worker.trace.status !== "available") return {
480
+ spansText: "",
481
+ spanCount: 0
482
+ };
493
483
  try {
494
- size = statSync(tail.file).size;
484
+ const raw = await opts.blobs.get(worker.trace.traceRef);
485
+ const artifact = parseWorkerToolTraceArtifact(raw, worker.trace.traceRef);
486
+ return {
487
+ spansText: safeJsonText(artifact.spans),
488
+ spanCount: artifact.spans.length
489
+ };
495
490
  } catch {
496
- return;
497
- }
498
- if (size < tail.offset) {
499
- tail.offset = 0;
500
- tail.partial = "";
501
- tail.at.clear();
502
- }
503
- if (size === tail.offset) return void 0;
504
- const buf = Buffer.allocUnsafe(size - tail.offset);
505
- const fd = openSync(tail.file, "r");
506
- try {
507
- const got = readSync(fd, buf, 0, buf.length, tail.offset);
508
- tail.offset += got;
509
- const text = tail.partial + buf.subarray(0, got).toString("utf8");
510
- const parts = text.split("\n");
511
- tail.partial = text.endsWith("\n") ? "" : parts.pop() ?? "";
512
- if (text.endsWith("\n")) parts.pop();
513
- return parts;
514
- } finally {
515
- closeSync(fd);
491
+ return {
492
+ spansText: "",
493
+ spanCount: 0
494
+ };
516
495
  }
517
496
  }
518
- function indexDeaths(tail) {
519
- const lines = appendedLines(tail);
520
- if (lines === void 0) return false;
521
- let grew = false;
522
- for (const line of lines) {
523
- const trimmed = line.trim();
524
- if (!trimmed) continue;
525
- try {
526
- for (const event of spawnJournalRecordEvents(JSON.parse(trimmed))) {
527
- if (event === void 0) continue;
528
- if (!(event.kind === "settled" && event.status === "down" || event.kind === "cancelled") || typeof event.id !== "string" || typeof event.at !== "string") continue;
529
- const prev = tail.at.get(event.id);
530
- if (prev !== void 0 && prev >= event.at) continue;
531
- tail.at.set(event.id, event.at);
532
- grew = true;
533
- }
534
- } catch {}
497
+ async function readSourceOutput(opts, worker) {
498
+ let output = null;
499
+ let outputError;
500
+ if (worker.outRef !== void 0) try {
501
+ output = await opts.blobs.get(worker.outRef);
502
+ } catch (error) {
503
+ outputError = error instanceof Error ? error.message : String(error);
535
504
  }
536
- return grew;
505
+ if (worker.outRef !== void 0 && output === void 0 && outputError === void 0) outputError = "referenced output blob unavailable";
506
+ return {
507
+ output,
508
+ outputError
509
+ };
537
510
  }
538
- function descendantsSince(tail, nodeId, sinceIso) {
539
- indexDeaths(tail);
540
- const prefix = `${nodeId}:`;
541
- const ids = [...tail.at.keys()].filter((id) => id.startsWith(prefix) && (tail.at.get(id) ?? "") >= sinceIso);
542
- ids.sort();
543
- return ids;
544
- }
545
- /** Unknown ack lands before delivery. A crash can lose the steer; a restart must not deliver it twice. */
546
- function createSteerAcknowledger(deps) {
547
- const iso = () => new Date(deps.now()).toISOString();
548
- const awaiting = /* @__PURE__ */ new Map();
549
- const named = /* @__PURE__ */ new Map();
550
- const paused = () => {
551
- const pause = deps.rootPause?.();
552
- if (pause === void 0) return { why: "" };
553
- const left = pause.tokensLeft === void 0 ? "" : ` with ${pause.tokensLeft} tokens left`;
554
- return {
555
- pausedOn: pause,
556
- why: `; the root is paused on ${pause.stop}${left}`
557
- };
558
- };
559
- const queuedRoot = (request) => {
560
- const { pausedOn, why } = paused();
561
- const key = pausedOn?.stop ?? "";
562
- if (named.get(request.operationId) === key) return;
563
- named.set(request.operationId, key);
564
- writeWorkerSteerAcknowledgement(deps.dir, {
565
- ...base(request),
566
- effect: "unknown",
567
- observedAt: iso(),
568
- detail: `queued in the root inbox; no root turn has consumed it yet${why}`,
569
- ...pausedOn === void 0 ? {} : { pausedOn }
570
- });
571
- };
572
- const answerRoot = (request, receipt) => {
573
- if (!awaiting.delete(request.operationId)) return;
574
- named.delete(request.operationId);
575
- const { pausedOn, why } = receipt.status === "consumed" ? { why: "" } : paused();
576
- writeWorkerSteerAcknowledgement(deps.dir, {
577
- ...base(request),
578
- ...receipt.status === "consumed" ? {
579
- effect: "delivered",
580
- detail: `the root consumed the steer in ${receipt.attemptId}`
581
- } : {
582
- effect: "not_live",
583
- detail: `the root did not consume the steer: ${receipt.reason}${why}`
584
- },
585
- observedAt: iso(),
586
- ...pausedOn === void 0 ? {} : { pausedOn }
587
- });
588
- };
589
- const base = (request) => ({
590
- schemaVersion: 1,
591
- operationId: request.operationId,
592
- requestDigest: request.requestDigest,
593
- worker: request.worker,
594
- requestedAt: request.at
595
- });
596
- let steerStamp = "";
597
- let steerIdle = false;
598
- const steerChanged = (phase) => {
599
- let stamp = "missing";
600
- try {
601
- const st = statSync(workerSteerRequestsDir(deps.dir), { bigint: true });
602
- stamp = `${st.dev}:${st.ino}:${st.mtimeNs}:${st.size}`;
603
- } catch {
604
- stamp = "missing";
605
- }
606
- const changed = stamp !== steerStamp;
607
- if (changed && phase !== "boundary") steerStamp = stamp;
608
- return changed;
609
- };
610
- return { async pass(phase) {
611
- if (phase === "turn") for (const request of awaiting.values()) queuedRoot(request);
612
- const changed = steerChanged(phase);
613
- if (phase !== "final" && !changed && steerIdle) return;
614
- for (const request of readWorkerSteerRequests(deps.dir)) {
615
- if (phase !== "final" && deps.signal?.aborted) {
616
- steerIdle = false;
617
- return;
618
- }
619
- const rootRequest = request.worker === deps.ownerId && deps.deliverRoot !== void 0;
620
- if (phase === "boundary" && !rootRequest) continue;
621
- if (!rootRequest && !isDirectChildNodeId(deps, request.worker)) continue;
622
- const queued = awaiting.get(request.operationId);
623
- if (phase === "final" && queued !== void 0) {
624
- answerRoot(queued, {
625
- status: "failed",
626
- messageId: request.operationId,
627
- cause: "closed",
628
- reason: "the run ended before a root turn read it"
629
- });
630
- continue;
631
- }
632
- if (readWorkerSteerAcknowledgement(deps.dir, request.operationId) !== void 0) continue;
633
- if (phase === "final") {
634
- writeWorkerSteerAcknowledgement(deps.dir, {
635
- ...base(request),
636
- effect: "not_live",
637
- observedAt: iso(),
638
- detail: "run ended before the steer was applied"
639
- });
640
- continue;
641
- }
642
- if (!claimWorkerSteerDelivery(deps.dir, {
643
- ...base(request),
644
- effect: "unknown",
645
- observedAt: iso(),
646
- detail: "delivery admitted; outcome not yet known"
647
- })) continue;
648
- try {
649
- let outcome;
650
- if (rootRequest) {
651
- awaiting.set(request.operationId, request);
652
- const delivered = deps.deliverRoot({
653
- steer: request.message,
654
- interrupt: request.interrupt,
655
- messageId: request.operationId,
656
- receipt: (receipt) => answerRoot(request, receipt)
657
- });
658
- if (!delivered) awaiting.delete(request.operationId);
659
- outcome = {
660
- delivered,
661
- outcome: delivered ? "delivered" : "runtime-has-no-inbox"
662
- };
663
- } else outcome = await deps.coord.steerWorker(request.worker, request.message, { interrupt: request.interrupt });
664
- if (rootRequest && outcome.delivered) {
665
- if (awaiting.has(request.operationId)) queuedRoot(request);
666
- continue;
667
- }
668
- const effect = outcome.delivered ? "delivered" : outcome.outcome === "runtime-has-no-inbox" ? "unsupported" : outcome.outcome === "unknown-worker" || outcome.outcome === "already-settled" || outcome.outcome === "scope-stopped" ? "not_live" : "unknown";
669
- writeWorkerSteerAcknowledgement(deps.dir, {
670
- ...base(request),
671
- effect,
672
- observedAt: iso(),
673
- detail: rootRequest ? "the root exposes no accepting inbox at delivery time" : steerAcknowledgementDetail(outcome)
674
- });
675
- } catch (error) {
676
- awaiting.delete(request.operationId);
677
- writeWorkerSteerAcknowledgement(deps.dir, {
678
- ...base(request),
679
- effect: "unknown",
680
- observedAt: iso(),
681
- detail: "delivery outcome is unknown after a runtime error"
682
- });
683
- }
684
- }
685
- if (phase === "turn") steerIdle = true;
686
- } };
687
- }
688
- function steerAcknowledgementDetail(outcome) {
689
- switch (outcome.outcome) {
690
- case "delivered": return "the owning manager delivered the steer to the exact live worker";
691
- case "runtime-has-no-inbox": return "the exact worker does not expose a steer inbox";
692
- case "unknown-worker": return "the owning manager does not know the exact worker";
693
- case "already-settled": return "the exact worker settled before delivery";
694
- case "scope-stopped": return "the owning manager stopped before delivery";
695
- case "runtime-error": return "delivery outcome is unknown after a runtime error";
696
- }
697
- }
698
- function createCancelAcknowledger(deps) {
699
- const tracked = /* @__PURE__ */ new Map();
700
- let runTracked;
701
- const abortIssuedAt = /* @__PURE__ */ new Map();
702
- const iso = () => new Date(deps.now()).toISOString();
703
- const waiting = /* @__PURE__ */ new Map();
704
- const reconciling = /* @__PURE__ */ new Map();
705
- const regrowing = /* @__PURE__ */ new Set();
706
- let inboxBytes;
707
- const deaths = {
708
- file: join(deps.dir, SPAWN_JOURNAL_FILE),
709
- offset: 0,
710
- partial: "",
711
- at: /* @__PURE__ */ new Map()
712
- };
713
- const watch = (record) => {
714
- if (record.effect === "cancel_requested") reconciling.set(record.operationId, record);
715
- else reconciling.delete(record.operationId);
716
- if (record.effect === "cancelled" && abortIssuedAt.has(record.operationId)) regrowing.add(record.operationId);
717
- else regrowing.delete(record.operationId);
718
- };
719
- const write = (record) => {
720
- writeWorkerCancellation(deps.dir, record);
721
- tracked.set(record.operationId, record);
722
- watch(record);
723
- };
724
- const owned = (ref) => {
725
- if (isDirectChildNodeId(deps, ref)) return true;
726
- if (deps.controlScope !== "run") return false;
727
- return !ref.startsWith(`${deps.ownerId}:`) && ref !== deps.ownerId;
728
- };
729
- const deliveredTerminal = (id) => {
730
- const row = deps.coord.settled().find((w) => w.id === id);
731
- if (row !== void 0) return row.status;
732
- const node = deps.scope.view.nodes.find((n) => n.id === id);
733
- if (node === void 0) return void 0;
734
- if (node.status === "done") return "done";
735
- if (node.status === "failed" || node.status === "cancelled") return "down";
736
- };
737
- const apply = (request) => {
738
- const aborted = deps.coord.abortWorker(request.worker, request.reason ?? "cancel requested");
739
- const base = {
740
- operationId: request.operationId,
741
- worker: request.worker,
742
- requestedAt: request.at,
743
- observedAt: iso(),
744
- ...request.reason === void 0 ? {} : { reason: request.reason }
745
- };
746
- if (aborted !== void 0) {
747
- abortIssuedAt.set(request.operationId, base.observedAt);
748
- write({
749
- ...base,
750
- effect: "cancel_requested",
751
- workerId: aborted.id,
752
- detail: `abort issued to live worker '${aborted.label}' (${aborted.id}); termination not yet proven`,
753
- terminated: []
754
- });
755
- return;
756
- }
757
- const goneId = deps.scope.view.nodes.find((n) => (n.id === request.worker || n.label === request.worker) && isTerminalNodeStatus(n.status))?.id ?? deps.coord.settled().find((w) => w.id === request.worker)?.id;
758
- if (goneId !== void 0) write({
759
- ...base,
760
- effect: "not_live",
761
- workerId: goneId,
762
- detail: `worker '${goneId}' had already settled before this operation was applied`,
763
- terminated: []
764
- });
765
- };
766
- /** Grows only: the worker, the record's ids, and subtree deaths at or after the abort. */
767
- const provenTerminated = (record, workerId) => {
768
- const since = abortIssuedAt.get(record.operationId) ?? record.observedAt;
769
- return [.../* @__PURE__ */ new Set([
770
- ...record.terminated,
771
- workerId,
772
- ...descendantsSince(deaths, workerId, since)
773
- ])].sort();
774
- };
775
- const reconcile = (record) => {
776
- const workerId = record.workerId;
777
- if (workerId === void 0) return;
778
- const terminal = deliveredTerminal(workerId);
779
- if (terminal === void 0) return;
780
- if (terminal === "down") {
781
- write({
782
- ...record,
783
- effect: "cancelled",
784
- observedAt: iso(),
785
- terminated: provenTerminated(record, workerId),
786
- detail: `worker '${workerId}' reached a terminal down state on the settle path`
787
- });
788
- return;
789
- }
790
- write({
791
- ...record,
792
- effect: "not_live",
793
- observedAt: iso(),
794
- terminated: [],
795
- detail: `worker '${workerId}' settled done despite the abort request; nothing was terminated`
796
- });
797
- };
798
- const regrow = (record) => {
799
- const workerId = record.workerId;
800
- if (workerId === void 0 || !abortIssuedAt.has(record.operationId)) return;
801
- const terminated = provenTerminated(record, workerId);
802
- if (terminated.length > record.terminated.length) write({
803
- ...record,
804
- observedAt: iso(),
805
- terminated
806
- });
807
- };
808
- const passRun = () => {
809
- if (deps.controlScope !== "run" || deps.abortRun === void 0) return;
810
- if (runTracked !== void 0) return;
811
- runTracked = applyRunCancellation(deps.dir, deps.abortRun, iso);
812
- };
813
- const ingest = () => {
814
- const file = workerCancelRequestsFile(deps.dir);
815
- let size;
816
- try {
817
- size = statSync(file).size;
818
- } catch {
819
- size = null;
820
- }
821
- if (size === inboxBytes) return;
822
- inboxBytes = size;
823
- for (const request of readWorkerCancelRequests(deps.dir)) {
824
- if (!owned(request.worker) || tracked.has(request.operationId) || waiting.has(request.operationId)) continue;
825
- const record = readWorkerCancellation(deps.dir, request.operationId);
826
- if (record === void 0) waiting.set(request.operationId, request);
827
- else {
828
- tracked.set(record.operationId, record);
829
- watch(record);
830
- }
831
- }
832
- };
833
- const pass = (phase) => {
834
- if (phase === "turn") passRun();
835
- ingest();
836
- const pending = [...reconciling.values()];
837
- if (phase === "turn") for (const request of [...waiting.values()]) {
838
- waiting.delete(request.operationId);
839
- apply(request);
840
- if (!tracked.has(request.operationId)) waiting.set(request.operationId, request);
841
- }
842
- const grew = indexDeaths(deaths);
843
- for (const record of pending) {
844
- const current = tracked.get(record.operationId);
845
- if (current?.effect === "cancel_requested") reconcile(current);
846
- }
847
- if (!grew) return;
848
- for (const id of [...regrowing]) {
849
- const record = tracked.get(id);
850
- if (record !== void 0) regrow(record);
851
- }
852
- };
853
- return {
854
- pass,
855
- finish() {
856
- const runRequest = deps.controlScope === "run" && deps.abortRun !== void 0 ? readRunCancelRequest(deps.dir) : void 0;
857
- if (runRequest !== void 0 && readRunCancellation(deps.dir, runRequest.operationId) === void 0) writeRunCancellation(deps.dir, {
858
- operationId: runRequest.operationId,
859
- effect: "not_live",
860
- requestedAt: runRequest.at,
861
- observedAt: iso(),
862
- ...runRequest.reason === void 0 ? {} : { reason: runRequest.reason },
863
- ...runRequest.operator === void 0 ? {} : { operator: runRequest.operator },
864
- detail: "run ended before the request was applied"
865
- });
866
- for (const request of readWorkerCancelRequests(deps.dir)) {
867
- if (!owned(request.worker)) continue;
868
- const record = tracked.get(request.operationId) ?? readWorkerCancellation(deps.dir, request.operationId);
869
- if (record === void 0) {
870
- write({
871
- operationId: request.operationId,
872
- worker: request.worker,
873
- effect: "not_live",
874
- requestedAt: request.at,
875
- observedAt: iso(),
876
- ...request.reason === void 0 ? {} : { reason: request.reason },
877
- detail: "run ended before the request was applied",
878
- terminated: []
879
- });
880
- continue;
881
- }
882
- if (record.effect === "cancel_requested") write({
883
- ...record,
884
- effect: "unknown",
885
- observedAt: iso(),
886
- detail: "abort issued; run ended before termination was observed"
887
- });
888
- }
889
- }
890
- };
891
- }
892
- function isDirectChildNodeId(owner, ref) {
893
- return ref.startsWith(`${owner.ownerId}:s`) && /^s\d+$/.test(ref.slice(owner.ownerId.length + 1));
894
- }
895
- // src/runtime/supervise/event-bus.ts
896
- /** Create the child→parent coordination bus: one typed pipe for settled outputs, questions, and analyst findings, with a priority-ordered pull queue and a pass-through subscribe lane.
897
- * @experimental In-process queue; durability is a transport swap that does not exist yet. */
898
- function createEventBus(now = Date.now) {
899
- const queue = [];
900
- const log = [];
901
- const subscribers = [];
902
- const queuedHandlers = [];
903
- const byKind = {};
904
- const staged = /* @__PURE__ */ new WeakMap();
905
- let seq = 0;
906
- let published = 0;
907
- let pulled = 0;
908
- const matches = (r, kinds) => !kinds || kinds.includes(r.event.type);
909
- const bestIndex = (kinds) => {
910
- let best = -1;
911
- let bestPriority = Number.NEGATIVE_INFINITY;
912
- for (let i = 0; i < queue.length; i++) {
913
- const r = queue[i];
914
- if (!r || !matches(r, kinds)) continue;
915
- if (r.priority > bestPriority) {
916
- best = i;
917
- bestPriority = r.priority;
918
- }
919
- }
920
- return best;
921
- };
922
- const pullAt = (i) => {
923
- if (i < 0) return void 0;
924
- pulled++;
925
- return queue.splice(i, 1)[0];
926
- };
927
- const pullRecord = (kinds) => pullAt(bestIndex(kinds));
928
- return {
929
- async publish(event, opts) {
930
- const record = staged.get(event) ?? {
931
- seq: seq++,
932
- at: now(),
933
- priority: opts?.priority ?? 0,
934
- event
935
- };
936
- staged.set(event, record);
937
- for (const handler of subscribers) await handler(record);
938
- staged.delete(event);
939
- if (opts?.queue !== false) queue.push(record);
940
- log.push(record);
941
- published += 1;
942
- byKind[event.type] = (byKind[event.type] ?? 0) + 1;
943
- if (opts?.queue !== false) for (const handler of [...queuedHandlers]) handler(record);
944
- return record;
945
- },
946
- pull: (kinds) => pullRecord(kinds)?.event,
947
- pullRecord,
948
- take: (seq) => pullAt(queue.findIndex((r) => r.seq === seq)),
949
- queued(kinds) {
950
- return queue.filter((r) => matches(r, kinds));
951
- },
952
- subscribe(handler) {
953
- subscribers.push(handler);
954
- return () => {
955
- const i = subscribers.indexOf(handler);
956
- if (i >= 0) subscribers.splice(i, 1);
957
- };
958
- },
959
- onQueued(handler) {
960
- queuedHandlers.push(handler);
961
- return () => {
962
- const i = queuedHandlers.indexOf(handler);
963
- if (i >= 0) queuedHandlers.splice(i, 1);
964
- };
965
- },
966
- pending(kinds) {
967
- return kinds ? queue.filter((r) => matches(r, kinds)).length : queue.length;
968
- },
969
- history() {
970
- return log;
971
- },
972
- stats() {
973
- return {
974
- published,
975
- pulled,
976
- byKind: { ...byKind }
977
- };
978
- }
979
- };
980
- }
981
- // src/mcp/tools/coordination-analysis.ts
982
- function createCoordinationAnalysis(deps) {
983
- const { opts } = deps;
984
- const analysisRoutes = (opts.analyzeOnSettle ?? []).map(normalizeAnalyzeOnSettle);
985
- const analystAssignments = loadAnalystAssignments(opts);
986
- const analystRuns = /* @__PURE__ */ new Map();
987
- const state = {
988
- ...deps,
989
- analysisRoutes,
990
- analystAssignments,
991
- analystRuns,
992
- flushedAnalystRuns: /* @__PURE__ */ new Set(),
993
- definedAnalysts: [...opts.priorAnalystDefinitions ?? []],
994
- maxDefinedAnalysts: opts.maxDefinedAnalysts ?? ANALYST_DEFINITION_BOUNDS.maxDefinitionsPerManager,
995
- analystRunOrdinal: nextAnalystRunOrdinal(analystAssignments),
996
- finishing: false,
997
- managerAnalysis: void 0
998
- };
999
- recoverAnalystRuns(opts, analystAssignments, analystRuns);
1000
- return {
1001
- analysisRoutes: state.analysisRoutes,
1002
- analystRuns,
1003
- flushedAnalystRuns: state.flushedAnalystRuns,
1004
- analystRunFinding,
1005
- spawnAnalystRun: spawnAnalystRun.bind(null, state),
1006
- deliverRoutedFinding: deliverRoutedFinding.bind(null, state),
1007
- analystRunContext: analystRunContext.bind(null, opts),
1008
- finishAnalysis: finishAnalysis.bind(null, state),
1009
- definedAnalysts: state.definedAnalysts,
1010
- analystMenu: analystMenu.bind(null, state),
1011
- defineAnalyst: defineAnalyst.bind(null, state),
1012
- isFinishing: () => state.finishing
1013
- };
1014
- }
1015
- /** The durable analyst assignments of a prior process, refusing two that disagree on one id. */
1016
- function loadAnalystAssignments(opts) {
1017
- const analystAssignments = /* @__PURE__ */ new Map();
1018
- for (const record of opts.priorJournal ?? []) {
1019
- if (record.event.type !== "analyst-assignment") continue;
1020
- const assignment = record.event.assignment;
1021
- const prior = analystAssignments.get(assignment.assignmentId);
1022
- if (prior && canonicalCandidateDigest(prior) !== canonicalCandidateDigest(assignment)) throw new Error(`coordination: conflicting analyst assignment '${assignment.assignmentId}'`);
1023
- analystAssignments.set(assignment.assignmentId, detachedFrozen(assignment));
1024
- }
1025
- return analystAssignments;
1026
- }
1027
- function nextAnalystRunOrdinal(analystAssignments) {
1028
- let analystRunOrdinal = 0;
1029
- for (const assignment of analystAssignments.values()) {
1030
- const ordinal = Number(/:o(\d+)$/.exec(assignment.assignmentId)?.[1]);
1031
- if (!Number.isSafeInteger(ordinal) || ordinal < 0 || ordinal === Number.MAX_SAFE_INTEGER) throw new Error(`coordination: invalid analyst assignment '${assignment.assignmentId}'`);
1032
- analystRunOrdinal = Math.max(analystRunOrdinal, ordinal + 1);
1033
- }
1034
- return analystRunOrdinal;
1035
- }
1036
- /** Re-attach every analyst node a prior process journaled to its durable assignment. */
1037
- function recoverAnalystRuns(opts, analystAssignments, analystRuns) {
1038
- for (const node of [...opts.scope.resume?.view.nodes ?? [], ...opts.scope.view.nodes]) {
1039
- if (node.parent !== opts.scope.view.root || !node.assignmentId?.startsWith("analyst:")) continue;
1040
- const assignment = analystAssignments.get(node.assignmentId);
1041
- if (!assignment) throw new Error(`coordination: analyst assignment '${node.assignmentId}' has no durable source record; refusing to treat its review as a worker result`);
1042
- if (node.identity && (node.identity.profileDigest !== assignment.profileDigest || node.identity.taskDigest !== assignment.taskDigest)) throw new Error(`coordination: analyst assignment '${node.assignmentId}' conflicts with its journaled execution identity`);
1043
- analystRuns.set(node.id, {
1044
- route: {
1045
- kind: assignment.kind,
1046
- ...assignment.to === void 0 ? {} : { to: assignment.to }
1047
- },
1048
- sourceWorker: assignment.sourceWorker,
1049
- assignmentId: assignment.assignmentId
1050
- });
1051
- }
1052
- }
1053
- const analystRunFinding = (run, settled) => detachedFrozen({
1054
- type: "finding",
1055
- finding: canonicalFindingEvent({
1056
- fromWorker: run.sourceWorker,
1057
- analyst: run.route.kind,
1058
- analystWorkerId: settled.handle.id,
1059
- assignmentId: run.assignmentId,
1060
- findings: settled.kind === "done" ? settled.out : { analystRunFailed: settled.reason }
1061
- })
1062
- });
1063
- /** The settled worker's persisted tool-trace spans; degraded evidence reads as empty, never a throw. */
1064
- async function readTraceSpans(opts, worker) {
1065
- if (worker.trace.status !== "available") return {
1066
- spansText: "",
1067
- spanCount: 0
1068
- };
1069
- try {
1070
- const raw = await opts.blobs.get(worker.trace.traceRef);
1071
- const artifact = parseWorkerToolTraceArtifact(raw, worker.trace.traceRef);
1072
- return {
1073
- spansText: safeJsonText(artifact.spans),
1074
- spanCount: artifact.spans.length
1075
- };
1076
- } catch {
1077
- return {
1078
- spansText: "",
1079
- spanCount: 0
1080
- };
1081
- }
1082
- }
1083
- async function readSourceOutput(opts, worker) {
1084
- let output = null;
1085
- let outputError;
1086
- if (worker.outRef !== void 0) try {
1087
- output = await opts.blobs.get(worker.outRef);
1088
- } catch (error) {
1089
- outputError = error instanceof Error ? error.message : String(error);
1090
- }
1091
- if (worker.outRef !== void 0 && output === void 0 && outputError === void 0) outputError = "referenced output blob unavailable";
1092
- return {
1093
- output,
1094
- outputError
1095
- };
1096
- }
1097
- /** The complete source envelope an analyst reads: the worker, its output, and a manager-end checkpoint. */
1098
- function sourceEvidenceEnvelope({ opts, ledger }, route, worker, output, outputError) {
1099
- return JSON.parse(safeJsonText({
1100
- worker,
1101
- output: output ?? null,
1102
- ...outputError ? { outputError } : {},
1103
- ...route.at === "manager-end" ? { managerCheckpoint: {
1104
- managerId: opts.scope.view.root,
1105
- nodes: opts.scope.view.nodes.filter((node) => !node.assignmentId?.startsWith("analyst:")).map((node) => ({
1106
- id: node.id,
1107
- parent: node.parent,
1108
- assignmentId: node.assignmentId,
1109
- status: node.status
1110
- })),
1111
- settled: ledger.map(({ resumed: _resumed, ...row }) => row)
1112
- } } : {}
1113
- }));
511
+ /** The complete source envelope an analyst reads: the worker, its output, and a manager-end checkpoint. */
512
+ function sourceEvidenceEnvelope({ opts, ledger }, route, worker, output, outputError) {
513
+ return JSON.parse(safeJsonText({
514
+ worker,
515
+ output: output ?? null,
516
+ ...outputError ? { outputError } : {},
517
+ ...route.at === "manager-end" ? { managerCheckpoint: {
518
+ managerId: opts.scope.view.root,
519
+ nodes: opts.scope.view.nodes.filter((node) => !node.assignmentId?.startsWith("analyst:")).map((node) => ({
520
+ id: node.id,
521
+ parent: node.parent,
522
+ assignmentId: node.assignmentId,
523
+ status: node.status
524
+ })),
525
+ settled: ledger.map(({ resumed: _resumed, ...row }) => row)
526
+ } } : {}
527
+ }));
1114
528
  }
1115
529
  const excerpt = (text, limit) => ({
1116
530
  text: text.slice(0, limit),
@@ -1560,6 +974,82 @@ function mountAnalystsTools({ opts, tools, ledger, nodeForWorker, analystMenu, a
1560
974
  });
1561
975
  }
1562
976
  }
977
+ // src/mcp/tools/coordination-events.ts
978
+ /** Default and maximum bounds for one {@link CoordinationTools} journal read. The defaults are
979
+ * sized for a driver turn (a page a model can read and still have room to act on); the maxima
980
+ * bound what a single tool result may cost even when the caller asks for everything. */
981
+ const JOURNAL_READ_BOUNDS = Object.freeze({
982
+ defaultLimit: 50,
983
+ maxLimit: 500,
984
+ defaultMaxBytes: 16384,
985
+ maxMaxBytes: 262144
986
+ });
987
+ /** Every `CoordinationEvent` kind `read_journal` can return — the tool advertises this list in its
988
+ * JSON Schema AND filters on it, so the schema cannot promise a kind the filter drops. */
989
+ const journalEventKinds = [
990
+ "question",
991
+ "settled",
992
+ "finding",
993
+ "submission",
994
+ "steer",
995
+ "answer",
996
+ "instruction",
997
+ "delivery-attempt",
998
+ "mail",
999
+ "escalation",
1000
+ "analyst-defined",
1001
+ "analyst-assignment",
1002
+ "acknowledgement",
1003
+ "tool-outcome",
1004
+ "tool-timing",
1005
+ "lead-message",
1006
+ "map",
1007
+ "route"
1008
+ ];
1009
+ /** The reserved coordination verb names — the complete set `createCoordinationTools` can emit
1010
+ * (the analyst pair is conditional but still reserved). A driver's extra WORK tools must not
1011
+ * collide with any of these, or it could no longer coordinate; callers validate eagerly against
1012
+ * this set so the conflict fails loud at construction, not buried in a swallowed `act()` throw.
1013
+ *
1014
+ * Every name here must also stay clear of the tools a coding harness publishes NATIVELY
1015
+ * (`harnessNativeToolNames`, `mcp/harness-native-tools`). A harness prefixes an MCP tool with its
1016
+ * server name, so the two never collide on the wire — but a driver reads a BARE word out of a
1017
+ * prompt, and a bare word that the harness also publishes resolves to the harness's own tool.
1018
+ * The spawn verb is `spawn_worker` for that reason: the runtime's vocabulary for the spawned
1019
+ * thing is a worker (`workerId`, `workerSlots`, the per-worker budget), and no known harness
1020
+ * publishes that name. `tests/kernel/harness-native-tools.test.ts` holds the set clear. */
1021
+ const coordinationVerbNames = [
1022
+ "spawn_worker",
1023
+ "cancel_worker",
1024
+ "observe_agent",
1025
+ "steer_agent",
1026
+ "list_questions",
1027
+ "answer_question",
1028
+ "ask_parent",
1029
+ "submit_result",
1030
+ "stop",
1031
+ "report_blocked",
1032
+ "read_continuation",
1033
+ "read_journal",
1034
+ "list_analysts",
1035
+ "run_analyst",
1036
+ "define_analyst",
1037
+ "run_graph"
1038
+ ];
1039
+ /**
1040
+ * The `CoordinationEvent` kinds that wake a waiting manager. The queue carries the UP-leg only:
1041
+ * `steer` / `answer` / `instruction` / `delivery-attempt` are recorded `queue: false` (history and
1042
+ * subscribers, never delivered back), and `mail` is delivered to its addressee's inbox. A
1043
+ * `question` on this bus is the manager's own `ask_parent`, already escalated: it never wakes the
1044
+ * asker, whose answer arrives as a `lead-message`.
1045
+ */
1046
+ const wakeEventKinds = [
1047
+ "settled",
1048
+ "finding",
1049
+ "tool-outcome",
1050
+ "lead-message",
1051
+ "map"
1052
+ ];
1563
1053
  // src/mcp/tools/coordination-tool-timeout.ts
1564
1054
  async function runWithin(work, ms, message) {
1565
1055
  let timer;
@@ -1849,6 +1339,110 @@ function createDownMessages({ opts, bus, lifetime }) {
1849
1339
  steerWorker
1850
1340
  };
1851
1341
  }
1342
+ // src/mcp/tools/coordination-budget.ts
1343
+ /** Each channel spent beyond its budget, as spent of budget: `tokens 235,857 of 42,000` or
1344
+ * `deadline 3,857 s of 2,400 s`. */
1345
+ function budgetOverspendText(violation) {
1346
+ const count = (value) => value.toLocaleString("en-US");
1347
+ return violation.overspent.map((entry) => entry.channel === "deadline" ? `deadline ${count(Math.round(entry.spent / 1e3))} s of ${count(Math.round(entry.reserved / 1e3))} s` : `${entry.channel} ${count(entry.spent)} of ${count(entry.reserved)}`).join("; ");
1348
+ }
1349
+ /** What a manager can do with a keyed worker its budget stopped. */
1350
+ const BUDGET_STOP_NEXT = "spawn_worker with the same key and a larger budget continues this session where it stopped; cancel_worker releases it";
1351
+ /** Every cause at zero — a pre-flight publishes its whole ledger from the first read. */
1352
+ function emptyPreflightCounts() {
1353
+ return {
1354
+ "model-route": 0,
1355
+ "bridge-full": 0,
1356
+ "unmountable-tool": 0,
1357
+ "unprovisionable-profile": 0
1358
+ };
1359
+ }
1360
+ /** The optional per-spawn budget `spawn_worker` and `run_graph` take. */
1361
+ const spawnBudgetArg = {
1362
+ type: "object",
1363
+ description: "Optional per-spawn budget that merges over the per-worker default (per field). Only set the ceilings this sub-task needs raised; the conserved pool still fences.",
1364
+ properties: {
1365
+ maxIterations: {
1366
+ type: "number",
1367
+ minimum: 0
1368
+ },
1369
+ maxTokens: {
1370
+ type: "number",
1371
+ minimum: 0
1372
+ },
1373
+ maxUsd: {
1374
+ type: "number",
1375
+ minimum: 0
1376
+ },
1377
+ deadlineMs: {
1378
+ type: "number",
1379
+ minimum: 0
1380
+ },
1381
+ resources: {
1382
+ type: "object",
1383
+ additionalProperties: {
1384
+ type: "object",
1385
+ properties: {
1386
+ unit: {
1387
+ type: "string",
1388
+ minLength: 1
1389
+ },
1390
+ limit: {
1391
+ type: "integer",
1392
+ minimum: 0,
1393
+ maximum: Number.MAX_SAFE_INTEGER
1394
+ }
1395
+ },
1396
+ required: ["unit", "limit"]
1397
+ }
1398
+ }
1399
+ }
1400
+ };
1401
+ function budgetField(channel) {
1402
+ return channel.startsWith("resource:") ? `resources.${channel.slice(9)}.limit` : BUDGET_FIELD[channel];
1403
+ }
1404
+ /** One clause per short channel. Iterations can be requested at exactly `free`: a driver's own
1405
+ * turns charge none. Tokens and dollars cannot: the driver's next turn is metered from the same
1406
+ * pool before its retry reaches admission, so the clause says to leave room. */
1407
+ function shortfallClause(shortfall) {
1408
+ const { channel, requested, free } = shortfall;
1409
+ const field = budgetField(channel);
1410
+ if (shortfall.closedByUnknownSpend === true) return `${channel} is closed: work with unmeasured ${channel} usage ran under the run's enforced limit, so this run admits no further spawn at any budget`;
1411
+ const asked = `this spawn asked for budget.${field} ${requested}`;
1412
+ const held = shortfall.held ?? 0;
1413
+ const most = free + held;
1414
+ if (most === 0) return `${channel} has nothing free and none held by your running workers (${asked})`;
1415
+ const room = held > 0 ? `${free} free now and ${held} held by your running workers, which a spawn waits for` : `${free} free${channel === "iterations" || channel.startsWith("resource:") ? "" : " right now"}`;
1416
+ if (channel === "iterations" || channel.startsWith("resource:")) return `${channel} has ${room} (${asked}); budget.${field} at most ${most} fits`;
1417
+ return `${channel} has ${room} (${asked}); your own turns draw ${channel} from this same pool before a retry is admitted, so ask for well under ${most}`;
1418
+ }
1419
+ /**
1420
+ * The reason text `spawn_worker` returns for a refused spawn. Every rejection kind names its own
1421
+ * cause: a live-worker cap, a depth limit, or a key collision is not an empty budget, and telling a
1422
+ * driver "no allocation left" for those sends it after the wrong fix. A `budget-exhausted` refusal
1423
+ * names every channel that did not fit and the amounts, so the driver can size its next request.
1424
+ */
1425
+ function spawnRefusalReason(reason, shortfalls, pinned) {
1426
+ switch (reason) {
1427
+ case "usd-unbudgeted": return pinned.usdUnbudgeted;
1428
+ case "in-doubt": return pinned.inDoubt;
1429
+ case "scope-settled": return pinned.scopeSettled;
1430
+ case "scope-aborted": return "this run stopped admitting work (it was cancelled, passed its deadline, or too many children went down); no further worker can start";
1431
+ case "depth-exceeded": return "this spawn would exceed the run's maxDepth; a worker at the deepest level cannot start children of its own";
1432
+ case "duplicate-key": return "a worker under this key is still live; wait for it to settle, or use a different key for different work";
1433
+ case "key-conflict": return "this key is already recorded for a different profile or task in this run's journal; use a new key for different work";
1434
+ case "invalid-identity": return "a keyed spawn needs a complete execution identity to journal, and this profile and task did not produce one; spawn again without a key";
1435
+ case "budget-exhausted":
1436
+ if (shortfalls === void 0 || shortfalls.length === 0) return "the conserved pool refused this spawn (budget-exhausted): the run's remaining budget cannot cover this worker's budget";
1437
+ if (shortfalls.some((shortfall) => shortfall.closedByUnknownSpend === true)) return `the run pool refused this spawn: ${shortfallClause(shortfalls.find((shortfall) => shortfall.closedByUnknownSpend === true))}; the caller must re-run with a measurable or larger root budget`;
1438
+ return `the run pool refused this spawn: ${shortfalls.map(shortfallClause).join("; ")}; or ask the caller for a larger root budget`;
1439
+ }
1440
+ }
1441
+ const BUDGET_FIELD = {
1442
+ tokens: "maxTokens",
1443
+ iterations: "maxIterations",
1444
+ usd: "maxUsd"
1445
+ };
1852
1446
  // src/mcp/tools/coordination-graph-tools.ts
1853
1447
  function mountGraphsTools({ opts, tools, admitSpawn }) {
1854
1448
  if (opts.graphs) {
@@ -2897,6 +2491,25 @@ async function submitResult(env, deliverable, raw) {
2897
2491
  };
2898
2492
  }
2899
2493
  const result = structuredClone(a.result);
2494
+ if (env.opts.withFileOutput) try {
2495
+ return await env.opts.withFileOutput(result, (prepared, onAccepted) => checkAndCommitSubmission(env, deliverable, prepared, onAccepted));
2496
+ } catch (error) {
2497
+ if (!(error instanceof CheckUnavailableError)) throw error;
2498
+ return {
2499
+ accepted: false,
2500
+ stop: false,
2501
+ unavailable: true,
2502
+ checkRead: appendCheckRead(state, {
2503
+ source: "submit",
2504
+ unavailable: error.message
2505
+ }).read,
2506
+ reason: error.message
2507
+ };
2508
+ }
2509
+ return checkAndCommitSubmission(env, deliverable, result);
2510
+ }
2511
+ async function checkAndCommitSubmission(env, deliverable, result, onAccepted) {
2512
+ const { state } = env;
2900
2513
  const { verdict, fault } = await runDeliverableCheck(deliverable, result);
2901
2514
  const read = appendCheckRead(state, {
2902
2515
  source: "submit",
@@ -2922,6 +2535,7 @@ async function submitResult(env, deliverable, raw) {
2922
2535
  return earlierPassingResult();
2923
2536
  }
2924
2537
  await commitSubmission(env, result);
2538
+ onAccepted?.();
2925
2539
  await env.acknowledge(state.deliveries, "result-accepted");
2926
2540
  return {
2927
2541
  accepted: true,
@@ -4994,272 +4608,678 @@ function assembleTools(parts) {
4994
4608
  });
4995
4609
  mountGraphsTools({
4996
4610
  opts,
4997
- tools,
4998
- admitSpawn
4611
+ tools,
4612
+ admitSpawn
4613
+ });
4614
+ mountAnalystsTools({
4615
+ opts,
4616
+ tools,
4617
+ ledger,
4618
+ nodeForWorker,
4619
+ analystMenu: analysis.analystMenu,
4620
+ analystRunContext: analysis.analystRunContext,
4621
+ defineAnalyst: analysis.defineAnalyst
4622
+ });
4623
+ return tools.map((tool) => timeCoordinationTool(bus, tool));
4624
+ }
4625
+ /** Record handler duration for every coordination tool call without changing its result. */
4626
+ function timeCoordinationTool(bus, tool) {
4627
+ return {
4628
+ ...tool,
4629
+ handler: async (raw) => {
4630
+ const receivedAt = Date.now();
4631
+ try {
4632
+ const value = await tool.handler(raw);
4633
+ await recordToolTiming(bus, tool.name, receivedAt, true, value);
4634
+ return value;
4635
+ } catch (error) {
4636
+ await recordToolTiming(bus, tool.name, receivedAt, false, error);
4637
+ throw error;
4638
+ }
4639
+ }
4640
+ };
4641
+ }
4642
+ async function recordToolTiming(bus, tool, receivedAt, ok, value) {
4643
+ try {
4644
+ await bus.publish({
4645
+ type: "tool-timing",
4646
+ call: {
4647
+ tool,
4648
+ receivedAt,
4649
+ elapsedMs: Math.max(0, Date.now() - receivedAt),
4650
+ responseBytes: responseUtf8Bytes(ok ? value : errorText(value)),
4651
+ ok
4652
+ }
4653
+ }, { queue: false });
4654
+ } catch (error) {
4655
+ console.error("Runtime could not record coordination tool timing", {
4656
+ tool,
4657
+ error: error instanceof Error ? error.message : String(error)
4658
+ });
4659
+ }
4660
+ }
4661
+ function responseUtf8Bytes(value) {
4662
+ if (typeof value === "string") return Buffer.byteLength(value);
4663
+ try {
4664
+ return Buffer.byteLength(JSON.stringify(value) ?? "null");
4665
+ } catch {
4666
+ return Buffer.byteLength(String(value));
4667
+ }
4668
+ }
4669
+ function errorText(error) {
4670
+ return error instanceof Error ? error.message : String(error);
4671
+ }
4672
+ function managerSurface(parts, tools) {
4673
+ const { opts, bus, state, ledger, questionLedger, spawnAdmission, analysis, settlements, messages, workers, waiting, intake, journal, peerMail, ackEnv, ready } = parts;
4674
+ return {
4675
+ tools,
4676
+ ready,
4677
+ history: () => bus.history(),
4678
+ raiseFinding: (finding) => bus.publish({
4679
+ type: "finding",
4680
+ finding: canonicalFindingEvent(finding)
4681
+ }).then(() => void 0),
4682
+ steerWorker: messages.steerWorker,
4683
+ stats: () => opts.preflightSpawn === void 0 ? bus.stats() : {
4684
+ ...bus.stats(),
4685
+ preflight: { ...spawnAdmission.preflightCounts }
4686
+ },
4687
+ isStopped: () => state.stopped,
4688
+ stopReason: () => state.reason,
4689
+ submittedResult: () => state.submitted,
4690
+ settled: () => ledger,
4691
+ questions: () => questionLedger.questions,
4692
+ escalations: () => questionLedger.escalations,
4693
+ definedAnalysts: () => analysis.definedAnalysts,
4694
+ drainResolved: settlements.drainResolved,
4695
+ finishAnalysis: analysis.finishAnalysis,
4696
+ abortWorker: spawnAdmission.abortWorker,
4697
+ beginDriverAttempt: (attempt) => {
4698
+ state.driverAttempt = attempt;
4699
+ },
4700
+ endDriverAttempt: async (outcome) => {
4701
+ const attempt = state.driverAttempt;
4702
+ if (outcome === "completed") await acknowledgeDeliveries(ackEnv, state.deliveries.filter((delivery) => delivery.attempt === attempt), "turn-completed");
4703
+ },
4704
+ hasOpenWork: waiting.hasOpenWork,
4705
+ awaitWake: waiting.awaitWake,
4706
+ awaitSettlement: waiting.awaitSettlement,
4707
+ receiveLeadMessage: intake.receiveLeadMessage,
4708
+ queuedLeadMessages: () => bus.queued(["lead-message"]).map((record) => record.seq),
4709
+ awaitLeadMessage: (signal) => new Promise((resolve) => {
4710
+ if (signal.aborted) {
4711
+ resolve();
4712
+ return;
4713
+ }
4714
+ const done = () => {
4715
+ unsubscribe();
4716
+ signal.removeEventListener("abort", done);
4717
+ resolve();
4718
+ };
4719
+ const unsubscribe = bus.onQueued((record) => {
4720
+ if (record.event.type === "lead-message") done();
4721
+ });
4722
+ signal.addEventListener("abort", done, { once: true });
4723
+ }),
4724
+ openToolReceipt: intake.openToolReceipt,
4725
+ settleToolReceipt: intake.settleToolReceipt,
4726
+ reentryState: () => managerReentryState({
4727
+ opts,
4728
+ ledger,
4729
+ deliveries: state.deliveries,
4730
+ priorJournal: journal.priorJournal,
4731
+ bus,
4732
+ journal,
4733
+ openWork: workers.openWork,
4734
+ driverAttempt: state.driverAttempt,
4735
+ lastRejection: state.lastRejection
4736
+ }),
4737
+ blocked: () => [...state.blockedReports],
4738
+ checkReads: () => state.checkReads,
4739
+ recordCheckRead: (read) => appendCheckRead(state, read),
4740
+ ...peerMail ? { peerMail } : {}
4741
+ };
4742
+ }
4743
+ /** The map and route schedulers of one manager, which share the nodes of a prior process's spawns. */
4744
+ function createFlowRouting({ opts, bus, spawnAdmission, settleCommitted, stop }) {
4745
+ const { profileNameByWorker, resolveContinuity, admitSpawn } = spawnAdmission;
4746
+ const committedNodes = /* @__PURE__ */ new Map();
4747
+ const nodeOf = (id) => profileNameByWorker.get(id) ?? committedNodes.get(id);
4748
+ const settleNode = (id, node) => {
4749
+ committedNodes.set(id, node);
4750
+ return settleCommitted(id);
4751
+ };
4752
+ const maps = createMapRouting({
4753
+ opts,
4754
+ bus,
4755
+ admitSpawn: (input) => admitSpawn(input),
4756
+ nodeOf,
4757
+ settleCommitted: settleNode,
4758
+ endInDoubt: (node, source) => routes.endInDoubt(node, source)
4999
4759
  });
5000
- mountAnalystsTools({
4760
+ const routes = createRouteRouting({
5001
4761
  opts,
5002
- tools,
5003
- ledger,
5004
- nodeForWorker,
5005
- analystMenu: analysis.analystMenu,
5006
- analystRunContext: analysis.analystRunContext,
5007
- defineAnalyst: analysis.defineAnalyst
4762
+ bus,
4763
+ admitSpawn: (input) => admitSpawn(input),
4764
+ resolveContinuity,
4765
+ nodeOf,
4766
+ settleCommitted: settleNode,
4767
+ stop
5008
4768
  });
5009
- return tools.map((tool) => timeCoordinationTool(bus, tool));
5010
- }
5011
- /** Record handler duration for every coordination tool call without changing its result. */
5012
- function timeCoordinationTool(bus, tool) {
5013
4769
  return {
4770
+ maps,
4771
+ routes
4772
+ };
4773
+ }
4774
+ function createPeerMail(opts, bus) {
4775
+ return opts.peerMail ? createPeerMailbox({
4776
+ scope: opts.scope,
4777
+ publish: (mail) => bus.publish({
4778
+ type: "mail",
4779
+ mail
4780
+ }, { queue: false }).then(() => void 0),
4781
+ ...opts.peerMail.limits ? { limits: opts.peerMail.limits } : {}
4782
+ }) : void 0;
4783
+ }
4784
+ function registerChildQuestionInbox(opts, { addQuestion, emitNewQuestion }, workerByAssignment, nodeForWorker) {
4785
+ opts.onChildQuestionInbox?.(async (assignmentId, asked) => {
4786
+ const workerId = workerByAssignment.get(assignmentId);
4787
+ if (workerId === void 0 || nodeForWorker(workerId) === void 0) return {
4788
+ delivered: false,
4789
+ reason: `the parent manager has no worker for assignment ${JSON.stringify(assignmentId)}`
4790
+ };
4791
+ return {
4792
+ delivered: true,
4793
+ to: `parent manager question ${(await emitNewQuestion(addQuestion({
4794
+ from: workerId,
4795
+ level: asked.level,
4796
+ question: asked.question,
4797
+ reason: asked.reason,
4798
+ ...asked.options ? { options: asked.options } : {},
4799
+ urgency: asked.urgency
4800
+ }, workerId))).id}`
4801
+ };
4802
+ });
4803
+ }
4804
+ /**
4805
+ * Let `observe_agent` and `read_journal` read a peer root's own record when the run enables peer
4806
+ * audit, then register this manager's tools with the peer registry. Mutates the two tools in place.
4807
+ */
4808
+ function mountPeerAudit({ opts, tools, readJournal }) {
4809
+ for (const tool of tools) {
4810
+ if (tool.name !== "observe_agent" && tool.name !== "read_journal") continue;
4811
+ const ownHandler = tool.handler;
4812
+ const name = tool.name;
4813
+ const schema = tool.inputSchema;
4814
+ schema.properties = {
4815
+ ...schema.properties,
4816
+ peerId: {
4817
+ type: "string",
4818
+ description: "Read a peer root's own record, using its workerId from read_mail.peers. Read-only; omit for your own tree."
4819
+ }
4820
+ };
4821
+ tool.handler = async (raw) => {
4822
+ const args = obj(raw);
4823
+ if (args.peerId === void 0) return ownHandler(raw);
4824
+ const peerId = str(args.peerId, "peerId");
4825
+ const { peerId: _peerId, ...readArgs } = args;
4826
+ return opts.peerAudit?.read(peerId, name, readArgs);
4827
+ };
4828
+ }
4829
+ opts.peerAudit.register(opts.scope.view.root, tools.map((tool) => tool.name === "read_journal" ? {
5014
4830
  ...tool,
5015
- handler: async (raw) => {
5016
- const receivedAt = Date.now();
4831
+ handler: async (raw) => readJournal(raw, false)
4832
+ } : tool));
4833
+ }
4834
+ /**
4835
+ * Seed the settled ledger from a resumed scope and own the replay of its events onto the bus.
4836
+ * Replayed reviews remain findings. They cannot enter the completion pool or recursively
4837
+ * trigger another analyst, even when the resumed configuration changes its analyst routes.
4838
+ */
4839
+ function createResumeReplay({ opts, bus, ledger, analysis, projectSettled }) {
4840
+ const { analystRuns, flushedAnalystRuns, analystRunFinding } = analysis;
4841
+ const resumedWorkers = [];
4842
+ const resumedFindings = [];
4843
+ for (const s of opts.scope.resume?.settled ?? []) {
4844
+ const analyst = analystRuns.get(s.handle.id);
4845
+ if (analyst) {
4846
+ resumedFindings.push(analystRunFinding(analyst, s));
4847
+ analystRuns.delete(s.handle.id);
4848
+ flushedAnalystRuns.add(s.handle.id);
4849
+ continue;
4850
+ }
4851
+ const worker = projectSettled(s, true);
4852
+ resumedWorkers.push(worker);
4853
+ ledger.push(worker);
4854
+ }
4855
+ const resumeEvents = opts.replaySettlements ? [...resumedWorkers.map((worker) => detachedFrozen({
4856
+ type: "settled",
4857
+ worker
4858
+ })), ...resumedFindings] : [];
4859
+ let resumeEventIndex = 0;
4860
+ let readyInFlight;
4861
+ return () => {
4862
+ if (resumeEventIndex >= resumeEvents.length) return Promise.resolve();
4863
+ if (readyInFlight) return readyInFlight;
4864
+ readyInFlight = (async () => {
4865
+ while (resumeEventIndex < resumeEvents.length) {
4866
+ const event = resumeEvents[resumeEventIndex];
4867
+ if (!event) break;
4868
+ await bus.publish(event);
4869
+ resumeEventIndex += 1;
4870
+ }
4871
+ })().finally(() => {
4872
+ readyInFlight = void 0;
4873
+ });
4874
+ return readyInFlight;
4875
+ };
4876
+ }
4877
+ // src/runtime/supervise/driver-control-acknowledgers.ts
4878
+ const SPAWN_JOURNAL_FILE = "spawn-journal.jsonl";
4879
+ function appendedLines(tail) {
4880
+ let size;
4881
+ try {
4882
+ size = statSync(tail.file).size;
4883
+ } catch {
4884
+ return;
4885
+ }
4886
+ if (size < tail.offset) {
4887
+ tail.offset = 0;
4888
+ tail.partial = "";
4889
+ tail.at.clear();
4890
+ }
4891
+ if (size === tail.offset) return void 0;
4892
+ const buf = Buffer.allocUnsafe(size - tail.offset);
4893
+ const fd = openSync(tail.file, "r");
4894
+ try {
4895
+ const got = readSync(fd, buf, 0, buf.length, tail.offset);
4896
+ tail.offset += got;
4897
+ const text = tail.partial + buf.subarray(0, got).toString("utf8");
4898
+ const parts = text.split("\n");
4899
+ tail.partial = text.endsWith("\n") ? "" : parts.pop() ?? "";
4900
+ if (text.endsWith("\n")) parts.pop();
4901
+ return parts;
4902
+ } finally {
4903
+ closeSync(fd);
4904
+ }
4905
+ }
4906
+ function indexDeaths(tail) {
4907
+ const lines = appendedLines(tail);
4908
+ if (lines === void 0) return false;
4909
+ let grew = false;
4910
+ for (const line of lines) {
4911
+ const trimmed = line.trim();
4912
+ if (!trimmed) continue;
4913
+ try {
4914
+ for (const event of spawnJournalRecordEvents(JSON.parse(trimmed))) {
4915
+ if (event === void 0) continue;
4916
+ if (!(event.kind === "settled" && event.status === "down" || event.kind === "cancelled") || typeof event.id !== "string" || typeof event.at !== "string") continue;
4917
+ const prev = tail.at.get(event.id);
4918
+ if (prev !== void 0 && prev >= event.at) continue;
4919
+ tail.at.set(event.id, event.at);
4920
+ grew = true;
4921
+ }
4922
+ } catch {}
4923
+ }
4924
+ return grew;
4925
+ }
4926
+ function descendantsSince(tail, nodeId, sinceIso) {
4927
+ indexDeaths(tail);
4928
+ const prefix = `${nodeId}:`;
4929
+ const ids = [...tail.at.keys()].filter((id) => id.startsWith(prefix) && (tail.at.get(id) ?? "") >= sinceIso);
4930
+ ids.sort();
4931
+ return ids;
4932
+ }
4933
+ /** Unknown ack lands before delivery. A crash can lose the steer; a restart must not deliver it twice. */
4934
+ function createSteerAcknowledger(deps) {
4935
+ const iso = () => new Date(deps.now()).toISOString();
4936
+ const awaiting = /* @__PURE__ */ new Map();
4937
+ const named = /* @__PURE__ */ new Map();
4938
+ const paused = () => {
4939
+ const pause = deps.rootPause?.();
4940
+ if (pause === void 0) return { why: "" };
4941
+ const left = pause.tokensLeft === void 0 ? "" : ` with ${pause.tokensLeft} tokens left`;
4942
+ return {
4943
+ pausedOn: pause,
4944
+ why: `; the root is paused on ${pause.stop}${left}`
4945
+ };
4946
+ };
4947
+ const queuedRoot = (request) => {
4948
+ const { pausedOn, why } = paused();
4949
+ const key = pausedOn?.stop ?? "";
4950
+ if (named.get(request.operationId) === key) return;
4951
+ named.set(request.operationId, key);
4952
+ writeWorkerSteerAcknowledgement(deps.dir, {
4953
+ ...base(request),
4954
+ effect: "unknown",
4955
+ observedAt: iso(),
4956
+ detail: `queued in the root inbox; no root turn has consumed it yet${why}`,
4957
+ ...pausedOn === void 0 ? {} : { pausedOn }
4958
+ });
4959
+ };
4960
+ const answerRoot = (request, receipt) => {
4961
+ if (!awaiting.delete(request.operationId)) return;
4962
+ named.delete(request.operationId);
4963
+ const { pausedOn, why } = receipt.status === "consumed" ? { why: "" } : paused();
4964
+ writeWorkerSteerAcknowledgement(deps.dir, {
4965
+ ...base(request),
4966
+ ...receipt.status === "consumed" ? {
4967
+ effect: "delivered",
4968
+ detail: `the root consumed the steer in ${receipt.attemptId}`
4969
+ } : {
4970
+ effect: "not_live",
4971
+ detail: `the root did not consume the steer: ${receipt.reason}${why}`
4972
+ },
4973
+ observedAt: iso(),
4974
+ ...pausedOn === void 0 ? {} : { pausedOn }
4975
+ });
4976
+ };
4977
+ const base = (request) => ({
4978
+ schemaVersion: 1,
4979
+ operationId: request.operationId,
4980
+ requestDigest: request.requestDigest,
4981
+ worker: request.worker,
4982
+ requestedAt: request.at
4983
+ });
4984
+ let steerStamp = "";
4985
+ let steerIdle = false;
4986
+ const steerChanged = (phase) => {
4987
+ let stamp = "missing";
4988
+ try {
4989
+ const st = statSync(workerSteerRequestsDir(deps.dir), { bigint: true });
4990
+ stamp = `${st.dev}:${st.ino}:${st.mtimeNs}:${st.size}`;
4991
+ } catch {
4992
+ stamp = "missing";
4993
+ }
4994
+ const changed = stamp !== steerStamp;
4995
+ if (changed && phase !== "boundary") steerStamp = stamp;
4996
+ return changed;
4997
+ };
4998
+ return { async pass(phase) {
4999
+ if (phase === "turn") for (const request of awaiting.values()) queuedRoot(request);
5000
+ const changed = steerChanged(phase);
5001
+ if (phase !== "final" && !changed && steerIdle) return;
5002
+ for (const request of readWorkerSteerRequests(deps.dir)) {
5003
+ if (phase !== "final" && deps.signal?.aborted) {
5004
+ steerIdle = false;
5005
+ return;
5006
+ }
5007
+ const rootRequest = request.worker === deps.ownerId && deps.deliverRoot !== void 0;
5008
+ if (phase === "boundary" && !rootRequest) continue;
5009
+ if (!rootRequest && !isDirectChildNodeId(deps, request.worker)) continue;
5010
+ const queued = awaiting.get(request.operationId);
5011
+ if (phase === "final" && queued !== void 0) {
5012
+ answerRoot(queued, {
5013
+ status: "failed",
5014
+ messageId: request.operationId,
5015
+ cause: "closed",
5016
+ reason: "the run ended before a root turn read it"
5017
+ });
5018
+ continue;
5019
+ }
5020
+ if (readWorkerSteerAcknowledgement(deps.dir, request.operationId) !== void 0) continue;
5021
+ if (phase === "final") {
5022
+ writeWorkerSteerAcknowledgement(deps.dir, {
5023
+ ...base(request),
5024
+ effect: "not_live",
5025
+ observedAt: iso(),
5026
+ detail: "run ended before the steer was applied"
5027
+ });
5028
+ continue;
5029
+ }
5030
+ if (!claimWorkerSteerDelivery(deps.dir, {
5031
+ ...base(request),
5032
+ effect: "unknown",
5033
+ observedAt: iso(),
5034
+ detail: "delivery admitted; outcome not yet known"
5035
+ })) continue;
5017
5036
  try {
5018
- const value = await tool.handler(raw);
5019
- await recordToolTiming(bus, tool.name, receivedAt, true, value);
5020
- return value;
5037
+ let outcome;
5038
+ if (rootRequest) {
5039
+ awaiting.set(request.operationId, request);
5040
+ const delivered = deps.deliverRoot({
5041
+ steer: request.message,
5042
+ interrupt: request.interrupt,
5043
+ messageId: request.operationId,
5044
+ receipt: (receipt) => answerRoot(request, receipt)
5045
+ });
5046
+ if (!delivered) awaiting.delete(request.operationId);
5047
+ outcome = {
5048
+ delivered,
5049
+ outcome: delivered ? "delivered" : "runtime-has-no-inbox"
5050
+ };
5051
+ } else outcome = await deps.coord.steerWorker(request.worker, request.message, { interrupt: request.interrupt });
5052
+ if (rootRequest && outcome.delivered) {
5053
+ if (awaiting.has(request.operationId)) queuedRoot(request);
5054
+ continue;
5055
+ }
5056
+ const effect = outcome.delivered ? "delivered" : outcome.outcome === "runtime-has-no-inbox" ? "unsupported" : outcome.outcome === "unknown-worker" || outcome.outcome === "already-settled" || outcome.outcome === "scope-stopped" ? "not_live" : "unknown";
5057
+ writeWorkerSteerAcknowledgement(deps.dir, {
5058
+ ...base(request),
5059
+ effect,
5060
+ observedAt: iso(),
5061
+ detail: rootRequest ? "the root exposes no accepting inbox at delivery time" : steerAcknowledgementDetail(outcome)
5062
+ });
5021
5063
  } catch (error) {
5022
- await recordToolTiming(bus, tool.name, receivedAt, false, error);
5023
- throw error;
5064
+ awaiting.delete(request.operationId);
5065
+ writeWorkerSteerAcknowledgement(deps.dir, {
5066
+ ...base(request),
5067
+ effect: "unknown",
5068
+ observedAt: iso(),
5069
+ detail: "delivery outcome is unknown after a runtime error"
5070
+ });
5024
5071
  }
5025
5072
  }
5026
- };
5027
- }
5028
- async function recordToolTiming(bus, tool, receivedAt, ok, value) {
5029
- try {
5030
- await bus.publish({
5031
- type: "tool-timing",
5032
- call: {
5033
- tool,
5034
- receivedAt,
5035
- elapsedMs: Math.max(0, Date.now() - receivedAt),
5036
- responseBytes: responseUtf8Bytes(ok ? value : errorText(value)),
5037
- ok
5038
- }
5039
- }, { queue: false });
5040
- } catch (error) {
5041
- console.error("Runtime could not record coordination tool timing", {
5042
- tool,
5043
- error: error instanceof Error ? error.message : String(error)
5044
- });
5045
- }
5073
+ if (phase === "turn") steerIdle = true;
5074
+ } };
5046
5075
  }
5047
- function responseUtf8Bytes(value) {
5048
- if (typeof value === "string") return Buffer.byteLength(value);
5049
- try {
5050
- return Buffer.byteLength(JSON.stringify(value) ?? "null");
5051
- } catch {
5052
- return Buffer.byteLength(String(value));
5076
+ function steerAcknowledgementDetail(outcome) {
5077
+ switch (outcome.outcome) {
5078
+ case "delivered": return "the owning manager delivered the steer to the exact live worker";
5079
+ case "runtime-has-no-inbox": return "the exact worker does not expose a steer inbox";
5080
+ case "unknown-worker": return "the owning manager does not know the exact worker";
5081
+ case "already-settled": return "the exact worker settled before delivery";
5082
+ case "scope-stopped": return "the owning manager stopped before delivery";
5083
+ case "runtime-error": return "delivery outcome is unknown after a runtime error";
5053
5084
  }
5054
5085
  }
5055
- function errorText(error) {
5056
- return error instanceof Error ? error.message : String(error);
5057
- }
5058
- function managerSurface(parts, tools) {
5059
- const { opts, bus, state, ledger, questionLedger, spawnAdmission, analysis, settlements, messages, workers, waiting, intake, journal, peerMail, ackEnv, ready } = parts;
5060
- return {
5061
- tools,
5062
- ready,
5063
- history: () => bus.history(),
5064
- raiseFinding: (finding) => bus.publish({
5065
- type: "finding",
5066
- finding: canonicalFindingEvent(finding)
5067
- }).then(() => void 0),
5068
- steerWorker: messages.steerWorker,
5069
- stats: () => opts.preflightSpawn === void 0 ? bus.stats() : {
5070
- ...bus.stats(),
5071
- preflight: { ...spawnAdmission.preflightCounts }
5072
- },
5073
- isStopped: () => state.stopped,
5074
- stopReason: () => state.reason,
5075
- submittedResult: () => state.submitted,
5076
- settled: () => ledger,
5077
- questions: () => questionLedger.questions,
5078
- escalations: () => questionLedger.escalations,
5079
- definedAnalysts: () => analysis.definedAnalysts,
5080
- drainResolved: settlements.drainResolved,
5081
- finishAnalysis: analysis.finishAnalysis,
5082
- abortWorker: spawnAdmission.abortWorker,
5083
- beginDriverAttempt: (attempt) => {
5084
- state.driverAttempt = attempt;
5085
- },
5086
- endDriverAttempt: async (outcome) => {
5087
- const attempt = state.driverAttempt;
5088
- if (outcome === "completed") await acknowledgeDeliveries(ackEnv, state.deliveries.filter((delivery) => delivery.attempt === attempt), "turn-completed");
5089
- },
5090
- hasOpenWork: waiting.hasOpenWork,
5091
- awaitWake: waiting.awaitWake,
5092
- awaitSettlement: waiting.awaitSettlement,
5093
- receiveLeadMessage: intake.receiveLeadMessage,
5094
- queuedLeadMessages: () => bus.queued(["lead-message"]).map((record) => record.seq),
5095
- awaitLeadMessage: (signal) => new Promise((resolve) => {
5096
- if (signal.aborted) {
5097
- resolve();
5098
- return;
5099
- }
5100
- const done = () => {
5101
- unsubscribe();
5102
- signal.removeEventListener("abort", done);
5103
- resolve();
5104
- };
5105
- const unsubscribe = bus.onQueued((record) => {
5106
- if (record.event.type === "lead-message") done();
5086
+ function createCancelAcknowledger(deps) {
5087
+ const tracked = /* @__PURE__ */ new Map();
5088
+ let runTracked;
5089
+ const abortIssuedAt = /* @__PURE__ */ new Map();
5090
+ const iso = () => new Date(deps.now()).toISOString();
5091
+ const waiting = /* @__PURE__ */ new Map();
5092
+ const reconciling = /* @__PURE__ */ new Map();
5093
+ const regrowing = /* @__PURE__ */ new Set();
5094
+ let inboxBytes;
5095
+ const deaths = {
5096
+ file: join(deps.dir, SPAWN_JOURNAL_FILE),
5097
+ offset: 0,
5098
+ partial: "",
5099
+ at: /* @__PURE__ */ new Map()
5100
+ };
5101
+ const watch = (record) => {
5102
+ if (record.effect === "cancel_requested") reconciling.set(record.operationId, record);
5103
+ else reconciling.delete(record.operationId);
5104
+ if (record.effect === "cancelled" && abortIssuedAt.has(record.operationId)) regrowing.add(record.operationId);
5105
+ else regrowing.delete(record.operationId);
5106
+ };
5107
+ const write = (record) => {
5108
+ writeWorkerCancellation(deps.dir, record);
5109
+ tracked.set(record.operationId, record);
5110
+ watch(record);
5111
+ };
5112
+ const owned = (ref) => {
5113
+ if (isDirectChildNodeId(deps, ref)) return true;
5114
+ if (deps.controlScope !== "run") return false;
5115
+ return !ref.startsWith(`${deps.ownerId}:`) && ref !== deps.ownerId;
5116
+ };
5117
+ const deliveredTerminal = (id) => {
5118
+ const row = deps.coord.settled().find((w) => w.id === id);
5119
+ if (row !== void 0) return row.status;
5120
+ const node = deps.scope.view.nodes.find((n) => n.id === id);
5121
+ if (node === void 0) return void 0;
5122
+ if (node.status === "done") return "done";
5123
+ if (node.status === "failed" || node.status === "cancelled") return "down";
5124
+ };
5125
+ const apply = (request) => {
5126
+ const aborted = deps.coord.abortWorker(request.worker, request.reason ?? "cancel requested");
5127
+ const base = {
5128
+ operationId: request.operationId,
5129
+ worker: request.worker,
5130
+ requestedAt: request.at,
5131
+ observedAt: iso(),
5132
+ ...request.reason === void 0 ? {} : { reason: request.reason }
5133
+ };
5134
+ if (aborted !== void 0) {
5135
+ abortIssuedAt.set(request.operationId, base.observedAt);
5136
+ write({
5137
+ ...base,
5138
+ effect: "cancel_requested",
5139
+ workerId: aborted.id,
5140
+ detail: `abort issued to live worker '${aborted.label}' (${aborted.id}); termination not yet proven`,
5141
+ terminated: []
5142
+ });
5143
+ return;
5144
+ }
5145
+ const goneId = deps.scope.view.nodes.find((n) => (n.id === request.worker || n.label === request.worker) && isTerminalNodeStatus(n.status))?.id ?? deps.coord.settled().find((w) => w.id === request.worker)?.id;
5146
+ if (goneId !== void 0) write({
5147
+ ...base,
5148
+ effect: "not_live",
5149
+ workerId: goneId,
5150
+ detail: `worker '${goneId}' had already settled before this operation was applied`,
5151
+ terminated: []
5152
+ });
5153
+ };
5154
+ /** Grows only: the worker, the record's ids, and subtree deaths at or after the abort. */
5155
+ const provenTerminated = (record, workerId) => {
5156
+ const since = abortIssuedAt.get(record.operationId) ?? record.observedAt;
5157
+ return [.../* @__PURE__ */ new Set([
5158
+ ...record.terminated,
5159
+ workerId,
5160
+ ...descendantsSince(deaths, workerId, since)
5161
+ ])].sort();
5162
+ };
5163
+ const reconcile = (record) => {
5164
+ const workerId = record.workerId;
5165
+ if (workerId === void 0) return;
5166
+ const terminal = deliveredTerminal(workerId);
5167
+ if (terminal === void 0) return;
5168
+ if (terminal === "down") {
5169
+ write({
5170
+ ...record,
5171
+ effect: "cancelled",
5172
+ observedAt: iso(),
5173
+ terminated: provenTerminated(record, workerId),
5174
+ detail: `worker '${workerId}' reached a terminal down state on the settle path`
5107
5175
  });
5108
- signal.addEventListener("abort", done, { once: true });
5109
- }),
5110
- openToolReceipt: intake.openToolReceipt,
5111
- settleToolReceipt: intake.settleToolReceipt,
5112
- reentryState: () => managerReentryState({
5113
- opts,
5114
- ledger,
5115
- deliveries: state.deliveries,
5116
- priorJournal: journal.priorJournal,
5117
- bus,
5118
- journal,
5119
- openWork: workers.openWork,
5120
- driverAttempt: state.driverAttempt,
5121
- lastRejection: state.lastRejection
5122
- }),
5123
- blocked: () => [...state.blockedReports],
5124
- checkReads: () => state.checkReads,
5125
- recordCheckRead: (read) => appendCheckRead(state, read),
5126
- ...peerMail ? { peerMail } : {}
5176
+ return;
5177
+ }
5178
+ write({
5179
+ ...record,
5180
+ effect: "not_live",
5181
+ observedAt: iso(),
5182
+ terminated: [],
5183
+ detail: `worker '${workerId}' settled done despite the abort request; nothing was terminated`
5184
+ });
5127
5185
  };
5128
- }
5129
- /** The map and route schedulers of one manager, which share the nodes of a prior process's spawns. */
5130
- function createFlowRouting({ opts, bus, spawnAdmission, settleCommitted, stop }) {
5131
- const { profileNameByWorker, resolveContinuity, admitSpawn } = spawnAdmission;
5132
- const committedNodes = /* @__PURE__ */ new Map();
5133
- const nodeOf = (id) => profileNameByWorker.get(id) ?? committedNodes.get(id);
5134
- const settleNode = (id, node) => {
5135
- committedNodes.set(id, node);
5136
- return settleCommitted(id);
5186
+ const regrow = (record) => {
5187
+ const workerId = record.workerId;
5188
+ if (workerId === void 0 || !abortIssuedAt.has(record.operationId)) return;
5189
+ const terminated = provenTerminated(record, workerId);
5190
+ if (terminated.length > record.terminated.length) write({
5191
+ ...record,
5192
+ observedAt: iso(),
5193
+ terminated
5194
+ });
5137
5195
  };
5138
- const maps = createMapRouting({
5139
- opts,
5140
- bus,
5141
- admitSpawn: (input) => admitSpawn(input),
5142
- nodeOf,
5143
- settleCommitted: settleNode,
5144
- endInDoubt: (node, source) => routes.endInDoubt(node, source)
5145
- });
5146
- const routes = createRouteRouting({
5147
- opts,
5148
- bus,
5149
- admitSpawn: (input) => admitSpawn(input),
5150
- resolveContinuity,
5151
- nodeOf,
5152
- settleCommitted: settleNode,
5153
- stop
5154
- });
5155
- return {
5156
- maps,
5157
- routes
5196
+ const passRun = () => {
5197
+ if (deps.controlScope !== "run" || deps.abortRun === void 0) return;
5198
+ if (runTracked !== void 0) return;
5199
+ runTracked = applyRunCancellation(deps.dir, deps.abortRun, iso);
5158
5200
  };
5159
- }
5160
- function createPeerMail(opts, bus) {
5161
- return opts.peerMail ? createPeerMailbox({
5162
- scope: opts.scope,
5163
- publish: (mail) => bus.publish({
5164
- type: "mail",
5165
- mail
5166
- }, { queue: false }).then(() => void 0),
5167
- ...opts.peerMail.limits ? { limits: opts.peerMail.limits } : {}
5168
- }) : void 0;
5169
- }
5170
- function registerChildQuestionInbox(opts, { addQuestion, emitNewQuestion }, workerByAssignment, nodeForWorker) {
5171
- opts.onChildQuestionInbox?.(async (assignmentId, asked) => {
5172
- const workerId = workerByAssignment.get(assignmentId);
5173
- if (workerId === void 0 || nodeForWorker(workerId) === void 0) return {
5174
- delivered: false,
5175
- reason: `the parent manager has no worker for assignment ${JSON.stringify(assignmentId)}`
5176
- };
5177
- return {
5178
- delivered: true,
5179
- to: `parent manager question ${(await emitNewQuestion(addQuestion({
5180
- from: workerId,
5181
- level: asked.level,
5182
- question: asked.question,
5183
- reason: asked.reason,
5184
- ...asked.options ? { options: asked.options } : {},
5185
- urgency: asked.urgency
5186
- }, workerId))).id}`
5187
- };
5188
- });
5189
- }
5190
- /**
5191
- * Let `observe_agent` and `read_journal` read a peer root's own record when the run enables peer
5192
- * audit, then register this manager's tools with the peer registry. Mutates the two tools in place.
5193
- */
5194
- function mountPeerAudit({ opts, tools, readJournal }) {
5195
- for (const tool of tools) {
5196
- if (tool.name !== "observe_agent" && tool.name !== "read_journal") continue;
5197
- const ownHandler = tool.handler;
5198
- const name = tool.name;
5199
- const schema = tool.inputSchema;
5200
- schema.properties = {
5201
- ...schema.properties,
5202
- peerId: {
5203
- type: "string",
5204
- description: "Read a peer root's own record, using its workerId from read_mail.peers. Read-only; omit for your own tree."
5201
+ const ingest = () => {
5202
+ const file = workerCancelRequestsFile(deps.dir);
5203
+ let size;
5204
+ try {
5205
+ size = statSync(file).size;
5206
+ } catch {
5207
+ size = null;
5208
+ }
5209
+ if (size === inboxBytes) return;
5210
+ inboxBytes = size;
5211
+ for (const request of readWorkerCancelRequests(deps.dir)) {
5212
+ if (!owned(request.worker) || tracked.has(request.operationId) || waiting.has(request.operationId)) continue;
5213
+ const record = readWorkerCancellation(deps.dir, request.operationId);
5214
+ if (record === void 0) waiting.set(request.operationId, request);
5215
+ else {
5216
+ tracked.set(record.operationId, record);
5217
+ watch(record);
5205
5218
  }
5206
- };
5207
- tool.handler = async (raw) => {
5208
- const args = obj(raw);
5209
- if (args.peerId === void 0) return ownHandler(raw);
5210
- const peerId = str(args.peerId, "peerId");
5211
- const { peerId: _peerId, ...readArgs } = args;
5212
- return opts.peerAudit?.read(peerId, name, readArgs);
5213
- };
5214
- }
5215
- opts.peerAudit.register(opts.scope.view.root, tools.map((tool) => tool.name === "read_journal" ? {
5216
- ...tool,
5217
- handler: async (raw) => readJournal(raw, false)
5218
- } : tool));
5219
- }
5220
- /**
5221
- * Seed the settled ledger from a resumed scope and own the replay of its events onto the bus.
5222
- * Replayed reviews remain findings. They cannot enter the completion pool or recursively
5223
- * trigger another analyst, even when the resumed configuration changes its analyst routes.
5224
- */
5225
- function createResumeReplay({ opts, bus, ledger, analysis, projectSettled }) {
5226
- const { analystRuns, flushedAnalystRuns, analystRunFinding } = analysis;
5227
- const resumedWorkers = [];
5228
- const resumedFindings = [];
5229
- for (const s of opts.scope.resume?.settled ?? []) {
5230
- const analyst = analystRuns.get(s.handle.id);
5231
- if (analyst) {
5232
- resumedFindings.push(analystRunFinding(analyst, s));
5233
- analystRuns.delete(s.handle.id);
5234
- flushedAnalystRuns.add(s.handle.id);
5235
- continue;
5236
5219
  }
5237
- const worker = projectSettled(s, true);
5238
- resumedWorkers.push(worker);
5239
- ledger.push(worker);
5240
- }
5241
- const resumeEvents = opts.replaySettlements ? [...resumedWorkers.map((worker) => detachedFrozen({
5242
- type: "settled",
5243
- worker
5244
- })), ...resumedFindings] : [];
5245
- let resumeEventIndex = 0;
5246
- let readyInFlight;
5247
- return () => {
5248
- if (resumeEventIndex >= resumeEvents.length) return Promise.resolve();
5249
- if (readyInFlight) return readyInFlight;
5250
- readyInFlight = (async () => {
5251
- while (resumeEventIndex < resumeEvents.length) {
5252
- const event = resumeEvents[resumeEventIndex];
5253
- if (!event) break;
5254
- await bus.publish(event);
5255
- resumeEventIndex += 1;
5220
+ };
5221
+ const pass = (phase) => {
5222
+ if (phase === "turn") passRun();
5223
+ ingest();
5224
+ const pending = [...reconciling.values()];
5225
+ if (phase === "turn") for (const request of [...waiting.values()]) {
5226
+ waiting.delete(request.operationId);
5227
+ apply(request);
5228
+ if (!tracked.has(request.operationId)) waiting.set(request.operationId, request);
5229
+ }
5230
+ const grew = indexDeaths(deaths);
5231
+ for (const record of pending) {
5232
+ const current = tracked.get(record.operationId);
5233
+ if (current?.effect === "cancel_requested") reconcile(current);
5234
+ }
5235
+ if (!grew) return;
5236
+ for (const id of [...regrowing]) {
5237
+ const record = tracked.get(id);
5238
+ if (record !== void 0) regrow(record);
5239
+ }
5240
+ };
5241
+ return {
5242
+ pass,
5243
+ finish() {
5244
+ const runRequest = deps.controlScope === "run" && deps.abortRun !== void 0 ? readRunCancelRequest(deps.dir) : void 0;
5245
+ if (runRequest !== void 0 && readRunCancellation(deps.dir, runRequest.operationId) === void 0) writeRunCancellation(deps.dir, {
5246
+ operationId: runRequest.operationId,
5247
+ effect: "not_live",
5248
+ requestedAt: runRequest.at,
5249
+ observedAt: iso(),
5250
+ ...runRequest.reason === void 0 ? {} : { reason: runRequest.reason },
5251
+ ...runRequest.operator === void 0 ? {} : { operator: runRequest.operator },
5252
+ detail: "run ended before the request was applied"
5253
+ });
5254
+ for (const request of readWorkerCancelRequests(deps.dir)) {
5255
+ if (!owned(request.worker)) continue;
5256
+ const record = tracked.get(request.operationId) ?? readWorkerCancellation(deps.dir, request.operationId);
5257
+ if (record === void 0) {
5258
+ write({
5259
+ operationId: request.operationId,
5260
+ worker: request.worker,
5261
+ effect: "not_live",
5262
+ requestedAt: request.at,
5263
+ observedAt: iso(),
5264
+ ...request.reason === void 0 ? {} : { reason: request.reason },
5265
+ detail: "run ended before the request was applied",
5266
+ terminated: []
5267
+ });
5268
+ continue;
5269
+ }
5270
+ if (record.effect === "cancel_requested") write({
5271
+ ...record,
5272
+ effect: "unknown",
5273
+ observedAt: iso(),
5274
+ detail: "abort issued; run ended before termination was observed"
5275
+ });
5256
5276
  }
5257
- })().finally(() => {
5258
- readyInFlight = void 0;
5259
- });
5260
- return readyInFlight;
5277
+ }
5261
5278
  };
5262
5279
  }
5263
- export { downMessageRefusalReasons as a, createSteerAcknowledger as c, coordinationVerbNames as d, createFileRunContext as f, watchTrace as i, budgetOverspendText as l, withRunContext as m, createCoordinationToolsForManager as n, createEventBus as o, createInMemoryRunContext as p, defaultToolDetectors as r, createCancelAcknowledger as s, createCoordinationTools as t, normalizeAnalyzeOnSettle as u };
5280
+ function isDirectChildNodeId(owner, ref) {
5281
+ return ref.startsWith(`${owner.ownerId}:s`) && /^s\d+$/.test(ref.slice(owner.ownerId.length + 1));
5282
+ }
5283
+ export { defaultToolDetectors as a, budgetOverspendText as c, createEventBus as d, createFileRunContext as f, createCoordinationToolsForManager as i, coordinationVerbNames as l, withRunContext as m, createSteerAcknowledger as n, watchTrace as o, createInMemoryRunContext as p, createCoordinationTools as r, downMessageRefusalReasons as s, createCancelAcknowledger as t, normalizeAnalyzeOnSettle as u };
5264
5284
 
5265
- //# sourceMappingURL=coordination-manager-CFtnSLPw.js.map
5285
+ //# sourceMappingURL=driver-control-acknowledgers-ByKwAgCI.js.map