@tangle-network/agent-runtime 0.206.1 → 0.208.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 (62) hide show
  1. package/dist/{activation-D8FvmCf5.js → activation-9wJniom2.js} +2 -2
  2. package/dist/{activation-D8FvmCf5.js.map → activation-9wJniom2.js.map} +1 -1
  3. package/dist/{activation-3drfS9_j.d.ts → activation-Dan50rKs.d.ts} +2 -2
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +2 -2
  6. package/dist/{coordination-driver-CwT-9dXa.js → coordination-driver-CqZGBqdt.js} +22 -8
  7. package/dist/coordination-driver-CqZGBqdt.js.map +1 -0
  8. package/dist/{delegate-yLW9_OGW.js → delegate-CU7bWMuW.js} +2 -2
  9. package/dist/{delegate-yLW9_OGW.js.map → delegate-CU7bWMuW.js.map} +1 -1
  10. package/dist/durable.d.ts +2 -2
  11. package/dist/durable.js +2 -2
  12. package/dist/{graph-Dcb2PVEB.js → graph-B0cNCFmD.js} +4 -4
  13. package/dist/{graph-Dcb2PVEB.js.map → graph-B0cNCFmD.js.map} +1 -1
  14. package/dist/{improvement-cycle-ByIC070x.js → improvement-cycle-Bsm8TBDT.js} +3 -3
  15. package/dist/{improvement-cycle-ByIC070x.js.map → improvement-cycle-Bsm8TBDT.js.map} +1 -1
  16. package/dist/{index-B62R6dL9.d.ts → index-CHkf3b2C.d.ts} +4171 -4095
  17. package/dist/index.d.ts +4 -4
  18. package/dist/index.js +7 -7
  19. package/dist/intelligence.d.ts +2 -2
  20. package/dist/intelligence.js +3 -3
  21. package/dist/kernel.d.ts +3 -3
  22. package/dist/kernel.js +10 -10
  23. package/dist/{loop-runner-bin-CArH3v2c.d.ts → loop-runner-bin-BUVcdgNU.d.ts} +3 -3
  24. package/dist/{loop-runner-bin-CNNq7tcp.js → loop-runner-bin-CLxG15ta.js} +3 -3
  25. package/dist/{loop-runner-bin-CNNq7tcp.js.map → loop-runner-bin-CLxG15ta.js.map} +1 -1
  26. package/dist/loop-runner-bin.d.ts +1 -1
  27. package/dist/loop-runner-bin.js +1 -1
  28. package/dist/mcp/bin.js +3 -3
  29. package/dist/mcp/index.d.ts +2 -2
  30. package/dist/mcp/index.js +4 -4
  31. package/dist/platform.d.ts +4 -2
  32. package/dist/platform.js +34 -3
  33. package/dist/platform.js.map +1 -1
  34. package/dist/{provision-supervisor-B8zEk1-7.js → provision-supervisor-CEMk0grI.js} +5 -5
  35. package/dist/{provision-supervisor-B8zEk1-7.js.map → provision-supervisor-CEMk0grI.js.map} +1 -1
  36. package/dist/{redact-CLRRxkXF.js → redact-BMwd8IBm.js} +243 -31
  37. package/dist/redact-BMwd8IBm.js.map +1 -0
  38. package/dist/{run-layout-B8I_LXN-.js → run-layout-hZREkcfu.js} +10 -5
  39. package/dist/run-layout-hZREkcfu.js.map +1 -0
  40. package/dist/{runtime-C-oKXuHJ.js → runtime-ByeeZbA3.js} +264 -13
  41. package/dist/runtime-ByeeZbA3.js.map +1 -0
  42. package/dist/{server-CLtEdwo_.js → server-Bl1F2Y3v.js} +3 -3
  43. package/dist/{server-CLtEdwo_.js.map → server-Bl1F2Y3v.js.map} +1 -1
  44. package/dist/{stream-agent-turn-CpRKkS19.d.ts → stream-agent-turn-B3NfR48z.d.ts} +34 -4
  45. package/dist/{structural-rollout-Bnewh9dN.js → structural-rollout-DsGWoyj4.js} +2 -2
  46. package/dist/{structural-rollout-Bnewh9dN.js.map → structural-rollout-DsGWoyj4.js.map} +1 -1
  47. package/dist/{supervise-BN5VMhRq.js → supervise-D3r_gEyO.js} +24 -22
  48. package/dist/supervise-D3r_gEyO.js.map +1 -0
  49. package/dist/testing.d.ts +2 -2
  50. package/dist/testing.js +12 -12
  51. package/dist/{top-app-KgIFpD9H.js → top-app-CMMd8DgR.js} +6 -2
  52. package/dist/top-app-CMMd8DgR.js.map +1 -0
  53. package/dist/tui/bin.js +1 -1
  54. package/dist/tui/index.d.ts +2 -1
  55. package/dist/tui/index.js +2 -2
  56. package/package.json +1 -1
  57. package/dist/coordination-driver-CwT-9dXa.js.map +0 -1
  58. package/dist/redact-CLRRxkXF.js.map +0 -1
  59. package/dist/run-layout-B8I_LXN-.js.map +0 -1
  60. package/dist/runtime-C-oKXuHJ.js.map +0 -1
  61. package/dist/supervise-BN5VMhRq.js.map +0 -1
  62. package/dist/top-app-KgIFpD9H.js.map +0 -1
@@ -489,6 +489,7 @@ function writeRunCancellation(eventDir, record) {
489
489
  * rather than silently replacing the pending one, because both would claim the same single abort.
490
490
  */
491
491
  function cancelRun(eventDir, operationId, options = {}) {
492
+ if (options.deadlineMs !== void 0 && (!Number.isFinite(options.deadlineMs) || options.deadlineMs < 0)) throw new Error("cancelRun: deadlineMs must be a finite nonnegative number");
492
493
  const opId = operationId.trim();
493
494
  if (!opId) throw new Error("cancelRun: operationId is empty");
494
495
  const pending = readRunCancelRequest(eventDir);
@@ -496,7 +497,8 @@ function cancelRun(eventDir, operationId, options = {}) {
496
497
  const candidate = {
497
498
  operationId: opId,
498
499
  source: options.source ?? "human",
499
- ...options.reason === void 0 ? {} : { reason: options.reason }
500
+ ...options.reason === void 0 ? {} : { reason: options.reason },
501
+ ...options.deadlineMs === void 0 ? {} : { deadlineMs: options.deadlineMs }
500
502
  };
501
503
  if (pending !== void 0) assertSameRunCancelRequest(pending, candidate);
502
504
  const acknowledged = readRunCancellation(eventDir, opId);
@@ -510,7 +512,8 @@ function cancelRun(eventDir, operationId, options = {}) {
510
512
  operationId: opId,
511
513
  at: (/* @__PURE__ */ new Date()).toISOString(),
512
514
  source,
513
- ...options.reason === void 0 ? {} : { reason: options.reason }
515
+ ...options.reason === void 0 ? {} : { reason: options.reason },
516
+ ...options.deadlineMs === void 0 ? {} : { deadlineMs: options.deadlineMs }
514
517
  };
515
518
  if (pending === void 0) {
516
519
  const dir = workerCancellationsDir(eventDir);
@@ -525,7 +528,8 @@ function cancelRun(eventDir, operationId, options = {}) {
525
528
  operationId: opId,
526
529
  source,
527
530
  queued: true,
528
- ...options.reason === void 0 ? {} : { reason: options.reason }
531
+ ...options.reason === void 0 ? {} : { reason: options.reason },
532
+ ...options.deadlineMs === void 0 ? {} : { deadlineMs: options.deadlineMs }
529
533
  });
530
534
  }
531
535
  return {
@@ -550,13 +554,14 @@ function assertWorkerCancellationMatchesCandidate(existing, candidate) {
550
554
  function assertSameRunCancelRequest(existing, candidate) {
551
555
  if (existing.operationId !== candidate.operationId) throw new Error(`cancelRun: operation '${candidate.operationId}' has an id collision`);
552
556
  if (existing.source !== candidate.source) throw new Error(`cancelRun: operation '${candidate.operationId}' conflicts with its admitted request (source '${existing.source}' != '${candidate.source}')`);
557
+ if (existing.deadlineMs !== candidate.deadlineMs) throw new Error(`cancelRun: operation '${candidate.operationId}' conflicts with its admitted request (deadlineMs differs)`);
553
558
  if (existing.reason !== candidate.reason) throw new Error(`cancelRun: operation '${candidate.operationId}' conflicts with its admitted request (reason differs)`);
554
559
  }
555
560
  function assertRunCancellationMatchesCandidate(existing, candidate) {
556
561
  if (existing.reason !== candidate.reason) throw new Error(`cancelRun: operation '${candidate.operationId}' conflicts with its acknowledgement (reason differs)`);
557
562
  }
558
563
  function isRunCancelRequest(value) {
559
- 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");
564
+ return typeof value.operationId === "string" && value.operationId.length > 0 && typeof value.at === "string" && typeof value.source === "string" && (value.deadlineMs === void 0 || Number.isFinite(value.deadlineMs) && value.deadlineMs >= 0) && (value.reason === void 0 || typeof value.reason === "string");
560
565
  }
561
566
  function isWorkerCancelRequest(value) {
562
567
  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");
@@ -642,4 +647,4 @@ function assertSameSteerRequest(existing, candidate) {
642
647
  //#endregion
643
648
  export { writeWorkerCancellation as A, workerInboxFileFromEventDir as C, workerSteerRequestsDir as D, workerSteerRequestFile as E, writeWorkerSteerAcknowledgement as M, workerSteersDir as O, workerInboxFile as S, workerSteerAcknowledgementsDir as T, supervisorWorkersDir as _, legacySupervisorRunsRoot as a, workerCancellationsDir as b, readWorkerCancelRequests as c, readWorkerSteerRequests as d, runCancelRequestFile as f, supervisorRunsRoot as g, supervisorRunDir as h, legacySupervisorRunDir as i, writeWorkerSteer as j, writeRunCancellation as k, readWorkerCancellation as l, safeWorkerFile as m, cancelWorker as n, readRunCancelRequest as o, runCancellationFile as p, claimWorkerSteerDelivery as r, readRunCancellation as s, cancelRun as t, readWorkerSteerAcknowledgement as u, workerCancelRequestsFile as v, workerSteerAcknowledgementFile as w, workerControlLogFile as x, workerCancellationFile as y };
644
649
 
645
- //# sourceMappingURL=run-layout-B8I_LXN-.js.map
650
+ //# sourceMappingURL=run-layout-hZREkcfu.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-layout-hZREkcfu.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 * steers/requests/<hash>.json one exact, caller-idempotent {@link WorkerSteerRequest}\n * steers/acks/<hash>.json runtime acknowledgement for that steer operation\n * workers/<id>.inbox.ndjson best-effort readable projection of admitted steer requests\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. Duplicate operation ids\n * collapse to the first admitted request, while a payload conflict fails closed.\n *\n * Promoted from `loops/src/supervisor-control.ts`. Steer admission now requires the exact worker id\n * and a caller-owned operation id. One atomic request file is the durable inbox; the NDJSON file is\n * a readable projection only and never controls idempotency.\n *\n * @experimental\n */\n\nimport { createHash } from 'node:crypto'\nimport { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { canonicalCandidateDigest, type Sha256Digest } from '@tangle-network/agent-interface'\nimport type { RetainedRunEffect } from '../retained-run-types'\nimport {\n appendDurableFile,\n assertNoSymlinkDescendant,\n publishExclusiveDurableFile,\n writeAtomicDurableFile,\n} from './durable-file'\n\n/** One atomically admitted down-leg request for an exact worker id. @stable */\nexport interface WorkerSteerRequest {\n readonly schemaVersion: 1\n /** Caller-minted stable idempotency key for this operation. */\n readonly operationId: string\n /** Digest of operation id, worker id, message, source, and interrupt mode. */\n readonly requestDigest: Sha256Digest\n /** ISO timestamp of durable admission. */\n readonly at: string\n /** Who asked — 'human', a brain label, a tool name. Provenance, not authorization. */\n readonly source: string\n /** Exact supervised worker node id. */\n readonly worker: string\n readonly message: string\n readonly interrupt: boolean\n}\n\n/** Runtime acknowledgement for one exact steer operation. @stable */\nexport interface WorkerSteerAcknowledgement {\n readonly schemaVersion: 1\n readonly operationId: string\n readonly requestDigest: Sha256Digest\n readonly worker: string\n readonly effect: 'unknown' | 'delivered' | 'not_live' | 'unsupported' | 'refused'\n readonly requestedAt: string\n readonly observedAt: string\n readonly detail: string\n}\n\n/** Caller input for one retry-safe steer operation. @stable */\nexport interface WriteWorkerSteerOptions {\n readonly operationId: string\n readonly message: string\n readonly source?: string\n readonly interrupt?: boolean\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 /** Requested observation target, measured by the acknowledgement's deadlineExceeded field.\n * The observer always cascades eagerly. This does not guarantee scheduler latency or cleanup. */\n readonly deadlineMs?: number\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 cancelled state with confirmed teardown.\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 /** Runtime path that issued the cascade. */\n readonly path?: 'observer' | 'turn-boundary' | 'fallback'\n /** Runtime clock elapsed between request timestamp and cascade application. */\n readonly appliedAfterMs?: number\n /** Whether application exceeded the requested deadlineMs; absent when no target was requested. */\n readonly deadlineExceeded?: boolean\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/** Directory containing atomically admitted steer requests and runtime acknowledgements. */\nexport function workerSteersDir(eventDir: string): string {\n return join(eventDir, 'steers')\n}\n\n/** Directory containing one canonical request file per steer operation. */\nexport function workerSteerRequestsDir(eventDir: string): string {\n return join(workerSteersDir(eventDir), 'requests')\n}\n\n/** Directory containing one runtime acknowledgement per steer operation. */\nexport function workerSteerAcknowledgementsDir(eventDir: string): string {\n return join(workerSteersDir(eventDir), 'acks')\n}\n\n/** Canonical request file for one caller-owned steer operation id. */\nexport function workerSteerRequestFile(eventDir: string, operationId: string): string {\n return join(workerSteerRequestsDir(eventDir), `${operationFileHash(operationId)}.json`)\n}\n\n/** Runtime acknowledgement file for one caller-owned steer operation id. */\nexport function workerSteerAcknowledgementFile(eventDir: string, operationId: string): string {\n return join(workerSteerAcknowledgementsDir(eventDir), `${operationFileHash(operationId)}.json`)\n}\n\n/**\n * Admit one steer exactly once under a caller-owned operation id.\n *\n * The per-operation request file is linked into place atomically after its bytes reach disk. A\n * same-body retry returns the winner's request. A changed-body retry fails loud. The NDJSON inbox\n * and control log are readable projections written only by the admission winner.\n * @stable\n */\nexport function writeWorkerSteer(\n rootDir: string,\n supervisorId: string,\n worker: string,\n options: WriteWorkerSteerOptions,\n): {\n worker: string\n file: string\n request: WorkerSteerRequest\n acknowledgement?: WorkerSteerAcknowledgement\n replayed: boolean\n} {\n const workerId = worker.trim()\n if (!workerId) throw new Error('writeWorkerSteer: worker id is empty')\n const operationId = options.operationId.trim()\n if (!operationId) throw new Error('writeWorkerSteer: operationId is empty')\n const trimmed = options.message.trim()\n if (!trimmed) throw new Error('steer message is empty')\n const source = options.source?.trim() || 'human'\n const interrupt = options.interrupt === true\n const dir = supervisorRunDir(rootDir, supervisorId)\n const requestDigest = workerSteerRequestDigest({\n operationId,\n worker: workerId,\n message: trimmed,\n source,\n interrupt,\n })\n const request: WorkerSteerRequest = {\n schemaVersion: 1,\n operationId,\n requestDigest,\n at: new Date().toISOString(),\n source,\n worker: workerId,\n message: trimmed,\n interrupt,\n }\n const file = workerSteerRequestFile(dir, operationId)\n assertNoSymlinkDescendant(dir, file, 'steer request')\n mkdirSync(workerSteerRequestsDir(dir), { recursive: true })\n assertNoSymlinkDescendant(dir, file, 'steer request')\n const admitted = admitSteerRequest(file, request)\n if (admitted.replayed) {\n return {\n worker: admitted.request.worker,\n file,\n request: admitted.request,\n ...(readWorkerSteerAcknowledgement(dir, operationId) === undefined\n ? {}\n : { acknowledgement: readWorkerSteerAcknowledgement(dir, operationId) }),\n replayed: true,\n }\n }\n mkdirSync(supervisorWorkersDir(dir), { recursive: true })\n const projection = workerInboxFile(rootDir, supervisorId, workerId)\n try {\n appendFileSync(projection, `${JSON.stringify(request)}\\n`, 'utf8')\n } catch {\n // The atomic operation file is the queue. This projection does not control admission.\n }\n appendWorkerControlEvent(dir, workerId, {\n kind: 'message',\n direction: 'down',\n source,\n operationId,\n requestDigest,\n message: trimmed,\n interrupt,\n queued: true,\n delivered: false,\n })\n return { worker: workerId, file, request, replayed: false }\n}\n\n/** Read every atomically admitted request for one exact worker id, in admission order. @stable */\nexport function readWorkerSteerRequests(eventDir: string, worker?: string): WorkerSteerRequest[] {\n const workerId = worker?.trim()\n if (worker !== undefined && !workerId) return []\n let names: string[]\n assertNoSymlinkDescendant(eventDir, workerSteerRequestsDir(eventDir), 'steer request')\n try {\n names = readdirSync(workerSteerRequestsDir(eventDir))\n } catch {\n return []\n }\n const out: WorkerSteerRequest[] = []\n for (const name of names) {\n if (!name.endsWith('.json')) continue\n try {\n const file = join(workerSteerRequestsDir(eventDir), name)\n assertNoSymlinkDescendant(eventDir, file, 'steer request')\n const parsed = parseWorkerSteerRequest(JSON.parse(readFileSync(file, 'utf8')))\n if (name !== `${operationFileHash(parsed.operationId)}.json`) continue\n if (workerId === undefined || parsed.worker === workerId) out.push(parsed)\n } catch {\n // One corrupt request cannot hide other independently committed operations.\n }\n }\n return out.sort((left, right) =>\n left.at === right.at\n ? left.operationId.localeCompare(right.operationId)\n : left.at.localeCompare(right.at),\n )\n}\n\n/** Read one runtime steer acknowledgement, or `undefined` while no manager has answered. @stable */\nexport function readWorkerSteerAcknowledgement(\n eventDir: string,\n operationId: string,\n): WorkerSteerAcknowledgement | undefined {\n const id = operationId.trim()\n if (!id) throw new Error('readWorkerSteerAcknowledgement: operationId is empty')\n const file = workerSteerAcknowledgementFile(eventDir, id)\n assertNoSymlinkDescendant(eventDir, file, 'steer acknowledgement')\n if (!existsSync(file)) return undefined\n const record = parseWorkerSteerAcknowledgement(JSON.parse(readFileSync(file, 'utf8')))\n if (record.operationId !== id) {\n throw new Error(`steer acknowledgement '${file}' belongs to another operation`)\n }\n return record\n}\n\n/**\n * Claim one steer for delivery with an atomic no-clobber acknowledgement.\n * Returns `true` only to the process that created the pre-delivery record.\n * @internal\n */\nexport function claimWorkerSteerDelivery(\n eventDir: string,\n record: WorkerSteerAcknowledgement,\n): boolean {\n const exact = parseWorkerSteerAcknowledgement(record)\n if (exact.effect !== 'unknown') {\n throw new Error('steer delivery claim must use effect unknown')\n }\n const request = readWorkerSteerRequest(eventDir, exact.operationId)\n if (request === undefined || request.requestDigest !== exact.requestDigest) {\n throw new Error('steer delivery claim does not match an admitted request')\n }\n const dir = workerSteerAcknowledgementsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'steer acknowledgement')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'steer acknowledgement')\n const file = workerSteerAcknowledgementFile(eventDir, exact.operationId)\n if (publishExclusiveDurableFile(file, `${JSON.stringify(exact, null, 2)}\\n`)) {\n return true\n }\n const winner = readWorkerSteerAcknowledgement(eventDir, exact.operationId)\n if (\n winner === undefined ||\n winner.operationId !== exact.operationId ||\n winner.requestDigest !== exact.requestDigest\n ) {\n throw new Error('steer delivery claim conflicts with another operation')\n }\n return false\n}\n\n/** Atomically replace the runtime acknowledgement for one steer operation. @internal */\nexport function writeWorkerSteerAcknowledgement(\n eventDir: string,\n record: WorkerSteerAcknowledgement,\n): void {\n const exact = parseWorkerSteerAcknowledgement(record)\n const request = readWorkerSteerRequest(eventDir, exact.operationId)\n if (request === undefined || request.requestDigest !== exact.requestDigest) {\n throw new Error('steer acknowledgement does not match an admitted request')\n }\n const dir = workerSteerAcknowledgementsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'steer acknowledgement')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'steer acknowledgement')\n const file = workerSteerAcknowledgementFile(eventDir, exact.operationId)\n const prior = readWorkerSteerAcknowledgement(eventDir, exact.operationId)\n if (\n prior !== undefined &&\n prior.effect !== 'unknown' &&\n canonicalCandidateDigest(prior) !== canonicalCandidateDigest(exact)\n ) {\n throw new Error(`steer operation '${exact.operationId}' already has a terminal acknowledgement`)\n }\n writeAtomicDurableFile(file, `${JSON.stringify(exact, null, 2)}\\n`)\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/**\n * The durable cancel-request inbox of one run — one NDJSON line per {@link WorkerCancelRequest}.\n * It stays append-only so independent operations retain admission order and readers can skip a\n * partial trailing line. `appendDurableFile` uses O_APPEND, one write, file fsync, and directory\n * fsync; single-record acknowledgements use atomic replacement instead.\n */\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 dir = workerCancellationsDir(eventDir)\n const file = workerCancelRequestsFile(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'cancel request')\n assertNoSymlinkDescendant(eventDir, file, 'cancel request')\n if (!existsSync(file)) return []\n const out: WorkerCancelRequest[] = []\n const byOperationId = new Map<string, 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 let parsed: Partial<WorkerCancelRequest>\n try {\n parsed = JSON.parse(trimmed) as Partial<WorkerCancelRequest>\n } catch {\n // Ignore partial or corrupt input lines; later valid lines still matter.\n continue\n }\n if (!isWorkerCancelRequest(parsed)) continue\n const prior = byOperationId.get(parsed.operationId)\n if (prior !== undefined) {\n assertSameWorkerCancelRequest(prior, parsed)\n } else {\n byOperationId.set(parsed.operationId, parsed)\n out.push(parsed)\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 dir = workerCancellationsDir(eventDir)\n const file = workerCancellationFile(eventDir, operationId)\n assertNoSymlinkDescendant(eventDir, dir, 'cancel acknowledgement')\n assertNoSymlinkDescendant(eventDir, file, 'cancel acknowledgement')\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. The shared writer fsyncs the file and containing\n * directory, so a concurrent reader sees the prior complete record or the new complete record.\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 assertNoSymlinkDescendant(eventDir, dir, 'cancel acknowledgement')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'cancel acknowledgement')\n const file = workerCancellationFile(eventDir, record.operationId)\n assertNoSymlinkDescendant(eventDir, file, 'cancel acknowledgement')\n writeAtomicDurableFile(file, `${JSON.stringify(record, null, 2)}\\n`, { mode: 0o600 })\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 * retry that changes the worker, source, or reason fails closed. A request the runtime has not\n * answered yet returns `effect: 'unknown'` (never a success); call again with the same\n * `operationId` — or `readWorkerCancellation` — to read the acknowledged result after a\n * 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 pending = readWorkerCancelRequests(eventDir).find((r) => r.operationId === opId)\n const candidate = {\n operationId: opId,\n worker: ref,\n source: options.source ?? 'human',\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n }\n if (pending !== undefined) assertSameWorkerCancelRequest(pending, candidate)\n const acknowledged = readWorkerCancellation(eventDir, opId)\n if (acknowledged !== undefined) {\n if (pending === undefined && options.source !== undefined) {\n throw new Error(\n `cancelWorker: operation '${opId}' cannot verify source without its admitted request`,\n )\n }\n assertWorkerCancellationMatchesCandidate(acknowledged, candidate)\n return acknowledged\n }\n const source = options.source ?? 'human'\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 const dir = workerCancellationsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'cancel request')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'cancel request')\n const file = workerCancelRequestsFile(eventDir)\n assertNoSymlinkDescendant(eventDir, file, 'cancel request')\n appendDurableFile(file, `${JSON.stringify(request)}\\n`, { mode: 0o600 })\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 dir = workerCancellationsDir(eventDir)\n const file = runCancelRequestFile(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel request')\n assertNoSymlinkDescendant(eventDir, file, 'run cancel request')\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 dir = workerCancellationsDir(eventDir)\n const file = runCancellationFile(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel acknowledgement')\n assertNoSymlinkDescendant(eventDir, file, 'run cancel acknowledgement')\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. The shared writer fsyncs the file and containing\n * directory, so a concurrent reader sees the prior complete record or the new complete record.\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 assertNoSymlinkDescendant(eventDir, dir, 'run cancel acknowledgement')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel acknowledgement')\n const file = runCancellationFile(eventDir)\n assertNoSymlinkDescendant(eventDir, file, 'run cancel acknowledgement')\n writeAtomicDurableFile(file, `${JSON.stringify(record, null, 2)}\\n`, { mode: 0o600 })\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 retry that changes the source or reason fails closed. A request\n * the runtime has not answered yet returns `effect: 'unknown'` (never a success); call again with\n * the same `operationId` — or {@link readRunCancellation} — to read the acknowledged result\n * 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: {\n readonly reason?: string\n readonly source?: string\n readonly deadlineMs?: number\n } = {},\n): RunCancellation {\n if (\n options.deadlineMs !== undefined &&\n (!Number.isFinite(options.deadlineMs) || options.deadlineMs < 0)\n ) {\n throw new Error('cancelRun: deadlineMs must be a finite nonnegative number')\n }\n const opId = operationId.trim()\n if (!opId) throw new Error('cancelRun: operationId is empty')\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 candidate = {\n operationId: opId,\n source: options.source ?? 'human',\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n }\n if (pending !== undefined) assertSameRunCancelRequest(pending, candidate)\n const acknowledged = readRunCancellation(eventDir, opId)\n if (acknowledged !== undefined) {\n if (pending === undefined && options.source !== undefined) {\n throw new Error(\n `cancelRun: operation '${opId}' cannot verify source without its admitted request`,\n )\n }\n assertRunCancellationMatchesCandidate(acknowledged, candidate)\n return acknowledged\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 ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n }\n if (pending === undefined) {\n const dir = workerCancellationsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel request')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel request')\n const file = runCancelRequestFile(eventDir)\n assertNoSymlinkDescendant(eventDir, file, 'run cancel request')\n writeAtomicDurableFile(file, `${JSON.stringify(request, null, 2)}\\n`, { mode: 0o600 })\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 ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\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\ntype WorkerCancelRequestCandidate = {\n readonly operationId: string\n readonly worker: string\n readonly source: string\n readonly reason?: string\n}\n\ntype RunCancelRequestCandidate = {\n readonly deadlineMs?: number\n readonly operationId: string\n readonly source: string\n readonly reason?: string\n}\n\nfunction assertSameWorkerCancelRequest(\n existing: WorkerCancelRequest,\n candidate: WorkerCancelRequestCandidate,\n): void {\n if (existing.operationId !== candidate.operationId) {\n throw new Error(`cancelWorker: operation '${candidate.operationId}' has an id collision`)\n }\n if (existing.worker !== candidate.worker) {\n throw new Error(\n `cancelWorker: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(worker '${existing.worker}' != '${candidate.worker}')`,\n )\n }\n if (existing.source !== candidate.source) {\n throw new Error(\n `cancelWorker: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(source '${existing.source}' != '${candidate.source}')`,\n )\n }\n if (existing.reason !== candidate.reason) {\n throw new Error(\n `cancelWorker: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(reason differs)`,\n )\n }\n}\n\nfunction assertWorkerCancellationMatchesCandidate(\n existing: WorkerCancellation,\n candidate: WorkerCancelRequestCandidate,\n): void {\n if (existing.worker !== candidate.worker) {\n throw new Error(\n `cancelWorker: operation '${candidate.operationId}' conflicts with its acknowledgement ` +\n `(worker '${existing.worker}' != '${candidate.worker}')`,\n )\n }\n if (existing.reason !== candidate.reason) {\n throw new Error(\n `cancelWorker: operation '${candidate.operationId}' conflicts with its acknowledgement ` +\n `(reason differs)`,\n )\n }\n}\n\nfunction assertSameRunCancelRequest(\n existing: RunCancelRequest,\n candidate: RunCancelRequestCandidate,\n): void {\n if (existing.operationId !== candidate.operationId) {\n throw new Error(`cancelRun: operation '${candidate.operationId}' has an id collision`)\n }\n if (existing.source !== candidate.source) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(source '${existing.source}' != '${candidate.source}')`,\n )\n }\n if (existing.deadlineMs !== candidate.deadlineMs) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request (deadlineMs differs)`,\n )\n }\n if (existing.reason !== candidate.reason) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(reason differs)`,\n )\n }\n}\n\nfunction assertRunCancellationMatchesCandidate(\n existing: RunCancellation,\n candidate: RunCancelRequestCandidate,\n): void {\n if (existing.reason !== candidate.reason) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its acknowledgement ` +\n `(reason differs)`,\n )\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.deadlineMs === undefined ||\n (Number.isFinite(value.deadlineMs) && value.deadlineMs >= 0)) &&\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 workerSteerRequestDigest(value: {\n readonly operationId: string\n readonly worker: string\n readonly message: string\n readonly source: string\n readonly interrupt: boolean\n}): Sha256Digest {\n return canonicalCandidateDigest({ kind: 'worker-steer-request.v1', ...value })\n}\n\nfunction operationFileHash(operationId: string): string {\n const id = operationId.trim()\n if (!id) throw new Error('steer operationId is empty')\n return createHash('sha256').update(id).digest('hex')\n}\n\nfunction admitSteerRequest(\n file: string,\n request: WorkerSteerRequest,\n): { readonly request: WorkerSteerRequest; readonly replayed: boolean } {\n const existing = readWorkerSteerRequestFile(file)\n if (existing !== undefined) {\n assertSameSteerRequest(existing, request)\n return { request: existing, replayed: true }\n }\n if (publishExclusiveDurableFile(file, `${JSON.stringify(request, null, 2)}\\n`)) {\n return { request, replayed: false }\n }\n const winner = readWorkerSteerRequestFile(file)\n if (winner === undefined) {\n throw new Error('steer request publication lost its winner')\n }\n assertSameSteerRequest(winner, request)\n return { request: winner, replayed: true }\n}\n\nfunction readWorkerSteerRequest(\n eventDir: string,\n operationId: string,\n): WorkerSteerRequest | undefined {\n const file = workerSteerRequestFile(eventDir, operationId)\n assertNoSymlinkDescendant(eventDir, file, 'steer request')\n const request = readWorkerSteerRequestFile(file)\n if (request !== undefined && request.operationId !== operationId) {\n throw new Error('steer request file belongs to another operation')\n }\n return request\n}\n\nfunction readWorkerSteerRequestFile(file: string): WorkerSteerRequest | undefined {\n if (!existsSync(file)) return undefined\n return parseWorkerSteerRequest(JSON.parse(readFileSync(file, 'utf8')))\n}\n\nfunction parseWorkerSteerRequest(value: unknown): WorkerSteerRequest {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('steer request is malformed')\n }\n const request = value as Partial<WorkerSteerRequest>\n if (\n request.schemaVersion !== 1 ||\n typeof request.operationId !== 'string' ||\n request.operationId.length === 0 ||\n typeof request.requestDigest !== 'string' ||\n typeof request.at !== 'string' ||\n typeof request.source !== 'string' ||\n request.source.length === 0 ||\n typeof request.worker !== 'string' ||\n request.worker.length === 0 ||\n typeof request.message !== 'string' ||\n request.message.trim().length === 0 ||\n typeof request.interrupt !== 'boolean'\n ) {\n throw new Error('steer request is malformed')\n }\n const exact = request as WorkerSteerRequest\n const expected = workerSteerRequestDigest({\n operationId: exact.operationId,\n worker: exact.worker,\n message: exact.message,\n source: exact.source,\n interrupt: exact.interrupt,\n })\n if (exact.requestDigest !== expected) throw new Error('steer request digest does not match')\n return exact\n}\n\nfunction parseWorkerSteerAcknowledgement(value: unknown): WorkerSteerAcknowledgement {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('steer acknowledgement is malformed')\n }\n const record = value as Partial<WorkerSteerAcknowledgement>\n if (\n record.schemaVersion !== 1 ||\n typeof record.operationId !== 'string' ||\n record.operationId.length === 0 ||\n typeof record.requestDigest !== 'string' ||\n typeof record.worker !== 'string' ||\n record.worker.length === 0 ||\n (record.effect !== 'unknown' &&\n record.effect !== 'delivered' &&\n record.effect !== 'not_live' &&\n record.effect !== 'unsupported' &&\n record.effect !== 'refused') ||\n typeof record.requestedAt !== 'string' ||\n typeof record.observedAt !== 'string' ||\n typeof record.detail !== 'string'\n ) {\n throw new Error('steer acknowledgement is malformed')\n }\n return record as WorkerSteerAcknowledgement\n}\n\nfunction assertSameSteerRequest(existing: WorkerSteerRequest, candidate: WorkerSteerRequest): void {\n if (existing.operationId !== candidate.operationId) {\n throw new Error('steer operation file collision')\n }\n if (existing.requestDigest !== candidate.requestDigest) {\n throw new Error(\n `writeWorkerSteer: operation '${candidate.operationId}' conflicts with its admitted request`,\n )\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiNA,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,S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CACxD;AAEJ"}
@@ -1,25 +1,25 @@
1
- import { Bt as insideCursorNamespace, C as settledToIteration, Ci as notifySandboxEventObserver, Cn as hasCompleteCacheBreakdown, Dn as sleep, En as randomSuffix, Hr as parseCommittedJsonLines, Mn as zeroSpend, On as stringifySafe, Rt as InMemoryResultBlobStore, Ur as prepareJsonlAppend, Vr as isNoEntError, Wr as writeAllBytes, Xt as contentAddress, Y as rollingDispatch, _t as createPushTraceSource, a as createSupervisor, an as createSandboxLineage, bn as chargedTokens, cn as assertBoxlessPromptOptions, di as detachedFrozen, dn as runBrainLoop, fn as canonicalObservedModelParts, in as runAgentRounds, li as executableAgentProfileSnapshot, ln as readPromptOptions, lt as createWorktreeCliExecutor, m as withDriverExecutor, nn as defaultSelectWinner, on as probeSandboxCapabilities, ot as createExecutor, qt as isTraceAnalysisStore, st as createExecutorRegistry, ui as executableAgentSpecSnapshot, un as routerBrain, wn as isAbortError, xn as cloneSpend, yn as addSpend, zt as InMemorySpawnJournal } from "./redact-CLRRxkXF.js";
1
+ import { Bt as insideCursorNamespace, C as settledToIteration, Cn as hasCompleteCacheBreakdown, Dn as sleep, En as randomSuffix, Gr as writeAllBytes, Hr as isNoEntError, Mn as zeroSpend, On as stringifySafe, Rt as InMemoryResultBlobStore, Ur as parseCommittedJsonLines, Wr as prepareJsonlAppend, Xt as contentAddress, Y as rollingDispatch, _t as createPushTraceSource, a as createSupervisor, an as createSandboxLineage, bn as chargedTokens, cn as assertBoxlessPromptOptions, di as executableAgentSpecSnapshot, dn as runBrainLoop, fi as detachedFrozen, fn as canonicalObservedModelParts, in as runAgentRounds, ln as readPromptOptions, lt as createWorktreeCliExecutor, m as withDriverExecutor, nn as defaultSelectWinner, on as probeSandboxCapabilities, ot as createExecutor, qt as isTraceAnalysisStore, st as createExecutorRegistry, ui as executableAgentProfileSnapshot, un as routerBrain, wi as notifySandboxEventObserver, wn as isAbortError, xn as cloneSpend, yn as addSpend, zt as InMemorySpawnJournal } from "./redact-BMwd8IBm.js";
2
2
  import { m as ValidationError, n as AnalystError, s as PlannerError } from "./errors-DodWX-cb.js";
3
- import { E as profileChatClient, S as ObservationError, T as renderReport, b as sample, k as strategyAuthorMethod, v as refine, w as observe, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-Bnewh9dN.js";
3
+ import { E as profileChatClient, S as ObservationError, T as renderReport, b as sample, k as strategyAuthorMethod, v as refine, w as observe, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-DsGWoyj4.js";
4
4
  import { c as profileModelExecutionSettings, i as concreteModelId, l as profileProviderModel, o as enforceTokenLimits, t as assertExecutableAgentProfile } from "./model-policy-DKDyr-fc.js";
5
5
  import { i as notifyRuntimeHookEvent } from "./runtime-hooks-tXpAarhW.js";
6
6
  import { f as sha256Bytes, i as redactProtectedValue, o as canonicalCandidateDigest$1, r as redactProtectedReason, u as immutableCandidateValue } from "./protected-redaction-wGo44k2K.js";
7
- import { b as mapExecutorResult, n as supervise, y as gateOnDeliverable } from "./supervise-BN5VMhRq.js";
8
- import "./run-layout-B8I_LXN-.js";
9
- import "./coordination-driver-CwT-9dXa.js";
10
- import "./provision-supervisor-B8zEk1-7.js";
11
- import "./delegate-yLW9_OGW.js";
12
- import "./graph-Dcb2PVEB.js";
7
+ import { b as mapExecutorResult, n as supervise, y as gateOnDeliverable } from "./supervise-D3r_gEyO.js";
8
+ import "./run-layout-hZREkcfu.js";
9
+ import "./coordination-driver-CqZGBqdt.js";
10
+ import "./provision-supervisor-CEMk0grI.js";
11
+ import "./delegate-CU7bWMuW.js";
12
+ import "./graph-B0cNCFmD.js";
13
13
  import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
14
14
  import { CODING_HARNESSES, DEFAULT_TRACE_ANALYST_KINDS, InMemoryTraceStore, OUTPUT_VALUE, benjaminiHochberg, buildTrajectory, computeFindingId as computeFindingId$1, confidenceInterval, createTraceAnalyst, expandProfileAxes, makeFinding as makeFinding$1, pairedBootstrap, paretoFrontier, wilcoxonSignedRank, wilson } from "@tangle-network/agent-eval";
15
15
  import { createAgentRunOutcomeTracker } from "@tangle-network/sandbox/runtime";
16
16
  import { createHash, randomUUID } from "node:crypto";
17
- import { execFileSync, spawn, spawnSync } from "node:child_process";
17
+ import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
18
18
  import { appendFileSync, chmodSync, constants, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
19
19
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
20
- import { mkdir, readFile, realpath, writeFile } from "node:fs/promises";
20
+ import { cp, mkdir, mkdtemp, readFile, realpath, stat, writeFile } from "node:fs/promises";
21
21
  import { tmpdir } from "node:os";
22
- import { isDeepStrictEqual } from "node:util";
22
+ import { isDeepStrictEqual, promisify } from "node:util";
23
23
  import { collectAgentResponseText } from "@tangle-network/sandbox";
24
24
  import { heldoutSignificance, runProfileMatrix } from "@tangle-network/agent-eval/campaign";
25
25
  import { createInterface } from "node:readline";
@@ -2434,6 +2434,257 @@ function inProcessSandboxClient(options) {
2434
2434
  } };
2435
2435
  }
2436
2436
  //#endregion
2437
+ //#region src/runtime/isolated-checker.ts
2438
+ const toolchains = [
2439
+ "/usr",
2440
+ "/bin",
2441
+ "/lib",
2442
+ "/lib64"
2443
+ ];
2444
+ const contains = (parent, child) => {
2445
+ const path = relative(parent, child);
2446
+ return path === "" || path !== ".." && !path.startsWith(`..${sep}`) && !path.startsWith(sep);
2447
+ };
2448
+ /**
2449
+ * Run untrusted checks inside Linux Bubblewrap. Never falls back to host execution.
2450
+ * Requires /usr/bin/bwrap and permission to create Linux namespaces.
2451
+ * Only trusted system toolchains, private proc/dev/tmp, and the writable copy are mounted.
2452
+ * The canonical input path remains the working directory; copy writes are discarded.
2453
+ * Limits bound command time and captured output, not copy size or memory consumption.
2454
+ * Callers must keep the input and trusted toolchains stable while preparing the check.
2455
+ */
2456
+ async function runIsolatedCheck(options) {
2457
+ let scratch;
2458
+ let result;
2459
+ try {
2460
+ if (process.platform !== "linux") throw new Error("Linux Bubblewrap namespaces are required");
2461
+ const timeoutMs = options.timeoutMs ?? 3e4;
2462
+ const maxOutputBytes = options.maxOutputBytes ?? 1048576;
2463
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647 || !Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 1) throw new Error("Invalid execution limits");
2464
+ if (!options.command.length || !options.command[0]) throw new Error("A command is required");
2465
+ if (options.signal?.aborted) return {
2466
+ succeeded: false,
2467
+ reason: "cancelled",
2468
+ diagnostic: "Check cancelled"
2469
+ };
2470
+ const workspace = await realpath(options.workspaceRoot);
2471
+ const tree = await realpath(options.tree);
2472
+ if (!contains(workspace, tree) || !(await stat(tree)).isDirectory()) throw new Error("Tree must be a directory inside the workspace");
2473
+ const binds = [];
2474
+ for (const path of toolchains) {
2475
+ let actual;
2476
+ try {
2477
+ actual = await realpath(path);
2478
+ } catch (error) {
2479
+ if (error.code === "ENOENT") continue;
2480
+ throw error;
2481
+ }
2482
+ for (const mount of [path, actual]) if (contains(mount, workspace) || contains(workspace, mount) || contains(mount, tree) || contains(tree, mount)) throw new Error(`Toolchain overlaps protected workspace: ${path}`);
2483
+ binds.push("--ro-bind", actual, path);
2484
+ }
2485
+ if (["/proc", "/dev"].some((path) => contains(path, tree) || contains(tree, path))) throw new Error("Tree overlaps a reserved namespace mount");
2486
+ scratch = await mkdtemp(join(tmpdir(), "runtime-check-"));
2487
+ if (contains(tree, scratch)) throw new Error("Temporary storage must be outside the input tree");
2488
+ const copy = join(scratch, "tree");
2489
+ await cp(tree, copy, {
2490
+ recursive: true,
2491
+ dereference: false,
2492
+ verbatimSymlinks: true
2493
+ });
2494
+ result = await execute([
2495
+ "--unshare-all",
2496
+ "--die-with-parent",
2497
+ "--new-session",
2498
+ "--cap-drop",
2499
+ "ALL",
2500
+ "--clearenv",
2501
+ "--setenv",
2502
+ "PATH",
2503
+ "/usr/bin:/bin",
2504
+ "--setenv",
2505
+ "HOME",
2506
+ "/tmp",
2507
+ "--setenv",
2508
+ "LANG",
2509
+ "C",
2510
+ ...binds,
2511
+ "--proc",
2512
+ "/proc",
2513
+ "--dev",
2514
+ "/dev",
2515
+ "--tmpfs",
2516
+ "/tmp",
2517
+ "--bind",
2518
+ copy,
2519
+ tree,
2520
+ "--chdir",
2521
+ tree,
2522
+ "--",
2523
+ ...options.command
2524
+ ], timeoutMs, maxOutputBytes, options.signal);
2525
+ } catch (error) {
2526
+ result = {
2527
+ succeeded: false,
2528
+ reason: "refused",
2529
+ diagnostic: String(error)
2530
+ };
2531
+ }
2532
+ if (scratch) try {
2533
+ await removeScratch(scratch);
2534
+ } catch (error) {
2535
+ const cleanupDiagnostic = String(error);
2536
+ result = result.succeeded ? {
2537
+ succeeded: false,
2538
+ reason: "cleanup-failed",
2539
+ diagnostic: cleanupDiagnostic,
2540
+ stdout: result.value.stdout,
2541
+ stderr: result.value.stderr,
2542
+ exitCode: 0
2543
+ } : {
2544
+ ...result,
2545
+ cleanupDiagnostic
2546
+ };
2547
+ }
2548
+ return result;
2549
+ }
2550
+ function execute(args, timeoutMs, limit, signal) {
2551
+ return new Promise((done) => {
2552
+ const child = spawn("/usr/bin/bwrap", [
2553
+ "--json-status-fd",
2554
+ "3",
2555
+ ...args
2556
+ ], {
2557
+ env: {},
2558
+ stdio: [
2559
+ "ignore",
2560
+ "pipe",
2561
+ "pipe",
2562
+ "pipe"
2563
+ ],
2564
+ detached: true
2565
+ });
2566
+ const stdout = [];
2567
+ const stderr = [];
2568
+ let bytes = 0;
2569
+ let status = "";
2570
+ let failure;
2571
+ const stop = (reason) => {
2572
+ failure ??= reason;
2573
+ if (child.pid) try {
2574
+ process.kill(-child.pid, "SIGKILL");
2575
+ } catch (error) {
2576
+ if (error.code !== "ESRCH") child.kill("SIGKILL");
2577
+ }
2578
+ };
2579
+ const timer = setTimeout(() => stop("timeout"), timeoutMs);
2580
+ const cancel = () => stop("cancelled");
2581
+ signal?.addEventListener("abort", cancel, { once: true });
2582
+ if (signal?.aborted) cancel();
2583
+ const capture = (target) => (chunk) => {
2584
+ const remaining = Math.max(0, limit - bytes);
2585
+ bytes += chunk.length;
2586
+ if (remaining) target.push(chunk.subarray(0, remaining));
2587
+ if (bytes > limit) stop("output-limit");
2588
+ };
2589
+ child.stdio[3]?.on("data", (chunk) => {
2590
+ if (status.length + chunk.length > 16384) {
2591
+ stop("output-limit");
2592
+ return;
2593
+ }
2594
+ status += chunk.toString();
2595
+ });
2596
+ child.stdout.on("data", capture(stdout));
2597
+ child.stderr.on("data", capture(stderr));
2598
+ let spawnError;
2599
+ child.on("error", (error) => {
2600
+ spawnError = error;
2601
+ });
2602
+ child.on("close", (code) => {
2603
+ clearTimeout(timer);
2604
+ signal?.removeEventListener("abort", cancel);
2605
+ const out = Buffer.concat(stdout).toString();
2606
+ const err = Buffer.concat(stderr).toString();
2607
+ const evidence = {
2608
+ stdout: out,
2609
+ stderr: err,
2610
+ exitCode: code
2611
+ };
2612
+ const executed = status.split("\n").some((line) => {
2613
+ try {
2614
+ const record = JSON.parse(line);
2615
+ return record !== null && typeof record === "object" && "exit-code" in record && typeof record["exit-code"] === "number" && record["exit-code"] === code;
2616
+ } catch {
2617
+ return false;
2618
+ }
2619
+ });
2620
+ if (failure) done({
2621
+ succeeded: false,
2622
+ reason: failure,
2623
+ diagnostic: err || failure,
2624
+ ...evidence
2625
+ });
2626
+ else if (spawnError) done({
2627
+ succeeded: false,
2628
+ reason: "refused",
2629
+ diagnostic: String(spawnError),
2630
+ ...evidence
2631
+ });
2632
+ else if (!executed) done({
2633
+ succeeded: false,
2634
+ reason: "refused",
2635
+ diagnostic: err || "Bubblewrap did not confirm command execution",
2636
+ ...evidence
2637
+ });
2638
+ else if (code !== 0) done({
2639
+ succeeded: false,
2640
+ reason: "failed",
2641
+ diagnostic: err || out || `Check exited ${code}`,
2642
+ ...evidence
2643
+ });
2644
+ else done({
2645
+ succeeded: true,
2646
+ value: {
2647
+ stdout: out,
2648
+ stderr: err
2649
+ }
2650
+ });
2651
+ });
2652
+ });
2653
+ }
2654
+ const executeFile = promisify(execFile);
2655
+ /** GNU tools traverse relative to open directories, including trees deeper than PATH_MAX.
2656
+ * Recursive chmod ignores encountered symlinks; rm never follows their targets. */
2657
+ async function removeScratch(path) {
2658
+ const options = {
2659
+ env: {},
2660
+ timeout: 1e4,
2661
+ maxBuffer: 16384
2662
+ };
2663
+ let permissionError;
2664
+ try {
2665
+ await executeFile("/bin/chmod", [
2666
+ "--recursive",
2667
+ "--preserve-root",
2668
+ "u+rwX",
2669
+ "--",
2670
+ path
2671
+ ], options);
2672
+ } catch (error) {
2673
+ permissionError = error;
2674
+ }
2675
+ try {
2676
+ await executeFile("/bin/rm", [
2677
+ "--recursive",
2678
+ "--force",
2679
+ "--one-file-system",
2680
+ "--",
2681
+ path
2682
+ ], options);
2683
+ } catch (error) {
2684
+ throw new Error([permissionError, error].filter((value) => value !== void 0).map(String).join("; "));
2685
+ }
2686
+ }
2687
+ //#endregion
2437
2688
  //#region src/runtime/observation-registry.ts
2438
2689
  /** Adapt any Eval analyst registry, including recursive engines, to observation and harvesting. */
2439
2690
  function observationFromRegistry(registry, options) {
@@ -6914,6 +7165,6 @@ function tail(s) {
6914
7165
  return s.slice(-400);
6915
7166
  }
6916
7167
  //#endregion
6917
- export { InMemoryCorpus as $, chatWorkerSeam as A, renderLeaderboardHtml as At, SandboxRunAbortError as B, sanitizeMcpToolSchema as Bt, withUntrackedArtifacts as C, superviseDispatch as Ct, codeModeSupervisorTools as D, stopSentinel as Dt, runCoderChecks as E, sentinelCompletion as Et, selectChampion as F, defaultAuditorInstruction as Ft, equalKOnCost as G, secretEnvOfMcpServer as Gt, printBenchmarkReport as H, mcpSecretEnvMetadataKey as Ht, assertStrategyContract as I, McpSpawnFault as It, runPersonified as J, trajectoryReport as K, createTangleSandboxExactProcessProvider as Kt, authorStrategy as L, connectStdioMcp as Lt, discriminatingMeans as M, renderLeaderboardSvg as Mt, pickChampion as N, renderPairwiseMarkdown as Nt, unsafeInProcessRunner as O, leaderboard as Ot, runStrategyEvolution as P, auditIntent as Pt, FileCorpus as Q, strategyAuthorContract as R, materializeLocalMcp as Rt, copyUntrackedIntoClone as S, loopDispatch as St, patchDelivered as T, deterministicCompletion as Tt, runBenchmark as U, resolveMcpServerLaunch as Ut, openSandboxRun as V, envKeyProvider as Vt, promotionGate as W, resolveSecretEnv as Wt, createShapeRegistry as X, builtinShapes as Y, registerShape as Z, NOTE_MAX_CHARS as _, defineLeaderboard as _t, localShell as a, pipeline as at, composeWorkerEvidence as b, inlineSandboxClient as bt, createVerifierEnvironment as c, widen as ct, harvestSurfaceDiffs as d, createScopeAnalyst as dt, renderCorpusToInstructions as et, analystsFromRegistry as f, registryScopeAnalyst as ft, EVIDENCE_MAX_CHARS as g, harvestCorpus as gt, worktreeFanout as h, HarvestError as ht, jjWorkspace as i, panel as it, createChatSessionStore as j, renderLeaderboardMarkdown as jt, chatTransportExecutor as k, pairwiseSignificance as kt, boxSurfaceReader as l, assertTraceDerivedFindings as lt, superviseSurface as m, inProcessSandboxClient as mt, makeFinding$1 as n, flatWidenGate as nt, runInWorkspace as o, selectValidWinner as ot, failuresAnalyst as p, observationFromRegistry as pt, definePersona as q, gitWorkspace as r, loopUntil as rt, createWaterfallCollector as s, verify as st, computeFindingId$1 as t, fanout as tt, fsSurfaceReader as u, buildSteerContext as ut, VERIFY_TAIL_CHARS as v, resolveSandboxClient as vt, analyzeTrace as w, completionAuthorizes as wt, settledWorkerOut as x, loopCampaignDispatch as xt, closingWorkerNote as y, localSandboxClient as yt, strategyAuthorSystemPrompt as z, createMcpEnvironment as zt };
7168
+ export { InMemoryCorpus as $, chatWorkerSeam as A, pairwiseSignificance as At, SandboxRunAbortError as B, createMcpEnvironment as Bt, withUntrackedArtifacts as C, loopDispatch as Ct, codeModeSupervisorTools as D, sentinelCompletion as Dt, runCoderChecks as E, deterministicCompletion as Et, selectChampion as F, auditIntent as Ft, equalKOnCost as G, resolveSecretEnv as Gt, printBenchmarkReport as H, envKeyProvider as Ht, assertStrategyContract as I, defaultAuditorInstruction as It, runPersonified as J, trajectoryReport as K, secretEnvOfMcpServer as Kt, authorStrategy as L, McpSpawnFault as Lt, discriminatingMeans as M, renderLeaderboardMarkdown as Mt, pickChampion as N, renderLeaderboardSvg as Nt, unsafeInProcessRunner as O, stopSentinel as Ot, runStrategyEvolution as P, renderPairwiseMarkdown as Pt, FileCorpus as Q, strategyAuthorContract as R, connectStdioMcp as Rt, copyUntrackedIntoClone as S, loopCampaignDispatch as St, patchDelivered as T, completionAuthorizes as Tt, runBenchmark as U, mcpSecretEnvMetadataKey as Ut, openSandboxRun as V, sanitizeMcpToolSchema as Vt, promotionGate as W, resolveMcpServerLaunch as Wt, createShapeRegistry as X, builtinShapes as Y, registerShape as Z, NOTE_MAX_CHARS as _, harvestCorpus as _t, localShell as a, pipeline as at, composeWorkerEvidence as b, localSandboxClient as bt, createVerifierEnvironment as c, widen as ct, harvestSurfaceDiffs as d, createScopeAnalyst as dt, renderCorpusToInstructions as et, analystsFromRegistry as f, registryScopeAnalyst as ft, EVIDENCE_MAX_CHARS as g, HarvestError as gt, worktreeFanout as h, inProcessSandboxClient as ht, jjWorkspace as i, panel as it, createChatSessionStore as j, renderLeaderboardHtml as jt, chatTransportExecutor as k, leaderboard as kt, boxSurfaceReader as l, assertTraceDerivedFindings as lt, superviseSurface as m, runIsolatedCheck as mt, makeFinding$1 as n, flatWidenGate as nt, runInWorkspace as o, selectValidWinner as ot, failuresAnalyst as p, observationFromRegistry as pt, definePersona as q, createTangleSandboxExactProcessProvider as qt, gitWorkspace as r, loopUntil as rt, createWaterfallCollector as s, verify as st, computeFindingId$1 as t, fanout as tt, fsSurfaceReader as u, buildSteerContext as ut, VERIFY_TAIL_CHARS as v, defineLeaderboard as vt, analyzeTrace as w, superviseDispatch as wt, settledWorkerOut as x, inlineSandboxClient as xt, closingWorkerNote as y, resolveSandboxClient as yt, strategyAuthorSystemPrompt as z, materializeLocalMcp as zt };
6918
7169
 
6919
- //# sourceMappingURL=runtime-C-oKXuHJ.js.map
7170
+ //# sourceMappingURL=runtime-ByeeZbA3.js.map