@tangle-network/agent-runtime 0.189.0 → 0.191.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.
- package/dist/{activation-DuYIFVQm.js → activation-BpTEBhQR.js} +3 -3
- package/dist/{activation-DuYIFVQm.js.map → activation-BpTEBhQR.js.map} +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +3 -3
- package/dist/{authoring-CIE6rF8N.js → authoring-DV0fkyxx.js} +7 -3
- package/dist/{authoring-CIE6rF8N.js.map → authoring-DV0fkyxx.js.map} +1 -1
- package/dist/candidate-execution/index.d.ts +3 -3
- package/dist/candidate-execution/index.js +5 -5
- package/dist/{candidate-execution-CQYU8E5a.js → candidate-execution-BSkZErxD.js} +255 -9
- package/dist/candidate-execution-BSkZErxD.js.map +1 -0
- package/dist/conversation.d.ts +1 -1
- package/dist/{coordination-driver-CtbyZv5d.js → coordination-driver-Bw0Prnim.js} +672 -39
- package/dist/coordination-driver-Bw0Prnim.js.map +1 -0
- package/dist/{durable-file-g3YdfEh4.js → durable-file-D24y9zg7.js} +2 -2
- package/dist/{durable-file-g3YdfEh4.js.map → durable-file-D24y9zg7.js.map} +1 -1
- package/dist/durable.d.ts +2 -2
- package/dist/durable.js +3 -3
- package/dist/{environment-provider-C4AQiUxj.d.ts → environment-provider-CJ43FJfJ.d.ts} +2 -2
- package/dist/{environment-provider-DZxuH3E4.js → environment-provider-DEwsolvi.js} +44 -7
- package/dist/environment-provider-DEwsolvi.js.map +1 -0
- package/dist/environment-provider.d.ts +1 -1
- package/dist/environment-provider.js +1 -1
- package/dist/{graph-DzkWh1BI.js → graph-BzsMtBYp.js} +6 -3
- package/dist/graph-BzsMtBYp.js.map +1 -0
- package/dist/graph.d.ts +3 -3
- package/dist/graph.js +5 -5
- package/dist/{redact-C9EWk1FT.d.ts → improve-Cbbt3jE6.d.ts} +4 -36
- package/dist/{improvement-cycle-DP9zf-IL.js → improvement-cycle-jC89uaRW.js} +7 -7
- package/dist/{improvement-cycle-DP9zf-IL.js.map → improvement-cycle-jC89uaRW.js.map} +1 -1
- package/dist/{index-k5bcID4t.d.ts → index-B2rVjcPT.d.ts} +417 -56
- package/dist/{index-DCqHTdmp.d.ts → index-CUosKU4N.d.ts} +144 -4
- package/dist/{index-DA9jKuJc.d.ts → index-OSRVFARy.d.ts} +2 -2
- package/dist/{index-tf6g2B27.d.ts → index-Y14IrBuB.d.ts} +4 -4
- package/dist/index.d.ts +11 -10
- package/dist/index.js +12 -13
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +6 -5
- package/dist/intelligence.js +6 -7
- package/dist/intelligence.js.map +1 -1
- package/dist/kernel.d.ts +6 -6
- package/dist/kernel.js +12 -12
- package/dist/{knowledge-C5lODZQC.js → knowledge-BuXP5ynd.js} +5 -5
- package/dist/{knowledge-C5lODZQC.js.map → knowledge-BuXP5ynd.js.map} +1 -1
- package/dist/knowledge.d.ts +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-BKsjoaVu.js → loop-runner-bin-B_Xh4jLi.js} +3 -3
- package/dist/{loop-runner-bin-BKsjoaVu.js.map → loop-runner-bin-B_Xh4jLi.js.map} +1 -1
- package/dist/{loop-runner-bin-ncN_8Msd.d.ts → loop-runner-bin-C2Yw-RBc.d.ts} +3 -3
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +4 -4
- package/dist/mcp/index.js +8 -8
- package/dist/mcp/memory-bin.js +1 -1
- package/dist/{memory-server-DsKOhzGf.js → memory-server-Crkevawz.js} +2 -2
- package/dist/{memory-server-DsKOhzGf.js.map → memory-server-Crkevawz.js.map} +1 -1
- package/dist/{openai-tools-x83CTnJM.js → openai-tools-Dqg8IhKd.js} +2 -2
- package/dist/{openai-tools-x83CTnJM.js.map → openai-tools-Dqg8IhKd.js.map} +1 -1
- package/dist/{prepare-BtXhV0qj.js → prepare-B5fJ7mLS.js} +239 -227
- package/dist/prepare-B5fJ7mLS.js.map +1 -0
- package/dist/primeintellect/index.d.ts +1 -1
- package/dist/primeintellect/index.js +1 -1
- package/dist/profiles.js +1 -1
- package/dist/{protected-model-port-DHrayPt4.js → protected-model-port-B0xFSAjt.js} +2 -2
- package/dist/{protected-model-port-DHrayPt4.js.map → protected-model-port-B0xFSAjt.js.map} +1 -1
- package/dist/{provision-supervisor-B-_4I1In.js → provision-supervisor-DAcTZDQG.js} +8 -8
- package/dist/{provision-supervisor-B-_4I1In.js.map → provision-supervisor-DAcTZDQG.js.map} +1 -1
- package/dist/{supervisor-BSNkaM2a.js → redact-BP8Xn2A3.js} +569 -12
- package/dist/redact-BP8Xn2A3.js.map +1 -0
- package/dist/{run-layout-Cd_l2XWV.js → run-layout-B8I_LXN-.js} +3 -3
- package/dist/{run-layout-Cd_l2XWV.js.map → run-layout-B8I_LXN-.js.map} +1 -1
- package/dist/{runtime-EQgE3942.d.ts → runtime-DI4mJNXI.d.ts} +202 -4
- package/dist/{runtime-C98JsP83.js → runtime-Dm63BrGY.js} +69 -25
- package/dist/{runtime-C98JsP83.js.map → runtime-Dm63BrGY.js.map} +1 -1
- package/dist/{spawn-journal-CxRa-NJ2.js → spawn-journal-B9eTmVAn.js} +2 -2
- package/dist/{spawn-journal-CxRa-NJ2.js.map → spawn-journal-B9eTmVAn.js.map} +1 -1
- package/dist/{stream-agent-turn-BomJ21AK.d.ts → stream-agent-turn-_GgUW49y.d.ts} +35 -3
- package/dist/{structural-rollout-C8sB6B4q.js → structural-rollout-ChpGSR0q.js} +3 -3
- package/dist/{structural-rollout-C8sB6B4q.js.map → structural-rollout-ChpGSR0q.js.map} +1 -1
- package/dist/{supervise-DSu4d0b6.js → supervise-B89x7rgF.js} +287 -23
- package/dist/supervise-B89x7rgF.js.map +1 -0
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +13 -13
- package/dist/{top-app-DIBApkt1.js → top-app-KgIFpD9H.js} +3 -3
- package/dist/{top-app-DIBApkt1.js.map → top-app-KgIFpD9H.js.map} +1 -1
- package/dist/tui/bin.js +1 -1
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +2 -2
- package/dist/{types-BbkiJR1D.d.ts → types-DKA_PDv0.d.ts} +62 -2
- package/dist/{util-BfoW6RU7.js → util-mCNUeboW.js} +21 -2
- package/dist/util-mCNUeboW.js.map +1 -0
- package/dist/{workspace-archive-SVeiWLNE.js → workspace-archive-yAPDklLV.js} +4 -4
- package/dist/{workspace-archive-SVeiWLNE.js.map → workspace-archive-yAPDklLV.js.map} +1 -1
- package/package.json +8 -8
- package/dist/candidate-execution-CQYU8E5a.js.map +0 -1
- package/dist/coordination-driver-CtbyZv5d.js.map +0 -1
- package/dist/environment-provider-DZxuH3E4.js.map +0 -1
- package/dist/graph-DzkWh1BI.js.map +0 -1
- package/dist/prepare-BtXhV0qj.js.map +0 -1
- package/dist/redact-D-u-rrcn.js +0 -82
- package/dist/redact-D-u-rrcn.js.map +0 -1
- package/dist/supervise-DSu4d0b6.js.map +0 -1
- package/dist/supervisor-BSNkaM2a.js.map +0 -1
- package/dist/util-BfoW6RU7.js.map +0 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { i as writeAtomicDurableFile, n as assertNoSymlinkDescendant, r as publishExclusiveDurableFile, t as appendDurableFile } from "./durable-file-
|
|
1
|
+
import { i as writeAtomicDurableFile, n as assertNoSymlinkDescendant, r as publishExclusiveDurableFile, t as appendDurableFile } from "./durable-file-D24y9zg7.js";
|
|
2
2
|
import { canonicalCandidateDigest } from "@tangle-network/agent-interface";
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
|
-
import { join, resolve } from "node:path";
|
|
5
4
|
import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
|
|
5
|
+
import { join, resolve } from "node:path";
|
|
6
6
|
//#region src/runtime/supervise/run-layout.ts
|
|
7
7
|
/**
|
|
8
8
|
* The on-disk supervisor-run layout: `<root>/.agent/supervisor/<id>`.
|
|
@@ -642,4 +642,4 @@ function assertSameSteerRequest(existing, candidate) {
|
|
|
642
642
|
//#endregion
|
|
643
643
|
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
644
|
|
|
645
|
-
//# sourceMappingURL=run-layout-
|
|
645
|
+
//# sourceMappingURL=run-layout-B8I_LXN-.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-layout-Cd_l2XWV.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 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/** 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: { 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 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 }\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 }\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 })\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 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.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.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 `writeWorkerS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AAS,uBAAuB,UAA8B,WAAqC;CACjG,IAAI,SAAS,gBAAgB,UAAU,aACrC,MAAM,IAAI,MAAM,gCAAgC;CAElD,IAAI,SAAS,kBAAkB,UAAU,eACvC,MAAM,IAAI,MACR,gCAAgC,UAAU,YAAY,sCACxD;AAEJ"}
|
|
1
|
+
{"version":3,"file":"run-layout-B8I_LXN-.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 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/** 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: { 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 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 }\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 }\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 })\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 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.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.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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwMA,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,oBAAo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a,MAAM;EACnB,QAAQ,MAAM;EACd,SAAS,MAAM;EACf,QAAQ,MAAM;EACd,WAAW,MAAM;CACnB,CAAC;CACD,IAAI,MAAM,kBAAkB,UAAU,MAAM,IAAI,MAAM,qCAAqC;CAC3F,OAAO;AACT;AAEA,SAAS,gCAAgC,OAA4C;CACnF,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GACpE,MAAM,IAAI,MAAM,oCAAoC;CAEtD,MAAM,SAAS;CACf,IACE,OAAO,kBAAkB,KACzB,OAAO,OAAO,gBAAgB,YAC9B,OAAO,YAAY,WAAW,KAC9B,OAAO,OAAO,kBAAkB,YAChC,OAAO,OAAO,WAAW,YACzB,OAAO,OAAO,WAAW,KACxB,OAAO,WAAW,aACjB,OAAO,WAAW,eAClB,OAAO,WAAW,cAClB,OAAO,WAAW,iBAClB,OAAO,WAAW,aACpB,OAAO,OAAO,gBAAgB,YAC9B,OAAO,OAAO,eAAe,YAC7B,OAAO,OAAO,WAAW,UAEzB,MAAM,IAAI,MAAM,oCAAoC;CAEtD,OAAO;AACT;AAEA,SAAS,uBAAuB,UAA8B,WAAqC;CACjG,IAAI,SAAS,gBAAgB,UAAU,aACrC,MAAM,IAAI,MAAM,gCAAgC;CAElD,IAAI,SAAS,kBAAkB,UAAU,eACvC,MAAM,IAAI,MACR,gCAAgC,UAAU,YAAY,sCACxD;AAEJ"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { E as SandboxClient, at as RuntimeStreamEvent, i as ExecCtx, k as Validator } from "./types-BdolQ6Zi.js";
|
|
2
|
-
import {
|
|
3
|
-
import { i as AgentEnvironmentProvider, o as AgentEnvironmentProviderRegistry, w as ProviderExecutorOptions } from "./environment-provider-
|
|
2
|
+
import { B as Scope, _ as ExecutorRegistry, _n as TraceSource, a as DefaultVerdict, b as ExecutorToolCall, g as ExecutorProgressEvent, it as UsageEvent, l as ExecutorCancellation, p as ExecutorFactory, q as Spend, u as ExecutorCancellationRequest, wn as ExecutorProgress } from "./types-DKA_PDv0.js";
|
|
3
|
+
import { i as AgentEnvironmentProvider, o as AgentEnvironmentProviderRegistry, w as ProviderExecutorOptions } from "./environment-provider-CJ43FJfJ.js";
|
|
4
4
|
import { AgentProfile, AgentProfileMcpServer, HarnessType, ReasoningEffort, StreamEvent } from "@tangle-network/agent-interface";
|
|
5
5
|
import { WorkspacePlanReceipt } from "@tangle-network/agent-profile-materialize";
|
|
6
6
|
import { ChildProcess } from "node:child_process";
|
|
@@ -752,6 +752,177 @@ interface InPlaceHarnessResult {
|
|
|
752
752
|
harness: WorktreeHarnessResult['harness'];
|
|
753
753
|
}
|
|
754
754
|
//#endregion
|
|
755
|
+
//#region src/runtime/harness-usage.d.ts
|
|
756
|
+
/**
|
|
757
|
+
* One harness's own token-usage report for one turn, in the runtime's field names.
|
|
758
|
+
*
|
|
759
|
+
* `input` is the provider's TOTAL prompt count and `output` is its TOTAL completion count.
|
|
760
|
+
* The other three counters CLASSIFY a part of one of those totals; none of them adds to it.
|
|
761
|
+
* `cachedInput` and `cacheWriteInput` classify `input`, which is the convention
|
|
762
|
+
* `promptCacheTokenClasses` (`util.ts`) folds: `freshInput = input - cacheRead - cacheWrite`.
|
|
763
|
+
* `reasoningOutput` classifies `output`.
|
|
764
|
+
*
|
|
765
|
+
* A counter the harness does not report stays absent, because a zero would claim the harness
|
|
766
|
+
* measured none.
|
|
767
|
+
*/
|
|
768
|
+
interface HarnessUsage {
|
|
769
|
+
/** The harness family whose adapter produced this report. */
|
|
770
|
+
readonly harness: HarnessType;
|
|
771
|
+
/** Total prompt tokens the provider charged for the turn, the cached ones included. */
|
|
772
|
+
readonly input: number;
|
|
773
|
+
/** Total completion tokens the provider charged for the turn, the reasoning ones included. */
|
|
774
|
+
readonly output: number;
|
|
775
|
+
/** The part of `input` the provider served from its prompt cache. */
|
|
776
|
+
readonly cachedInput?: number;
|
|
777
|
+
/** The part of `input` the provider wrote into its prompt cache. */
|
|
778
|
+
readonly cacheWriteInput?: number;
|
|
779
|
+
/** The part of `output` the model spent on reasoning. Never added to `output`. */
|
|
780
|
+
readonly reasoningOutput?: number;
|
|
781
|
+
}
|
|
782
|
+
/**
|
|
783
|
+
* Decode a sandbox event with one harness's adapter, or `undefined` when the event carries no
|
|
784
|
+
* harness-native usage.
|
|
785
|
+
*
|
|
786
|
+
* A NAMED harness reads with that harness's adapter only, and a named harness with no adapter
|
|
787
|
+
* reports nothing. It never falls through to another harness's adapter: a different harness's
|
|
788
|
+
* `turn.completed` decoded as codex would either drop the counters codex does not name or fail on
|
|
789
|
+
* a field codex requires, and both answers would be about the wrong harness. The composite over
|
|
790
|
+
* every registered adapter runs only when the caller cannot name the harness.
|
|
791
|
+
*
|
|
792
|
+
* Throws `ValidationError` when an adapter recognizes the event as its harness's usage carrier and
|
|
793
|
+
* cannot read the numbers.
|
|
794
|
+
*/
|
|
795
|
+
declare function decodeHarnessUsage(event: SandboxEvent, harness?: HarnessType): HarnessUsage | undefined;
|
|
796
|
+
//#endregion
|
|
797
|
+
//#region src/runtime/codex-rollout-store.d.ts
|
|
798
|
+
/** Who wrote one rollout, exactly as its own `session_meta` states it. Nothing here is inferred. */
|
|
799
|
+
interface CodexRolloutIdentity {
|
|
800
|
+
/** The rollout's own thread id (`session_meta.payload.id`). */
|
|
801
|
+
readonly sessionId: string;
|
|
802
|
+
/** The thread this one was spawned or forked from, when it was. */
|
|
803
|
+
readonly parentThreadId?: string;
|
|
804
|
+
/** The thread whose rows are prepended into this file, when this file is a fork. */
|
|
805
|
+
readonly forkedFromId?: string;
|
|
806
|
+
/** True when `thread_source` reads `subagent`: a harness-native child, invisible to the journal. */
|
|
807
|
+
readonly nativeChild: boolean;
|
|
808
|
+
/** The child's own path in the harness's agent tree (`/root/c1_b_grid`), when it has one. */
|
|
809
|
+
readonly agentPath?: string;
|
|
810
|
+
/** The harness's own nickname for the child ("Turing"), when it has one. */
|
|
811
|
+
readonly agentNickname?: string;
|
|
812
|
+
/** Spawn depth the harness recorded. `1` is a direct child of the seat. */
|
|
813
|
+
readonly depth?: number;
|
|
814
|
+
/** The working directory the session ran in, used to attribute a store to a workspace. */
|
|
815
|
+
readonly cwd?: string;
|
|
816
|
+
/** The codex build that wrote it. */
|
|
817
|
+
readonly cliVersion?: string;
|
|
818
|
+
/** When the session itself started, from its own `session_meta` timestamp. */
|
|
819
|
+
readonly startedAtMs?: number;
|
|
820
|
+
}
|
|
821
|
+
/** How this reader isolated the session's own rows from the parent rows prepended to its file. */
|
|
822
|
+
type CodexForkBoundary =
|
|
823
|
+
/** Not a fork: every row in the file belongs to this session. */
|
|
824
|
+
{
|
|
825
|
+
readonly kind: 'whole-file';
|
|
826
|
+
} |
|
|
827
|
+
/** A fork whose own first turn was isolated, and by which rule. */
|
|
828
|
+
{
|
|
829
|
+
readonly kind: 'resolved';
|
|
830
|
+
readonly rule: 'history-start-ordinal' | 'turn-is-session' | 'turn-uuid-v7' | 'turn-start-time';
|
|
831
|
+
/** The `turn_id` of the session's own first turn. */
|
|
832
|
+
readonly turnId?: string;
|
|
833
|
+
/** Rows credited to the parent and excluded from `own`. */
|
|
834
|
+
readonly inheritedTurns: number;
|
|
835
|
+
} |
|
|
836
|
+
/** A fork this reader could not isolate. `own` is absent; nothing may be charged. */
|
|
837
|
+
{
|
|
838
|
+
readonly kind: 'unresolved';
|
|
839
|
+
readonly reason: string;
|
|
840
|
+
};
|
|
841
|
+
/** One turn of one session, with the counters it added to the session's cumulative total. */
|
|
842
|
+
interface CodexRolloutTurn {
|
|
843
|
+
readonly turnId?: string;
|
|
844
|
+
readonly startedAtMs?: number;
|
|
845
|
+
readonly usage: HarnessUsage;
|
|
846
|
+
}
|
|
847
|
+
/** One rollout file, read. */
|
|
848
|
+
interface CodexRolloutSession {
|
|
849
|
+
readonly identity: CodexRolloutIdentity;
|
|
850
|
+
readonly boundary: CodexForkBoundary;
|
|
851
|
+
/**
|
|
852
|
+
* The session's OWN spend — the cumulative delta from its fork boundary to its last report.
|
|
853
|
+
* ABSENT when the boundary is unresolved: an unattributable number must not be charged.
|
|
854
|
+
*/
|
|
855
|
+
readonly own?: HarnessUsage;
|
|
856
|
+
/** The session's own turns, newest last. Empty when the file reported no usage. */
|
|
857
|
+
readonly turns: readonly CodexRolloutTurn[];
|
|
858
|
+
/**
|
|
859
|
+
* The file's final cumulative `total_token_usage`, kept ONLY as the diagnostic that shows how
|
|
860
|
+
* far a naive file total is from the truth. Never charge this.
|
|
861
|
+
*/
|
|
862
|
+
readonly fileCumulativeInput: number;
|
|
863
|
+
readonly fileCumulativeOutput: number;
|
|
864
|
+
}
|
|
865
|
+
/** What one incremental read of a store observed. */
|
|
866
|
+
interface CodexStoreDelta {
|
|
867
|
+
/** Spend by sessions that are NOT native children — the seat's own turns. */
|
|
868
|
+
readonly seat: HarnessUsage;
|
|
869
|
+
/** Spend by `thread_source: subagent` sessions — the harness-native children. */
|
|
870
|
+
readonly native: HarnessUsage;
|
|
871
|
+
/** Sessions whose fork boundary could not be isolated, so their spend is absent, not zero. */
|
|
872
|
+
readonly unresolved: ReadonlyArray<{
|
|
873
|
+
readonly sessionId: string;
|
|
874
|
+
readonly reason: string;
|
|
875
|
+
}>;
|
|
876
|
+
/**
|
|
877
|
+
* Every session this read touched, for evidence. Each one states its WHOLE own spend and turn
|
|
878
|
+
* list, which is not the same number as `seat` / `native`: those two carry only what this read
|
|
879
|
+
* newly observed.
|
|
880
|
+
*/
|
|
881
|
+
readonly sessions: readonly CodexRolloutSession[];
|
|
882
|
+
}
|
|
883
|
+
/** A store reader that credits each turn once: it tails only the bytes appended since the last read. */
|
|
884
|
+
interface CodexRolloutStoreReader {
|
|
885
|
+
/**
|
|
886
|
+
* Read everything appended since the previous call and attribute it.
|
|
887
|
+
*
|
|
888
|
+
* The FIRST call establishes the baseline. Call it before the first turn so pre-existing rows are
|
|
889
|
+
* consumed and credited to nothing; every later call returns exactly that turn's spend.
|
|
890
|
+
*/
|
|
891
|
+
read(): Promise<CodexStoreDelta>;
|
|
892
|
+
}
|
|
893
|
+
/** Where a harness keeps its own session store, and which workspace may be credited from it. */
|
|
894
|
+
interface CodexRolloutStoreRef {
|
|
895
|
+
/**
|
|
896
|
+
* Absolute path to the harness home the CLI writes into — `CODEX_HOME`, or `$HOME/.codex`.
|
|
897
|
+
* This MUST be the run's own isolated store. Pointing it at an ambient host store credits one
|
|
898
|
+
* run with another run's files, which is the exact defect this reader exists to end.
|
|
899
|
+
*/
|
|
900
|
+
readonly root: string;
|
|
901
|
+
/**
|
|
902
|
+
* Credit only sessions whose recorded `cwd` is this path or below it. Absent credits every
|
|
903
|
+
* session under `root`, which is correct only for a store no other run writes to.
|
|
904
|
+
*/
|
|
905
|
+
readonly workspaceRoot?: string;
|
|
906
|
+
}
|
|
907
|
+
/**
|
|
908
|
+
* Read one rollout's rows into a session record.
|
|
909
|
+
*
|
|
910
|
+
* `rows` is the file's JSON values in file order. Pass the whole file to read a completed session;
|
|
911
|
+
* the store reader passes appended slices and carries the identity forward itself.
|
|
912
|
+
*/
|
|
913
|
+
declare function readCodexRolloutSession(rows: Iterable<unknown>): CodexRolloutSession | undefined;
|
|
914
|
+
/**
|
|
915
|
+
* Open an incremental reader over a codex store.
|
|
916
|
+
*
|
|
917
|
+
* Nothing is read until `read()` is called, and every read is bounded by the bytes appended since
|
|
918
|
+
* the previous one, so a 695MB rollout is scanned once rather than once per turn.
|
|
919
|
+
*/
|
|
920
|
+
declare function createCodexRolloutStoreReader(ref: CodexRolloutStoreRef): CodexRolloutStoreReader;
|
|
921
|
+
/** Sum two usage reports on every counter both of them state. */
|
|
922
|
+
declare function addHarnessUsage(left: HarnessUsage, right: HarnessUsage): HarnessUsage;
|
|
923
|
+
/** True when a report states any spend at all. */
|
|
924
|
+
declare function harnessUsageIsEmpty(usage: HarnessUsage): boolean;
|
|
925
|
+
//#endregion
|
|
755
926
|
//#region src/runtime/key-provider.d.ts
|
|
756
927
|
/** Resolve named secrets. The ONE seam every secret store adapts to. */
|
|
757
928
|
interface KeyProvider {
|
|
@@ -1354,6 +1525,22 @@ interface BridgeSeam {
|
|
|
1354
1525
|
modelCredential?: BridgeModelCredential;
|
|
1355
1526
|
/** Optional working directory forwarded to cli-bridge and persisted with the session. */
|
|
1356
1527
|
cwd?: string;
|
|
1528
|
+
/**
|
|
1529
|
+
* The harness's OWN on-disk session store, read as a spend receipt.
|
|
1530
|
+
*
|
|
1531
|
+
* cli-bridge forwards no token usage for a codex worker, so a turn whose provider counters exist
|
|
1532
|
+
* only in codex's rollout meters `{0, 0}` with `tokensKnown: false`. Measured on one live seat
|
|
1533
|
+
* (discovery#80): 9 of 9 `metered` events read zero while 27,320,482 codex tokens sat in the same
|
|
1534
|
+
* run directory, 1,453,948 of them belonging to harness-native children the journal never saw.
|
|
1535
|
+
*
|
|
1536
|
+
* Naming the store here turns those rows into evidence. The executor tails it once per turn and
|
|
1537
|
+
* credits the DELTA, so each turn is charged once, and it reports the counters with
|
|
1538
|
+
* `provenance: 'harness-store'` so a reader can tell a disk receipt from a stream receipt.
|
|
1539
|
+
*
|
|
1540
|
+
* The path must be the run's OWN isolated store. An ambient host store credits this run with
|
|
1541
|
+
* another run's files, and `workspaceRoot` is the structural guard against it.
|
|
1542
|
+
*/
|
|
1543
|
+
harnessStore?: BridgeHarnessStore;
|
|
1357
1544
|
/** Caller-owned deadline for each bridge turn. Runtime enforces it locally and sends the
|
|
1358
1545
|
* same value in `execution.timeoutMs` so the bridge-owned process follows the same policy. */
|
|
1359
1546
|
timeoutMs?: number;
|
|
@@ -1365,6 +1552,17 @@ interface BridgeSeam {
|
|
|
1365
1552
|
/** Newest-last activity window `progress()` reports. Default 12. */
|
|
1366
1553
|
activityWindow?: number;
|
|
1367
1554
|
}
|
|
1555
|
+
/**
|
|
1556
|
+
* A harness's own session store on the bridge host, named so the runtime may read it.
|
|
1557
|
+
*
|
|
1558
|
+
* Only `codex` has a reader today. Any other harness is REFUSED rather than read with codex's
|
|
1559
|
+
* decoder: a different harness's file decoded as a codex rollout would either drop counters it does
|
|
1560
|
+
* not name or credit a number that is about the wrong wire shape.
|
|
1561
|
+
*/
|
|
1562
|
+
interface BridgeHarnessStore extends CodexRolloutStoreRef {
|
|
1563
|
+
/** The harness family that wrote the store. */
|
|
1564
|
+
readonly harness: HarnessType;
|
|
1565
|
+
}
|
|
1368
1566
|
/** A live, request-scoped model credential reference for a local cli-bridge. */
|
|
1369
1567
|
interface BridgeModelCredential {
|
|
1370
1568
|
/** Provider key name for the scoped model token. */
|
|
@@ -1493,5 +1691,5 @@ declare function createExecutor(config: ExecutorConfig): ExecutorFactory<unknown
|
|
|
1493
1691
|
*/
|
|
1494
1692
|
declare function createExecutorRegistry(): ExecutorRegistry;
|
|
1495
1693
|
//#endregion
|
|
1496
|
-
export {
|
|
1497
|
-
//# sourceMappingURL=runtime-
|
|
1694
|
+
export { CodexRolloutTurn as $, PeerMailboxOptions as $t, SandboxToolPartState as A, localHarnessExecutable as At, sumSandboxUsage as B, ToolLoopToolCall as Bt, Inbox as C, CodexTokenUsage as Ct, SandboxLeafOut as D, LocalHarnessResult as Dt, createInbox as E, LocalHarness as Et, extractLlmCallEvent as F, ToolLoopCallContext as Ft, resolveMcpServerLaunch as G, PeerMailEvent as Gt, ResolvedMcpServerLaunch as H, DEFAULT_PEER_MAIL_LIMITS as Ht, mapSandboxEvent as I, ToolLoopChat as It, CodexForkBoundary as J, PeerMailOutcome as Jt, resolveSecretEnv as K, PeerMailKind as Kt, mapSandboxToolEvent as L, ToolLoopCompaction as Lt, assertSandboxServedModel as M, runLocalHarness as Mt, createSandboxToolPartState as N, RouterTransportConfig as Nt, SandboxOutputMarker as O, RunLocalHarnessOptions as Ot, createSandboxUsageLedger as P, ToolSpec as Pt, CodexRolloutStoreRef as Q, PeerMailbox as Qt, sandboxEventServedBackend as R, ToolLoopCompactionOptions as Rt, AuthorityInboxMessage as S, CodexExecutionPolicy as St, PeerInboxMessage as T, LOCAL_HARNESSES as Tt, envKeyProvider as U, PEER_MAIL_WIRE_KEY as Ut, KeyProvider as V, AUTHORITY_MARKERS as Vt, mcpSecretEnvMetadataKey as W, PeerMailEnvelope as Wt, CodexRolloutSession as X, PeerMailRefusal as Xt, CodexRolloutIdentity as Y, PeerMailReadout as Yt, CodexRolloutStoreReader as Z, PeerMailSendInput as Zt, DEFAULT_SANDBOX_STEERING_MAX_TURNS as _, WorktreeHandle as _t, CliSeam as a, JsonRpcMessage as an, HarnessUsage as at, SteerableSandboxSession as b, removeWorktree as bt, ExecutorConfig as c, McpTransport as cn, WorktreeCheckRunner as ct, RouterToolsSeam as d, WorktreeProfileMaterializationReceipt as dt, claimsAuthority as en, CodexStoreDelta as et, SandboxSeam as f, CreateWorktreeOptions as ft, createExecutorRegistry as g, RemoveWorktreeOptions as gt, createExecutor as h, GitRunner as ht, CliInPlaceSeam as i, peerMailVerbNames as in, readCodexRolloutSession as it, SandboxUsageLedger as j, parseCodexTokenUsage as jt, SandboxServedBackend as k, harnessSupportsReasoningEffort as kt, ProviderSeam as l, WorktreeCommandResult as lt, cliWorktreeExecutor as m, DiffResult as mt, BridgeModelCredential as n, isPeerMailEnvelope as nn, createCodexRolloutStoreReader as nt, CliWorktreeBridgeSeam as o, JsonRpcResponse as on, decodeHarnessUsage as ot, cliInPlaceExecutor as p, DiffOptions as pt, secretEnvOfMcpServer as q, PeerMailLimits as qt, BridgeSeam as r, peerMailTools as rn, harnessUsageIsEmpty as rt, CliWorktreeSeam as s, McpToolDescriptor as sn, InPlaceHarnessResult as st, BridgeHarnessStore as t, createPeerMailbox as tn, addHarnessUsage as tt, RouterSeam as u, WorktreeHarnessResult as ut, SandboxSteeringOptions as v, captureWorktreeDiff as vt, InboxMessage as w, DEFAULT_LOCAL_HARNESS as wt, createSteerableSandboxSession as x, CodexExecutionEvidence as xt, SteerableSandboxArgs as y, createWorktree as yt, sandboxProgressEvents as z, ToolLoopMessageRecord as zt };
|
|
1695
|
+
//# sourceMappingURL=runtime-DI4mJNXI.d.ts.map
|