@tangle-network/agent-runtime 0.107.4 → 0.108.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 (64) hide show
  1. package/README.md +17 -4
  2. package/dist/{activation-Ck5ksFWg.js → activation-DRpnplEm.js} +3 -3
  3. package/dist/{activation-Ck5ksFWg.js.map → activation-DRpnplEm.js.map} +1 -1
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +2 -2
  6. package/dist/candidate-execution/index.js +4 -4
  7. package/dist/{candidate-execution-BUpR0mSD.js → candidate-execution-nYMa-bc-.js} +4 -4
  8. package/dist/{candidate-execution-BUpR0mSD.js.map → candidate-execution-nYMa-bc-.js.map} +1 -1
  9. package/dist/durable.d.ts +134 -0
  10. package/dist/durable.js +124 -0
  11. package/dist/durable.js.map +1 -0
  12. package/dist/{environment-provider-IUGU3epE.d.ts → environment-provider-D0NXc4Qz.d.ts} +73 -4
  13. package/dist/environment-provider.d.ts +1 -1
  14. package/dist/{improvement-cycle-Ulvvbg5p.js → improvement-cycle-CRnDDdX0.js} +49 -155
  15. package/dist/improvement-cycle-CRnDDdX0.js.map +1 -0
  16. package/dist/{index-CeawCSEg.d.ts → index-BZbJWqoZ.d.ts} +175 -27
  17. package/dist/{index-D6MwUzvB.d.ts → index-DQp3BPeC.d.ts} +11 -159
  18. package/dist/{index-jmFVBIHo.d.ts → index-cdkwHruJ.d.ts} +3 -3
  19. package/dist/index.d.ts +6 -6
  20. package/dist/index.js +14 -121
  21. package/dist/index.js.map +1 -1
  22. package/dist/intelligence.d.ts +15 -7
  23. package/dist/intelligence.js +4 -4
  24. package/dist/{knowledge-Dizh_AtL.js → knowledge-rdrpPIXs.js} +5 -5
  25. package/dist/{knowledge-Dizh_AtL.js.map → knowledge-rdrpPIXs.js.map} +1 -1
  26. package/dist/knowledge.d.ts +1 -1
  27. package/dist/knowledge.js +1 -1
  28. package/dist/{loop-runner-bin-BbYG9CeA.d.ts → loop-runner-bin-9-JlGqN7.d.ts} +3 -3
  29. package/dist/{loop-runner-bin-CvdKZkE4.js → loop-runner-bin-B1V-XS5A.js} +3 -3
  30. package/dist/{loop-runner-bin-CvdKZkE4.js.map → loop-runner-bin-B1V-XS5A.js.map} +1 -1
  31. package/dist/loop-runner-bin.d.ts +1 -1
  32. package/dist/loop-runner-bin.js +1 -1
  33. package/dist/loops.d.ts +3 -3
  34. package/dist/loops.js +5 -5
  35. package/dist/mcp/bin.js +1 -1
  36. package/dist/mcp/index.d.ts +1 -1
  37. package/dist/mcp/index.js +4 -4
  38. package/dist/{openai-tools-CKLy1C7M.js → openai-tools-BjQq2TTL.js} +2 -2
  39. package/dist/{openai-tools-CKLy1C7M.js.map → openai-tools-BjQq2TTL.js.map} +1 -1
  40. package/dist/{prepare-_WTTffkz.js → prepare-Pr19X93k.js} +141 -6
  41. package/dist/prepare-Pr19X93k.js.map +1 -0
  42. package/dist/primeintellect/index.d.ts +1 -1
  43. package/dist/{protected-model-port-ZUwVuftA.js → protected-model-port-uthtDNqu.js} +2 -2
  44. package/dist/{protected-model-port-ZUwVuftA.js.map → protected-model-port-uthtDNqu.js.map} +1 -1
  45. package/dist/{redact-C5xOm8cu.d.ts → redact-BkasKlyd.d.ts} +17 -27
  46. package/dist/{runtime-5zM5XxLr.js → runtime-CDekUROm.js} +20 -13
  47. package/dist/runtime-CDekUROm.js.map +1 -0
  48. package/dist/{structural-rollout-IXUEplky.js → structural-rollout-BC81Otmc.js} +10 -9
  49. package/dist/structural-rollout-BC81Otmc.js.map +1 -0
  50. package/dist/{supervise-BiRutHS9.js → supervise-JfKPwIlO.js} +270 -69
  51. package/dist/supervise-JfKPwIlO.js.map +1 -0
  52. package/dist/{supervisor-DTKhF-RV.js → supervisor-B2LzaWRb.js} +221 -16
  53. package/dist/supervisor-B2LzaWRb.js.map +1 -0
  54. package/dist/testing.js +3544 -657
  55. package/dist/testing.js.map +1 -1
  56. package/dist/{workspace-archive-CIG1VNCj.js → workspace-archive-C9w_rxt6.js} +2 -2
  57. package/dist/{workspace-archive-CIG1VNCj.js.map → workspace-archive-C9w_rxt6.js.map} +1 -1
  58. package/package.json +11 -6
  59. package/dist/improvement-cycle-Ulvvbg5p.js.map +0 -1
  60. package/dist/prepare-_WTTffkz.js.map +0 -1
  61. package/dist/runtime-5zM5XxLr.js.map +0 -1
  62. package/dist/structural-rollout-IXUEplky.js.map +0 -1
  63. package/dist/supervise-BiRutHS9.js.map +0 -1
  64. package/dist/supervisor-DTKhF-RV.js.map +0 -1
@@ -1,7 +1,7 @@
1
- import { i as ConfigError, o as NotFoundError, t as AgentEvalError$1, u as ValidationError } from "./errors-DEAvWQPy.js";
1
+ import { c as RuntimeRunStateError, i as ConfigError, o as NotFoundError, t as AgentEvalError$1, u as ValidationError } from "./errors-DEAvWQPy.js";
2
2
  import { a as randomSuffix, c as stringifySafe, d as withTimeout, f as zeroTokenUsage, i as mapWithConcurrency, l as throwAbort, n as deleteBoxSafe, o as randomUuid, s as sleep, t as addTokenUsage, u as throwIfAborted } from "./util-MVgdwuIS.js";
3
3
  import { a as contentAddress, i as InMemorySpawnJournal, n as FileSpawnJournal, r as InMemoryResultBlobStore, t as FileResultBlobStore } from "./spawn-journal-CwPvKUTa.js";
4
- import { A as removeWorktree, D as runWorktreeHarness, E as runWorktreeChecks, O as captureWorktreeDiff, S as routerChatWithUsage, b as routerBrain, i as withDriverExecutor, k as createWorktree, m as createActivityLog, t as createSupervisor, w as runBrainLoop, y as notifyRuntimeHookEvent } from "./supervisor-DTKhF-RV.js";
4
+ import { D as routerChatWithUsage, F as removeWorktree, M as runWorktreeHarness, N as captureWorktreeDiff, P as createWorktree, T as routerBrain, a as runFinalizer, i as pickBestDelivered, j as runWorktreeChecks, k as runBrainLoop, l as withDriverExecutor, n as bestDelivered, o as runTree, t as createSupervisor, w as notifyRuntimeHookEvent, y as createActivityLog } from "./supervisor-B2LzaWRb.js";
5
5
  import { a as notifySandboxEventObserver, n as extractLlmCallEvent } from "./sandbox-events-DeI5xX8P.js";
6
6
  import { i as resolveAgentEnvironmentProvider, n as providerAsExecutor } from "./environment-provider-CfLUmKmf.js";
7
7
  import { r as buildLoopSpanNodes } from "./otel-export-D34IQW1C.js";
@@ -90,6 +90,80 @@ function assertModelAllowed(model, allowed) {
90
90
  if (!allowed.includes(model)) throw new ConfigError(`model ${JSON.stringify(model)} is not in the allowed set ${JSON.stringify([...allowed])}`);
91
91
  }
92
92
  //#endregion
93
+ //#region src/runtime/supervise/coordination-log.ts
94
+ /** Should this bus event be persisted? Questions and findings ARE the prior context a resumed
95
+ * driver needs; answers fold their status; everything else has a better ledger or none. */
96
+ function persisted(event) {
97
+ return event.type === "question" || event.type === "finding" || event.type === "answer";
98
+ }
99
+ /** FS-backed `CoordinationLog`: append-only JSONL, fsynced per record. */
100
+ var FileCoordinationLog = class {
101
+ path;
102
+ constructor(path) {
103
+ this.path = path;
104
+ }
105
+ async append(runId, event, at) {
106
+ if (!persisted(event)) return;
107
+ const fs = await import("node:fs/promises");
108
+ const path = await import("node:path");
109
+ await fs.mkdir(path.dirname(this.path), { recursive: true });
110
+ const record = {
111
+ runId,
112
+ at,
113
+ event
114
+ };
115
+ const fh = await fs.open(this.path, "a");
116
+ try {
117
+ await fh.write(`${JSON.stringify(record)}\n`);
118
+ await fh.sync();
119
+ } finally {
120
+ await fh.close();
121
+ }
122
+ }
123
+ async load(runId) {
124
+ const fs = await import("node:fs/promises");
125
+ let text;
126
+ try {
127
+ text = await fs.readFile(this.path, "utf8");
128
+ } catch (err) {
129
+ if (isNoEntError(err)) return {
130
+ questions: [],
131
+ findings: []
132
+ };
133
+ throw err;
134
+ }
135
+ const byId = /* @__PURE__ */ new Map();
136
+ const findings = [];
137
+ for (const line of text.split("\n")) {
138
+ if (line.length === 0) continue;
139
+ const record = JSON.parse(line);
140
+ if (record.runId !== runId) continue;
141
+ const ev = record.event;
142
+ if (ev.type === "question") byId.set(ev.question.id, ev.question);
143
+ else if (ev.type === "finding") findings.push(ev.finding);
144
+ else if (ev.type === "answer") {
145
+ const prior = byId.get(ev.questionId);
146
+ if (prior) byId.set(ev.questionId, {
147
+ ...prior,
148
+ status: "answered",
149
+ decision: {
150
+ kind: "answer",
151
+ answer: ev.down.instruction,
152
+ by: "prior-run"
153
+ }
154
+ });
155
+ }
156
+ }
157
+ return {
158
+ questions: [...byId.values()],
159
+ findings
160
+ };
161
+ }
162
+ };
163
+ function isNoEntError(err) {
164
+ return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
165
+ }
166
+ //#endregion
93
167
  //#region src/runtime/sandbox-acquire.ts
94
168
  /**
95
169
  * HTTP statuses where create should be retried — gateway timeouts
@@ -979,7 +1053,7 @@ async function invokePrepareBox(spec, box, signal, recordMount) {
979
1053
  }
980
1054
  /** Shared no-op recorder for box-preparation paths that have no run manifest. */
981
1055
  const noopMountRecorder = () => {};
982
- function finalize$1(args) {
1056
+ function finalize(args) {
983
1057
  let selector;
984
1058
  let winner;
985
1059
  if (args.options.selectWinner) {
@@ -1082,7 +1156,7 @@ async function decideAndFinalize(options, iterations, startMs, now, runId, mount
1082
1156
  /** Finalize the loop and emit the terminal `loop.ended` span. Used by the
1083
1157
  * in-loop terminal path (decision trace already emitted) and decideAndFinalize. */
1084
1158
  async function finalizeAndEmitEnded(options, decision, iterations, startMs, now, runId, mounts) {
1085
- const result = finalize$1({
1159
+ const result = finalize({
1086
1160
  options,
1087
1161
  decision,
1088
1162
  iterations,
@@ -3540,8 +3614,9 @@ function createInMemoryRunContext(opts = {}) {
3540
3614
  * resumes when it is re-run with the SAME `runId` and the SAME `dir`: the committed children come
3541
3615
  * back on `Scope.resume` (rehydrated by `replaySpawnTree`) instead of being re-executed.
3542
3616
  *
3543
- * Layout: `${dir}/spawn-journal.jsonl` (one JSONL record per event) and `${dir}/blobs/` (one
3544
- * content-addressed JSON file per settled result). The directory is created on first write.
3617
+ * Layout: `${dir}/spawn-journal.jsonl` (one JSONL record per event), `${dir}/blobs/` (one
3618
+ * content-addressed JSON file per settled result), and `${dir}/coordination-log.jsonl` (questions
3619
+ * + findings, replayed into a resumed driver). The directory is created on first write.
3545
3620
  *
3546
3621
  * Opt-in by construction — `createInMemoryRunContext()` is unchanged and stays the default, so no
3547
3622
  * existing consumer writes to disk or resumes unless it asks for this.
@@ -3552,7 +3627,8 @@ function createFileRunContext(dir, opts = {}) {
3552
3627
  journal: new FileSpawnJournal(`${dir}/spawn-journal.jsonl`),
3553
3628
  blobs: new FileResultBlobStore(`${dir}/blobs`),
3554
3629
  executors: opts.withDriver ? withDriverExecutor(base) : base,
3555
- resume: true
3630
+ resume: true,
3631
+ coordinationLog: new FileCoordinationLog(`${dir}/coordination-log.jsonl`)
3556
3632
  };
3557
3633
  }
3558
3634
  //#endregion
@@ -3857,8 +3933,22 @@ function createCoordinationTools(opts) {
3857
3933
  let reason;
3858
3934
  let questionSeq = 0;
3859
3935
  const ledger = [];
3860
- const questions = [];
3936
+ const questions = [...opts.priorQuestions ?? []];
3861
3937
  const questionPolicy = opts.questionPolicy ?? "auto";
3938
+ const completedKeys = /* @__PURE__ */ new Set();
3939
+ const keyByWorker = /* @__PURE__ */ new Map();
3940
+ for (const [key, prior] of opts.scope.resume?.keys ?? []) if (prior.state === "completed") completedKeys.add(key);
3941
+ for (const s of opts.scope.resume?.settled ?? []) ledger.push(s.kind === "done" ? {
3942
+ id: s.handle.id,
3943
+ status: "done",
3944
+ score: s.verdict?.score ?? 0,
3945
+ valid: s.verdict?.valid ?? false,
3946
+ outRef: s.outRef
3947
+ } : {
3948
+ id: s.handle.id,
3949
+ status: "down",
3950
+ reason: s.reason
3951
+ });
3862
3952
  const bus = createEventBus();
3863
3953
  if (opts.onEvent) {
3864
3954
  const cb = opts.onEvent;
@@ -3903,6 +3993,8 @@ function createCoordinationTools(opts) {
3903
3993
  };
3904
3994
  const recordSettled = (s) => {
3905
3995
  const settledAt = Date.now();
3996
+ const settledKey = keyByWorker.get(s.handle.id);
3997
+ if (settledKey !== void 0 && s.kind === "done") completedKeys.add(settledKey);
3906
3998
  const w = s.kind === "done" ? {
3907
3999
  id: s.handle.id,
3908
4000
  status: "done",
@@ -4159,7 +4251,7 @@ function createCoordinationTools(opts) {
4159
4251
  const tools = [
4160
4252
  {
4161
4253
  name: "spawn_agent",
4162
- description: "Start a worker the driver will drive. `profile` is the worker or another driver; `task` is what it should do. Reserves budget from the conserved pool and fails closed. Pass an optional `budget` (per-field) to give a hard sub-task more than the default — it merges over the per-worker default; the conserved pool is still the hard fence. When a max-live-workers cap is set it also fails closed (`error: \"max-live-workers\"`) while that many workers are still in flight — settle or steer one before spawning another. Returns `freeSlots`: how many MORE workers you can start right now (`null` = uncapped). While `freeSlots > 0` there is idle capacity — call this again to fill it rather than waiting; parallel workers finish the run sooner than one at a time.",
4254
+ description: "Start a worker the driver will drive. `profile` is the worker or another driver; `task` is what it should do. Reserves budget from the conserved pool and fails closed. Pass an optional `budget` (per-field) to give a hard sub-task more than the default — it merges over the per-worker default; the conserved pool is still the hard fence. When a max-live-workers cap is set it also fails closed (`error: \"max-live-workers\"`) while that many workers are still in flight — settle or steer one before spawning another. Pass a `key` naming the assignment to make it run-once ACROSS restarts: a key that already completed returns the finished result (`resumed: \"completed\"` — no work re-runs, nothing is spent), a key whose prior attempt failed or was lost with a dead process spawns fresh and says so (`resumed: \"retried\" | \"lost\"`), and a key still running is refused (`error: \"duplicate-key\"`). Returns `freeSlots`: how many MORE workers you can start right now (`null` = uncapped). While `freeSlots > 0` there is idle capacity — call this again to fill it rather than waiting; parallel workers finish the run sooner than one at a time.",
4163
4255
  inputSchema: {
4164
4256
  type: "object",
4165
4257
  properties: {
@@ -4169,6 +4261,10 @@ function createCoordinationTools(opts) {
4169
4261
  type: "string",
4170
4262
  description: "Optional trace label."
4171
4263
  },
4264
+ key: {
4265
+ type: "string",
4266
+ description: "Optional semantic name for this assignment (e.g. \"summarize-ch3\"). The same key never runs twice: completed keys return their committed result, even after a coordinator restart."
4267
+ },
4172
4268
  budget: {
4173
4269
  type: "object",
4174
4270
  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.",
@@ -4184,7 +4280,8 @@ function createCoordinationTools(opts) {
4184
4280
  },
4185
4281
  handler: (raw) => {
4186
4282
  const a = obj(raw);
4187
- if (maxLiveWorkers !== void 0 && maxLiveWorkers > 0 && liveWorkerCount() >= maxLiveWorkers) return Promise.resolve({
4283
+ const key = a.key === void 0 ? void 0 : str(a.key, "key");
4284
+ if (!(key !== void 0 && completedKeys.has(key)) && maxLiveWorkers !== void 0 && maxLiveWorkers > 0 && liveWorkerCount() >= maxLiveWorkers) return Promise.resolve({
4188
4285
  error: "max-live-workers",
4189
4286
  live: liveWorkerCount(),
4190
4287
  freeSlots: freeWorkerSlots()
@@ -4193,13 +4290,37 @@ function createCoordinationTools(opts) {
4193
4290
  const budget = a.budget === void 0 ? opts.perWorker : mergeBudget(opts.perWorker, a.budget);
4194
4291
  const res = opts.scope.spawn(agent, a.task, {
4195
4292
  budget,
4196
- label: typeof a.label === "string" ? a.label : "worker"
4293
+ label: typeof a.label === "string" ? a.label : "worker",
4294
+ ...key !== void 0 ? { key } : {}
4197
4295
  });
4198
- if (res.ok) watchWorker(res.handle.id);
4296
+ if (res.ok && res.prior?.state === "completed") {
4297
+ const s = res.prior.settled;
4298
+ if (key !== void 0) completedKeys.add(key);
4299
+ return Promise.resolve({
4300
+ workerId: s.handle.id,
4301
+ resumed: "completed",
4302
+ status: "done",
4303
+ score: s.verdict?.score ?? 0,
4304
+ valid: s.verdict?.valid ?? false,
4305
+ outRef: s.outRef,
4306
+ live: liveWorkerCount(),
4307
+ freeSlots: freeWorkerSlots()
4308
+ });
4309
+ }
4310
+ if (res.ok) {
4311
+ watchWorker(res.handle.id);
4312
+ if (key !== void 0) keyByWorker.set(res.handle.id, key);
4313
+ }
4314
+ const priorHistory = res.ok && res.prior !== void 0 && res.prior.state !== "completed" ? {
4315
+ resumed: res.prior.state,
4316
+ priorWorkerId: res.prior.priorId,
4317
+ ...res.prior.state === "retried" ? { priorReason: res.prior.reason } : {}
4318
+ } : {};
4199
4319
  return Promise.resolve(res.ok ? {
4200
4320
  workerId: res.handle.id,
4201
4321
  live: liveWorkerCount(),
4202
- freeSlots: freeWorkerSlots()
4322
+ freeSlots: freeWorkerSlots(),
4323
+ ...priorHistory
4203
4324
  } : {
4204
4325
  error: res.reason,
4205
4326
  live: liveWorkerCount(),
@@ -4218,7 +4339,19 @@ function createCoordinationTools(opts) {
4218
4339
  handler: async (raw) => {
4219
4340
  const id = str(obj(raw).workerId, "workerId");
4220
4341
  const node = opts.scope.view.nodes.find((n) => n.id === id);
4221
- if (!node) return { error: `unknown workerId ${JSON.stringify(id)}` };
4342
+ if (!node) {
4343
+ const resumed = opts.scope.resume?.view.nodes.find((n) => n.id === id);
4344
+ if (!resumed) return { error: `unknown workerId ${JSON.stringify(id)}` };
4345
+ const output = resumed.outRef ? await opts.blobs.get(resumed.outRef) : void 0;
4346
+ return {
4347
+ status: resumed.status,
4348
+ spent: resumed.spent,
4349
+ outRef: resumed.outRef ?? null,
4350
+ output: output ?? null,
4351
+ progress: null,
4352
+ resumed: true
4353
+ };
4354
+ }
4222
4355
  const output = node.outRef ? await opts.blobs.get(node.outRef) : void 0;
4223
4356
  const progress = readProgress(id);
4224
4357
  return {
@@ -4983,8 +5116,14 @@ function driverAgent(opts) {
4983
5116
  ...opts.analysts ? { analysts: opts.analysts } : {},
4984
5117
  ...opts.analyzeOnSettle ? { analyzeOnSettle: opts.analyzeOnSettle } : {},
4985
5118
  ...opts.watchWorkers ? { watchWorkers: opts.watchWorkers } : {},
4986
- ...opts.stallAfterMs !== void 0 ? { stallAfterMs: opts.stallAfterMs } : {}
5119
+ ...opts.stallAfterMs !== void 0 ? { stallAfterMs: opts.stallAfterMs } : {},
5120
+ ...opts.onEvent ? { onEvent: opts.onEvent } : {},
5121
+ ...opts.priorCoordination?.questions.length ? { priorQuestions: opts.priorCoordination.questions } : {}
4987
5122
  });
5123
+ for (const w of scope.resume?.waits ?? []) {
5124
+ const rearmed = scope.wait(w.spec, { label: w.label });
5125
+ if (!rearmed.ok) throw new RuntimeRunStateError(`driverAgent: cannot re-arm resumed wait '${w.label}' (${rearmed.reason})`);
5126
+ }
4988
5127
  const byName = new Map(coord.tools.map((t) => [t.name, t]));
4989
5128
  const toolSpecs = [...coord.tools.map((t) => ({
4990
5129
  type: "function",
@@ -5066,13 +5205,20 @@ function driverAgent(opts) {
5066
5205
  const tool = byName.get(name);
5067
5206
  return safeJson(tool ? await runTool(tool, args) : { error: `unknown tool: ${name}` });
5068
5207
  },
5069
- initialMessages: [{
5070
- role: "system",
5071
- content: system
5072
- }, {
5073
- role: "user",
5074
- content: stringifyTask(task)
5075
- }],
5208
+ initialMessages: [
5209
+ {
5210
+ role: "system",
5211
+ content: system
5212
+ },
5213
+ {
5214
+ role: "user",
5215
+ content: stringifyTask(task)
5216
+ },
5217
+ ...scope.resume ? [{
5218
+ role: "user",
5219
+ content: resumeBrief(scope.resume, opts.priorCoordination)
5220
+ }] : []
5221
+ ],
5076
5222
  maxTurns,
5077
5223
  hooks: { stopBefore: () => {
5078
5224
  if (coord.isStopped() || scope.signal.aborted || poolStarved(scope, opts.perWorker) || deadlinePassed(scope, now)) return true;
@@ -5087,10 +5233,46 @@ function driverAgent(opts) {
5087
5233
  } }
5088
5234
  });
5089
5235
  await coord.drainResolved();
5090
- return finalize(coord, opts.blobs);
5236
+ return runFinalizer(opts.finalizer ?? bestDelivered, {
5237
+ settled: coord.settled(),
5238
+ blobs: opts.blobs,
5239
+ tree: runTree(scope),
5240
+ budget: scope.budget
5241
+ });
5091
5242
  }
5092
5243
  };
5093
5244
  }
5245
+ /**
5246
+ * The factual context a resumed driver starts from — everything the durable stores prove about
5247
+ * the prior process(es): committed settlements, per-key states (completed / lost / failed),
5248
+ * re-armed waits, carried-over questions and findings, and the spend already paid. Injected as
5249
+ * the brain's first user-context on a resumed run so it continues from the unresolved work.
5250
+ */
5251
+ function resumeBrief(resume, prior) {
5252
+ const lines = [
5253
+ "RESUME: this run continues a prior coordinator process. Its committed work is restored",
5254
+ "below and already counts toward the deliverable — do NOT redo it. Continue from the",
5255
+ "unresolved work only.",
5256
+ "",
5257
+ `Committed workers (${resume.settled.length}):`
5258
+ ];
5259
+ if (resume.settled.length === 0) lines.push("- none");
5260
+ for (const s of resume.settled) lines.push(s.kind === "done" ? `- ${s.handle.id} (${s.handle.label}): done, score=${s.verdict?.score ?? 0}, valid=${s.verdict?.valid ?? false}, outRef=${s.outRef}` : `- ${s.handle.id} (${s.handle.label}): down, reason=${s.reason}`);
5261
+ const byState = (state) => [...resume.keys].filter(([, v]) => v.state === state);
5262
+ const completed = byState("completed");
5263
+ const lost = byState("in-doubt");
5264
+ const failed = byState("down");
5265
+ if (completed.length > 0) lines.push("", "COMPLETED keys — spawn_agent with the same key returns the finished result, spending nothing:", ...completed.map(([k, v]) => `- ${k} → ${v.id} (${v.label})`));
5266
+ if (lost.length > 0) lines.push("", "Keys LOST in flight with the prior process — this is the unresolved work; spawn_agent with the same key starts a fresh attempt:", ...lost.map(([k, v]) => `- ${k} (prior attempt ${v.id}, ${v.label})`));
5267
+ if (failed.length > 0) lines.push("", "Keys whose prior attempt FAILED (settled down) — spawn_agent with the same key retries:", ...failed.map(([k, v]) => `- ${k} (prior attempt ${v.id}, ${v.label})`));
5268
+ if (resume.waits.length > 0) lines.push("", "Pending waits RE-ARMED on their original deadlines (they settle through await_event):", ...resume.waits.map((w) => `- ${w.label} (${w.spec.kind})`));
5269
+ const openQuestions = (prior?.questions ?? []).filter((q) => q.status === "open" || q.status === "escalated");
5270
+ if (openQuestions.length > 0) lines.push("", "Questions carried over, still undecided (answer_question decides them; list_questions shows all):", ...openQuestions.map((q) => `- [${q.id}] from=${q.from}, urgency=${q.urgency}: ${q.question}`));
5271
+ if ((prior?.findings.length ?? 0) > 0) lines.push("", "Analyst findings from the prior process:", ...(prior?.findings ?? []).map((f) => `- ${f.analyst} on ${f.fromWorker}: ${safeJson(f.findings)}`));
5272
+ const spent = resume.priorSpend;
5273
+ lines.push("", "Budget the run ALREADY spent before this process (it counts toward the run total):", `- child work: tokens in=${spent.childWork.tokens.input} out=${spent.childWork.tokens.output}, usd=${spent.childWork.usd}, iterations=${spent.childWork.iterations}`, `- driver inference: tokens in=${spent.driverInference.tokens.input} out=${spent.driverInference.tokens.output}, usd=${spent.driverInference.usd}`);
5274
+ return lines.join("\n");
5275
+ }
5094
5276
  /** Run a work tool. A throw is data to the driver (it can recover next turn), not a crash — fold
5095
5277
  * the error back as a string result. null/undefined passes through (the caller treats it as "not
5096
5278
  * handled" and falls to the coordination dispatch). */
@@ -5113,17 +5295,13 @@ async function runTool(tool, args) {
5113
5295
  * child delivered — an honest "the driver produced nothing", never a high-scoring result that
5114
5296
  * ran without passing its check (Foreman's 0/18 lesson). `valid` is the single delivery signal,
5115
5297
  * matching `defaultSelectWinner`'s valid-first rule; the oracle just doesn't fall back to an
5116
- * unchecked best-effort. */
5298
+ * unchecked best-effort. The same argmax as the `bestDelivered` finalizer (`pickBestDelivered`);
5299
+ * this direct form serves callers that hold a bare ledger + blob store. */
5117
5300
  async function finalizeBestDelivered(settled, blobs) {
5118
- const delivered = settled.filter((w) => w.status === "done" && w.valid === true);
5119
- if (delivered.length === 0) return void 0;
5120
- let best = delivered[0];
5121
- for (const w of delivered) if ((w.score ?? 0) > (best.score ?? 0)) best = w;
5301
+ const best = pickBestDelivered(settled.filter((w) => w.status === "done" && w.valid === true));
5302
+ if (best === void 0) return void 0;
5122
5303
  return best.outRef ? await blobs.get(best.outRef) : void 0;
5123
5304
  }
5124
- async function finalize(coord, blobs) {
5125
- return finalizeBestDelivered(coord.settled(), blobs);
5126
- }
5127
5305
  function stringifyTask(task) {
5128
5306
  return typeof task === "string" ? task : safeJson(task);
5129
5307
  }
@@ -7070,7 +7248,8 @@ async function serveCoordinationMcp(opts) {
7070
7248
  ...opts.watchWorkers ? { watchWorkers: opts.watchWorkers } : {},
7071
7249
  ...opts.stallAfterMs !== void 0 ? { stallAfterMs: opts.stallAfterMs } : {},
7072
7250
  ...opts.onEvent ? { onEvent: opts.onEvent } : {},
7073
- ...opts.questionPolicy ? { questionPolicy: opts.questionPolicy } : {}
7251
+ ...opts.questionPolicy ? { questionPolicy: opts.questionPolicy } : {},
7252
+ ...opts.priorQuestions?.length ? { priorQuestions: opts.priorQuestions } : {}
7074
7253
  });
7075
7254
  const mcp = createMcpServer({
7076
7255
  extraTools: coord.tools,
@@ -7147,8 +7326,9 @@ async function serveCoordinationMcp(opts) {
7147
7326
  * coordination verbs: `serveCoordinationMcp` exposes spawn/await/steer/stop over the live scope,
7148
7327
  * and the caller's `driveHarness` runs the harness with that MCP mounted. The harness IS the brain.
7149
7328
  *
7150
- * Both arms spawn children through the SAME `makeWorkerAgent` seam and settle on the SAME completion
7151
- * oracle (`finalizeBestDelivered` — the best DELIVERED child, never the driver's own prose).
7329
+ * Both arms spawn children through the SAME `makeWorkerAgent` seam and finalize through the SAME
7330
+ * seam (`runFinalizer` over DELIVERED children only default keep-best, never the driver's own
7331
+ * prose).
7152
7332
  */
7153
7333
  /** The standing strategy a router-brained supervisor runs with when its profile names no
7154
7334
  * `systemPrompt`. The brain's competence IS this prompt: without it the brain has the coordination
@@ -7194,7 +7374,10 @@ function supervisorAgent(profile, deps) {
7194
7374
  ...deps.stopRule ? { stopRule: deps.stopRule } : {},
7195
7375
  ...deps.onProgressStop ? { onProgressStop: deps.onProgressStop } : {},
7196
7376
  ...deps.maxTurns !== void 0 ? { maxTurns: deps.maxTurns } : {},
7197
- ...deps.compaction ? { compaction: deps.compaction } : {}
7377
+ ...deps.compaction ? { compaction: deps.compaction } : {},
7378
+ ...deps.onEvent ? { onEvent: deps.onEvent } : {},
7379
+ ...deps.priorCoordination ? { priorCoordination: deps.priorCoordination } : {},
7380
+ ...deps.finalizer ? { finalizer: deps.finalizer } : {}
7198
7381
  });
7199
7382
  const driveHarness = deps.driveHarness;
7200
7383
  if (!driveHarness) throw new ValidationError(`supervisorAgent: profile.harness="${harness}" needs deps.driveHarness (how to run the harness with the coordination MCP mounted)`);
@@ -7210,7 +7393,9 @@ function supervisorAgent(profile, deps) {
7210
7393
  ...deps.analysts ? { analysts: deps.analysts } : {},
7211
7394
  ...deps.analyzeOnSettle ? { analyzeOnSettle: deps.analyzeOnSettle } : {},
7212
7395
  ...deps.watchWorkers ? { watchWorkers: deps.watchWorkers } : {},
7213
- ...deps.stallAfterMs !== void 0 ? { stallAfterMs: deps.stallAfterMs } : {}
7396
+ ...deps.stallAfterMs !== void 0 ? { stallAfterMs: deps.stallAfterMs } : {},
7397
+ ...deps.onEvent ? { onEvent: deps.onEvent } : {},
7398
+ ...deps.priorCoordination?.questions.length ? { priorQuestions: deps.priorCoordination.questions } : {}
7214
7399
  });
7215
7400
  try {
7216
7401
  await driveHarness({
@@ -7220,7 +7405,12 @@ function supervisorAgent(profile, deps) {
7220
7405
  coordinationMcpUrl: mcp.url
7221
7406
  });
7222
7407
  await mcp.drainResolved();
7223
- return await finalizeBestDelivered(mcp.settled(), deps.blobs);
7408
+ return await runFinalizer(deps.finalizer ?? bestDelivered, {
7409
+ settled: mcp.settled(),
7410
+ blobs: deps.blobs,
7411
+ tree: runTree(scope),
7412
+ budget: scope.budget
7413
+ });
7224
7414
  } finally {
7225
7415
  await mcp.close();
7226
7416
  }
@@ -7284,38 +7474,49 @@ function supervise(profile, task, opts) {
7284
7474
  if (!opts.backend) throw new ValidationError("supervise: provide opts.backend (where workers run) or opts.makeWorkerAgent");
7285
7475
  makeWorkerAgent = workerFromBackend(opts.backend, opts.deliverable);
7286
7476
  }
7287
- const agent = supervisorAgent(profile, {
7288
- blobs,
7289
- makeWorkerAgent,
7290
- perWorker,
7291
- ...opts.maxLiveWorkers !== void 0 ? { maxLiveWorkers: opts.maxLiveWorkers } : {},
7292
- ...opts.router ? { router: opts.router } : {},
7293
- ...opts.brain ? { brain: opts.brain } : {},
7294
- ...opts.driveHarness ? { driveHarness: opts.driveHarness } : {},
7295
- ...opts.extraTools ? { extraTools: opts.extraTools } : {},
7296
- ...opts.executeExtraTool ? { executeExtraTool: opts.executeExtraTool } : {},
7297
- ...opts.analysts ? { analysts: opts.analysts } : {},
7298
- ...opts.analyzeOnSettle ? { analyzeOnSettle: opts.analyzeOnSettle } : {},
7299
- ...opts.watchWorkers ? { watchWorkers: opts.watchWorkers } : {},
7300
- ...opts.stallAfterMs !== void 0 ? { stallAfterMs: opts.stallAfterMs } : {},
7301
- ...opts.stopRule ? { stopRule: opts.stopRule } : {},
7302
- ...opts.onProgressStop ? { onProgressStop: opts.onProgressStop } : {},
7303
- ...opts.maxTurns !== void 0 ? { maxTurns: opts.maxTurns } : {},
7304
- ...opts.compaction ? { compaction: opts.compaction } : {}
7305
- });
7306
- return createSupervisor().run(agent, task, {
7307
- budget: opts.budget,
7308
- runId: opts.runId ?? "supervise",
7309
- journal: opts.journal ?? ctx.journal,
7310
- blobs,
7311
- executors: ctx.executors,
7312
- maxDepth: opts.maxDepth ?? 8,
7313
- ...opts.probes ? { probes: opts.probes } : {},
7314
- ...ctx.resume === true ? { resume: true } : {},
7315
- ...opts.now ? { now: opts.now } : {}
7316
- });
7477
+ const workerFactory = makeWorkerAgent;
7478
+ const runId = opts.runId ?? "supervise";
7479
+ const log = ctx.coordinationLog;
7480
+ const now = opts.now ?? Date.now;
7481
+ const start = async () => {
7482
+ const priorCoordination = log ? await log.load(runId) : void 0;
7483
+ const agent = supervisorAgent(profile, {
7484
+ blobs,
7485
+ makeWorkerAgent: workerFactory,
7486
+ perWorker,
7487
+ ...log ? { onEvent: (ev) => log.append(runId, ev, new Date(now()).toISOString()) } : {},
7488
+ ...priorCoordination && (priorCoordination.questions.length > 0 || priorCoordination.findings.length > 0) ? { priorCoordination } : {},
7489
+ ...opts.finalizer ? { finalizer: opts.finalizer } : {},
7490
+ ...opts.maxLiveWorkers !== void 0 ? { maxLiveWorkers: opts.maxLiveWorkers } : {},
7491
+ ...opts.router ? { router: opts.router } : {},
7492
+ ...opts.brain ? { brain: opts.brain } : {},
7493
+ ...opts.driveHarness ? { driveHarness: opts.driveHarness } : {},
7494
+ ...opts.extraTools ? { extraTools: opts.extraTools } : {},
7495
+ ...opts.executeExtraTool ? { executeExtraTool: opts.executeExtraTool } : {},
7496
+ ...opts.analysts ? { analysts: opts.analysts } : {},
7497
+ ...opts.analyzeOnSettle ? { analyzeOnSettle: opts.analyzeOnSettle } : {},
7498
+ ...opts.watchWorkers ? { watchWorkers: opts.watchWorkers } : {},
7499
+ ...opts.stallAfterMs !== void 0 ? { stallAfterMs: opts.stallAfterMs } : {},
7500
+ ...opts.stopRule ? { stopRule: opts.stopRule } : {},
7501
+ ...opts.onProgressStop ? { onProgressStop: opts.onProgressStop } : {},
7502
+ ...opts.maxTurns !== void 0 ? { maxTurns: opts.maxTurns } : {},
7503
+ ...opts.compaction ? { compaction: opts.compaction } : {}
7504
+ });
7505
+ return createSupervisor().run(agent, task, {
7506
+ budget: opts.budget,
7507
+ runId,
7508
+ journal: opts.journal ?? ctx.journal,
7509
+ blobs,
7510
+ executors: ctx.executors,
7511
+ maxDepth: opts.maxDepth ?? 8,
7512
+ ...opts.probes ? { probes: opts.probes } : {},
7513
+ ...ctx.resume === true ? { resume: true } : {},
7514
+ ...opts.now ? { now: opts.now } : {}
7515
+ });
7516
+ };
7517
+ return start();
7317
7518
  }
7318
7519
  //#endregion
7319
- export { eventToSnapshot as $, createDelegateHandler as A, createSteerableSandboxSession as At, DelegationTaskQueue as B, runAgentRounds as Bt, DELEGATE_FEEDBACK_INPUT_SCHEMA as C, createFileRunContext as Ct, DELEGATE_DESCRIPTION as D, createExecutorRegistry as Dt, validateDelegateFeedbackArgs as E, createExecutor as Et, assessAuthoredProfile as F, decodeToolPart as Ft, capDelegationTrace as G, assertModelAllowed as Gt, DELEGATION_TRACE_MAX_BYTES as H, createSandboxLineage as Ht, authoredWorker as I, sandboxSessionTraceSource as It, DelegationPersistenceError as J, composeLoopTraceEmitters as K, gateOnDeliverable as Kt, defaultProfileRichnessThresholds as L, createInbox as Lt, defaultDelegateBudget as M, piExecutor as Mt, delegate as N, piSeamKey as Nt, DELEGATE_INPUT_SCHEMA as O, createWorktreeCliExecutor as Ot, asAuthoredProfile as P, createPushTraceSource as Pt, InMemoryFeedbackStore as Q, profileRichnessFinding as R, createSandboxForSpec as Rt, DELEGATE_FEEDBACK_DESCRIPTION as S, watchTrace as St, createDelegateFeedbackHandler as T, cliWorktreeExecutor as Tt, DELEGATION_TRACE_MAX_SPANS as U, probeSandboxCapabilities as Ut, hashIdempotencyInput as V, runLoop as Vt, buildDelegationTraceSpans as W, acquireSandbox as Wt, FileDelegationStore as X, DelegationStateCorruptError as Y, InMemoryDelegationStore as Z, DELEGATE_UI_AUDIT_DESCRIPTION as _, effectiveConcurrency as _t, createInProcessTransport as a, createProgressTracker as at, createDelegateUiAuditHandler as b, rollingDispatch as bt, DELEGATION_STATUS_INPUT_SCHEMA as c, sampleFromSettled as ct, validateDelegationStatusArgs as d, bestSoFar as dt, driverAgent as et, DELEGATION_HISTORY_DESCRIPTION as f, plateauLength as ft, validateDelegationHistoryArgs as g, createEventBus as gt, createDelegationHistoryHandler as h, createCoordinationTools as ht, serveCoordinationMcp as i, anyOf as it, validateDelegateArgs as j, PI_RUNTIME as jt, DELEGATE_TOOL_NAME as k, DEFAULT_SANDBOX_STEERING_MAX_TURNS as kt, DELEGATION_STATUS_TOOL_NAME as l, anytimeReport as lt, DELEGATION_HISTORY_TOOL_NAME as m, DEFAULT_AWAIT_EVENT_TIMEOUT_MS as mt, workerFromBackend as n, allOf as nt, createMcpServer as o, noProgressFor as ot, DELEGATION_HISTORY_INPUT_SCHEMA as p, renderAnytimeTable as pt, createDelegationTraceCollector as q, supervisorAgent as r, allWorkersStalled as rt, DELEGATION_STATUS_DESCRIPTION as s, plateau as st, supervise as t, finalizeBestDelivered as tt, createDelegationStatusHandler as u, areaUnderCurve as ut, DELEGATE_UI_AUDIT_INPUT_SCHEMA as v, freeSlots as vt, DELEGATE_FEEDBACK_TOOL_NAME as w, createInMemoryRunContext as wt, validateDelegateUiAuditArgs as x, defaultToolDetectors as xt, DELEGATE_UI_AUDIT_TOOL_NAME as y, queueOf as yt, supervisorInstructions as z, defaultSelectWinner as zt };
7520
+ export { eventToSnapshot as $, createDelegateHandler as A, createSteerableSandboxSession as At, DelegationTaskQueue as B, runAgentRounds as Bt, DELEGATE_FEEDBACK_INPUT_SCHEMA as C, createFileRunContext as Ct, DELEGATE_DESCRIPTION as D, createExecutorRegistry as Dt, validateDelegateFeedbackArgs as E, createExecutor as Et, assessAuthoredProfile as F, decodeToolPart as Ft, capDelegationTrace as G, FileCoordinationLog as Gt, DELEGATION_TRACE_MAX_BYTES as H, createSandboxLineage as Ht, authoredWorker as I, sandboxSessionTraceSource as It, DelegationPersistenceError as J, composeLoopTraceEmitters as K, assertModelAllowed as Kt, defaultProfileRichnessThresholds as L, createInbox as Lt, defaultDelegateBudget as M, piExecutor as Mt, delegate as N, piSeamKey as Nt, DELEGATE_INPUT_SCHEMA as O, createWorktreeCliExecutor as Ot, asAuthoredProfile as P, createPushTraceSource as Pt, InMemoryFeedbackStore as Q, profileRichnessFinding as R, createSandboxForSpec as Rt, DELEGATE_FEEDBACK_DESCRIPTION as S, watchTrace as St, createDelegateFeedbackHandler as T, cliWorktreeExecutor as Tt, DELEGATION_TRACE_MAX_SPANS as U, probeSandboxCapabilities as Ut, hashIdempotencyInput as V, runLoop as Vt, buildDelegationTraceSpans as W, acquireSandbox as Wt, FileDelegationStore as X, DelegationStateCorruptError as Y, InMemoryDelegationStore as Z, DELEGATE_UI_AUDIT_DESCRIPTION as _, effectiveConcurrency as _t, createInProcessTransport as a, createProgressTracker as at, createDelegateUiAuditHandler as b, rollingDispatch as bt, DELEGATION_STATUS_INPUT_SCHEMA as c, sampleFromSettled as ct, validateDelegationStatusArgs as d, bestSoFar as dt, driverAgent as et, DELEGATION_HISTORY_DESCRIPTION as f, plateauLength as ft, validateDelegationHistoryArgs as g, createEventBus as gt, createDelegationHistoryHandler as h, createCoordinationTools as ht, serveCoordinationMcp as i, anyOf as it, validateDelegateArgs as j, PI_RUNTIME as jt, DELEGATE_TOOL_NAME as k, DEFAULT_SANDBOX_STEERING_MAX_TURNS as kt, DELEGATION_STATUS_TOOL_NAME as l, anytimeReport as lt, DELEGATION_HISTORY_TOOL_NAME as m, DEFAULT_AWAIT_EVENT_TIMEOUT_MS as mt, workerFromBackend as n, allOf as nt, createMcpServer as o, noProgressFor as ot, DELEGATION_HISTORY_INPUT_SCHEMA as p, renderAnytimeTable as pt, createDelegationTraceCollector as q, gateOnDeliverable as qt, supervisorAgent as r, allWorkersStalled as rt, DELEGATION_STATUS_DESCRIPTION as s, plateau as st, supervise as t, finalizeBestDelivered as tt, createDelegationStatusHandler as u, areaUnderCurve as ut, DELEGATE_UI_AUDIT_INPUT_SCHEMA as v, freeSlots as vt, DELEGATE_FEEDBACK_TOOL_NAME as w, createInMemoryRunContext as wt, validateDelegateUiAuditArgs as x, defaultToolDetectors as xt, DELEGATE_UI_AUDIT_TOOL_NAME as y, queueOf as yt, supervisorInstructions as z, defaultSelectWinner as zt };
7320
7521
 
7321
- //# sourceMappingURL=supervise-BiRutHS9.js.map
7522
+ //# sourceMappingURL=supervise-JfKPwIlO.js.map