@tangle-network/agent-runtime 0.193.1 → 0.194.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/dist/{activation-BismttgN.js → activation-BQFIiyUG.js} +3 -3
  2. package/dist/{activation-BismttgN.js.map → activation-BQFIiyUG.js.map} +1 -1
  3. package/dist/agent.d.ts +1 -1
  4. package/dist/agent.js +2 -2
  5. package/dist/candidate-execution/index.js +4 -4
  6. package/dist/{candidate-execution-BSkZErxD.js → candidate-execution-B6CDW-fp.js} +4 -4
  7. package/dist/{candidate-execution-BSkZErxD.js.map → candidate-execution-B6CDW-fp.js.map} +1 -1
  8. package/dist/{conversation-DILnmy84.js → conversation-BXPWMOSd.js} +4 -5
  9. package/dist/{conversation-DILnmy84.js.map → conversation-BXPWMOSd.js.map} +1 -1
  10. package/dist/conversation.d.ts +1 -1
  11. package/dist/conversation.js +1 -1
  12. package/dist/{coordination-driver-DujHiIGa.js → coordination-driver-iSN-m3VX.js} +281 -244
  13. package/dist/coordination-driver-iSN-m3VX.js.map +1 -0
  14. package/dist/{authoring-DWiqKSDY.js → delegate-DCC2muUd.js} +56 -13
  15. package/dist/delegate-DCC2muUd.js.map +1 -0
  16. package/dist/delegation-status-BlsbSeOB.js +358 -0
  17. package/dist/delegation-status-BlsbSeOB.js.map +1 -0
  18. package/dist/durable.d.ts +2 -2
  19. package/dist/durable.js +3 -3
  20. package/dist/{environment-provider-DEwsolvi.js → environment-provider-Dr-wfnHg.js} +422 -8
  21. package/dist/environment-provider-Dr-wfnHg.js.map +1 -0
  22. package/dist/{environment-provider-DpPGJfK-.d.ts → environment-provider-adVa6X7a.d.ts} +2 -2
  23. package/dist/environment-provider.d.ts +1 -1
  24. package/dist/environment-provider.js +1 -1
  25. package/dist/{graph-DORfp9WX.js → graph-DghidDx5.js} +138 -5
  26. package/dist/graph-DghidDx5.js.map +1 -0
  27. package/dist/graph.d.ts +3 -3
  28. package/dist/graph.js +4 -5
  29. package/dist/graph.js.map +1 -1
  30. package/dist/{improve-Bn1zpWHF.d.ts → improve-COGzLCiY.d.ts} +3 -3
  31. package/dist/{improvement-cycle-BbsiYcpH.js → improvement-cycle-DeS1ZC5B.js} +6 -6
  32. package/dist/{improvement-cycle-BbsiYcpH.js.map → improvement-cycle-DeS1ZC5B.js.map} +1 -1
  33. package/dist/{index-DV1lzp9p.d.ts → index-BEPjOPwH.d.ts} +49 -50
  34. package/dist/{index-Vz-13VZq.d.ts → index-CrBgLCIf.d.ts} +4 -4
  35. package/dist/{index-RM2oRI9s.d.ts → index-DO6DHgRP.d.ts} +2 -2
  36. package/dist/index.d.ts +8 -8
  37. package/dist/index.js +13 -13
  38. package/dist/intelligence.d.ts +5 -5
  39. package/dist/intelligence.js +6 -6
  40. package/dist/{executable-spec-DxuiDFAU.js → jsonl-file-Bh1Q9nt0.js} +59 -3
  41. package/dist/jsonl-file-Bh1Q9nt0.js.map +1 -0
  42. package/dist/kernel.d.ts +6 -6
  43. package/dist/kernel.js +11 -12
  44. package/dist/{knowledge-RW1pbZCH.js → knowledge-B5okOzBQ.js} +6 -6
  45. package/dist/{knowledge-RW1pbZCH.js.map → knowledge-B5okOzBQ.js.map} +1 -1
  46. package/dist/knowledge.d.ts +1 -1
  47. package/dist/knowledge.js +1 -1
  48. package/dist/{loop-runner-bin-CGraqNiA.d.ts → loop-runner-bin-Clc5IAwu.d.ts} +3 -3
  49. package/dist/{loop-runner-bin-sBwcyQTc.js → loop-runner-bin-U1J6x_UF.js} +3 -3
  50. package/dist/{loop-runner-bin-sBwcyQTc.js.map → loop-runner-bin-U1J6x_UF.js.map} +1 -1
  51. package/dist/loop-runner-bin.d.ts +1 -1
  52. package/dist/loop-runner-bin.js +1 -1
  53. package/dist/{materialization-CekWK6OO.js → materialization-vZssF9Nx.js} +28 -3
  54. package/dist/materialization-vZssF9Nx.js.map +1 -0
  55. package/dist/mcp/bin.js +3 -3
  56. package/dist/mcp/index.d.ts +4 -4
  57. package/dist/mcp/index.js +8 -8
  58. package/dist/mcp/index.js.map +1 -1
  59. package/dist/{openai-tools-6jUqkGG7.js → openai-tools-DmvmaG0a.js} +2 -2
  60. package/dist/{openai-tools-6jUqkGG7.js.map → openai-tools-DmvmaG0a.js.map} +1 -1
  61. package/dist/{prepare-B5fJ7mLS.js → prepare-C29kNAon.js} +9 -14
  62. package/dist/prepare-C29kNAon.js.map +1 -0
  63. package/dist/primeintellect/index.d.ts +1 -1
  64. package/dist/profiles.js +1 -1
  65. package/dist/{protected-model-port-B0xFSAjt.js → protected-model-port-CKYND416.js} +2 -2
  66. package/dist/{protected-model-port-B0xFSAjt.js.map → protected-model-port-CKYND416.js.map} +1 -1
  67. package/dist/{provision-supervisor-CddfH9mg.js → provision-supervisor-CRPbnJiB.js} +6 -8
  68. package/dist/{provision-supervisor-CddfH9mg.js.map → provision-supervisor-CRPbnJiB.js.map} +1 -1
  69. package/dist/{redact-D0OzQsyt.js → redact-BOU77QfQ.js} +1013 -24
  70. package/dist/redact-BOU77QfQ.js.map +1 -0
  71. package/dist/{researcher-hgPa5p9i.js → researcher-Cp4JRbFp.js} +2 -2
  72. package/dist/researcher-Cp4JRbFp.js.map +1 -0
  73. package/dist/{runtime-V91N6sPc.d.ts → runtime-B8x43nGP.d.ts} +5 -4
  74. package/dist/{runtime-ZM4i-jEF.js → runtime-BVrqSu0-.js} +22 -21
  75. package/dist/{runtime-ZM4i-jEF.js.map → runtime-BVrqSu0-.js.map} +1 -1
  76. package/dist/server-D6XmE1Du.js +1311 -0
  77. package/dist/server-D6XmE1Du.js.map +1 -0
  78. package/dist/{stream-agent-turn-1ahpdeIo.d.ts → stream-agent-turn-B-gtBlOy.d.ts} +2 -2
  79. package/dist/{stream-agent-turn-DWWe_7bh.js → stream-agent-turn-DOtEsvCV.js} +3 -3
  80. package/dist/{stream-agent-turn-DWWe_7bh.js.map → stream-agent-turn-DOtEsvCV.js.map} +1 -1
  81. package/dist/{structural-rollout-CktnUTCC.js → structural-rollout-BcPXFzVb.js} +16 -43
  82. package/dist/structural-rollout-BcPXFzVb.js.map +1 -0
  83. package/dist/{supervise-Dj6zd2C7.js → supervise-C0V3pZXK.js} +154 -1961
  84. package/dist/supervise-C0V3pZXK.js.map +1 -0
  85. package/dist/testing.d.ts +2 -2
  86. package/dist/testing.js +13 -13
  87. package/dist/tui/index.d.ts +1 -1
  88. package/dist/tui/index.js +1 -1
  89. package/dist/{types-CGez_ZHQ.d.ts → types-B_pNTBjK.d.ts} +5 -2
  90. package/dist/{workspace-archive-yAPDklLV.js → workspace-archive-BCezkeIk.js} +2 -2
  91. package/dist/{workspace-archive-yAPDklLV.js.map → workspace-archive-BCezkeIk.js.map} +1 -1
  92. package/package.json +1 -1
  93. package/skills/codemode/SKILL.md +2 -2
  94. package/skills/supervise/SKILL.md +24 -6
  95. package/dist/authoring-DWiqKSDY.js.map +0 -1
  96. package/dist/coordination-driver-DujHiIGa.js.map +0 -1
  97. package/dist/environment-provider-DEwsolvi.js.map +0 -1
  98. package/dist/executable-spec-DxuiDFAU.js.map +0 -1
  99. package/dist/graph-DORfp9WX.js.map +0 -1
  100. package/dist/jsonl-file-CDfsCI5s.js +0 -59
  101. package/dist/jsonl-file-CDfsCI5s.js.map +0 -1
  102. package/dist/materialization-CekWK6OO.js.map +0 -1
  103. package/dist/prepare-B5fJ7mLS.js.map +0 -1
  104. package/dist/redact-D0OzQsyt.js.map +0 -1
  105. package/dist/researcher-hgPa5p9i.js.map +0 -1
  106. package/dist/snapshot-CTAf4uuA.js +0 -26
  107. package/dist/snapshot-CTAf4uuA.js.map +0 -1
  108. package/dist/spawn-journal-B9eTmVAn.js +0 -999
  109. package/dist/spawn-journal-B9eTmVAn.js.map +0 -1
  110. package/dist/structural-rollout-CktnUTCC.js.map +0 -1
  111. package/dist/supervise-Dj6zd2C7.js.map +0 -1
  112. package/dist/util-mCNUeboW.js +0 -419
  113. package/dist/util-mCNUeboW.js.map +0 -1
@@ -1,16 +1,212 @@
1
- import { d as providerAttemptEvidence } from "./materialization-CekWK6OO.js";
1
+ import { E as detachedFrozen, d as providerAttemptEvidence } from "./materialization-vZssF9Nx.js";
2
2
  import { f as RuntimeRunStateError, m as ValidationError } from "./errors-CDZ8XsVj.js";
3
- import { t as detachedFrozen } from "./snapshot-CTAf4uuA.js";
4
- import { b as workerTraceAnalysisStore, i as InMemorySpawnJournal, n as FileSpawnJournal, r as InMemoryResultBlobStore, t as FileResultBlobStore, y as parseWorkerToolTraceArtifact } from "./spawn-journal-B9eTmVAn.js";
5
- import { r as chargedTokens, u as promptCacheTokenClasses, v as unmeteredSpend } from "./util-mCNUeboW.js";
6
- import { i as writeAllBytes, n as parseCommittedJsonLines, r as prepareJsonlAppend, t as isNoEntError } from "./jsonl-file-CDfsCI5s.js";
7
- import { Et as createInbox, Ft as isLiveNodeStatus, It as isTerminalNodeStatus, Q as assertValidBudget, Xt as runBrainLoop, b as meterRuntimeOwnedProviderAttempt, d as pickBestDelivered, f as runFinalizer, h as withDriverExecutor, jt as createPeerMailbox, l as bestDelivered, p as runTree, q as freeSlots, r as resolveRedactor, ut as createExecutorRegistry } from "./redact-D0OzQsyt.js";
3
+ import { i as writeAllBytes, n as parseCommittedJsonLines, r as prepareJsonlAppend, t as isNoEntError } from "./jsonl-file-Bh1Q9nt0.js";
4
+ import { $t as workerTraceAnalysisStore, Bt as FileSpawnJournal, Et as createInbox, Ft as isLiveNodeStatus, Ht as InMemorySpawnJournal, It as isTerminalNodeStatus, Q as assertValidBudget, Qt as parseWorkerToolTraceArtifact, Vt as InMemoryResultBlobStore, b as meterRuntimeOwnedProviderAttempt, d as pickBestDelivered, f as runFinalizer, fn as runBrainLoop, h as withDriverExecutor, jt as createPeerMailbox, l as bestDelivered, p as runTree, q as freeSlots, r as resolveRedactor, ut as createExecutorRegistry, zt as FileResultBlobStore } from "./redact-BOU77QfQ.js";
5
+ import { g as promptCacheTokenClasses, l as chargedTokens, w as unmeteredSpend } from "./environment-provider-Dr-wfnHg.js";
8
6
  import { A as writeWorkerCancellation, M as writeWorkerSteerAcknowledgement, c as readWorkerCancelRequests, d as readWorkerSteerRequests, k as writeRunCancellation, l as readWorkerCancellation, o as readRunCancelRequest, r as claimWorkerSteerDelivery, s as readRunCancellation, u as readWorkerSteerAcknowledgement } from "./run-layout-B8I_LXN-.js";
9
7
  import { agentProfileSchema, canonicalCandidateDigest } from "@tangle-network/agent-interface";
10
8
  import { argHash, errorStreakDetector, observeAll, repeatedActionDetector } from "@tangle-network/agent-eval";
11
9
  import { randomUUID } from "node:crypto";
12
10
  import { readFileSync } from "node:fs";
13
11
  import { join } from "node:path";
12
+ //#region src/runtime/supervise/coordination-log.ts
13
+ /**
14
+ * Durable side-log for coordination evidence the spawn journal does not own: questions, analyst
15
+ * findings, answer decisions, authorized continuation receipts, delivery-attempt markers, and
16
+ * delivery outcomes. A durable run
17
+ * (`supervise({ runDir })`) appends them as they publish and loads them on resume, so a restarted
18
+ * coordinator retains the exact evidence produced by prior processes.
19
+ *
20
+ * Answer down-events also fold status on load: a question answered before the crash reloads as
21
+ * `answered`, not as a re-blocking `open`. Settled events are skipped (the spawn journal is their
22
+ * ledger). A receipt followed by an attempt but no outcome proves the process died in the delivery
23
+ * window; that outcome remains unknown and no prior instruction is auto-delivered.
24
+ *
25
+ * JSONL, one fsynced record per event, keyed by `runId` — several runs may share one log file
26
+ * exactly as they share one spawn-journal file.
27
+ *
28
+ * @experimental
29
+ */
30
+ /** Persist prior context plus exact continuation authorization, attempt, and result evidence.
31
+ * Settlements have their own journal. */
32
+ function persisted(event) {
33
+ return event.type !== "settled";
34
+ }
35
+ /** FS-backed `CoordinationLog`: append-only JSONL, fsynced per record. */
36
+ var FileCoordinationLog = class {
37
+ path;
38
+ appendTail = Promise.resolve();
39
+ constructor(path) {
40
+ this.path = path;
41
+ }
42
+ async append(runId, record, ownerId) {
43
+ if (!persisted(record.event)) return;
44
+ const append = this.appendTail.then(() => this.appendRecord(runId, record, ownerId));
45
+ this.appendTail = append.catch(() => void 0);
46
+ return append;
47
+ }
48
+ async appendRecord(runId, busRecord, ownerId) {
49
+ const fs = await import("node:fs/promises");
50
+ const path = await import("node:path");
51
+ await fs.mkdir(path.dirname(this.path), { recursive: true });
52
+ const record = {
53
+ runId,
54
+ ...ownerId !== void 0 ? { ownerId } : {},
55
+ ...busRecord
56
+ };
57
+ const needsSeparator = await prepareJsonlAppend(this.path);
58
+ const fh = await fs.open(this.path, "a");
59
+ try {
60
+ await writeAllBytes(fh, `${needsSeparator ? "\n" : ""}${JSON.stringify(record)}\n`);
61
+ await fh.sync();
62
+ } finally {
63
+ await fh.close();
64
+ }
65
+ }
66
+ async load(runId, ownerId) {
67
+ const fs = await import("node:fs/promises");
68
+ let text;
69
+ try {
70
+ text = await fs.readFile(this.path, "utf8");
71
+ } catch (err) {
72
+ if (isNoEntError(err)) return emptyPriorCoordination(ownerId);
73
+ throw err;
74
+ }
75
+ const byId = /* @__PURE__ */ new Map();
76
+ const findings = [];
77
+ const escalations = [];
78
+ const analystDefinitions = [];
79
+ const continuations = [];
80
+ const deliveryEvidence = [];
81
+ const mail = [];
82
+ const records = [];
83
+ let legacySeq = 0;
84
+ for (const stored of parseCommittedJsonLines(text, this.path)) {
85
+ if (stored.runId !== runId) continue;
86
+ if (ownerId !== void 0 && stored.ownerId !== ownerId) continue;
87
+ const record = "seq" in stored ? {
88
+ seq: stored.seq,
89
+ at: stored.at,
90
+ priority: stored.priority,
91
+ event: stored.event
92
+ } : {
93
+ seq: legacySeq++,
94
+ at: Date.parse(stored.at),
95
+ priority: 0,
96
+ event: stored.event
97
+ };
98
+ records.push(record);
99
+ const ev = record.event;
100
+ if (ev.type === "delivery-attempt" || ev.type === "steer" || ev.type === "answer") deliveryEvidence.push(ev);
101
+ if (ev.type === "question") byId.set(ev.question.id, ev.question);
102
+ else if (ev.type === "finding") findings.push(ev.finding);
103
+ else if (ev.type === "answer") {
104
+ const prior = byId.get(ev.questionId);
105
+ if (prior && ev.down.delivered) byId.set(ev.questionId, {
106
+ ...prior,
107
+ status: "answered",
108
+ decision: {
109
+ kind: "answer",
110
+ answer: ev.down.instruction,
111
+ by: "prior-run"
112
+ }
113
+ });
114
+ } else if (ev.type === "instruction") continuations.push(ev.instruction);
115
+ else if (ev.type === "mail") mail.push(ev.mail);
116
+ else if (ev.type === "escalation") escalations.push(ev.escalation);
117
+ else if (ev.type === "analyst-defined") analystDefinitions.push(ev.analyst);
118
+ }
119
+ return {
120
+ ...ownerId !== void 0 ? { ownerId } : {},
121
+ questions: [...byId.values()],
122
+ findings,
123
+ escalations,
124
+ analystDefinitions,
125
+ continuations,
126
+ deliveryEvidence,
127
+ mail,
128
+ records
129
+ };
130
+ }
131
+ };
132
+ function emptyPriorCoordination(ownerId) {
133
+ return {
134
+ ...ownerId !== void 0 ? { ownerId } : {},
135
+ questions: [],
136
+ findings: [],
137
+ escalations: [],
138
+ analystDefinitions: [],
139
+ continuations: [],
140
+ deliveryEvidence: [],
141
+ mail: [],
142
+ records: []
143
+ };
144
+ }
145
+ //#endregion
146
+ //#region src/runtime/supervise/run-context.ts
147
+ /**
148
+ *
149
+ * `createInMemoryRunContext` — the one-call bundle of the in-memory stores a
150
+ * `createSupervisor().run(root, task, opts)` needs: a fresh `InMemorySpawnJournal`
151
+ * (the event-sourced spawn log), a fresh `InMemoryResultBlobStore` (the
152
+ * content-addressed `outRef` payload store the driver's `observe`/`finalize` reads
153
+ * settled outputs through), and a fresh `createExecutorRegistry()` (the open
154
+ * `AgentSpec → Executor` resolver).
155
+ *
156
+ * It exists to kill the boilerplate every offline/local supervised run repeats by
157
+ * hand — three constructors threaded into `SupervisorOpts` — and to single-source the
158
+ * ONE wiring invariant that is easy to get wrong: when the root is the recursive
159
+ * `driverAgent` LLM-driver brain AND it may spawn nested managed children, the registry MUST be
160
+ * wrapped with `withDriverExecutor` so a child constructed by `driverChild` resolves to the
161
+ * nested-scope executor — and that SAME blob
162
+ * store MUST be the one passed to `driverAgent({ blobs })`, or the driver
163
+ * reads from a different store than the scope writes to. Pass `{ withDriver: true }`
164
+ * and reuse the returned `blobs` for both.
165
+ *
166
+ * The spread shape matches `SupervisorOpts` exactly, so the call site reads:
167
+ * const run = createInMemoryRunContext()
168
+ * await createSupervisor().run(root, task, { budget, runId, ...run })
169
+ *
170
+ * @experimental
171
+ */
172
+ /**
173
+ * Build a fresh in-memory run context. Every call returns NEW stores (no shared global
174
+ * state between runs), so two runs never cross-contaminate their journals/blobs.
175
+ */
176
+ function createInMemoryRunContext(opts = {}) {
177
+ const base = createExecutorRegistry();
178
+ return {
179
+ journal: new InMemorySpawnJournal(),
180
+ blobs: new InMemoryResultBlobStore(),
181
+ executors: opts.withDriver ? withDriverExecutor(base) : base
182
+ };
183
+ }
184
+ /**
185
+ * Build a DURABLE run context: the spawn journal and the result blobs are file-backed (fsynced
186
+ * per append/write) under `dir`, and the context carries `resume: true` so spreading it into
187
+ * `SupervisorOpts` makes the supervisor `loadTree`-first. A run that dies mid-flight therefore
188
+ * resumes when it is re-run with the SAME `runId` and the SAME `dir`: the committed children come
189
+ * back on `Scope.resume` (rehydrated by `replaySpawnTree`) instead of being re-executed.
190
+ *
191
+ * Layout: `${dir}/spawn-journal.jsonl` (one JSONL record per event), `${dir}/blobs/` (one
192
+ * content-addressed JSON file per settled result), and `${dir}/coordination-log.jsonl`
193
+ * (questions, findings, answer decisions, and authorized continuation receipts retained as
194
+ * evidence). The directory is created on first write.
195
+ *
196
+ * Opt-in by construction — `createInMemoryRunContext()` is unchanged and stays the default, so no
197
+ * existing consumer writes to disk or resumes unless it asks for this.
198
+ */
199
+ function createFileRunContext(dir, opts = {}) {
200
+ const base = createExecutorRegistry();
201
+ return {
202
+ journal: new FileSpawnJournal(`${dir}/spawn-journal.jsonl`),
203
+ blobs: new FileResultBlobStore(`${dir}/blobs`),
204
+ executors: opts.withDriver ? withDriverExecutor(base) : base,
205
+ resume: true,
206
+ coordinationLog: new FileCoordinationLog(`${dir}/coordination-log.jsonl`)
207
+ };
208
+ }
209
+ //#endregion
14
210
  //#region src/runtime/supervise/detector-monitor.ts
15
211
  /**
16
212
  *
@@ -392,6 +588,7 @@ const journalEventKinds = [
392
588
  "question",
393
589
  "settled",
394
590
  "finding",
591
+ "submission",
395
592
  "steer",
396
593
  "answer",
397
594
  "instruction",
@@ -616,10 +813,12 @@ function spawnProfileArg() {
616
813
  /** Build the driver's MCP tools over a live scope. */
617
814
  function createCoordinationTools(opts) {
618
815
  const deliverable = opts.deliverable;
619
- let stopped = false;
620
- let reason;
816
+ const priorSubmission = deliverable === void 0 ? void 0 : opts.priorJournal?.find((record) => record.event.type === "submission");
817
+ let stopped = priorSubmission !== void 0;
818
+ let reason = priorSubmission === void 0 ? void 0 : "result-accepted";
621
819
  let stopNotified = false;
622
- let submitted;
820
+ let submitted = priorSubmission === void 0 ? void 0 : detachedFrozen({ result: priorSubmission.event.result });
821
+ let submissionInFlight;
623
822
  let questionSeq = 0;
624
823
  const ledger = [];
625
824
  const questions = [...opts.priorQuestions ?? []];
@@ -1174,6 +1373,10 @@ function createCoordinationTools(opts) {
1174
1373
  type: "finding",
1175
1374
  ...ev.finding
1176
1375
  };
1376
+ if (ev.type === "submission") return {
1377
+ type: "submission",
1378
+ result: ev.result
1379
+ };
1177
1380
  if (ev.type === "answer") return {
1178
1381
  type: "answer",
1179
1382
  ...ev.down,
@@ -2042,10 +2245,30 @@ function createCoordinationTools(opts) {
2042
2245
  retained: "earlier-passing-result",
2043
2246
  stop: true
2044
2247
  };
2045
- submitted = Object.freeze({ result });
2046
- stopped = true;
2047
- reason = "result-accepted";
2048
- notifyStop();
2248
+ if (submissionInFlight) {
2249
+ await submissionInFlight;
2250
+ return {
2251
+ accepted: true,
2252
+ retained: "earlier-passing-result",
2253
+ stop: true
2254
+ };
2255
+ }
2256
+ const acceptedSubmission = detachedFrozen({ result });
2257
+ const commit = bus.publish({
2258
+ type: "submission",
2259
+ result: acceptedSubmission.result
2260
+ }, { queue: false }).then(() => {
2261
+ submitted = acceptedSubmission;
2262
+ stopped = true;
2263
+ reason = "result-accepted";
2264
+ notifyStop();
2265
+ });
2266
+ submissionInFlight = commit;
2267
+ try {
2268
+ await commit;
2269
+ } finally {
2270
+ if (submissionInFlight === commit) submissionInFlight = void 0;
2271
+ }
2049
2272
  return {
2050
2273
  accepted: true,
2051
2274
  retained: "this-result",
@@ -2332,204 +2555,6 @@ function safeJsonText(value) {
2332
2555
  }
2333
2556
  }
2334
2557
  //#endregion
2335
- //#region src/runtime/supervise/coordination-log.ts
2336
- /**
2337
- * Durable side-log for coordination evidence the spawn journal does not own: questions, analyst
2338
- * findings, answer decisions, authorized continuation receipts, delivery-attempt markers, and
2339
- * delivery outcomes. A durable run
2340
- * (`supervise({ runDir })`) appends them as they publish and loads them on resume, so a restarted
2341
- * coordinator retains the exact evidence produced by prior processes.
2342
- *
2343
- * Answer down-events also fold status on load: a question answered before the crash reloads as
2344
- * `answered`, not as a re-blocking `open`. Settled events are skipped (the spawn journal is their
2345
- * ledger). A receipt followed by an attempt but no outcome proves the process died in the delivery
2346
- * window; that outcome remains unknown and no prior instruction is auto-delivered.
2347
- *
2348
- * JSONL, one fsynced record per event, keyed by `runId` — several runs may share one log file
2349
- * exactly as they share one spawn-journal file.
2350
- *
2351
- * @experimental
2352
- */
2353
- /** Persist prior context plus exact continuation authorization, attempt, and result evidence.
2354
- * Settlements have their own journal. */
2355
- function persisted(event) {
2356
- return event.type !== "settled";
2357
- }
2358
- /** FS-backed `CoordinationLog`: append-only JSONL, fsynced per record. */
2359
- var FileCoordinationLog = class {
2360
- path;
2361
- appendTail = Promise.resolve();
2362
- constructor(path) {
2363
- this.path = path;
2364
- }
2365
- async append(runId, record, ownerId) {
2366
- if (!persisted(record.event)) return;
2367
- const append = this.appendTail.then(() => this.appendRecord(runId, record, ownerId));
2368
- this.appendTail = append.catch(() => void 0);
2369
- return append;
2370
- }
2371
- async appendRecord(runId, busRecord, ownerId) {
2372
- const fs = await import("node:fs/promises");
2373
- const path = await import("node:path");
2374
- await fs.mkdir(path.dirname(this.path), { recursive: true });
2375
- const record = {
2376
- runId,
2377
- ...ownerId !== void 0 ? { ownerId } : {},
2378
- ...busRecord
2379
- };
2380
- const needsSeparator = await prepareJsonlAppend(this.path);
2381
- const fh = await fs.open(this.path, "a");
2382
- try {
2383
- await writeAllBytes(fh, `${needsSeparator ? "\n" : ""}${JSON.stringify(record)}\n`);
2384
- await fh.sync();
2385
- } finally {
2386
- await fh.close();
2387
- }
2388
- }
2389
- async load(runId, ownerId) {
2390
- const fs = await import("node:fs/promises");
2391
- let text;
2392
- try {
2393
- text = await fs.readFile(this.path, "utf8");
2394
- } catch (err) {
2395
- if (isNoEntError(err)) return emptyPriorCoordination(ownerId);
2396
- throw err;
2397
- }
2398
- const byId = /* @__PURE__ */ new Map();
2399
- const findings = [];
2400
- const escalations = [];
2401
- const analystDefinitions = [];
2402
- const continuations = [];
2403
- const deliveryEvidence = [];
2404
- const mail = [];
2405
- const records = [];
2406
- let legacySeq = 0;
2407
- for (const stored of parseCommittedJsonLines(text, this.path)) {
2408
- if (stored.runId !== runId) continue;
2409
- if (ownerId !== void 0 && stored.ownerId !== ownerId) continue;
2410
- const record = "seq" in stored ? {
2411
- seq: stored.seq,
2412
- at: stored.at,
2413
- priority: stored.priority,
2414
- event: stored.event
2415
- } : {
2416
- seq: legacySeq++,
2417
- at: Date.parse(stored.at),
2418
- priority: 0,
2419
- event: stored.event
2420
- };
2421
- records.push(record);
2422
- const ev = record.event;
2423
- if (ev.type === "delivery-attempt" || ev.type === "steer" || ev.type === "answer") deliveryEvidence.push(ev);
2424
- if (ev.type === "question") byId.set(ev.question.id, ev.question);
2425
- else if (ev.type === "finding") findings.push(ev.finding);
2426
- else if (ev.type === "answer") {
2427
- const prior = byId.get(ev.questionId);
2428
- if (prior && ev.down.delivered) byId.set(ev.questionId, {
2429
- ...prior,
2430
- status: "answered",
2431
- decision: {
2432
- kind: "answer",
2433
- answer: ev.down.instruction,
2434
- by: "prior-run"
2435
- }
2436
- });
2437
- } else if (ev.type === "instruction") continuations.push(ev.instruction);
2438
- else if (ev.type === "mail") mail.push(ev.mail);
2439
- else if (ev.type === "escalation") escalations.push(ev.escalation);
2440
- else if (ev.type === "analyst-defined") analystDefinitions.push(ev.analyst);
2441
- }
2442
- return {
2443
- ...ownerId !== void 0 ? { ownerId } : {},
2444
- questions: [...byId.values()],
2445
- findings,
2446
- escalations,
2447
- analystDefinitions,
2448
- continuations,
2449
- deliveryEvidence,
2450
- mail,
2451
- records
2452
- };
2453
- }
2454
- };
2455
- function emptyPriorCoordination(ownerId) {
2456
- return {
2457
- ...ownerId !== void 0 ? { ownerId } : {},
2458
- questions: [],
2459
- findings: [],
2460
- escalations: [],
2461
- analystDefinitions: [],
2462
- continuations: [],
2463
- deliveryEvidence: [],
2464
- mail: [],
2465
- records: []
2466
- };
2467
- }
2468
- //#endregion
2469
- //#region src/runtime/supervise/run-context.ts
2470
- /**
2471
- *
2472
- * `createInMemoryRunContext` — the one-call bundle of the in-memory stores a
2473
- * `createSupervisor().run(root, task, opts)` needs: a fresh `InMemorySpawnJournal`
2474
- * (the event-sourced spawn log), a fresh `InMemoryResultBlobStore` (the
2475
- * content-addressed `outRef` payload store the driver's `observe`/`finalize` reads
2476
- * settled outputs through), and a fresh `createExecutorRegistry()` (the open
2477
- * `AgentSpec → Executor` resolver).
2478
- *
2479
- * It exists to kill the boilerplate every offline/local supervised run repeats by
2480
- * hand — three constructors threaded into `SupervisorOpts` — and to single-source the
2481
- * ONE wiring invariant that is easy to get wrong: when the root is the recursive
2482
- * `driverAgent` LLM-driver brain AND it may spawn DRIVER children (agents
2483
- * driving agents), the registry MUST be wrapped with `withDriverExecutor` so a
2484
- * `role: 'driver'` child resolves to the nested-scope executor — and that SAME blob
2485
- * store MUST be the one passed to `driverAgent({ blobs })`, or the driver
2486
- * reads from a different store than the scope writes to. Pass `{ withDriver: true }`
2487
- * and reuse the returned `blobs` for both.
2488
- *
2489
- * The spread shape matches `SupervisorOpts` exactly, so the call site reads:
2490
- * const run = createInMemoryRunContext()
2491
- * await createSupervisor().run(root, task, { budget, runId, ...run })
2492
- *
2493
- * @experimental
2494
- */
2495
- /**
2496
- * Build a fresh in-memory run context. Every call returns NEW stores (no shared global
2497
- * state between runs), so two runs never cross-contaminate their journals/blobs.
2498
- */
2499
- function createInMemoryRunContext(opts = {}) {
2500
- const base = createExecutorRegistry();
2501
- return {
2502
- journal: new InMemorySpawnJournal(),
2503
- blobs: new InMemoryResultBlobStore(),
2504
- executors: opts.withDriver ? withDriverExecutor(base) : base
2505
- };
2506
- }
2507
- /**
2508
- * Build a DURABLE run context: the spawn journal and the result blobs are file-backed (fsynced
2509
- * per append/write) under `dir`, and the context carries `resume: true` so spreading it into
2510
- * `SupervisorOpts` makes the supervisor `loadTree`-first. A run that dies mid-flight therefore
2511
- * resumes when it is re-run with the SAME `runId` and the SAME `dir`: the committed children come
2512
- * back on `Scope.resume` (rehydrated by `replaySpawnTree`) instead of being re-executed.
2513
- *
2514
- * Layout: `${dir}/spawn-journal.jsonl` (one JSONL record per event), `${dir}/blobs/` (one
2515
- * content-addressed JSON file per settled result), and `${dir}/coordination-log.jsonl`
2516
- * (questions, findings, answer decisions, and authorized continuation receipts retained as
2517
- * evidence). The directory is created on first write.
2518
- *
2519
- * Opt-in by construction — `createInMemoryRunContext()` is unchanged and stays the default, so no
2520
- * existing consumer writes to disk or resumes unless it asks for this.
2521
- */
2522
- function createFileRunContext(dir, opts = {}) {
2523
- const base = createExecutorRegistry();
2524
- return {
2525
- journal: new FileSpawnJournal(`${dir}/spawn-journal.jsonl`),
2526
- blobs: new FileResultBlobStore(`${dir}/blobs`),
2527
- executors: opts.withDriver ? withDriverExecutor(base) : base,
2528
- resume: true,
2529
- coordinationLog: new FileCoordinationLog(`${dir}/coordination-log.jsonl`)
2530
- };
2531
- }
2532
- //#endregion
2533
2558
  //#region src/runtime/anytime.ts
2534
2559
  /**
2535
2560
  * The best-so-far fold — the ONE definition of "how good was the run after k results", shared by
@@ -3346,6 +3371,8 @@ function terminatedDescendants(dir, nodeId, sinceIso) {
3346
3371
  */
3347
3372
  function driverAgent(opts) {
3348
3373
  if (typeof opts.brain !== "function") throw new ValidationError("driverAgent: opts.brain must be a function");
3374
+ if (!Array.isArray(opts.toolNames)) throw new ValidationError("driverAgent: toolNames must name every granted tool explicitly");
3375
+ if (new Set(opts.toolNames).size !== opts.toolNames.length) throw new ValidationError("driverAgent: toolNames contains a duplicate name");
3349
3376
  if ((opts.extraTools?.length ?? 0) > 0 && typeof opts.executeExtraTool !== "function") throw new ValidationError("driverAgent: extraTools requires executeExtraTool (how to run a work-tool call)");
3350
3377
  if ((opts.analyzeOnSettle ?? []).map(normalizeAnalyzeOnSettle).some((route) => route.agent === void 0) && !opts.analysts) throw new ValidationError("driverAgent: analyzeOnSettle requires analysts (the lens registry the kinds resolve against)");
3351
3378
  const reserved = new Set(coordinationVerbNames);
@@ -3391,7 +3418,25 @@ function driverAgent(opts) {
3391
3418
  ...opts.priorCoordination?.analystDefinitions?.length ? { priorAnalystDefinitions: opts.priorCoordination.analystDefinitions } : {}
3392
3419
  });
3393
3420
  await coord.ready();
3394
- opts.onCoordinationTools?.(coord.tools);
3421
+ const availableTools = [...coord.tools, ...opts.nodeTools ?? []];
3422
+ const availableByName = new Map(availableTools.map((tool) => [tool.name, tool]));
3423
+ const extraByName = new Map((opts.extraTools ?? []).map((tool) => [tool.name, tool]));
3424
+ const selectedTools = opts.toolNames.map((name) => {
3425
+ const descriptor = availableByName.get(name);
3426
+ if (descriptor !== void 0) return {
3427
+ kind: "descriptor",
3428
+ descriptor
3429
+ };
3430
+ const extra = extraByName.get(name);
3431
+ if (extra === void 0) throw new ValidationError(`driverAgent: requested tool ${JSON.stringify(name)} is unavailable`);
3432
+ return {
3433
+ kind: "extra",
3434
+ extra
3435
+ };
3436
+ });
3437
+ const modelTools = selectedTools.flatMap((selected) => selected.kind === "descriptor" ? [selected.descriptor] : []);
3438
+ const selectedExtraNames = new Set(selectedTools.flatMap((selected) => selected.kind === "extra" ? [selected.extra.name] : []));
3439
+ opts.onCoordinationTools?.(modelTools);
3395
3440
  const acknowledger = opts.controlDir === void 0 ? void 0 : createCancelAcknowledger({
3396
3441
  dir: opts.controlDir,
3397
3442
  coord,
@@ -3411,33 +3456,22 @@ function driverAgent(opts) {
3411
3456
  const rearmed = scope.wait(w.spec, { label: w.label });
3412
3457
  if (!rearmed.ok) throw new RuntimeRunStateError(`driverAgent: cannot re-arm resumed wait '${w.label}' (${rearmed.reason})`);
3413
3458
  }
3414
- const byName = new Map([...coord.tools, ...opts.nodeTools ?? []].map((t) => [t.name, t]));
3415
- const toolSpecs = [
3416
- ...coord.tools.map((t) => ({
3417
- type: "function",
3418
- function: {
3419
- name: t.name,
3420
- description: t.description,
3421
- parameters: t.inputSchema
3422
- }
3423
- })),
3424
- ...(opts.nodeTools ?? []).map((t) => ({
3425
- type: "function",
3426
- function: {
3427
- name: t.name,
3428
- description: t.description,
3429
- parameters: t.inputSchema
3430
- }
3431
- })),
3432
- ...(opts.extraTools ?? []).map((t) => ({
3433
- type: "function",
3434
- function: {
3435
- name: t.name,
3436
- description: t.description,
3437
- parameters: t.parameters
3438
- }
3439
- }))
3440
- ];
3459
+ const byName = new Map(modelTools.map((tool) => [tool.name, tool]));
3460
+ const toolSpecs = selectedTools.map((selected) => selected.kind === "descriptor" ? {
3461
+ type: "function",
3462
+ function: {
3463
+ name: selected.descriptor.name,
3464
+ description: selected.descriptor.description,
3465
+ parameters: selected.descriptor.inputSchema
3466
+ }
3467
+ } : {
3468
+ type: "function",
3469
+ function: {
3470
+ name: selected.extra.name,
3471
+ description: selected.extra.description,
3472
+ parameters: selected.extra.parameters
3473
+ }
3474
+ });
3441
3475
  const system = typeof opts.systemPrompt === "function" ? opts.systemPrompt(task) : opts.systemPrompt;
3442
3476
  const tracker = opts.stopRule ? createProgressTracker({ now }) : void 0;
3443
3477
  let progressStopReason;
@@ -3538,7 +3572,7 @@ function driverAgent(opts) {
3538
3572
  tools: toolSpecs,
3539
3573
  ...compaction ? { compaction } : {},
3540
3574
  execute: async (name, args) => {
3541
- if (opts.executeExtraTool) {
3575
+ if (opts.executeExtraTool && selectedExtraNames.has(name)) {
3542
3576
  const worked = await runExtraTool(opts.executeExtraTool, name, args);
3543
3577
  if (worked !== null && worked !== void 0) return worked;
3544
3578
  }
@@ -3591,7 +3625,10 @@ function driverAgent(opts) {
3591
3625
  acknowledger?.pass("final");
3592
3626
  acknowledger?.finish();
3593
3627
  const submitted = coord.submittedResult();
3594
- if (submitted) return submitted.result;
3628
+ if (submitted) {
3629
+ opts.onAcceptedSubmission?.(submitted.result);
3630
+ return submitted.result;
3631
+ }
3595
3632
  return runFinalizer(opts.finalizer ?? bestDelivered, {
3596
3633
  settled: coord.settled(),
3597
3634
  blobs: opts.blobs,
@@ -3632,7 +3669,7 @@ function resumeBrief(resume, prior) {
3632
3669
  return lines.join("\n");
3633
3670
  }
3634
3671
  function hasPriorCoordination(prior) {
3635
- return prior !== void 0 && (prior.questions.length > 0 || prior.findings.length > 0 || prior.continuations.length > 0 || prior.deliveryEvidence.length > 0);
3672
+ return prior !== void 0 && (prior.questions.length > 0 || prior.findings.length > 0 || prior.continuations.length > 0 || prior.deliveryEvidence.length > 0 || prior.records.some((record) => record.event.type === "submission"));
3636
3673
  }
3637
3674
  function priorCoordinationBrief(prior) {
3638
3675
  const lines = [
@@ -3699,6 +3736,6 @@ function errMessage(e) {
3699
3736
  return e instanceof Error ? e.message : String(e);
3700
3737
  }
3701
3738
  //#endregion
3702
- export { questionEscalationTargets as A, analystToolGroupNames as C, downMessageRefusalReasons as D, createCoordinationTools as E, defaultToolDetectors as M, watchTrace as N, normalizeAnalyzeOnSettle as O, DEFAULT_AWAIT_EVENT_TIMEOUT_MS as S, coordinationVerbNames as T, renderAnytimeTable as _, allOf as a, FileCoordinationLog as b, createProgressTracker as c, progressStop as d, sampleFromSettled as f, plateauLength as g, bestSoFar as h, finalizeBestDelivered as i, createEventBus as j, parseAuthoredAnalystDefinition as k, noProgressFor as l, areaUnderCurve as m, createSteerAcknowledger as n, allWorkersStalled as o, anytimeReport as p, driverAgent as r, anyOf as s, createCancelAcknowledger as t, plateau as u, createFileRunContext as v, canonicalFindingEvent as w, ANALYST_DEFINITION_BOUNDS as x, createInMemoryRunContext as y };
3739
+ export { watchTrace as A, createCoordinationTools as C, questionEscalationTargets as D, parseAuthoredAnalystDefinition as E, createInMemoryRunContext as M, FileCoordinationLog as N, createEventBus as O, coordinationVerbNames as S, normalizeAnalyzeOnSettle as T, renderAnytimeTable as _, allOf as a, analystToolGroupNames as b, createProgressTracker as c, progressStop as d, sampleFromSettled as f, plateauLength as g, bestSoFar as h, finalizeBestDelivered as i, createFileRunContext as j, defaultToolDetectors as k, noProgressFor as l, areaUnderCurve as m, createSteerAcknowledger as n, allWorkersStalled as o, anytimeReport as p, driverAgent as r, anyOf as s, createCancelAcknowledger as t, plateau as u, ANALYST_DEFINITION_BOUNDS as v, downMessageRefusalReasons as w, canonicalFindingEvent as x, DEFAULT_AWAIT_EVENT_TIMEOUT_MS as y };
3703
3740
 
3704
- //# sourceMappingURL=coordination-driver-DujHiIGa.js.map
3741
+ //# sourceMappingURL=coordination-driver-iSN-m3VX.js.map