@tangle-network/agent-runtime 0.143.0 → 0.153.2
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.
- package/README.md +32 -0
- package/dist/{activation-mi8TgSLM.js → activation-Bbic0THc.js} +3 -3
- package/dist/{activation-mi8TgSLM.js.map → activation-Bbic0THc.js.map} +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +3 -3
- package/dist/{analyst-loop-CvkmfhUB.js → analyst-loop-Bouu53-l.js} +2 -2
- package/dist/{analyst-loop-CvkmfhUB.js.map → analyst-loop-Bouu53-l.js.map} +1 -1
- package/dist/analyst-loop.js +1 -1
- package/dist/{authoring-DuyShLdw.js → authoring-CcVhJ1lP.js} +2 -2
- package/dist/{authoring-DuyShLdw.js.map → authoring-CcVhJ1lP.js.map} +1 -1
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{candidate-execution-CD5PoNmC.js → candidate-execution-DYOB1juU.js} +4 -4
- package/dist/{candidate-execution-CD5PoNmC.js.map → candidate-execution-DYOB1juU.js.map} +1 -1
- package/dist/{conversation-1hNtDeMM.js → conversation-BHMwAiMo.js} +28 -13
- package/dist/{conversation-1hNtDeMM.js.map → conversation-BHMwAiMo.js.map} +1 -1
- package/dist/conversation.d.ts +1 -1
- package/dist/conversation.js +1 -1
- package/dist/durable.d.ts +102 -4
- package/dist/durable.js +259 -13
- package/dist/durable.js.map +1 -1
- package/dist/{environment-provider-DCBJ13VP.js → environment-provider-3eCszBEm.js} +218 -34
- package/dist/environment-provider-3eCszBEm.js.map +1 -0
- package/dist/{environment-provider-B8eZ85Ga.d.ts → environment-provider-DJG0yIYl.d.ts} +2 -2
- package/dist/environment-provider.d.ts +1 -1
- package/dist/environment-provider.js +1 -1
- package/dist/executable-spec-BUcUcEPk.js +73 -0
- package/dist/executable-spec-BUcUcEPk.js.map +1 -0
- package/dist/{graph-De_XEsfH.js → graph-CIh2HDmH.js} +4 -4
- package/dist/{graph-De_XEsfH.js.map → graph-CIh2HDmH.js.map} +1 -1
- package/dist/{improvement-cycle-Bi-Tf4QF.js → improvement-cycle-GCDSsTN6.js} +7 -7
- package/dist/{improvement-cycle-Bi-Tf4QF.js.map → improvement-cycle-GCDSsTN6.js.map} +1 -1
- package/dist/{index-C2caGomG.d.ts → index-DLn9WI-f.d.ts} +342 -505
- package/dist/{index-B8rKtH3U.d.ts → index-lMADJLfq.d.ts} +4 -4
- package/dist/{index-D4sLkOPY.d.ts → index-rxVSm9-z.d.ts} +6 -4
- package/dist/index.d.ts +7 -7
- package/dist/index.js +13 -13
- package/dist/intelligence.d.ts +4 -4
- package/dist/intelligence.js +6 -6
- package/dist/jsonl-file-CDfsCI5s.js +59 -0
- package/dist/jsonl-file-CDfsCI5s.js.map +1 -0
- package/dist/kernel.d.ts +6 -6
- package/dist/kernel.js +13 -13
- package/dist/{knowledge-CVE6Wk1i.js → knowledge-CaY53BW2.js} +10 -7
- package/dist/{knowledge-CVE6Wk1i.js.map → knowledge-CaY53BW2.js.map} +1 -1
- package/dist/knowledge.d.ts +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-BoHdQqLm.d.ts → loop-runner-bin-BwPqxKhR.d.ts} +3 -3
- package/dist/{loop-runner-bin-DdaI1nLL.js → loop-runner-bin-Dw43kB_-.js} +4 -4
- package/dist/{loop-runner-bin-DdaI1nLL.js.map → loop-runner-bin-Dw43kB_-.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/{materialization-P86EciBw.js → materialization-Dl9J8ek4.js} +279 -58
- package/dist/materialization-Dl9J8ek4.js.map +1 -0
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +3 -3
- package/dist/mcp/index.js +6 -6
- package/dist/{model-policy-DgRJIJse.js → model-policy-Sw4ywhtL.js} +68 -6
- package/dist/model-policy-Sw4ywhtL.js.map +1 -0
- package/dist/{openai-tools-BiAWKjh6.js → openai-tools-C4XKuK4t.js} +2 -2
- package/dist/{openai-tools-BiAWKjh6.js.map → openai-tools-C4XKuK4t.js.map} +1 -1
- package/dist/{prepare-D3n7cA39.js → prepare-C5tI-H4o.js} +2 -2
- package/dist/{prepare-D3n7cA39.js.map → prepare-C5tI-H4o.js.map} +1 -1
- package/dist/primeintellect/index.d.ts +1 -1
- package/dist/profiles.js +1 -1
- package/dist/{protected-model-port-bq6bD9YX.js → protected-model-port-DHDKNeY7.js} +2 -2
- package/dist/{protected-model-port-bq6bD9YX.js.map → protected-model-port-DHDKNeY7.js.map} +1 -1
- package/dist/{redact-DexTuAiX.d.ts → redact-NAptmqKw.d.ts} +3 -3
- package/dist/{researcher-CiSY6Wzb.js → researcher-BMFFPwKb.js} +2 -2
- package/dist/{researcher-CiSY6Wzb.js.map → researcher-BMFFPwKb.js.map} +1 -1
- package/dist/{run-layout-Be_Z0dF8.js → run-layout-C2jgwsCq.js} +111 -6
- package/dist/run-layout-C2jgwsCq.js.map +1 -0
- package/dist/{runtime-BnqjbOGX.js → runtime--Jsq8JCC.js} +118 -97
- package/dist/runtime--Jsq8JCC.js.map +1 -0
- package/dist/{runtime-J6Toky8K.d.ts → runtime-B-5dp5Iz.d.ts} +214 -14
- package/dist/{sandbox-events-COwCWUVB.js → sandbox-events-BVjstFgb.js} +70 -3
- package/dist/sandbox-events-BVjstFgb.js.map +1 -0
- package/dist/{spawn-journal-D2HKUImC.js → spawn-journal-BLnveCRS.js} +34 -104
- package/dist/spawn-journal-BLnveCRS.js.map +1 -0
- package/dist/{stream-agent-turn-C1Vs_3B9.d.ts → stream-agent-turn-BGyszuPH.d.ts} +2 -2
- package/dist/{stream-agent-turn-CXRugSGO.js → stream-agent-turn-DYi8ymsU.js} +91 -16
- package/dist/stream-agent-turn-DYi8ymsU.js.map +1 -0
- package/dist/{structural-rollout-CJgj9YXH.js → structural-rollout-D7V-HgXJ.js} +30 -13
- package/dist/structural-rollout-D7V-HgXJ.js.map +1 -0
- package/dist/{supervise-hCgG6ROJ.js → supervise-k_8VOASb.js} +2499 -2171
- package/dist/supervise-k_8VOASb.js.map +1 -0
- package/dist/{supervisor-s8SfZYbW.js → supervisor-CMZsJ7Wn.js} +673 -446
- package/dist/supervisor-CMZsJ7Wn.js.map +1 -0
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +12 -12
- package/dist/{top-app-BMOSKK06.js → top-app-3rYfFPTW.js} +192 -147
- package/dist/top-app-3rYfFPTW.js.map +1 -0
- package/dist/tui/bin.js +1 -1
- package/dist/tui/index.d.ts +32 -5
- package/dist/tui/index.js +1 -1
- package/dist/{types-Df9vulGc.d.ts → types-BPQhQRrC.d.ts} +507 -10
- package/dist/{util-C1bv6yog.js → util-D6ZEuBMi.js} +71 -2
- package/dist/util-D6ZEuBMi.js.map +1 -0
- package/dist/{workspace-archive-C52LjkeN.js → workspace-archive-B9ui4rrR.js} +2 -2
- package/dist/{workspace-archive-C52LjkeN.js.map → workspace-archive-B9ui4rrR.js.map} +1 -1
- package/package.json +7 -7
- package/dist/environment-provider-DCBJ13VP.js.map +0 -1
- package/dist/materialization-P86EciBw.js.map +0 -1
- package/dist/model-policy-DgRJIJse.js.map +0 -1
- package/dist/retained-run-binding-Dp2e8xne.js +0 -268
- package/dist/retained-run-binding-Dp2e8xne.js.map +0 -1
- package/dist/run-layout-Be_Z0dF8.js.map +0 -1
- package/dist/runtime-BnqjbOGX.js.map +0 -1
- package/dist/sandbox-events-COwCWUVB.js.map +0 -1
- package/dist/spawn-journal-D2HKUImC.js.map +0 -1
- package/dist/stream-agent-turn-CXRugSGO.js.map +0 -1
- package/dist/structural-rollout-CJgj9YXH.js.map +0 -1
- package/dist/supervise-hCgG6ROJ.js.map +0 -1
- package/dist/supervisor-s8SfZYbW.js.map +0 -1
- package/dist/top-app-BMOSKK06.js.map +0 -1
- package/dist/util-C1bv6yog.js.map +0 -1
|
@@ -28,7 +28,15 @@ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeF
|
|
|
28
28
|
* {@link WorkerCancelRequest}
|
|
29
29
|
* cancellations/<opId>.json the acknowledgement for one cancel operation — a
|
|
30
30
|
* {@link WorkerCancellation} written ONLY by the runtime
|
|
31
|
-
* acknowledger
|
|
31
|
+
* acknowledger in the OWNING manager's turn loop: exact node
|
|
32
|
+
* ids route to the manager that parents them (any depth);
|
|
33
|
+
* label/profile-name references to the root manager alone
|
|
34
|
+
* cancellations/run.request.json the run-scoped cancel request — one {@link RunCancelRequest},
|
|
35
|
+
* the whole RUN rather than one worker
|
|
36
|
+
* cancellations/run.json the acknowledgement for the run-scoped request — a
|
|
37
|
+
* {@link RunCancellation} written ONLY by the runtime (the root
|
|
38
|
+
* manager issues the abort; the `supervise()` settle path records
|
|
39
|
+
* what the run actually did)
|
|
32
40
|
*
|
|
33
41
|
* Reads are tolerant by contract: a partial trailing line (a writer mid-append) or a corrupt line
|
|
34
42
|
* never poisons the rest of the file — later valid lines still matter.
|
|
@@ -217,9 +225,10 @@ function writeWorkerCancellation(eventDir, record) {
|
|
|
217
225
|
* durable state.
|
|
218
226
|
*
|
|
219
227
|
* The write half of the acknowledged-cancellation contract (`writeWorkerSteer` is the steer
|
|
220
|
-
* analog): append the request to the run's cancellation inbox, where the
|
|
221
|
-
* (
|
|
222
|
-
*
|
|
228
|
+
* analog): append the request to the run's cancellation inbox, where the OWNING manager's
|
|
229
|
+
* acknowledger (its turn loop — the root for label/profile references, the parent manager for an
|
|
230
|
+
* exact node id at any depth) applies it — aborting exactly that worker's subtree and recording
|
|
231
|
+
* what it proved. This function never applies the cancellation itself; writing a
|
|
223
232
|
* request file is not an acknowledgement.
|
|
224
233
|
*
|
|
225
234
|
* Idempotency is a lookup: when an acknowledgement for `operationId` already exists, it is
|
|
@@ -266,6 +275,102 @@ function cancelWorker(eventDir, worker, operationId, options = {}) {
|
|
|
266
275
|
terminated: []
|
|
267
276
|
};
|
|
268
277
|
}
|
|
278
|
+
/** The run-scoped cancel request file of one run — one {@link RunCancelRequest}. */
|
|
279
|
+
function runCancelRequestFile(eventDir) {
|
|
280
|
+
return join(workerCancellationsDir(eventDir), "run.request.json");
|
|
281
|
+
}
|
|
282
|
+
/** The run-scoped acknowledgement file of one run — one {@link RunCancellation}. */
|
|
283
|
+
function runCancellationFile(eventDir) {
|
|
284
|
+
return join(workerCancellationsDir(eventDir), "run.json");
|
|
285
|
+
}
|
|
286
|
+
/** Read the run-scoped cancel request, or `undefined` when none was written. */
|
|
287
|
+
function readRunCancelRequest(eventDir) {
|
|
288
|
+
const file = runCancelRequestFile(eventDir);
|
|
289
|
+
if (!existsSync(file)) return void 0;
|
|
290
|
+
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
291
|
+
if (!isRunCancelRequest(parsed)) throw new Error(`run cancel request '${file}' is not a complete RunCancelRequest`);
|
|
292
|
+
return parsed;
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Read the acknowledgement for the run-scoped cancel operation. `undefined` when the runtime has
|
|
296
|
+
* not answered. A record holding a DIFFERENT `operationId` belongs to another operation on the
|
|
297
|
+
* same run — fail loud rather than answer for it.
|
|
298
|
+
*/
|
|
299
|
+
function readRunCancellation(eventDir, operationId) {
|
|
300
|
+
const file = runCancellationFile(eventDir);
|
|
301
|
+
if (!existsSync(file)) return void 0;
|
|
302
|
+
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
303
|
+
if (parsed.operationId !== operationId) throw new Error(`run cancel acknowledgement '${file}' holds operation '${parsed.operationId}', not '${operationId}' — one run carries one run-scoped cancel operation`);
|
|
304
|
+
return parsed;
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Durably write the run-scoped acknowledgement. Write-then-rename, so a concurrent reader sees the
|
|
308
|
+
* prior complete record or the new complete record, never a partial file.
|
|
309
|
+
*
|
|
310
|
+
* @internal The runtime is the only intended writer; clients read via {@link readRunCancellation}
|
|
311
|
+
* or {@link cancelRun}.
|
|
312
|
+
*/
|
|
313
|
+
function writeRunCancellation(eventDir, record) {
|
|
314
|
+
mkdirSync(workerCancellationsDir(eventDir), { recursive: true });
|
|
315
|
+
const file = runCancellationFile(eventDir);
|
|
316
|
+
const tmp = `${file}.${randomUUID()}.tmp`;
|
|
317
|
+
writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\n`, "utf8");
|
|
318
|
+
renameSync(tmp, file);
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Request the cancellation of the WHOLE run, idempotently, and return the operation's current
|
|
322
|
+
* durable state.
|
|
323
|
+
*
|
|
324
|
+
* The run-scoped twin of {@link cancelWorker}: write the request into the run's cancellation
|
|
325
|
+
* directory, where the run's own root manager applies it — aborting the root through the one
|
|
326
|
+
* cascade controller the run already has, so every live worker comes down with it. This function
|
|
327
|
+
* never applies the cancellation itself; writing a request file is not an acknowledgement.
|
|
328
|
+
*
|
|
329
|
+
* Idempotency is a lookup: when an acknowledgement for `operationId` already exists it is returned
|
|
330
|
+
* AS-IS and nothing is written. A request the runtime has not answered yet returns
|
|
331
|
+
* `effect: 'unknown'` (never a success); call again with the same `operationId` — or
|
|
332
|
+
* {@link readRunCancellation} — to read the acknowledged result after a reconnect.
|
|
333
|
+
*
|
|
334
|
+
* A run carries ONE run-scoped operation: a second request under a different `operationId` throws
|
|
335
|
+
* rather than silently replacing the pending one, because both would claim the same single abort.
|
|
336
|
+
*/
|
|
337
|
+
function cancelRun(eventDir, operationId, options = {}) {
|
|
338
|
+
const opId = operationId.trim();
|
|
339
|
+
if (!opId) throw new Error("cancelRun: operationId is empty");
|
|
340
|
+
const acknowledged = readRunCancellation(eventDir, opId);
|
|
341
|
+
if (acknowledged) return acknowledged;
|
|
342
|
+
const pending = readRunCancelRequest(eventDir);
|
|
343
|
+
if (pending !== void 0 && pending.operationId !== opId) throw new Error(`cancelRun: run cancel '${pending.operationId}' is already pending for this run; read it with readRunCancellation instead of issuing '${opId}'`);
|
|
344
|
+
const source = options.source ?? "human";
|
|
345
|
+
const request = pending ?? {
|
|
346
|
+
operationId: opId,
|
|
347
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
348
|
+
source,
|
|
349
|
+
...options.reason === void 0 ? {} : { reason: options.reason }
|
|
350
|
+
};
|
|
351
|
+
if (pending === void 0) {
|
|
352
|
+
mkdirSync(workerCancellationsDir(eventDir), { recursive: true });
|
|
353
|
+
writeFileSync(runCancelRequestFile(eventDir), `${JSON.stringify(request, null, 2)}\n`, "utf8");
|
|
354
|
+
appendWorkerControlEvent(eventDir, "run", {
|
|
355
|
+
kind: "run-cancel-request",
|
|
356
|
+
operationId: opId,
|
|
357
|
+
source,
|
|
358
|
+
queued: true,
|
|
359
|
+
...options.reason === void 0 ? {} : { reason: options.reason }
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
return {
|
|
363
|
+
operationId: opId,
|
|
364
|
+
effect: "unknown",
|
|
365
|
+
requestedAt: request.at,
|
|
366
|
+
observedAt: request.at,
|
|
367
|
+
...request.reason === void 0 ? {} : { reason: request.reason },
|
|
368
|
+
detail: "request queued; no runtime acknowledger has answered yet"
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
function isRunCancelRequest(value) {
|
|
372
|
+
return typeof value.operationId === "string" && value.operationId.length > 0 && typeof value.at === "string" && typeof value.source === "string" && (value.reason === void 0 || typeof value.reason === "string");
|
|
373
|
+
}
|
|
269
374
|
function isWorkerCancelRequest(value) {
|
|
270
375
|
return typeof value.operationId === "string" && value.operationId.length > 0 && typeof value.at === "string" && typeof value.source === "string" && typeof value.worker === "string" && value.worker.length > 0 && (value.reason === void 0 || typeof value.reason === "string");
|
|
271
376
|
}
|
|
@@ -283,6 +388,6 @@ function isWorkerSteerRequest(value) {
|
|
|
283
388
|
return typeof value.id === "string" && typeof value.at === "string" && typeof value.source === "string" && typeof value.worker === "string" && typeof value.message === "string" && value.message.trim().length > 0;
|
|
284
389
|
}
|
|
285
390
|
//#endregion
|
|
286
|
-
export { writeWorkerCancellation as _,
|
|
391
|
+
export { writeWorkerCancellation as C, writeRunCancellation as S, workerCancellationFile as _, readRunCancelRequest as a, workerInboxFile as b, readWorkerCancellation as c, runCancellationFile as d, safeWorkerFile as f, workerCancelRequestsFile as g, supervisorWorkersDir as h, legacySupervisorRunsRoot as i, readWorkerSteerRequests as l, supervisorRunsRoot as m, cancelWorker as n, readRunCancellation as o, supervisorRunDir as p, legacySupervisorRunDir as r, readWorkerCancelRequests as s, cancelRun as t, runCancelRequestFile as u, workerCancellationsDir as v, writeWorkerSteer as w, workerInboxFileFromEventDir as x, workerControlLogFile as y };
|
|
287
392
|
|
|
288
|
-
//# sourceMappingURL=run-layout-
|
|
393
|
+
//# sourceMappingURL=run-layout-C2jgwsCq.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-layout-C2jgwsCq.js","names":[],"sources":["../src/runtime/supervise/run-layout.ts"],"sourcesContent":["/**\n * The on-disk supervisor-run layout: `<root>/.agent/supervisor/<id>`.\n *\n * This is the durable, cross-process face of a supervisor run — the counterpart to the in-process\n * `Inbox` seam in `./inbox`. A run persists its state under one directory so that any OTHER process\n * can find it after the fact: `@tangle-network/traces` reads exactly this layout via\n * `traces analyze --supervisor-run-dir`, a restarted host can rehydrate a run it no longer holds\n * handles to, and a human can steer a live worker by appending one NDJSON line. Until now the\n * layout was defined only in the unpublished `loops` repo (`src/supervisor-control.ts`) — a\n * published reader depending on an unpublished writer's convention — so the contract is promoted\n * here, names preserved.\n *\n * `.agent` is the one dot-dir for ALL agent-owned state (skills already write\n * `.agent/hypotheses/`, `.agent/skill-runs.jsonl`); supervisor runs live beside them rather than\n * under a product-branded dir. Runs written by older writers used `.loops/supervisor/<id>` —\n * readers that must see those keep a legacy fallback; this writer never creates `.loops` again.\n *\n * Layout, relative to `supervisorRunDir(root, id)`:\n *\n * workers/<label>.inbox.ndjson down-leg steer/answer requests for one worker (durable inbox);\n * each line is a {@link WorkerSteerRequest}\n * workers/<label>.ndjson best-effort per-worker control-event log (delivery bookkeeping)\n * cancellations/requests.ndjson worker-scoped cancel requests (durable inbox); each line is a\n * {@link WorkerCancelRequest}\n * cancellations/<opId>.json the acknowledgement for one cancel operation — a\n * {@link WorkerCancellation} written ONLY by the runtime\n * acknowledger in the OWNING manager's turn loop: exact node\n * ids route to the manager that parents them (any depth);\n * label/profile-name references to the root manager alone\n * cancellations/run.request.json the run-scoped cancel request — one {@link RunCancelRequest},\n * the whole RUN rather than one worker\n * cancellations/run.json the acknowledgement for the run-scoped request — a\n * {@link RunCancellation} written ONLY by the runtime (the root\n * manager issues the abort; the `supervise()` settle path records\n * what the run actually did)\n *\n * Reads are tolerant by contract: a partial trailing line (a writer mid-append) or a corrupt line\n * never poisons the rest of the file — later valid lines still matter.\n *\n * Promoted from `loops/src/supervisor-control.ts`. The one deliberate difference: the loops version\n * resolved a worker id to its label through the run journal before writing a steer; that resolution\n * stays with the caller (it is journal-format-specific), so `writeWorkerSteer` here takes the worker\n * LABEL directly.\n *\n * @experimental\n */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n appendFileSync,\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n writeFileSync,\n} from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport type { RetainedRunEffect } from '../retained-run-types'\n\n/** One durable down-leg request appended to a worker's inbox file. */\nexport interface WorkerSteerRequest {\n readonly id: string\n /** ISO timestamp of the append. */\n readonly at: string\n /** Who asked — 'human', a brain label, a tool name. Provenance, not authorization. */\n readonly source: string\n /** The worker LABEL the request targets (already resolved by the caller). */\n readonly worker: string\n readonly message: string\n}\n\n/** One durable worker-scoped cancel request appended to the run's cancellation inbox. */\nexport interface WorkerCancelRequest {\n /** Caller-minted stable operation identifier — the idempotency key of the whole operation. */\n readonly operationId: string\n /** ISO timestamp of the append. */\n readonly at: string\n /** Who asked — 'human', a brain label, a tool name. Provenance, not authorization. */\n readonly source: string\n /** The worker the request targets: a workerId (node id — routed to the owning manager at any\n * depth), or a profile name or spawn label (resolved by the root manager against its direct\n * children only). */\n readonly worker: string\n readonly reason?: string\n}\n\n/**\n * The durable acknowledgement state for one worker-scoped cancel operation, keyed by\n * `operationId`. The runtime acknowledger is the ONLY writer; `cancelWorker` only reads it.\n *\n * `effect` reuses the retained-run vocabulary ({@link RetainedRunEffect}) so the runtime has one\n * spelling of the four cancellation states:\n * - `'unknown'` — not yet resolved by the runtime (also what `cancelWorker` returns for\n * a request no acknowledger has answered), or — terminally, with the\n * run-over detail — an abort was issued but the run ended before the\n * termination could be observed. Never a success.\n * - `'cancel_requested'` — the runtime issued the worker's abort; termination not yet proven.\n * - `'cancelled'` — the worker reached a terminal `down` state on the settle path.\n * - `'not_live'` — the worker was not live to cancel (already settled, it settled\n * `done` despite the abort, or the run ended before the request was\n * ever applied). Never a success of THIS operation.\n *\n * Expiry is run end: the owning manager's final pass closes every still-open request it owns\n * (`not_live` never applied, `unknown` issued-but-unproven), so a pending request cannot outlive\n * its run and abort a future spawn that happens to reuse a label.\n */\nexport interface WorkerCancellation {\n readonly operationId: string\n /** The worker reference exactly as requested. */\n readonly worker: string\n readonly effect: RetainedRunEffect\n /** ISO timestamp of the original request. */\n readonly requestedAt: string\n /** ISO timestamp of the runtime's most recent observation of this operation. */\n readonly observedAt: string\n /** The node id the acknowledger resolved `worker` to, once resolved. */\n readonly workerId?: string\n /** The caller's reason, carried verbatim from the request. */\n readonly reason?: string\n /** The runtime's explanation of how it arrived at `effect`. */\n readonly detail?: string\n /**\n * Every node id this operation PROVED terminated: the requested worker plus each descendant of\n * its subtree observed to reach a terminal `down`/`cancelled` journal record at or after the\n * abort was ISSUED — the acknowledger's own `observedAt` on the `cancel_requested` record\n * (runtime clock), never the client's `requestedAt` (a cancelled lead cascades to its subtree\n * by design — the scope signal chain — so the acknowledgement names the set, not one id).\n * Proven at acknowledgement time; post-abort causation is approximate: a descendant that died\n * of its own cause after the abort is indistinguishable from the cascade and may be included,\n * a late teardown journal joins the set on a later pass while the manager still runs, and one\n * still absent at run end is absent from the set. Grows monotonically; empty until termination\n * is proven.\n */\n readonly terminated: ReadonlyArray<string>\n}\n\n/** One durable run-scoped cancel request: cancel the WHOLE run, not one worker. */\nexport interface RunCancelRequest {\n /** Caller-minted stable operation identifier — the idempotency key of the whole operation. */\n readonly operationId: string\n /** ISO timestamp of the write. */\n readonly at: string\n /** Who asked — 'human', a brain label, a tool name. Provenance, not authorization. */\n readonly source: string\n readonly reason?: string\n}\n\n/**\n * The durable acknowledgement state for the run-scoped cancel operation, keyed by `operationId`.\n * The runtime is the ONLY writer; {@link cancelRun} only reads it.\n *\n * `effect` is the same {@link RetainedRunEffect} vocabulary the worker-scoped and retained-run\n * paths use, so the runtime has one spelling of the four cancellation states:\n * - `'unknown'` — no runtime has answered yet. Never a success.\n * - `'cancel_requested'` — the root manager issued the run's cascading abort; the run's terminal\n * state is not yet observed.\n * - `'cancelled'` — the run reached its terminal state ABORTED after that request.\n * - `'not_live'` — the run was not live to cancel: it settled on its own despite the\n * request, or it ended before the request was applied.\n */\nexport interface RunCancellation {\n readonly operationId: string\n readonly effect: RetainedRunEffect\n /** ISO timestamp of the original request. */\n readonly requestedAt: string\n /** ISO timestamp of the runtime's most recent observation of this operation. */\n readonly observedAt: string\n /** The caller's reason, carried verbatim from the request. */\n readonly reason?: string\n /** The runtime's explanation of how it arrived at `effect`. */\n readonly detail?: string\n}\n\n/** The root every supervisor run of one workspace lives under. */\nexport function supervisorRunsRoot(rootDir: string): string {\n return join(resolve(rootDir), '.agent', 'supervisor')\n}\n\n/** The run directory every artifact of one supervisor run lives under. */\nexport function supervisorRunDir(rootDir: string, id: string): string {\n return join(supervisorRunsRoot(rootDir), id)\n}\n\n/**\n * Where a pre-rename writer put the same run (`<root>/.loops/supervisor/<id>`). Readers that must\n * see historical runs check {@link supervisorRunDir} first and fall back to this; nothing writes\n * here anymore.\n */\nexport function legacySupervisorRunDir(rootDir: string, id: string): string {\n return join(legacySupervisorRunsRoot(rootDir), id)\n}\n\n/**\n * The pre-rename runs root (`<root>/.loops/supervisor`). Only readers that ENUMERATE historical\n * runs need this — the per-id form is {@link legacySupervisorRunDir}. Nothing writes here.\n */\nexport function legacySupervisorRunsRoot(rootDir: string): string {\n return join(resolve(rootDir), '.loops', 'supervisor')\n}\n\n/** A worker label reduced to a safe filename stem. Empty labels get a stable fallback. */\nexport function safeWorkerFile(label: string): string {\n const safe = label.replace(/[^A-Za-z0-9._-]/g, '_')\n return safe.length > 0 ? safe : 'worker'\n}\n\n/** The directory holding every per-worker file of one run (inboxes and control-event logs). */\nexport function supervisorWorkersDir(eventDir: string): string {\n return join(eventDir, 'workers')\n}\n\n/** The durable inbox file for one worker of one run. */\nexport function workerInboxFile(rootDir: string, supervisorId: string, worker: string): string {\n return workerInboxFileFromEventDir(supervisorRunDir(rootDir, supervisorId), worker)\n}\n\n/** Same, addressed from an already-known run directory (the reader's usual entry point). */\nexport function workerInboxFileFromEventDir(eventDir: string, worker: string): string {\n return join(supervisorWorkersDir(eventDir), `${safeWorkerFile(worker)}.inbox.ndjson`)\n}\n\n/**\n * The best-effort control-event log for one worker (`workers/<label>.ndjson`) — delivery\n * bookkeeping for steers, plus whatever lifecycle events a writer chooses to append. Distinct from\n * the inbox: the inbox is the durable down-leg queue, this is the record of what happened to it.\n */\nexport function workerControlLogFile(eventDir: string, worker: string): string {\n return join(supervisorWorkersDir(eventDir), `${safeWorkerFile(worker)}.ndjson`)\n}\n\n/**\n * Durably append one steer request to a worker's inbox and log the delivery attempt.\n *\n * The inbox append is the durable act; the control-event log is best-effort bookkeeping and may\n * silently fail without voiding the steer.\n */\nexport function writeWorkerSteer(\n rootDir: string,\n supervisorId: string,\n worker: string,\n message: string,\n source = 'human',\n): { worker: string; file: string; request: WorkerSteerRequest } {\n const trimmed = message.trim()\n if (!trimmed) throw new Error('steer message is empty')\n const dir = supervisorRunDir(rootDir, supervisorId)\n mkdirSync(supervisorWorkersDir(dir), { recursive: true })\n const request: WorkerSteerRequest = {\n id: randomUUID(),\n at: new Date().toISOString(),\n source,\n worker,\n message: trimmed,\n }\n const file = workerInboxFile(rootDir, supervisorId, worker)\n appendFileSync(file, `${JSON.stringify(request)}\\n`, 'utf8')\n appendWorkerControlEvent(dir, worker, {\n kind: 'message',\n direction: 'down',\n source,\n requestId: request.id,\n message: trimmed,\n queued: true,\n delivered: false,\n })\n return { worker, file, request }\n}\n\n/** Read every valid steer request in a worker's inbox. Corrupt or partial lines are skipped. */\nexport function readWorkerSteerRequests(eventDir: string, worker: string): WorkerSteerRequest[] {\n const file = workerInboxFileFromEventDir(eventDir, worker)\n if (!existsSync(file)) return []\n const out: WorkerSteerRequest[] = []\n let raw = ''\n try {\n raw = readFileSync(file, 'utf8')\n } catch {\n return out\n }\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n try {\n const parsed = JSON.parse(trimmed) as Partial<WorkerSteerRequest>\n if (isWorkerSteerRequest(parsed)) out.push(parsed)\n } catch {\n // Ignore partial or corrupt input lines; later valid lines still matter.\n }\n }\n return out\n}\n\n/** The directory holding every cancellation artifact of one run (request inbox + acknowledgements). */\nexport function workerCancellationsDir(eventDir: string): string {\n return join(eventDir, 'cancellations')\n}\n\n/** The durable cancel-request inbox of one run — one NDJSON line per {@link WorkerCancelRequest}. */\nexport function workerCancelRequestsFile(eventDir: string): string {\n return join(workerCancellationsDir(eventDir), 'requests.ndjson')\n}\n\n/**\n * The acknowledgement file for one cancel operation. The filename is a sanitized stem of the\n * `operationId`; the record inside carries the exact id, and readers verify it so two distinct\n * ids that sanitize to one stem fail loud instead of answering for each other.\n */\nexport function workerCancellationFile(eventDir: string, operationId: string): string {\n return join(workerCancellationsDir(eventDir), `${safeOperationFile(operationId)}.json`)\n}\n\nfunction safeOperationFile(operationId: string): string {\n const safe = operationId.replace(/[^A-Za-z0-9._-]/g, '_')\n if (safe.length === 0) throw new Error('cancel operationId is empty')\n return safe\n}\n\n/** Read every valid cancel request in the run's cancellation inbox. Corrupt lines are skipped. */\nexport function readWorkerCancelRequests(eventDir: string): WorkerCancelRequest[] {\n const file = workerCancelRequestsFile(eventDir)\n if (!existsSync(file)) return []\n const out: WorkerCancelRequest[] = []\n let raw = ''\n try {\n raw = readFileSync(file, 'utf8')\n } catch {\n return out\n }\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n try {\n const parsed = JSON.parse(trimmed) as Partial<WorkerCancelRequest>\n if (isWorkerCancelRequest(parsed)) out.push(parsed)\n } catch {\n // Ignore partial or corrupt input lines; later valid lines still matter.\n }\n }\n return out\n}\n\n/**\n * Read the acknowledgement for one cancel operation. `undefined` when the runtime has not\n * answered. A record whose stored `operationId` differs from the requested one is a filename\n * collision between two sanitized ids — fail loud rather than return another operation's answer.\n */\nexport function readWorkerCancellation(\n eventDir: string,\n operationId: string,\n): WorkerCancellation | undefined {\n const file = workerCancellationFile(eventDir, operationId)\n if (!existsSync(file)) return undefined\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as WorkerCancellation\n if (parsed.operationId !== operationId) {\n throw new Error(\n `cancel acknowledgement collision: '${file}' holds operation '${parsed.operationId}', ` +\n `not '${operationId}' — use operation ids that stay distinct after filename sanitization`,\n )\n }\n return parsed\n}\n\n/**\n * Durably write one acknowledgement record. Write-then-rename, so a concurrent reader sees the\n * prior complete record or the new complete record, never a partial file.\n *\n * @internal The runtime acknowledger is the only intended writer; clients read via\n * {@link readWorkerCancellation} or {@link cancelWorker}.\n */\nexport function writeWorkerCancellation(eventDir: string, record: WorkerCancellation): void {\n const dir = workerCancellationsDir(eventDir)\n mkdirSync(dir, { recursive: true })\n const file = workerCancellationFile(eventDir, record.operationId)\n const tmp = `${file}.${randomUUID()}.tmp`\n writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\\n`, 'utf8')\n renameSync(tmp, file)\n}\n\n/**\n * Request the cancellation of ONE worker, idempotently, and return the operation's current\n * durable state.\n *\n * The write half of the acknowledged-cancellation contract (`writeWorkerSteer` is the steer\n * analog): append the request to the run's cancellation inbox, where the OWNING manager's\n * acknowledger (its turn loop — the root for label/profile references, the parent manager for an\n * exact node id at any depth) applies it — aborting exactly that worker's subtree and recording\n * what it proved. This function never applies the cancellation itself; writing a\n * request file is not an acknowledgement.\n *\n * Idempotency is a lookup: when an acknowledgement for `operationId` already exists, it is\n * returned AS-IS and nothing is appended — repeating one operation can never apply twice. A\n * request the runtime has not answered yet returns `effect: 'unknown'` (never a success); call\n * again with the same `operationId` — or `readWorkerCancellation` — to read the acknowledged\n * result after a reconnect.\n */\nexport function cancelWorker(\n eventDir: string,\n worker: string,\n operationId: string,\n options: { readonly reason?: string; readonly source?: string } = {},\n): WorkerCancellation {\n const ref = worker.trim()\n if (!ref) throw new Error('cancelWorker: worker reference is empty')\n const opId = operationId.trim()\n if (!opId) throw new Error('cancelWorker: operationId is empty')\n const acknowledged = readWorkerCancellation(eventDir, opId)\n if (acknowledged) return acknowledged\n const source = options.source ?? 'human'\n const pending = readWorkerCancelRequests(eventDir).find((r) => r.operationId === opId)\n const request: WorkerCancelRequest = pending ?? {\n operationId: opId,\n at: new Date().toISOString(),\n source,\n worker: ref,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n }\n if (!pending) {\n mkdirSync(workerCancellationsDir(eventDir), { recursive: true })\n appendFileSync(workerCancelRequestsFile(eventDir), `${JSON.stringify(request)}\\n`, 'utf8')\n appendWorkerControlEvent(eventDir, ref, {\n kind: 'cancel-request',\n operationId: opId,\n source,\n queued: true,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n })\n }\n return {\n operationId: opId,\n worker: request.worker,\n effect: 'unknown',\n requestedAt: request.at,\n observedAt: request.at,\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n detail: 'request queued; no runtime acknowledger has answered yet',\n terminated: [],\n }\n}\n\n/** The run-scoped cancel request file of one run — one {@link RunCancelRequest}. */\nexport function runCancelRequestFile(eventDir: string): string {\n return join(workerCancellationsDir(eventDir), 'run.request.json')\n}\n\n/** The run-scoped acknowledgement file of one run — one {@link RunCancellation}. */\nexport function runCancellationFile(eventDir: string): string {\n return join(workerCancellationsDir(eventDir), 'run.json')\n}\n\n/** Read the run-scoped cancel request, or `undefined` when none was written. */\nexport function readRunCancelRequest(eventDir: string): RunCancelRequest | undefined {\n const file = runCancelRequestFile(eventDir)\n if (!existsSync(file)) return undefined\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as Partial<RunCancelRequest>\n if (!isRunCancelRequest(parsed)) {\n throw new Error(`run cancel request '${file}' is not a complete RunCancelRequest`)\n }\n return parsed\n}\n\n/**\n * Read the acknowledgement for the run-scoped cancel operation. `undefined` when the runtime has\n * not answered. A record holding a DIFFERENT `operationId` belongs to another operation on the\n * same run — fail loud rather than answer for it.\n */\nexport function readRunCancellation(\n eventDir: string,\n operationId: string,\n): RunCancellation | undefined {\n const file = runCancellationFile(eventDir)\n if (!existsSync(file)) return undefined\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as RunCancellation\n if (parsed.operationId !== operationId) {\n throw new Error(\n `run cancel acknowledgement '${file}' holds operation '${parsed.operationId}', not ` +\n `'${operationId}' — one run carries one run-scoped cancel operation`,\n )\n }\n return parsed\n}\n\n/**\n * Durably write the run-scoped acknowledgement. Write-then-rename, so a concurrent reader sees the\n * prior complete record or the new complete record, never a partial file.\n *\n * @internal The runtime is the only intended writer; clients read via {@link readRunCancellation}\n * or {@link cancelRun}.\n */\nexport function writeRunCancellation(eventDir: string, record: RunCancellation): void {\n const dir = workerCancellationsDir(eventDir)\n mkdirSync(dir, { recursive: true })\n const file = runCancellationFile(eventDir)\n const tmp = `${file}.${randomUUID()}.tmp`\n writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\\n`, 'utf8')\n renameSync(tmp, file)\n}\n\n/**\n * Request the cancellation of the WHOLE run, idempotently, and return the operation's current\n * durable state.\n *\n * The run-scoped twin of {@link cancelWorker}: write the request into the run's cancellation\n * directory, where the run's own root manager applies it — aborting the root through the one\n * cascade controller the run already has, so every live worker comes down with it. This function\n * never applies the cancellation itself; writing a request file is not an acknowledgement.\n *\n * Idempotency is a lookup: when an acknowledgement for `operationId` already exists it is returned\n * AS-IS and nothing is written. A request the runtime has not answered yet returns\n * `effect: 'unknown'` (never a success); call again with the same `operationId` — or\n * {@link readRunCancellation} — to read the acknowledged result after a reconnect.\n *\n * A run carries ONE run-scoped operation: a second request under a different `operationId` throws\n * rather than silently replacing the pending one, because both would claim the same single abort.\n */\nexport function cancelRun(\n eventDir: string,\n operationId: string,\n options: { readonly reason?: string; readonly source?: string } = {},\n): RunCancellation {\n const opId = operationId.trim()\n if (!opId) throw new Error('cancelRun: operationId is empty')\n const acknowledged = readRunCancellation(eventDir, opId)\n if (acknowledged) return acknowledged\n const pending = readRunCancelRequest(eventDir)\n if (pending !== undefined && pending.operationId !== opId) {\n throw new Error(\n `cancelRun: run cancel '${pending.operationId}' is already pending for this run; ` +\n `read it with readRunCancellation instead of issuing '${opId}'`,\n )\n }\n const source = options.source ?? 'human'\n const request: RunCancelRequest = pending ?? {\n operationId: opId,\n at: new Date().toISOString(),\n source,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n }\n if (pending === undefined) {\n mkdirSync(workerCancellationsDir(eventDir), { recursive: true })\n writeFileSync(runCancelRequestFile(eventDir), `${JSON.stringify(request, null, 2)}\\n`, 'utf8')\n appendWorkerControlEvent(eventDir, 'run', {\n kind: 'run-cancel-request',\n operationId: opId,\n source,\n queued: true,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n })\n }\n return {\n operationId: opId,\n effect: 'unknown',\n requestedAt: request.at,\n observedAt: request.at,\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n detail: 'request queued; no runtime acknowledger has answered yet',\n }\n}\n\nfunction isRunCancelRequest(value: Partial<RunCancelRequest>): value is RunCancelRequest {\n return (\n typeof value.operationId === 'string' &&\n value.operationId.length > 0 &&\n typeof value.at === 'string' &&\n typeof value.source === 'string' &&\n (value.reason === undefined || typeof value.reason === 'string')\n )\n}\n\nfunction isWorkerCancelRequest(value: Partial<WorkerCancelRequest>): value is WorkerCancelRequest {\n return (\n typeof value.operationId === 'string' &&\n value.operationId.length > 0 &&\n typeof value.at === 'string' &&\n typeof value.source === 'string' &&\n typeof value.worker === 'string' &&\n value.worker.length > 0 &&\n (value.reason === undefined || typeof value.reason === 'string')\n )\n}\n\nfunction appendWorkerControlEvent(\n eventDir: string,\n label: string,\n event: Record<string, unknown>,\n): void {\n try {\n mkdirSync(supervisorWorkersDir(eventDir), { recursive: true })\n appendFileSync(\n workerControlLogFile(eventDir, label),\n `${JSON.stringify({ at: new Date().toISOString(), label, ...event })}\\n`,\n 'utf8',\n )\n } catch {\n // Control logging is best-effort; the inbox write above is the durable part.\n }\n}\n\nfunction isWorkerSteerRequest(value: Partial<WorkerSteerRequest>): value is WorkerSteerRequest {\n return (\n typeof value.id === 'string' &&\n typeof value.at === 'string' &&\n typeof value.source === 'string' &&\n typeof value.worker === 'string' &&\n typeof value.message === 'string' &&\n value.message.trim().length > 0\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8KA,SAAgB,mBAAmB,SAAyB;CAC1D,OAAO,KAAK,QAAQ,OAAO,GAAG,UAAU,YAAY;AACtD;;AAGA,SAAgB,iBAAiB,SAAiB,IAAoB;CACpE,OAAO,KAAK,mBAAmB,OAAO,GAAG,EAAE;AAC7C;;;;;;AAOA,SAAgB,uBAAuB,SAAiB,IAAoB;CAC1E,OAAO,KAAK,yBAAyB,OAAO,GAAG,EAAE;AACnD;;;;;AAMA,SAAgB,yBAAyB,SAAyB;CAChE,OAAO,KAAK,QAAQ,OAAO,GAAG,UAAU,YAAY;AACtD;;AAGA,SAAgB,eAAe,OAAuB;CACpD,MAAM,OAAO,MAAM,QAAQ,oBAAoB,GAAG;CAClD,OAAO,KAAK,SAAS,IAAI,OAAO;AAClC;;AAGA,SAAgB,qBAAqB,UAA0B;CAC7D,OAAO,KAAK,UAAU,SAAS;AACjC;;AAGA,SAAgB,gBAAgB,SAAiB,cAAsB,QAAwB;CAC7F,OAA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AO,MAAM,WAAW,aACvB,MAAM,WAAW,KAAA,KAAa,OAAO,MAAM,WAAW;AAE3D;AAEA,SAAS,sBAAsB,OAAmE;CAChG,OACE,OAAO,MAAM,gBAAgB,YAC7B,MAAM,YAAY,SAAS,KAC3B,OAAO,MAAM,OAAO,YACpB,OAAO,MAAM,WAAW,YACxB,OAAO,MAAM,WAAW,YACxB,MAAM,OAAO,SAAS,MACrB,MAAM,WAAW,KAAA,KAAa,OAAO,MAAM,WAAW;AAE3D;AAEA,SAAS,yBACP,UACA,OACA,OACM;CACN,IAAI;EACF,UAAU,qBAAqB,QAAQ,GAAG,EAAE,WAAW,KAAK,CAAC;EAC7D,eACE,qBAAqB,UAAU,KAAK,GACpC,GAAG,KAAK,UAAU;GAAE,qBAAI,IAAI,KAAK,EAAA,CAAE,YAAY;GAAG;GAAO,GAAG;EAAM,CAAC,EAAE,KACrE,MACF;CACF,QAAQ,CAER;AACF;AAEA,SAAS,qBAAqB,OAAiE;CAC7F,OACE,OAAO,MAAM,OAAO,YACpB,OAAO,MAAM,OAAO,YACpB,OAAO,MAAM,WAAW,YACxB,OAAO,MAAM,WAAW,YACxB,OAAO,MAAM,YAAY,YACzB,MAAM,QAAQ,KAAK,CAAC,CAAC,SAAS;AAElC"}
|
|
@@ -1,24 +1,25 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as assertInteractionBinding, B as exactControlRef, D as assertBoundaryBinding, E as abortError, F as awaitAbortable, G as hasDurableCancel, H as exactSessionCancel, I as cancellationRequest, J as freshTurnInput, K as isTerminalSessionStatus, L as copyControlRef, M as assertSequence, N as assertStableText, O as assertCanonicalEventBinding, P as assertWaitDuration, R as delay, T as RetainedRunProviderContractError, U as exactSessionResult, V as exactSession, W as freezeControlRef, j as assertResultBinding, k as assertEventBinding, q as sameControlCoordinates, z as exactContinuedControlRef } from "./materialization-Dl9J8ek4.js";
|
|
2
2
|
import { c as RetainedInteractiveAdmissionError, d as RetainedRunDispatchBindingError, l as RetainedInteractiveBindingError, m as ValidationError, n as AnalystError, s as PlannerError, u as RetainedRunAdmissionError } from "./errors-CDZ8XsVj.js";
|
|
3
|
-
import "./stream-agent-turn-
|
|
3
|
+
import "./stream-agent-turn-DYi8ymsU.js";
|
|
4
4
|
import { t as detachedSnapshot } from "./snapshot-cK9K420n.js";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
5
|
+
import { i as InMemorySpawnJournal, r as InMemoryResultBlobStore, s as insideCursorNamespace, v as isTraceAnalysisStore, x as contentAddress } from "./spawn-journal-BLnveCRS.js";
|
|
6
|
+
import { c as isAbortError, d as randomSuffix, i as cloneSpend, m as stringifySafe, p as sleep, r as chargedTokens, s as hasCompleteCacheBreakdown, t as addSpend, y as zeroSpend } from "./util-D6ZEuBMi.js";
|
|
7
|
+
import { i as writeAllBytes, n as parseCommittedJsonLines, r as prepareJsonlAppend, t as isNoEntError } from "./jsonl-file-CDfsCI5s.js";
|
|
7
8
|
import { i as redactProtectedValue, r as redactProtectedReason } from "./protected-redaction--F3v1oo8.js";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import { c as
|
|
11
|
-
import { E as rollingDispatch,
|
|
12
|
-
import "./environment-provider-
|
|
9
|
+
import { c as notifySandboxEventObserver, m as parseCanonicalTransportEvent, p as extractTransportEventIdentity } from "./sandbox-events-BVjstFgb.js";
|
|
10
|
+
import { n as executableAgentSpecSnapshot, t as executableAgentProfileSnapshot } from "./executable-spec-BUcUcEPk.js";
|
|
11
|
+
import { c as profileModelExecutionSettings, i as concreteModelId, l as profileProviderModel, o as enforceTokenLimits, t as assertExecutableAgentProfile } from "./model-policy-Sw4ywhtL.js";
|
|
12
|
+
import { B as createExecutorRegistry, Ct as canonicalObservedModel, E as rollingDispatch, H as createWorktreeCliExecutor, St as runBrainLoop, X as createPushTraceSource, _t as runAgentRounds, g as settledToIteration, ht as defaultSelectWinner, l as withDriverExecutor, n as createSupervisor, vt as createSandboxLineage, xt as routerBrain, yt as probeSandboxCapabilities, z as createExecutor } from "./supervisor-CMZsJ7Wn.js";
|
|
13
|
+
import "./environment-provider-3eCszBEm.js";
|
|
13
14
|
import { i as notifyRuntimeHookEvent } from "./runtime-hooks-tXpAarhW.js";
|
|
14
|
-
import { C as observe, O as strategyAuthorMethod, T as profileChatClient, b as sample, v as refine, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-
|
|
15
|
-
import {
|
|
16
|
-
import "./authoring-
|
|
17
|
-
import "./graph-
|
|
15
|
+
import { C as observe, O as strategyAuthorMethod, T as profileChatClient, b as sample, v as refine, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-D7V-HgXJ.js";
|
|
16
|
+
import { At as mapExecutorResult, kt as gateOnDeliverable, n as supervise } from "./supervise-k_8VOASb.js";
|
|
17
|
+
import "./authoring-CcVhJ1lP.js";
|
|
18
|
+
import "./graph-CIh2HDmH.js";
|
|
18
19
|
import { AgentEnvironmentCapabilitiesSchema, AgentExactRunControlRefSchema, AgentInteractiveSessionControlClaimAcknowledgementSchema, AgentInteractiveSessionControlClaimSchema, AgentInteractiveSessionPromptAcknowledgementSchema, AgentInteractiveSessionRefSchema, AgentInteractiveSessionStatusSchema, AgentInteractiveSessionStopAcknowledgementSchema, AgentNativeContextContinuationResultSchema, AgentTurnResultSchema, InteractionAcknowledgementSchema, InteractionResponseCommandSchema, NativeContextBoundaryProofSchema, NativeContextContinuationRequestSchema, RuntimeEventEnvelopeSchema, TerminalReplayWindowSchema, TerminalSessionRefSchema, agentInteractiveSessionControlClaimAcknowledgementMatchesRequest, agentInteractiveSessionControlClaimMatchesRef, agentInteractiveSessionControlClaimRequestDigest, agentInteractiveSessionPromptAcknowledgementMatchesCommand, agentInteractiveSessionRefMatchesStart, agentInteractiveSessionRunRef, agentInteractiveSessionStatusMatchesRef, agentInteractiveSessionStopAcknowledgementMatchesCommand, agentNativeContextContinuationResultMatchesRequest, agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, exactAgentInteractiveSessionStart, nativeContextContinuationTurnDigest, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
|
|
19
|
-
import { CODING_HARNESSES, InMemoryTraceStore, OUTPUT_VALUE, benjaminiHochberg, buildTrajectory, computeFindingId as computeFindingId$1, confidenceInterval, expandProfileAxes, makeFinding as makeFinding$1, pairedBootstrap, paretoFrontier, wilcoxonSignedRank, wilson } from "@tangle-network/agent-eval";
|
|
20
|
+
import { CODING_HARNESSES, DEFAULT_TRACE_ANALYST_KINDS, InMemoryTraceStore, OUTPUT_VALUE, benjaminiHochberg, buildTrajectory, computeFindingId as computeFindingId$1, confidenceInterval, expandProfileAxes, makeFinding as makeFinding$1, pairedBootstrap, paretoFrontier, wilcoxonSignedRank, wilson } from "@tangle-network/agent-eval";
|
|
20
21
|
import { heldoutSignificance, runProfileMatrix } from "@tangle-network/agent-eval/campaign";
|
|
21
|
-
import { createHash } from "node:crypto";
|
|
22
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
22
23
|
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
23
24
|
import { mkdir, readFile, realpath, writeFile } from "node:fs/promises";
|
|
24
25
|
import { appendFileSync, chmodSync, constants, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
@@ -1390,7 +1391,7 @@ function localSandboxClient(opts) {
|
|
|
1390
1391
|
routerKey: router.key,
|
|
1391
1392
|
model,
|
|
1392
1393
|
...settings.retry !== void 0 ? { retry: settings.retry } : {},
|
|
1393
|
-
...settings.
|
|
1394
|
+
...enforceTokenLimits(settings.tokenLimits, "router", "localSandboxClient").applied,
|
|
1394
1395
|
...settings.stream !== void 0 ? { stream: settings.stream } : {}
|
|
1395
1396
|
}, {
|
|
1396
1397
|
...settings.temperature !== void 0 ? { temperature: settings.temperature } : {},
|
|
@@ -2703,8 +2704,9 @@ var InMemoryCorpus = class {
|
|
|
2703
2704
|
* back silently) and folding by `id`: a later identical line dedups, a later conflicting line
|
|
2704
2705
|
* under the same `id` is a corruption (fail loud). `append` first replays to enforce the same
|
|
2705
2706
|
* idempotence/conflict contract as the in-mem impl, then fsyncs the new line so a crash between
|
|
2706
|
-
* writes never loses an acknowledged fact.
|
|
2707
|
-
*
|
|
2707
|
+
* writes never loses an acknowledged fact. Reads and appends over the shared append-only
|
|
2708
|
+
* spine (`durable/jsonl-file`) — the same one the spawn journal uses — but the interface stays
|
|
2709
|
+
* separate (a learned fact is not a replay record).
|
|
2708
2710
|
*/
|
|
2709
2711
|
var FileCorpus = class {
|
|
2710
2712
|
path;
|
|
@@ -2752,16 +2754,10 @@ var FileCorpus = class {
|
|
|
2752
2754
|
if (isNoEntError(err)) return /* @__PURE__ */ new Map();
|
|
2753
2755
|
throw err;
|
|
2754
2756
|
}
|
|
2755
|
-
const lines = text.split("\n").filter((line) => line.length > 0);
|
|
2756
2757
|
const byId = /* @__PURE__ */ new Map();
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
try {
|
|
2761
|
-
parsed = JSON.parse(line);
|
|
2762
|
-
} catch (err) {
|
|
2763
|
-
throw new Error(`corpus corrupted: ${this.path} line ${i + 1} is not valid JSON: ` + (err instanceof Error ? err.message : String(err)));
|
|
2764
|
-
}
|
|
2758
|
+
const records = parseCommittedJsonLines(text, this.path);
|
|
2759
|
+
for (let i = 0; i < records.length; i++) {
|
|
2760
|
+
const parsed = records[i];
|
|
2765
2761
|
assertCorpusRecord(parsed, `corpus ${this.path} line ${i + 1}`);
|
|
2766
2762
|
const existing = byId.get(parsed.id);
|
|
2767
2763
|
if (existing && !recordsEqual(existing, parsed)) throw new Error(`corpus corrupted: ${this.path} has two different records for id '${parsed.id}'; an append-only corpus must never hold a conflicting re-append under one id`);
|
|
@@ -2773,9 +2769,10 @@ var FileCorpus = class {
|
|
|
2773
2769
|
const fs = await import("node:fs/promises");
|
|
2774
2770
|
const path = await import("node:path");
|
|
2775
2771
|
await fs.mkdir(path.dirname(this.path), { recursive: true });
|
|
2772
|
+
const needsSeparator = await prepareJsonlAppend(this.path);
|
|
2776
2773
|
const fh = await fs.open(this.path, "a");
|
|
2777
2774
|
try {
|
|
2778
|
-
await fh
|
|
2775
|
+
await writeAllBytes(fh, `${needsSeparator ? "\n" : ""}${JSON.stringify(record)}\n`);
|
|
2779
2776
|
await fh.sync();
|
|
2780
2777
|
} finally {
|
|
2781
2778
|
await fh.close();
|
|
@@ -2828,9 +2825,6 @@ function renderLine(record) {
|
|
|
2828
2825
|
function freeze(record) {
|
|
2829
2826
|
return Object.freeze({ ...record });
|
|
2830
2827
|
}
|
|
2831
|
-
function isNoEntError(err) {
|
|
2832
|
-
return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
|
|
2833
|
-
}
|
|
2834
2828
|
//#endregion
|
|
2835
2829
|
//#region src/runtime/personify/registry.ts
|
|
2836
2830
|
/**
|
|
@@ -3062,6 +3056,30 @@ function mergeSeams(ctx, seams) {
|
|
|
3062
3056
|
}
|
|
3063
3057
|
//#endregion
|
|
3064
3058
|
//#region src/runtime/personify/trajectory.ts
|
|
3059
|
+
/**
|
|
3060
|
+
*
|
|
3061
|
+
* Trajectory trace + cost ledger — the post-hoc tree reconstructor (§4 of `wave-types`).
|
|
3062
|
+
*
|
|
3063
|
+
* `trajectoryReport` rebuilds the WHOLE realized spawn tree from the durable
|
|
3064
|
+
* `SpawnJournal` (+ optionally the `ResultBlobStore` for `done` artifacts): every node
|
|
3065
|
+
* (driver AND leaf), the real parent/child edges, each node's terminal status, its OWN
|
|
3066
|
+
* conserved `Spend`, and the `Spend` ROLLED UP over its subtree. Roll-up is a post-order
|
|
3067
|
+
* fold over the parent edges: a node's `rolledUpSpend` is its own spend plus every
|
|
3068
|
+
* descendant's, so a driver is charged for the fanout it caused — the root's roll-up is
|
|
3069
|
+
* the whole run's conserved total (tokens + usd + iterations + ms).
|
|
3070
|
+
*
|
|
3071
|
+
* `equalKOnCost` compares separate runs (arms) on that conserved COST, not on raw
|
|
3072
|
+
* iteration COUNT. The sandbox executor reports tokens/usd INCLUSIVE of a leaf's internal
|
|
3073
|
+
* sub-agent fanout, so charging an arm by `total.tokens`/`total.usd` (not by how many
|
|
3074
|
+
* `next()` cursors it logged) closes the leaf-fanout confound: a treatment leaf that fanned
|
|
3075
|
+
* out internally pays for it in cost, where a per-iteration count would hide it. The
|
|
3076
|
+
* within-run conserved pool already guarantees `Σk` equal by construction; this check is the
|
|
3077
|
+
* CROSS-run analogue the pool cannot reach — proving equal compute before any win is claimed.
|
|
3078
|
+
*
|
|
3079
|
+
* Pure over the journal/blobs — no live agent calls; safe to run on a finished run's log.
|
|
3080
|
+
*
|
|
3081
|
+
* @experimental
|
|
3082
|
+
*/
|
|
3065
3083
|
const defaultEqualKTolerance = .05;
|
|
3066
3084
|
/**
|
|
3067
3085
|
* Reconstruct the whole spawn tree for `root` with per-node + rolled-up `Spend`. Reads the
|
|
@@ -3074,7 +3092,7 @@ async function trajectoryReport(journal, blobs, root, options = {}) {
|
|
|
3074
3092
|
const events = await journal.loadTree(root);
|
|
3075
3093
|
if (events === void 0) throw new Error(`trajectoryReport: no journaled tree for root '${root}'`);
|
|
3076
3094
|
const spawns = events.filter(isNodeCreation).sort(bySeq);
|
|
3077
|
-
const closes = events.filter(
|
|
3095
|
+
const closes = events.filter(insideCursorNamespace).sort(bySeq);
|
|
3078
3096
|
const nodes = /* @__PURE__ */ new Map();
|
|
3079
3097
|
for (const ev of spawns) nodes.set(ev.id, {
|
|
3080
3098
|
id: ev.id,
|
|
@@ -3104,7 +3122,7 @@ async function trajectoryReport(journal, blobs, root, options = {}) {
|
|
|
3104
3122
|
for (const ev of events) {
|
|
3105
3123
|
if (ev.kind !== "metered") continue;
|
|
3106
3124
|
const node = requireNode(nodes, ev.id, root);
|
|
3107
|
-
node.ownSpend =
|
|
3125
|
+
node.ownSpend = addSpend(node.ownSpend, ev.spend);
|
|
3108
3126
|
}
|
|
3109
3127
|
if (!nodes.has(root)) throw new Error(`trajectoryReport: root '${root}' has no spawned event in its journaled tree (corrupted log)`);
|
|
3110
3128
|
for (const ev of spawns) {
|
|
@@ -3181,8 +3199,8 @@ function rollUpSpend(nodes, root) {
|
|
|
3181
3199
|
});
|
|
3182
3200
|
continue;
|
|
3183
3201
|
}
|
|
3184
|
-
|
|
3185
|
-
for (const child of node.children) addSpend(sum, requireSpend(rolled, child, root));
|
|
3202
|
+
let sum = cloneSpend(node.ownSpend);
|
|
3203
|
+
for (const child of node.children) sum = addSpend(sum, requireSpend(rolled, child, root));
|
|
3186
3204
|
rolled.set(frame.id, sum);
|
|
3187
3205
|
}
|
|
3188
3206
|
return rolled;
|
|
@@ -3226,51 +3244,6 @@ function countStatuses(reported) {
|
|
|
3226
3244
|
for (const node of reported) counts[node.status] += 1;
|
|
3227
3245
|
return counts;
|
|
3228
3246
|
}
|
|
3229
|
-
function zeroSpend() {
|
|
3230
|
-
return {
|
|
3231
|
-
iterations: 0,
|
|
3232
|
-
tokens: zeroTokenUsage(),
|
|
3233
|
-
usd: 0,
|
|
3234
|
-
ms: 0
|
|
3235
|
-
};
|
|
3236
|
-
}
|
|
3237
|
-
/** Add a `metered` event's spend onto a node's accumulated ownSpend (per channel). */
|
|
3238
|
-
function addNodeSpend(a, b) {
|
|
3239
|
-
return {
|
|
3240
|
-
iterations: a.iterations + b.iterations,
|
|
3241
|
-
tokens: (() => {
|
|
3242
|
-
const tokens = cloneTokenUsage(a.tokens);
|
|
3243
|
-
addTokenUsage(tokens, b.tokens);
|
|
3244
|
-
return tokens;
|
|
3245
|
-
})(),
|
|
3246
|
-
...a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {},
|
|
3247
|
-
usd: a.usd + b.usd,
|
|
3248
|
-
...a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {},
|
|
3249
|
-
...usdEstimatedOf(a, b),
|
|
3250
|
-
ms: a.ms + b.ms
|
|
3251
|
-
};
|
|
3252
|
-
}
|
|
3253
|
-
function cloneSpend(spend) {
|
|
3254
|
-
return {
|
|
3255
|
-
iterations: spend.iterations,
|
|
3256
|
-
tokens: cloneTokenUsage(spend.tokens),
|
|
3257
|
-
...spend.tokensKnown === false ? { tokensKnown: false } : {},
|
|
3258
|
-
usd: spend.usd,
|
|
3259
|
-
...spend.usdKnown === false ? { usdKnown: false } : {},
|
|
3260
|
-
...spend.usdEstimated !== void 0 ? { usdEstimated: spend.usdEstimated } : {},
|
|
3261
|
-
ms: spend.ms
|
|
3262
|
-
};
|
|
3263
|
-
}
|
|
3264
|
-
/** Add `delta` into `acc` in place across every conserved channel. */
|
|
3265
|
-
function addSpend(acc, delta) {
|
|
3266
|
-
acc.iterations += delta.iterations;
|
|
3267
|
-
addTokenUsage(acc.tokens, delta.tokens);
|
|
3268
|
-
if (delta.tokensKnown === false) acc.tokensKnown = false;
|
|
3269
|
-
acc.usd += delta.usd;
|
|
3270
|
-
if (delta.usdKnown === false) acc.usdKnown = false;
|
|
3271
|
-
if (delta.usdEstimated !== void 0) acc.usdEstimated = (acc.usdEstimated ?? 0) + delta.usdEstimated;
|
|
3272
|
-
acc.ms += delta.ms;
|
|
3273
|
-
}
|
|
3274
3247
|
function spreadOf(values) {
|
|
3275
3248
|
if (values.length === 0) return 0;
|
|
3276
3249
|
return Math.max(...values) - Math.min(...values);
|
|
@@ -4069,11 +4042,26 @@ async function dispatchRetainedRun(options) {
|
|
|
4069
4042
|
sessionId: identity.sessionId,
|
|
4070
4043
|
executionId: identity.executionId
|
|
4071
4044
|
});
|
|
4072
|
-
const
|
|
4073
|
-
|
|
4074
|
-
|
|
4075
|
-
|
|
4076
|
-
|
|
4045
|
+
const destroyIfCreated = async (cause) => {
|
|
4046
|
+
if (environment.creation !== "created") throw cause;
|
|
4047
|
+
try {
|
|
4048
|
+
await environment.destroy?.();
|
|
4049
|
+
} catch (cleanupError) {
|
|
4050
|
+
throw new AggregateError([cause, cleanupError], "retained run dispatch failed and the environment it created could not be destroyed");
|
|
4051
|
+
}
|
|
4052
|
+
throw cause;
|
|
4053
|
+
};
|
|
4054
|
+
let reference;
|
|
4055
|
+
try {
|
|
4056
|
+
reference = await environment.dispatch(freshTurnInput(options.turn, {
|
|
4057
|
+
turnId: options.turn.turnId,
|
|
4058
|
+
detach: true,
|
|
4059
|
+
...identity
|
|
4060
|
+
}));
|
|
4061
|
+
} catch (error) {
|
|
4062
|
+
await destroyIfCreated(error);
|
|
4063
|
+
throw error;
|
|
4064
|
+
}
|
|
4077
4065
|
let exact;
|
|
4078
4066
|
try {
|
|
4079
4067
|
if (reference.provider !== void 0 && reference.provider !== options.provider.name) throw new Error("provider dispatch returned a session reference for another provider");
|
|
@@ -4086,7 +4074,7 @@ async function dispatchRetainedRun(options) {
|
|
|
4086
4074
|
if (controlRef.executionId !== identity.executionId) throw new Error("provider bound another execution than the requested identity");
|
|
4087
4075
|
exact = exactSession(environment, controlRef);
|
|
4088
4076
|
} catch (error) {
|
|
4089
|
-
|
|
4077
|
+
const bindingError = new RetainedRunDispatchBindingError({
|
|
4090
4078
|
provider: options.provider.name,
|
|
4091
4079
|
environmentId: environment.id,
|
|
4092
4080
|
sessionId: identity.sessionId,
|
|
@@ -4096,6 +4084,8 @@ async function dispatchRetainedRun(options) {
|
|
|
4096
4084
|
...reference.provider === void 0 ? {} : { provider: reference.provider },
|
|
4097
4085
|
...reference.controlRef === void 0 ? {} : { controlRef: reference.controlRef }
|
|
4098
4086
|
}, { cause: error });
|
|
4087
|
+
await destroyIfCreated(bindingError);
|
|
4088
|
+
throw bindingError;
|
|
4099
4089
|
}
|
|
4100
4090
|
await admitDurably(options.onAdmission, {
|
|
4101
4091
|
phase: "dispatched",
|
|
@@ -4676,13 +4666,13 @@ async function runBenchmark(cfg) {
|
|
|
4676
4666
|
resolved: false,
|
|
4677
4667
|
progression: [],
|
|
4678
4668
|
usd: 0,
|
|
4679
|
-
usdKnown:
|
|
4669
|
+
usdKnown: false,
|
|
4680
4670
|
ms: 0,
|
|
4681
4671
|
tokens: {
|
|
4682
4672
|
input: 0,
|
|
4683
4673
|
output: 0
|
|
4684
4674
|
},
|
|
4685
|
-
tokensKnown:
|
|
4675
|
+
tokensKnown: false
|
|
4686
4676
|
};
|
|
4687
4677
|
}
|
|
4688
4678
|
row = {
|
|
@@ -6291,6 +6281,43 @@ function traceSurfaceCalls(base) {
|
|
|
6291
6281
|
traceSource: trace.source
|
|
6292
6282
|
};
|
|
6293
6283
|
}
|
|
6284
|
+
/**
|
|
6285
|
+
* Adapt an `agent-eval` `AnalystRegistry` into the lens shape `supervise({ analysts })` takes.
|
|
6286
|
+
*
|
|
6287
|
+
* The two registries were never structurally compatible: eval's class exposes `list()` and
|
|
6288
|
+
* `run(runId, inputs, opts)` and returns an `AnalystRunResult`, while `supervise` wants `kinds`
|
|
6289
|
+
* and `run(kindId, trace)`. So `'kinds' in buildDefaultAnalystRegistry()` is `false` and the five
|
|
6290
|
+
* calibrated lenses in `DEFAULT_TRACE_ANALYST_KINDS` were unreachable from any supervised run —
|
|
6291
|
+
* every consumer hand-rolled a lens instead (#630).
|
|
6292
|
+
*
|
|
6293
|
+
* The adapter lives HERE, not in eval, for one reason: eval must never import runtime, and runtime
|
|
6294
|
+
* already owns both shapes — it consumes `AnalystFinding` / `AnalystRunResult` from eval for its
|
|
6295
|
+
* analyst loop and defines the supervise lens itself. Writing it in eval would mean eval declaring
|
|
6296
|
+
* a duck-typed copy of a type this package already exports.
|
|
6297
|
+
*
|
|
6298
|
+
* `kinds` is the DEFINITION list, not `registry.list()`, because `Analyst` carries no `area` while
|
|
6299
|
+
* `TraceAnalystDefinition` does — `list()` cannot supply the field the lens shape requires. Every
|
|
6300
|
+
* id must be registered: an unknown kind throws at adapt time rather than returning nothing at run
|
|
6301
|
+
* time, when the driver would read the silence as "no findings".
|
|
6302
|
+
*/
|
|
6303
|
+
function analystsFromRegistry(registry, kinds = DEFAULT_TRACE_ANALYST_KINDS, opts) {
|
|
6304
|
+
const registered = new Set(registry.list().map((analyst) => analyst.id));
|
|
6305
|
+
const missing = kinds.map((kind) => kind.id).filter((id) => !registered.has(id));
|
|
6306
|
+
if (missing.length > 0) throw new ValidationError(`analystsFromRegistry: ${missing.map((id) => JSON.stringify(id)).join(", ")} ${missing.length === 1 ? "is" : "are"} not registered; the registry has ${[...registered].map((id) => JSON.stringify(id)).join(", ") || "<none>"}`);
|
|
6307
|
+
return {
|
|
6308
|
+
kinds: kinds.map((kind) => ({
|
|
6309
|
+
id: kind.id,
|
|
6310
|
+
description: kind.description,
|
|
6311
|
+
area: kind.area
|
|
6312
|
+
})),
|
|
6313
|
+
run: async (kindId, trace) => {
|
|
6314
|
+
return (await registry.run(`supervise-analyst-${kindId}-${randomUUID()}`, { traceStore: trace }, {
|
|
6315
|
+
...opts?.runOpts,
|
|
6316
|
+
only: [kindId]
|
|
6317
|
+
})).findings;
|
|
6318
|
+
}
|
|
6319
|
+
};
|
|
6320
|
+
}
|
|
6294
6321
|
/** The default self-improvement LENS — authored content, not a code path. On each settled worker it hands
|
|
6295
6322
|
* the driver the still-FAILING tests (not just a score), so the next spawn targets the persistently-hard
|
|
6296
6323
|
* cases. Swap `analysts` to change what the driver improves from — that's the one knob. */
|
|
@@ -6431,7 +6458,7 @@ async function superviseSurface(profile, task, opts) {
|
|
|
6431
6458
|
maxIterations: (innerTurns + 2) * 5 + 16,
|
|
6432
6459
|
maxTokens: 1e9
|
|
6433
6460
|
};
|
|
6434
|
-
const workerMaxTokens =
|
|
6461
|
+
const workerMaxTokens = Math.max(1, Math.floor(budget.maxTokens / 8));
|
|
6435
6462
|
const makeWorkerAgent = (rawProfile) => {
|
|
6436
6463
|
const p = rawProfile ?? {};
|
|
6437
6464
|
return {
|
|
@@ -6476,12 +6503,6 @@ async function superviseSurface(profile, task, opts) {
|
|
|
6476
6503
|
completions: sp.iterations
|
|
6477
6504
|
};
|
|
6478
6505
|
}
|
|
6479
|
-
function profileMaxTokens(profile) {
|
|
6480
|
-
const value = profile.model?.metadata?.maxTokens;
|
|
6481
|
-
if (value === void 0) return void 0;
|
|
6482
|
-
if (!Number.isSafeInteger(value) || value < 1) throw new Error("superviseSurface: AgentProfile.model.metadata.maxTokens must be a positive safe integer");
|
|
6483
|
-
return value;
|
|
6484
|
-
}
|
|
6485
6506
|
//#endregion
|
|
6486
6507
|
//#region src/runtime/surface-diff.ts
|
|
6487
6508
|
/**
|
|
@@ -7095,6 +7116,6 @@ function tail(s) {
|
|
|
7095
7116
|
return s.slice(-400);
|
|
7096
7117
|
}
|
|
7097
7118
|
//#endregion
|
|
7098
|
-
export {
|
|
7119
|
+
export { definePersona as $, discriminatingMeans as A, sentinelCompletion as At, printBenchmarkReport as B, McpSpawnFault as Bt, withUntrackedArtifacts as C, localSandboxClient as Ct, chatTransportExecutor as D, superviseDispatch as Dt, runCoderChecks as E, loopDispatch as Et, authorStrategy as F, renderLeaderboardMarkdown as Ft, startRetainedInteractiveRun as G, envKeyProvider as Gt, claimRetainedInteractiveControl as H, materializeLocalMcp as Ht, strategyAuthorContract as I, renderLeaderboardSvg as It, startRetainedRun as J, resolveSecretEnv as Jt, reconnectRetainedRun as K, mcpSecretEnvMetadataKey as Kt, strategyAuthorSystemPrompt as L, renderPairwiseMarkdown as Lt, runStrategyEvolution as M, leaderboard as Mt, selectChampion as N, pairwiseSignificance as Nt, chatWorkerSeam as O, completionAuthorizes as Ot, assertStrategyContract as P, renderLeaderboardHtml as Pt, trajectoryReport as Q, SandboxRunAbortError as R, auditIntent as Rt, copyUntrackedIntoClone as S, resolveSandboxClient as St, patchDelivered as T, loopCampaignDispatch as Tt, reconnectRetainedInteractiveRun as U, createMcpEnvironment as Ut, runBenchmark as V, connectStdioMcp as Vt, recoverRetainedInteractiveRun as W, sanitizeMcpToolSchema as Wt, promotionGate as X, startRetainedRunInEnvironment as Y, secretEnvOfMcpServer as Yt, equalKOnCost as Z, NOTE_MAX_CHARS as _, createScopeAnalyst as _t, localShell as a, InMemoryCorpus as at, composeWorkerEvidence as b, harvestCorpus as bt, createVerifierEnvironment as c, flatWidenGate as ct, harvestSurfaceDiffs as d, pipeline as dt, runPersonified as et, analystsFromRegistry as f, selectValidWinner as ft, EVIDENCE_MAX_CHARS as g, buildSteerContext as gt, worktreeFanout as h, assertTraceDerivedFindings as ht, jjWorkspace as i, FileCorpus as it, pickChampion as j, stopSentinel as jt, createChatSessionStore as k, deterministicCompletion as kt, boxSurfaceReader as l, loopUntil as lt, superviseSurface as m, widen as mt, makeFinding$1 as n, createShapeRegistry as nt, runInWorkspace as o, renderCorpusToInstructions as ot, failuresAnalyst as p, verify as pt, recoverRetainedRun as q, resolveMcpServerLaunch as qt, gitWorkspace as r, registerShape as rt, createWaterfallCollector as s, fanout as st, computeFindingId$1 as t, builtinShapes as tt, fsSurfaceReader as u, panel as ut, VERIFY_TAIL_CHARS as v, registryScopeAnalyst as vt, analyzeTrace as w, inlineSandboxClient as wt, settledWorkerOut as x, defineLeaderboard as xt, closingWorkerNote as y, inProcessSandboxClient as yt, openSandboxRun as z, defaultAuditorInstruction as zt };
|
|
7099
7120
|
|
|
7100
|
-
//# sourceMappingURL=runtime
|
|
7121
|
+
//# sourceMappingURL=runtime--Jsq8JCC.js.map
|