@tangle-network/agent-runtime 10.0.3 → 10.0.5
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/CHANGELOG.md +30 -0
- package/dist/{activation-kitznAHo.js → activation-DvvM7gG5.js} +2 -2
- package/dist/{activation-kitznAHo.js.map → activation-DvvM7gG5.js.map} +1 -1
- package/dist/{activation-DbSxPRUW.d.ts → activation-DyFt-GHq.d.ts} +2 -2
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +3 -3
- package/dist/{continuation-BDeKJgV3.js → continuation-Bccak14N.js} +3 -3
- package/dist/{continuation-BDeKJgV3.js.map → continuation-Bccak14N.js.map} +1 -1
- package/dist/{delegate-D8yX_2K7.js → delegate-YBqrrbq7.js} +2 -2
- package/dist/{delegate-D8yX_2K7.js.map → delegate-YBqrrbq7.js.map} +1 -1
- package/dist/{driver-control-acknowledgers-BTSr3Znq.js → driver-control-acknowledgers-CNNRjIo9.js} +99 -57
- package/dist/{driver-control-acknowledgers-BTSr3Znq.js.map → driver-control-acknowledgers-CNNRjIo9.js.map} +1 -1
- package/dist/durable-file-iPCEs_-s.js +1 -0
- package/dist/{durable-file-DUcTDWJD.js → durable-file-pao7FijS.js} +10 -3
- package/dist/{durable-file-DUcTDWJD.js.map → durable-file-pao7FijS.js.map} +1 -1
- package/dist/durable-writer-thread.js +5 -5
- package/dist/durable.d.ts +4 -1
- package/dist/durable.js +21 -15
- package/dist/durable.js.map +1 -1
- package/dist/failure-cause-DoCCGLDH.js.map +1 -1
- package/dist/{graph-4ep9laIH.js → graph-CUUtx7qT.js} +8 -12
- package/dist/{graph-4ep9laIH.js.map → graph-CUUtx7qT.js.map} +1 -1
- package/dist/{graph-registry-B-EGvJ-3.js → graph-registry-CGKyYabE.js} +1 -1
- package/dist/{graph-registry-BxEBeihr.js → graph-registry-CRskE_Yp.js} +4 -4
- package/dist/{graph-registry-BxEBeihr.js.map → graph-registry-CRskE_Yp.js.map} +1 -1
- package/dist/{improve-CJf87tBs.js → improve-Cy8PZUdw.js} +8 -8
- package/dist/{improve-CJf87tBs.js.map → improve-Cy8PZUdw.js.map} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +10 -10
- package/dist/intelligence.d.ts +2 -2
- package/dist/intelligence.js +4 -4
- package/dist/{jsonl-file-CVAWegN-.js → jsonl-file-vE9H9UXa.js} +3 -3
- package/dist/{jsonl-file-CVAWegN-.js.map → jsonl-file-vE9H9UXa.js.map} +1 -1
- package/dist/kernel.d.ts +2 -2
- package/dist/kernel.js +19 -19
- package/dist/{loop-runner-Ckj-Zz3-.js → loop-runner-BwkX4ViS.js} +2 -2
- package/dist/{loop-runner-Ckj-Zz3-.js.map → loop-runner-BwkX4ViS.js.map} +1 -1
- package/dist/{loop-runner-CayC8e9K.d.ts → loop-runner-Icc1iBR-.d.ts} +2 -2
- 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 +1 -1
- package/dist/mcp/index.js +6 -6
- package/dist/{model-policy-DZnL8Yj9.js → model-policy-DTbTFyOG.js} +12 -6
- package/dist/model-policy-DTbTFyOG.js.map +1 -0
- package/dist/profiles.d.ts +1 -1
- package/dist/profiles.js +1 -1
- package/dist/{provision-supervisor-NjROV7AQ.js → provision-supervisor-Dtn8RjHe.js} +7 -7
- package/dist/{provision-supervisor-NjROV7AQ.js.map → provision-supervisor-Dtn8RjHe.js.map} +1 -1
- package/dist/{result-blob-store-BR-BVZrg.js → result-blob-store-UGXQYACQ.js} +3 -3
- package/dist/{result-blob-store-BR-BVZrg.js.map → result-blob-store-UGXQYACQ.js.map} +1 -1
- package/dist/{run-cancellation-C9V1lYhq.js → run-cancellation-BpUQZqBS.js} +3 -3
- package/dist/{run-cancellation-C9V1lYhq.js.map → run-cancellation-BpUQZqBS.js.map} +1 -1
- package/dist/{run-lock-Y3u9kwM0.js → run-lock-Ckakh1Uq.js} +3 -3
- package/dist/{run-lock-Y3u9kwM0.js.map → run-lock-Ckakh1Uq.js.map} +1 -1
- package/dist/{run-reopen-CHYTHk7x.js → run-reopen-BvF3Gjj9.js} +6 -6
- package/dist/{run-reopen-CHYTHk7x.js.map → run-reopen-BvF3Gjj9.js.map} +1 -1
- package/dist/{run-state-DgKo8_tO.js → run-state-CZcFJjHn.js} +7 -7
- package/dist/{run-state-DgKo8_tO.js.map → run-state-CZcFJjHn.js.map} +1 -1
- package/dist/{runtime-CdthBQUs.js → runtime-BvDaNyFf.js} +44 -53
- package/dist/runtime-BvDaNyFf.js.map +1 -0
- package/dist/{search-executor-Bb0WuI_Z.js → search-executor-DWQW-9WN.js} +4 -4
- package/dist/{search-executor-Bb0WuI_Z.js.map → search-executor-DWQW-9WN.js.map} +1 -1
- package/dist/{server-BCtyL7jH.js → server-D5GpuQnT.js} +3 -3
- package/dist/{server-BCtyL7jH.js.map → server-D5GpuQnT.js.map} +1 -1
- package/dist/{settle-record-Beh-sXBW.js → settle-record-BFhJigPW.js} +4 -4
- package/dist/{settle-record-Beh-sXBW.js.map → settle-record-BFhJigPW.js.map} +1 -1
- package/dist/{structural-rollout-BRfSDPkv.js → structural-rollout-D1pZn6Cu.js} +4 -4
- package/dist/{structural-rollout-BRfSDPkv.js.map → structural-rollout-D1pZn6Cu.js.map} +1 -1
- package/dist/{supervise-DTUYxnoJ.js → supervise-fmugf6Y2.js} +16 -15
- package/dist/supervise-fmugf6Y2.js.map +1 -0
- package/dist/{supervise-identity-eMF-h1uP.js → supervise-identity-7_7DUghQ.js} +4 -4
- package/dist/{supervise-identity-eMF-h1uP.js.map → supervise-identity-7_7DUghQ.js.map} +1 -1
- package/dist/{supervision-discovery-CAUsSDno.js → supervision-discovery-DwRtZNdy.js} +5 -8
- package/dist/supervision-discovery-DwRtZNdy.js.map +1 -0
- package/dist/{supervisor-BtRRFbgF.js → supervisor-BlACe-uO.js} +126 -61
- package/dist/supervisor-BlACe-uO.js.map +1 -0
- package/dist/{supervisor-accounting-Cuehs4te.js → supervisor-accounting-DuFyM-_h.js} +159 -57
- package/dist/supervisor-accounting-DuFyM-_h.js.map +1 -0
- package/dist/{supervisor-root-contract-CmFKzPps.js → supervisor-root-contract-DCMw4u0V.js} +2 -2
- package/dist/{supervisor-root-contract-CmFKzPps.js.map → supervisor-root-contract-DCMw4u0V.js.map} +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +11 -11
- package/dist/{top-web-D-wuEVdM.js → top-web-C5vhiOFA.js} +7 -7
- package/dist/{top-web-D-wuEVdM.js.map → top-web-C5vhiOFA.js.map} +1 -1
- package/dist/tui/bin.js +3 -3
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +2 -2
- package/dist/{types-PBoTtcbX.d.ts → types-CFmKHKiN.d.ts} +16 -3
- package/package.json +1 -1
- package/dist/durable-file-XqOyDf7q.js +0 -1
- package/dist/model-policy-DZnL8Yj9.js.map +0 -1
- package/dist/runtime-CdthBQUs.js.map +0 -1
- package/dist/supervise-DTUYxnoJ.js.map +0 -1
- package/dist/supervision-discovery-CAUsSDno.js.map +0 -1
- package/dist/supervisor-BtRRFbgF.js.map +0 -1
- package/dist/supervisor-accounting-Cuehs4te.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { u as writeAtomicDurableFile } from "./durable-file-pao7FijS.js";
|
|
@@ -326,7 +326,10 @@ function durableCallAsync(operation) {
|
|
|
326
326
|
function publishExclusiveDurableFile(filePath, content, options = {}) {
|
|
327
327
|
return typeof content === "string" ? runFenced("publishExclusiveDurableFile", publishExclusiveFenced, filePath, content, options) : publishExclusiveFenced(filePath, content, options);
|
|
328
328
|
}
|
|
329
|
-
/**
|
|
329
|
+
/**
|
|
330
|
+
* `publishExclusiveDurableFile` without blocking the calling thread on the disk: a claimed write
|
|
331
|
+
* runs on the durable writer, an unclaimed one inline as its caller's own single write.
|
|
332
|
+
*/
|
|
330
333
|
function publishExclusiveDurableFileAsync(filePath, content, options = {}) {
|
|
331
334
|
return runFencedAsync("publishExclusiveDurableFile", publishExclusiveFenced, filePath, content, options);
|
|
332
335
|
}
|
|
@@ -444,6 +447,10 @@ function writeAtomicDurableFile(filePath, content, options = {}) {
|
|
|
444
447
|
if (typeof content === "string") runFenced("writeAtomicDurableFile", writeAtomicFenced, filePath, content, options);
|
|
445
448
|
else writeAtomicFenced(filePath, content, options);
|
|
446
449
|
}
|
|
450
|
+
/** `writeAtomicDurableFile` off the calling thread when the write is claimed. */
|
|
451
|
+
function writeAtomicDurableFileAsync(filePath, content, options = {}) {
|
|
452
|
+
return runFencedAsync("writeAtomicDurableFile", writeAtomicFenced, filePath, content, options);
|
|
453
|
+
}
|
|
447
454
|
/** The fenced atomic replacement the durable writer runs. @internal */
|
|
448
455
|
function writeAtomicFenced(filePath, content, options = {}) {
|
|
449
456
|
fenceRunWrite(() => writeAtomicDurableFileUnchecked(filePath, content, options));
|
|
@@ -493,6 +500,6 @@ function isAlreadyExistsError(error) {
|
|
|
493
500
|
function isNoEntryError(error) {
|
|
494
501
|
return error !== null && typeof error === "object" && "code" in error && error.code === "ENOENT";
|
|
495
502
|
}
|
|
496
|
-
export {
|
|
503
|
+
export { runGenerationPath as C, mutateRunClaim as S, runFenced as _, assertNoSymlinkDescendant as a, captureRunWriteContext as b, publishExclusiveFenced as c, writeAtomicDurableFileAsync as d, writeAtomicFenced as f, routesToDurableWriter as g, registerDurableErrorClass as h, appendRunLinesFenced as i, syncDurableDirectory as l, durableCallAsync as m, appendDurableFile as n, publishExclusiveDurableFile as o, becomeDurableWriter as p, appendRunLines as r, publishExclusiveDurableFileAsync as s, appendDurableFenced as t, writeAtomicDurableFile as u, runFencedAlways as v, runWithWriteClaim as w, fenceRunWrite as x, runFencedAsync as y };
|
|
497
504
|
|
|
498
|
-
//# sourceMappingURL=durable-file-
|
|
505
|
+
//# sourceMappingURL=durable-file-pao7FijS.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"durable-file-DUcTDWJD.js","names":["fsConstants"],"sources":["../src/durable/run-fence.ts","../src/durable/durable-writer.ts","../src/runtime/supervise/durable-file.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport { closeSync, existsSync, fstatSync, openSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { isMainThread } from 'node:worker_threads'\nimport { tryAcquireAtomicFileLock } from '@tangle-network/agent-eval/ledger-core'\nimport type { LockIdentity } from '@tangle-network/agent-eval/lock-holder'\n\n/** The immutable claim carried by every write in one directory execution. @internal */\nexport interface RunWriteClaim {\n readonly path: string\n readonly generation: number\n readonly lock: LockIdentity\n}\n\nconst claims = new AsyncLocalStorage<RunWriteClaim | undefined>()\nconst publications = new AsyncLocalStorage<{ readonly claim: RunWriteClaim; active: boolean }>()\n\n// Set on the durable writer thread (durable-writer-thread.ts): the one thread that runs claimed writes.\nlet writerThread = false\n\n/** Mark this thread as the process's durable writer. @internal */\nexport function markDurableWriterThread(): void {\n writerThread = true\n}\n\n/** True on the durable writer thread. @internal */\nexport function onDurableWriterThread(): boolean {\n return writerThread\n}\n\n/** The claim the current asynchronous context carries, if any. @internal */\nexport function currentRunWriteClaim(): RunWriteClaim | undefined {\n return claims.getStore()\n}\n\n/** Bind asynchronous work, including callbacks, to the generation that admitted it. @internal */\nexport function runWithWriteClaim<T>(claim: RunWriteClaim, operation: () => T): T {\n return claims.run(claim, operation)\n}\n\n/** Capture a store's acquisition once, even when later called from an unrelated emitter. @internal */\nexport function captureRunWriteContext(): <T>(operation: () => T) => T {\n let claim = claims.getStore()\n return <T>(operation: () => T): T => {\n claim ??= claims.getStore()\n return claims.run(claim, operation)\n }\n}\n\n/** Serialize claim changes and file mutations under the same cross-process guard. @internal */\nexport function mutateRunClaim<T>(path: string, operation: () => T): T {\n // Old writers use an unowned directory guard. Never race one or guess that it is stale.\n const legacyGuard = `${path}.guard`\n if (existsSync(legacyGuard)) {\n throw new Error(\n `supervisePursuit: cannot mutate ${path}; inspect ${legacyGuard} and remove it only after confirming no lock mutation is active`,\n )\n }\n const deadline = performance.now() + 5_000\n const sleeper = new Int32Array(new SharedArrayBuffer(4))\n for (;;) {\n const acquisition = tryAcquireAtomicFileLock({ lockPath: `${path}.mutation` })\n if (acquisition.acquired) {\n try {\n return operation()\n } finally {\n acquisition.lock.release()\n }\n }\n if (performance.now() >= deadline) throw new Error(`run directory mutation is held: ${path}`)\n Atomics.wait(sleeper, 0, 0, 10)\n }\n}\n\n/**\n * Fence an actual file mutation, not an earlier advisory check. No await occurs between the\n * ownership check and publication, and acquire/release use this same guard. Unclaimed standalone\n * stores retain their existing single-writer contract; pursuit-owned work always carries a claim.\n * @internal\n */\nexport function fenceRunWrite<T>(operation: () => T): T {\n const claim = claims.getStore()\n if (claim === undefined) return operation()\n // A claimed write on the main thread would hold the run's mutation lock against the durable\n // writer and block the event loop on the disk: it must be sent through `runFenced`.\n if (isMainThread && !writerThread) {\n throw new Error('a claimed run write reached the main thread; send it through runFenced')\n }\n const publication = publications.getStore()\n if (\n publication?.active &&\n publication.claim.path === claim.path &&\n publication.claim.generation === claim.generation\n )\n return operation()\n return mutateRunClaim(claim.path, () => {\n let holder: Partial<RunWriteClaim> | undefined\n try {\n const fd = openSync(claim.path, 'r')\n try {\n const stat = fstatSync(fd, { bigint: true })\n if (\n stat.dev.toString() !== claim.lock.dev ||\n stat.ino.toString() !== claim.lock.ino ||\n stat.birthtimeNs.toString() !== claim.lock.birthtimeNs\n ) {\n throw new Error('run lock inode changed')\n }\n holder = JSON.parse(readFileSync(fd, 'utf8')) as Partial<RunWriteClaim>\n } finally {\n closeSync(fd)\n }\n } catch (cause) {\n throw new Error(`run directory generation ${claim.generation} lost its claim`, { cause })\n }\n if (\n holder?.generation !== claim.generation ||\n holder.lock?.dev !== claim.lock.dev ||\n holder.lock?.ino !== claim.lock.ino ||\n holder.lock?.birthtimeNs !== claim.lock.birthtimeNs\n ) {\n throw new Error(`run directory generation ${claim.generation} lost its claim`)\n }\n // Nested synchronous primitives share the guard. A callback queued here keeps its claim,\n // but cannot inherit a live guard after this publication has returned.\n const publication = { claim, active: true }\n try {\n return publications.run(publication, operation)\n } finally {\n publication.active = false\n }\n })\n}\n\n/** Persistent generation counter survives a clean release of supervise.lock. @internal */\nexport function runGenerationPath(runDir: string): string {\n return resolve(runDir, 'supervise.generation')\n}\n","/**\n * The durable writer: one thread per process that performs every claimed run-directory write.\n *\n * A fenced write is synchronous by contract (lock, claim check, mutation and fsync with no await\n * between them), and on a saturated disk its open, link and fsync calls wait on the filesystem\n * journal: a coordinator whose event loop ran them was measured blocked 20 to 70 s at a time.\n * Here the same synchronous code runs on its own thread. Only that thread takes a run directory's\n * mutation lock in this process, so a caller never spins on a lock this process holds.\n *\n * - `durableCall` blocks the calling thread until the writer answers, exactly as the inline write\n * did, for callers whose contract is synchronous.\n * - `durableCallAsync` resolves with the writer's answer and leaves the event loop free.\n * - On the writer thread both run the operation inline, so a fenced helper may call another.\n * - Operations run in the order they were sent, sync and async alike.\n * - A call the writer does not answer within `DURABLE_WRITER_DEADLINE_MS` fails, and the writer\n * keeps running. A writer that errors or exits fails every waiting and later call and is never\n * replaced. Nothing falls back to writing on the calling thread.\n *\n * @internal\n */\n\nimport { existsSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { fileURLToPath } from 'node:url'\nimport { isMainThread, MessageChannel, receiveMessageOnPort, Worker } from 'node:worker_threads'\nimport {\n currentRunWriteClaim,\n markDurableWriterThread,\n onDurableWriterThread,\n type RunWriteClaim,\n} from './run-fence'\n\n/** Longer than the worst fsync measured on a saturated disk (70 s), so only a dead writer trips it. */\nexport const DURABLE_WRITER_DEADLINE_MS = 180_000\n\n/** A named operation and its JSON arguments; names resolve in `durable-writer-thread.ts`. */\nexport interface DurableOperation {\n readonly name: string\n readonly args: readonly unknown[]\n}\n\ninterface Request extends DurableOperation {\n readonly id: number\n readonly claim: RunWriteClaim | undefined\n readonly sync: boolean\n}\n\ntype Reply =\n | { readonly id: number; readonly ok: true; readonly value: unknown }\n | {\n readonly id: number\n readonly ok: false\n readonly error: {\n message: string\n name?: string\n code?: string\n stack?: string\n fields?: Record<string, unknown>\n }\n }\n\nlet runInline: ((operation: DurableOperation) => unknown) | undefined\n\n/** Called by the writer thread's entry: operations sent from this thread now run inline. */\nexport function becomeDurableWriter(inline: (operation: DurableOperation) => unknown): void {\n markDurableWriterThread()\n runInline = inline\n}\n\n/**\n * Whether a write goes to the writer: a claimed write made by the main thread, or with `always`,\n * any write the main thread makes (run-directory acquisition and release take the same lock before\n * a claim exists). Unclaimed writes keep their caller-owned single-writer contract and run inline,\n * and other worker threads never start a second writer that would contend for the same lock.\n */\nexport function routesToDurableWriter(always = false): boolean {\n return (\n !onDurableWriterThread() && isMainThread && (always || currentRunWriteClaim() !== undefined)\n )\n}\n\n/**\n * Run the fenced operation `fn(...args)`: inline when the write is not routed, otherwise on the\n * writer under the caller's claim, blocking this thread until it answers. `fn` takes its own fence\n * (`fenceRunWrite` or `mutateRunClaim`) and is registered under `name` in durable-writer-thread.ts;\n * arguments and the result cross the thread as structured clones.\n */\nexport function runFenced<A extends unknown[], T>(\n name: string,\n fn: (...args: A) => T,\n ...args: A\n): T {\n return routesToDurableWriter() ? durableCall<T>({ name, args }) : fn(...args)\n}\n\n/** `runFenced` without blocking: the event loop stays free while the writer works. */\nexport function runFencedAsync<A extends unknown[], T>(\n name: string,\n fn: (...args: A) => T,\n ...args: A\n): Promise<T> {\n if (routesToDurableWriter()) return durableCallAsync<T>({ name, args })\n try {\n return Promise.resolve(fn(...args))\n } catch (error) {\n return Promise.reject(error)\n }\n}\n\n/** `runFencedAsync` for run-directory acquisition and release, routed from the main thread even\n * before a claim exists, since they take the same mutation lock the writer holds. */\nexport function runFencedAlways<A extends unknown[], T>(\n name: string,\n fn: (...args: A) => T,\n ...args: A\n): Promise<T> {\n if (routesToDurableWriter(true)) return durableCallAsync<T>({ name, args })\n try {\n return Promise.resolve(fn(...args))\n } catch (error) {\n return Promise.reject(error)\n }\n}\n\ninterface Writer {\n readonly worker: Worker\n readonly syncReplies: MessageChannel\n readonly signal: Int32Array\n readonly pending: Map<\n number,\n { resolve: (value: unknown) => void; reject: (error: Error) => void; timer: NodeJS.Timeout }\n >\n}\n\nlet writer: Writer | undefined\n// Set when the writer errors or exits. It is never replaced: it may have died inside a fence\n// holding the run's mutation lock under this live pid, and a new writer could only spin on that\n// lock. Every later routed write fails at once with this cause.\nlet writerDeath: Error | undefined\nlet nextId = 0\n\n// Errors an operation throws are rebuilt on the caller's thread as their own class, with their\n// own fields, so `instanceof` and fields such as a lock holder survive the thread boundary.\nconst errorClasses = new Map<string, { prototype: Error }>()\n\n/** Rebuild errors named `name` thrown on the writer as instances of `errorClass`. @internal */\nexport function registerDurableErrorClass(name: string, errorClass: { prototype: Error }): void {\n errorClasses.set(name, errorClass)\n}\n\n/**\n * The writer's entry beside this module: TypeScript in a source checkout, JavaScript in a built\n * package. A tool that bundles Runtime again must emit `src/durable/durable-writer-thread.ts` as\n * `durable-writer-thread.js` (or `.mjs`) beside the bundle; without it, writes fail with this cause.\n */\nfunction threadUrl(): URL {\n const here = import.meta.url\n if (here.endsWith('.ts')) return new URL('./durable-writer-thread.ts', here)\n for (const name of ['./durable-writer-thread.js', './durable-writer-thread.mjs']) {\n const candidate = new URL(name, here)\n if (existsSync(candidate)) return candidate\n }\n throw new Error(\n `durable writer entry durable-writer-thread.js is not beside ${fileURLToPath(here)}; a bundle of Runtime must emit it there`,\n )\n}\n\nfunction start(): Writer {\n const url = threadUrl()\n // Source checkouts (tests) load the TypeScript entry through tsx; a built package ships JavaScript.\n // Only what the entry needs: some of the parent's flags (--expose-gc) are refused in a worker.\n const execArgv = url.pathname.endsWith('.ts')\n ? ['--import', createRequire(import.meta.url).resolve('tsx')]\n : []\n const syncReplies = new MessageChannel()\n const signal = new Int32Array(new SharedArrayBuffer(4))\n const worker = new Worker(fileURLToPath(url), {\n execArgv,\n workerData: { syncReplies: syncReplies.port2, signal },\n transferList: [syncReplies.port2],\n })\n worker.unref()\n const state: Writer = { worker, syncReplies, signal, pending: new Map() }\n const die = (error: Error) => {\n writerDeath ??= error\n for (const waiting of state.pending.values()) {\n clearTimeout(waiting.timer)\n waiting.reject(writerDeath)\n }\n state.pending.clear()\n }\n worker.on('message', (reply: Reply) => {\n const waiting = state.pending.get(reply.id)\n // A reply whose caller already gave up at its deadline has nobody to answer.\n if (!waiting) return\n state.pending.delete(reply.id)\n clearTimeout(waiting.timer)\n if (state.pending.size === 0) worker.unref()\n if (reply.ok) waiting.resolve(reply.value)\n else waiting.reject(revive(reply.error))\n })\n worker.on('error', (error: Error) =>\n die(new Error(`durable writer failed: ${error.message}`, { cause: error })),\n )\n worker.on('exit', (code) => die(new Error(`durable writer exited with code ${code}`)))\n return state\n}\n\nfunction current(): Writer {\n if (writerDeath !== undefined) throw writerDeath\n writer ??= start()\n return writer\n}\n\nfunction revive(error: Extract<Reply, { ok: false }>['error']): Error {\n const errorClass = error.name === undefined ? undefined : errorClasses.get(error.name)\n const revived: Error = errorClass ? Object.create(errorClass.prototype) : new Error(error.message)\n return Object.assign(revived, error.fields ?? {}, {\n message: error.message,\n name: error.name ?? 'Error',\n ...(error.code === undefined ? {} : { code: error.code }),\n ...(error.stack === undefined ? {} : { stack: error.stack }),\n })\n}\n\nfunction overdue(operation: DurableOperation): Error {\n // The writer keeps running: stopping it inside a fence would leave the run's mutation lock held.\n return new Error(\n `durable writer did not answer ${operation.name} within ${DURABLE_WRITER_DEADLINE_MS} ms; the writer is still running`,\n )\n}\n\nfunction request(operation: DurableOperation, sync: boolean): Request {\n return {\n id: ++nextId,\n name: operation.name,\n args: operation.args,\n claim: currentRunWriteClaim(),\n sync,\n }\n}\n\n/** Perform `operation` on the writer and wait for it, blocking this thread as the inline write did. */\nexport function durableCall<T>(operation: DurableOperation): T {\n if (onDurableWriterThread()) return runInline!(operation) as T\n const state = current()\n const sent = request(operation, true)\n const deadline = performance.now() + DURABLE_WRITER_DEADLINE_MS\n Atomics.store(state.signal, 0, 0)\n state.worker.postMessage(sent)\n // The writer's exit and error events need this loop, which waits here; the deadline catches a\n // writer killed without a reply (out of memory, native abort) and a backlog that never drains.\n for (;;) {\n for (\n let received = receiveMessageOnPort(state.syncReplies.port1);\n received;\n received = receiveMessageOnPort(state.syncReplies.port1)\n ) {\n const reply = received.message as Reply\n // An older id is the late answer to a call that already failed at its deadline.\n if (reply.id !== sent.id) continue\n if (!reply.ok) throw revive(reply.error)\n return reply.value as T\n }\n const remaining = deadline - performance.now()\n if (remaining <= 0) throw overdue(operation)\n Atomics.wait(state.signal, 0, 0, remaining)\n Atomics.store(state.signal, 0, 0)\n }\n}\n\n/** Perform `operation` on the writer without blocking this thread. */\nexport function durableCallAsync<T>(operation: DurableOperation): Promise<T> {\n if (onDurableWriterThread()) {\n try {\n return Promise.resolve(runInline!(operation) as T)\n } catch (error) {\n return Promise.reject(error)\n }\n }\n let state: Writer\n try {\n state = current()\n } catch (error) {\n return Promise.reject(error)\n }\n const sent = request(operation, false)\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n state.pending.delete(sent.id)\n if (state.pending.size === 0) state.worker.unref()\n reject(overdue(operation))\n }, DURABLE_WRITER_DEADLINE_MS)\n timer.unref()\n state.pending.set(sent.id, { resolve: resolve as (value: unknown) => void, reject, timer })\n state.worker.ref()\n state.worker.postMessage(sent)\n })\n}\n\nexport type { Reply as DurableWriterReply, Request as DurableWriterRequest }\n","/**\n * Small filesystem durability primitives for Runtime-owned state.\n *\n * Callers must validate their path and parent directory before invoking these functions.\n * The exclusive writer protects a no-clobber publication race; the atomic writer replaces one\n * state file after its temporary contents reach stable storage.\n *\n * @internal\n */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n appendFileSync,\n type BigIntStats,\n closeSync,\n existsSync,\n fchmodSync,\n constants as fsConstants,\n fstatSync,\n fsyncSync,\n linkSync,\n lstatSync,\n mkdirSync,\n openSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n writeSync,\n} from 'node:fs'\nimport { dirname, join, relative, resolve } from 'node:path'\nimport { runFenced, runFencedAsync } from '../../durable/durable-writer'\nimport { fenceRunWrite } from '../../durable/run-fence'\n\ninterface DurableFileOptions {\n readonly mode?: number\n}\n\n/**\n * File content, or content computed from the new file's own stat when it must name the file's\n * inode (a lock record that later proves it was written for this very file).\n */\ntype DurableFileContent = string | ((file: BigIntStats) => string)\n\n/**\n * Publish a new file without replacing a concurrent winner. The published entry is a hard link\n * of the temporary file, so a content function sees the published file's inode.\n */\nexport function publishExclusiveDurableFile(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions = {},\n): boolean {\n // Content computed from the new file's own stat cannot cross a thread; its one caller, run-lock\n // acquisition, already runs on the durable writer.\n return typeof content === 'string'\n ? runFenced('publishExclusiveDurableFile', publishExclusiveFenced, filePath, content, options)\n : publishExclusiveFenced(filePath, content, options)\n}\n\n/** `publishExclusiveDurableFile` without blocking the calling thread on the disk. */\nexport function publishExclusiveDurableFileAsync(\n filePath: string,\n content: string,\n options: DurableFileOptions = {},\n): Promise<boolean> {\n return runFencedAsync(\n 'publishExclusiveDurableFile',\n publishExclusiveFenced,\n filePath,\n content,\n options,\n )\n}\n\n/** The fenced exclusive publication the durable writer runs. @internal */\nexport function publishExclusiveFenced(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions = {},\n): boolean {\n return fenceRunWrite(() => publishExclusiveDurableFileUnchecked(filePath, content, options))\n}\n\nfunction publishExclusiveDurableFileUnchecked(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions = {},\n): boolean {\n const temporaryPath = `${filePath}.${randomUUID()}.tmp`\n let operationFailed = false\n let operationError: unknown\n let published = false\n try {\n writeExclusiveDurableFile(temporaryPath, content, options)\n try {\n linkSync(temporaryPath, filePath)\n syncDurableDirectory(dirname(filePath))\n published = true\n } catch (error) {\n if (!isAlreadyExistsError(error)) throw error\n }\n } catch (error) {\n operationFailed = true\n operationError = error\n }\n let cleanupError: unknown\n try {\n unlinkSync(temporaryPath)\n } catch (error) {\n if (!isNoEntryError(error)) cleanupError = error\n }\n if (operationFailed) throw operationError\n if (cleanupError !== undefined) throw cleanupError\n return published\n}\n\n/** Fsync a directory after publishing a durable file entry. */\nexport function syncDurableDirectory(directoryPath: string): void {\n const fd = openSync(directoryPath, 'r')\n try {\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n}\n\n/** Fsync one durable file after its contents reach stable storage. */\nfunction syncDurableFile(filePath: string, exactMode?: number): void {\n const fd = openSync(filePath, 'r')\n try {\n if (exactMode !== undefined && process.platform !== 'win32') fchmodSync(fd, exactMode)\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n}\n\n/**\n * Append whole lines to a run file under the fence, creating `directory` first when given. Each\n * line is one O_APPEND write (well under PIPE_BUF), so concurrent writers never interleave; there\n * is no fsync, as for the observability logs that use it.\n */\nexport function appendRunLines(\n filePath: string,\n lines: readonly string[],\n options: { readonly directory?: string; readonly mode?: number } = {},\n): void {\n runFenced('appendRunLines', appendRunLinesFenced, filePath, lines, options)\n}\n\n/** The fenced line append the durable writer runs. @internal */\nexport function appendRunLinesFenced(\n filePath: string,\n lines: readonly string[],\n options: { readonly directory?: string; readonly mode?: number } = {},\n): void {\n fenceRunWrite(() => {\n if (options.directory !== undefined) mkdirSync(options.directory, { recursive: true })\n const fd = openSync(filePath, 'a', options.mode ?? 0o666)\n try {\n for (const line of lines) appendFileSync(fd, line)\n } finally {\n closeSync(fd)\n }\n })\n}\n\n/** Append one record with O_APPEND, then fsync the file and containing directory. */\nexport function appendDurableFile(\n filePath: string,\n content: string,\n options: DurableFileOptions = {},\n): void {\n runFenced('appendDurableFile', appendDurableFenced, filePath, content, options)\n}\n\n/** The fenced durable append the durable writer runs. @internal */\nexport function appendDurableFenced(\n filePath: string,\n content: string,\n options: DurableFileOptions = {},\n): void {\n fenceRunWrite(() => appendDurableFileUnchecked(filePath, content, options))\n}\n\nfunction appendDurableFileUnchecked(\n filePath: string,\n content: string,\n options: DurableFileOptions = {},\n): void {\n const flags =\n fsConstants.O_APPEND |\n fsConstants.O_CREAT |\n fsConstants.O_WRONLY |\n (typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0)\n const fd = openSync(filePath, flags, options.mode ?? 0o600)\n try {\n if (process.platform !== 'win32') fchmodSync(fd, options.mode ?? 0o600)\n const expectedBytes = Buffer.byteLength(content, 'utf8')\n const writtenBytes = writeSync(fd, content, undefined, 'utf8')\n if (writtenBytes !== expectedBytes) {\n throw new Error(\n `durable append wrote ${writtenBytes} of ${expectedBytes} bytes to '${filePath}'`,\n )\n }\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n syncDurableDirectory(dirname(filePath))\n}\n\n/** Reject a path that escapes its run directory or traverses a symbolic link. */\nexport function assertNoSymlinkDescendant(root: string, target: string, label = 'path'): void {\n const base = resolve(root)\n const exact = resolve(target)\n const rel = relative(base, exact)\n if (rel === '..' || rel.startsWith(`..${process.platform === 'win32' ? '\\\\' : '/'}`)) {\n throw new Error(`${label} path escapes its run directory`)\n }\n if (existsSync(base) && lstatSync(base).isSymbolicLink()) {\n throw new Error(`${label} path contains a symbolic link: ${base}`)\n }\n let current = base\n for (const part of rel.split(/[\\\\/]/u).filter(Boolean)) {\n current = join(current, part)\n if (!existsSync(current)) continue\n if (lstatSync(current).isSymbolicLink()) {\n throw new Error(`${label} path contains a symbolic link: ${current}`)\n }\n }\n}\n\n/** Write, fsync, atomically replace, and fsync one Runtime-owned state file.\n * preserveMode retains ordinary access permissions despite the current umask; a new\n * file keeps normal creation semantics. Callers still own path validation and write exclusion. */\nexport function writeAtomicDurableFile(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions & { readonly preserveMode?: boolean } = {},\n): void {\n if (typeof content === 'string')\n runFenced('writeAtomicDurableFile', writeAtomicFenced, filePath, content, options)\n else writeAtomicFenced(filePath, content, options)\n}\n\n/** The fenced atomic replacement the durable writer runs. @internal */\nexport function writeAtomicFenced(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions & { readonly preserveMode?: boolean } = {},\n): void {\n fenceRunWrite(() => writeAtomicDurableFileUnchecked(filePath, content, options))\n}\n\nfunction writeAtomicDurableFileUnchecked(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions & { readonly preserveMode?: boolean } = {},\n): void {\n const temporaryPath = `${filePath}.${randomUUID()}.tmp`\n let operationFailed = false\n let operationError: unknown\n try {\n let mode = options.mode\n let exactMode = false\n if (options.preserveMode) {\n try {\n mode = statSync(filePath).mode & 0o777\n exactMode = true\n } catch (error) {\n if (!isNoEntryError(error)) throw error\n }\n }\n writeExclusiveDurableFile(temporaryPath, content, { mode }, exactMode)\n renameSync(temporaryPath, filePath)\n syncDurableDirectory(dirname(filePath))\n } catch (error) {\n operationFailed = true\n operationError = error\n }\n let cleanupError: unknown\n try {\n unlinkSync(temporaryPath)\n } catch (error) {\n if (!isNoEntryError(error)) cleanupError = error\n // A successful rename removes the temporary directory entry.\n }\n if (operationFailed) throw operationError\n if (cleanupError !== undefined) throw cleanupError\n}\n\nfunction writeExclusiveDurableFile(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions,\n exactMode = false,\n): void {\n const fd = openSync(filePath, 'wx', options.mode ?? 0o666)\n try {\n const text = typeof content === 'string' ? content : content(fstatSync(fd, { bigint: true }))\n writeFileSync(fd, text, 'utf8')\n } finally {\n closeSync(fd)\n }\n syncDurableFile(filePath, exactMode ? options.mode : undefined)\n}\n\nfunction isAlreadyExistsError(error: unknown): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'EEXIST'\n )\n}\n\nfunction isNoEntryError(error: unknown): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'ENOENT'\n )\n}\n"],"mappings":";;;;;;;;;AAcA,MAAM,SAAS,IAAI,kBAA6C;AAChE,MAAM,eAAe,IAAI,kBAAsE;AAG/F,IAAI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AAS;AAChE;AAEA,SAAS,qBAAqB,OAAyB;CACrD,OACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS;AAE3C;AAEA,SAAS,eAAe,OAAyB;CAC/C,OACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS;AAE3C"}
|
|
1
|
+
{"version":3,"file":"durable-file-pao7FijS.js","names":["fsConstants"],"sources":["../src/durable/run-fence.ts","../src/durable/durable-writer.ts","../src/runtime/supervise/durable-file.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport { closeSync, existsSync, fstatSync, openSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { isMainThread } from 'node:worker_threads'\nimport { tryAcquireAtomicFileLock } from '@tangle-network/agent-eval/ledger-core'\nimport type { LockIdentity } from '@tangle-network/agent-eval/lock-holder'\n\n/** The immutable claim carried by every write in one directory execution. @internal */\nexport interface RunWriteClaim {\n readonly path: string\n readonly generation: number\n readonly lock: LockIdentity\n}\n\nconst claims = new AsyncLocalStorage<RunWriteClaim | undefined>()\nconst publications = new AsyncLocalStorage<{ readonly claim: RunWriteClaim; active: boolean }>()\n\n// Set on the durable writer thread (durable-writer-thread.ts): the one thread that runs claimed writes.\nlet writerThread = false\n\n/** Mark this thread as the process's durable writer. @internal */\nexport function markDurableWriterThread(): void {\n writerThread = true\n}\n\n/** True on the durable writer thread. @internal */\nexport function onDurableWriterThread(): boolean {\n return writerThread\n}\n\n/** The claim the current asynchronous context carries, if any. @internal */\nexport function currentRunWriteClaim(): RunWriteClaim | undefined {\n return claims.getStore()\n}\n\n/** Bind asynchronous work, including callbacks, to the generation that admitted it. @internal */\nexport function runWithWriteClaim<T>(claim: RunWriteClaim, operation: () => T): T {\n return claims.run(claim, operation)\n}\n\n/** Capture a store's acquisition once, even when later called from an unrelated emitter. @internal */\nexport function captureRunWriteContext(): <T>(operation: () => T) => T {\n let claim = claims.getStore()\n return <T>(operation: () => T): T => {\n claim ??= claims.getStore()\n return claims.run(claim, operation)\n }\n}\n\n/** Serialize claim changes and file mutations under the same cross-process guard. @internal */\nexport function mutateRunClaim<T>(path: string, operation: () => T): T {\n // Old writers use an unowned directory guard. Never race one or guess that it is stale.\n const legacyGuard = `${path}.guard`\n if (existsSync(legacyGuard)) {\n throw new Error(\n `supervisePursuit: cannot mutate ${path}; inspect ${legacyGuard} and remove it only after confirming no lock mutation is active`,\n )\n }\n const deadline = performance.now() + 5_000\n const sleeper = new Int32Array(new SharedArrayBuffer(4))\n for (;;) {\n const acquisition = tryAcquireAtomicFileLock({ lockPath: `${path}.mutation` })\n if (acquisition.acquired) {\n try {\n return operation()\n } finally {\n acquisition.lock.release()\n }\n }\n if (performance.now() >= deadline) throw new Error(`run directory mutation is held: ${path}`)\n Atomics.wait(sleeper, 0, 0, 10)\n }\n}\n\n/**\n * Fence an actual file mutation, not an earlier advisory check. No await occurs between the\n * ownership check and publication, and acquire/release use this same guard. Unclaimed standalone\n * stores retain their existing single-writer contract; pursuit-owned work always carries a claim.\n * @internal\n */\nexport function fenceRunWrite<T>(operation: () => T): T {\n const claim = claims.getStore()\n if (claim === undefined) return operation()\n // A claimed write on the main thread would hold the run's mutation lock against the durable\n // writer and block the event loop on the disk: it must be sent through `runFenced`.\n if (isMainThread && !writerThread) {\n throw new Error('a claimed run write reached the main thread; send it through runFenced')\n }\n const publication = publications.getStore()\n if (\n publication?.active &&\n publication.claim.path === claim.path &&\n publication.claim.generation === claim.generation\n )\n return operation()\n return mutateRunClaim(claim.path, () => {\n let holder: Partial<RunWriteClaim> | undefined\n try {\n const fd = openSync(claim.path, 'r')\n try {\n const stat = fstatSync(fd, { bigint: true })\n if (\n stat.dev.toString() !== claim.lock.dev ||\n stat.ino.toString() !== claim.lock.ino ||\n stat.birthtimeNs.toString() !== claim.lock.birthtimeNs\n ) {\n throw new Error('run lock inode changed')\n }\n holder = JSON.parse(readFileSync(fd, 'utf8')) as Partial<RunWriteClaim>\n } finally {\n closeSync(fd)\n }\n } catch (cause) {\n throw new Error(`run directory generation ${claim.generation} lost its claim`, { cause })\n }\n if (\n holder?.generation !== claim.generation ||\n holder.lock?.dev !== claim.lock.dev ||\n holder.lock?.ino !== claim.lock.ino ||\n holder.lock?.birthtimeNs !== claim.lock.birthtimeNs\n ) {\n throw new Error(`run directory generation ${claim.generation} lost its claim`)\n }\n // Nested synchronous primitives share the guard. A callback queued here keeps its claim,\n // but cannot inherit a live guard after this publication has returned.\n const publication = { claim, active: true }\n try {\n return publications.run(publication, operation)\n } finally {\n publication.active = false\n }\n })\n}\n\n/** Persistent generation counter survives a clean release of supervise.lock. @internal */\nexport function runGenerationPath(runDir: string): string {\n return resolve(runDir, 'supervise.generation')\n}\n","/**\n * The durable writer: one thread per process that performs every claimed run-directory write.\n *\n * A fenced write is synchronous by contract (lock, claim check, mutation and fsync with no await\n * between them), and on a saturated disk its open, link and fsync calls wait on the filesystem\n * journal: a coordinator whose event loop ran them was measured blocked 20 to 70 s at a time.\n * Here the same synchronous code runs on its own thread. Only that thread takes a run directory's\n * mutation lock in this process, so a caller never spins on a lock this process holds.\n *\n * - `durableCall` blocks the calling thread until the writer answers, exactly as the inline write\n * did, for callers whose contract is synchronous.\n * - `durableCallAsync` resolves with the writer's answer and leaves the event loop free.\n * - On the writer thread both run the operation inline, so a fenced helper may call another.\n * - Operations run in the order they were sent, sync and async alike.\n * - A call the writer does not answer within `DURABLE_WRITER_DEADLINE_MS` fails, and the writer\n * keeps running. A writer that errors or exits fails every waiting and later call and is never\n * replaced. Nothing falls back to writing on the calling thread.\n *\n * @internal\n */\n\nimport { existsSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { fileURLToPath } from 'node:url'\nimport { isMainThread, MessageChannel, receiveMessageOnPort, Worker } from 'node:worker_threads'\nimport {\n currentRunWriteClaim,\n markDurableWriterThread,\n onDurableWriterThread,\n type RunWriteClaim,\n} from './run-fence'\n\n/** Longer than the worst fsync measured on a saturated disk (70 s), so only a dead writer trips it. */\nexport const DURABLE_WRITER_DEADLINE_MS = 180_000\n\n/** A named operation and its JSON arguments; names resolve in `durable-writer-thread.ts`. */\nexport interface DurableOperation {\n readonly name: string\n readonly args: readonly unknown[]\n}\n\ninterface Request extends DurableOperation {\n readonly id: number\n readonly claim: RunWriteClaim | undefined\n readonly sync: boolean\n}\n\ntype Reply =\n | { readonly id: number; readonly ok: true; readonly value: unknown }\n | {\n readonly id: number\n readonly ok: false\n readonly error: {\n message: string\n name?: string\n code?: string\n stack?: string\n fields?: Record<string, unknown>\n }\n }\n\nlet runInline: ((operation: DurableOperation) => unknown) | undefined\n\n/** Called by the writer thread's entry: operations sent from this thread now run inline. */\nexport function becomeDurableWriter(inline: (operation: DurableOperation) => unknown): void {\n markDurableWriterThread()\n runInline = inline\n}\n\n/**\n * Whether a write goes to the writer: a claimed write made by the main thread, or with `always`,\n * any write the main thread makes (run-directory acquisition and release take the same lock before\n * a claim exists). Unclaimed writes keep their caller-owned single-writer contract and run inline,\n * and other worker threads never start a second writer that would contend for the same lock.\n */\nexport function routesToDurableWriter(always = false): boolean {\n return (\n !onDurableWriterThread() && isMainThread && (always || currentRunWriteClaim() !== undefined)\n )\n}\n\n/**\n * Run the fenced operation `fn(...args)`: inline when the write is not routed, otherwise on the\n * writer under the caller's claim, blocking this thread until it answers. `fn` takes its own fence\n * (`fenceRunWrite` or `mutateRunClaim`) and is registered under `name` in durable-writer-thread.ts;\n * arguments and the result cross the thread as structured clones.\n */\nexport function runFenced<A extends unknown[], T>(\n name: string,\n fn: (...args: A) => T,\n ...args: A\n): T {\n return routesToDurableWriter() ? durableCall<T>({ name, args }) : fn(...args)\n}\n\n/** `runFenced` without blocking: the event loop stays free while the writer works. */\nexport function runFencedAsync<A extends unknown[], T>(\n name: string,\n fn: (...args: A) => T,\n ...args: A\n): Promise<T> {\n if (routesToDurableWriter()) return durableCallAsync<T>({ name, args })\n try {\n return Promise.resolve(fn(...args))\n } catch (error) {\n return Promise.reject(error)\n }\n}\n\n/** `runFencedAsync` for run-directory acquisition and release, routed from the main thread even\n * before a claim exists, since they take the same mutation lock the writer holds. */\nexport function runFencedAlways<A extends unknown[], T>(\n name: string,\n fn: (...args: A) => T,\n ...args: A\n): Promise<T> {\n if (routesToDurableWriter(true)) return durableCallAsync<T>({ name, args })\n try {\n return Promise.resolve(fn(...args))\n } catch (error) {\n return Promise.reject(error)\n }\n}\n\ninterface Writer {\n readonly worker: Worker\n readonly syncReplies: MessageChannel\n readonly signal: Int32Array\n readonly pending: Map<\n number,\n { resolve: (value: unknown) => void; reject: (error: Error) => void; timer: NodeJS.Timeout }\n >\n}\n\nlet writer: Writer | undefined\n// Set when the writer errors or exits. It is never replaced: it may have died inside a fence\n// holding the run's mutation lock under this live pid, and a new writer could only spin on that\n// lock. Every later routed write fails at once with this cause.\nlet writerDeath: Error | undefined\nlet nextId = 0\n\n// Errors an operation throws are rebuilt on the caller's thread as their own class, with their\n// own fields, so `instanceof` and fields such as a lock holder survive the thread boundary.\nconst errorClasses = new Map<string, { prototype: Error }>()\n\n/** Rebuild errors named `name` thrown on the writer as instances of `errorClass`. @internal */\nexport function registerDurableErrorClass(name: string, errorClass: { prototype: Error }): void {\n errorClasses.set(name, errorClass)\n}\n\n/**\n * The writer's entry beside this module: TypeScript in a source checkout, JavaScript in a built\n * package. A tool that bundles Runtime again must emit `src/durable/durable-writer-thread.ts` as\n * `durable-writer-thread.js` (or `.mjs`) beside the bundle; without it, writes fail with this cause.\n */\nfunction threadUrl(): URL {\n const here = import.meta.url\n if (here.endsWith('.ts')) return new URL('./durable-writer-thread.ts', here)\n for (const name of ['./durable-writer-thread.js', './durable-writer-thread.mjs']) {\n const candidate = new URL(name, here)\n if (existsSync(candidate)) return candidate\n }\n throw new Error(\n `durable writer entry durable-writer-thread.js is not beside ${fileURLToPath(here)}; a bundle of Runtime must emit it there`,\n )\n}\n\nfunction start(): Writer {\n const url = threadUrl()\n // Source checkouts (tests) load the TypeScript entry through tsx; a built package ships JavaScript.\n // Only what the entry needs: some of the parent's flags (--expose-gc) are refused in a worker.\n const execArgv = url.pathname.endsWith('.ts')\n ? ['--import', createRequire(import.meta.url).resolve('tsx')]\n : []\n const syncReplies = new MessageChannel()\n const signal = new Int32Array(new SharedArrayBuffer(4))\n const worker = new Worker(fileURLToPath(url), {\n execArgv,\n workerData: { syncReplies: syncReplies.port2, signal },\n transferList: [syncReplies.port2],\n })\n worker.unref()\n const state: Writer = { worker, syncReplies, signal, pending: new Map() }\n const die = (error: Error) => {\n writerDeath ??= error\n for (const waiting of state.pending.values()) {\n clearTimeout(waiting.timer)\n waiting.reject(writerDeath)\n }\n state.pending.clear()\n }\n worker.on('message', (reply: Reply) => {\n const waiting = state.pending.get(reply.id)\n // A reply whose caller already gave up at its deadline has nobody to answer.\n if (!waiting) return\n state.pending.delete(reply.id)\n clearTimeout(waiting.timer)\n if (state.pending.size === 0) worker.unref()\n if (reply.ok) waiting.resolve(reply.value)\n else waiting.reject(revive(reply.error))\n })\n worker.on('error', (error: Error) =>\n die(new Error(`durable writer failed: ${error.message}`, { cause: error })),\n )\n worker.on('exit', (code) => die(new Error(`durable writer exited with code ${code}`)))\n return state\n}\n\nfunction current(): Writer {\n if (writerDeath !== undefined) throw writerDeath\n writer ??= start()\n return writer\n}\n\nfunction revive(error: Extract<Reply, { ok: false }>['error']): Error {\n const errorClass = error.name === undefined ? undefined : errorClasses.get(error.name)\n const revived: Error = errorClass ? Object.create(errorClass.prototype) : new Error(error.message)\n return Object.assign(revived, error.fields ?? {}, {\n message: error.message,\n name: error.name ?? 'Error',\n ...(error.code === undefined ? {} : { code: error.code }),\n ...(error.stack === undefined ? {} : { stack: error.stack }),\n })\n}\n\nfunction overdue(operation: DurableOperation): Error {\n // The writer keeps running: stopping it inside a fence would leave the run's mutation lock held.\n return new Error(\n `durable writer did not answer ${operation.name} within ${DURABLE_WRITER_DEADLINE_MS} ms; the writer is still running`,\n )\n}\n\nfunction request(operation: DurableOperation, sync: boolean): Request {\n return {\n id: ++nextId,\n name: operation.name,\n args: operation.args,\n claim: currentRunWriteClaim(),\n sync,\n }\n}\n\n/** Perform `operation` on the writer and wait for it, blocking this thread as the inline write did. */\nexport function durableCall<T>(operation: DurableOperation): T {\n if (onDurableWriterThread()) return runInline!(operation) as T\n const state = current()\n const sent = request(operation, true)\n const deadline = performance.now() + DURABLE_WRITER_DEADLINE_MS\n Atomics.store(state.signal, 0, 0)\n state.worker.postMessage(sent)\n // The writer's exit and error events need this loop, which waits here; the deadline catches a\n // writer killed without a reply (out of memory, native abort) and a backlog that never drains.\n for (;;) {\n for (\n let received = receiveMessageOnPort(state.syncReplies.port1);\n received;\n received = receiveMessageOnPort(state.syncReplies.port1)\n ) {\n const reply = received.message as Reply\n // An older id is the late answer to a call that already failed at its deadline.\n if (reply.id !== sent.id) continue\n if (!reply.ok) throw revive(reply.error)\n return reply.value as T\n }\n const remaining = deadline - performance.now()\n if (remaining <= 0) throw overdue(operation)\n Atomics.wait(state.signal, 0, 0, remaining)\n Atomics.store(state.signal, 0, 0)\n }\n}\n\n/** Perform `operation` on the writer without blocking this thread. */\nexport function durableCallAsync<T>(operation: DurableOperation): Promise<T> {\n if (onDurableWriterThread()) {\n try {\n return Promise.resolve(runInline!(operation) as T)\n } catch (error) {\n return Promise.reject(error)\n }\n }\n let state: Writer\n try {\n state = current()\n } catch (error) {\n return Promise.reject(error)\n }\n const sent = request(operation, false)\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n state.pending.delete(sent.id)\n if (state.pending.size === 0) state.worker.unref()\n reject(overdue(operation))\n }, DURABLE_WRITER_DEADLINE_MS)\n timer.unref()\n state.pending.set(sent.id, { resolve: resolve as (value: unknown) => void, reject, timer })\n state.worker.ref()\n state.worker.postMessage(sent)\n })\n}\n\nexport type { Reply as DurableWriterReply, Request as DurableWriterRequest }\n","/**\n * Small filesystem durability primitives for Runtime-owned state.\n *\n * Callers must validate their path and parent directory before invoking these functions.\n * The exclusive writer protects a no-clobber publication race; the atomic writer replaces one\n * state file after its temporary contents reach stable storage.\n *\n * @internal\n */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n appendFileSync,\n type BigIntStats,\n closeSync,\n existsSync,\n fchmodSync,\n constants as fsConstants,\n fstatSync,\n fsyncSync,\n linkSync,\n lstatSync,\n mkdirSync,\n openSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n writeSync,\n} from 'node:fs'\nimport { dirname, join, relative, resolve } from 'node:path'\nimport { runFenced, runFencedAsync } from '../../durable/durable-writer'\nimport { fenceRunWrite } from '../../durable/run-fence'\n\ninterface DurableFileOptions {\n readonly mode?: number\n}\n\n/**\n * File content, or content computed from the new file's own stat when it must name the file's\n * inode (a lock record that later proves it was written for this very file).\n */\ntype DurableFileContent = string | ((file: BigIntStats) => string)\n\n/**\n * Publish a new file without replacing a concurrent winner. The published entry is a hard link\n * of the temporary file, so a content function sees the published file's inode.\n */\nexport function publishExclusiveDurableFile(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions = {},\n): boolean {\n // Content computed from the new file's own stat cannot cross a thread; its one caller, run-lock\n // acquisition, already runs on the durable writer.\n return typeof content === 'string'\n ? runFenced('publishExclusiveDurableFile', publishExclusiveFenced, filePath, content, options)\n : publishExclusiveFenced(filePath, content, options)\n}\n\n/**\n * `publishExclusiveDurableFile` without blocking the calling thread on the disk: a claimed write\n * runs on the durable writer, an unclaimed one inline as its caller's own single write.\n */\nexport function publishExclusiveDurableFileAsync(\n filePath: string,\n content: string,\n options: DurableFileOptions = {},\n): Promise<boolean> {\n return runFencedAsync(\n 'publishExclusiveDurableFile',\n publishExclusiveFenced,\n filePath,\n content,\n options,\n )\n}\n\n/** The fenced exclusive publication the durable writer runs. @internal */\nexport function publishExclusiveFenced(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions = {},\n): boolean {\n return fenceRunWrite(() => publishExclusiveDurableFileUnchecked(filePath, content, options))\n}\n\nfunction publishExclusiveDurableFileUnchecked(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions = {},\n): boolean {\n const temporaryPath = `${filePath}.${randomUUID()}.tmp`\n let operationFailed = false\n let operationError: unknown\n let published = false\n try {\n writeExclusiveDurableFile(temporaryPath, content, options)\n try {\n linkSync(temporaryPath, filePath)\n syncDurableDirectory(dirname(filePath))\n published = true\n } catch (error) {\n if (!isAlreadyExistsError(error)) throw error\n }\n } catch (error) {\n operationFailed = true\n operationError = error\n }\n let cleanupError: unknown\n try {\n unlinkSync(temporaryPath)\n } catch (error) {\n if (!isNoEntryError(error)) cleanupError = error\n }\n if (operationFailed) throw operationError\n if (cleanupError !== undefined) throw cleanupError\n return published\n}\n\n/** Fsync a directory after publishing a durable file entry. */\nexport function syncDurableDirectory(directoryPath: string): void {\n const fd = openSync(directoryPath, 'r')\n try {\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n}\n\n/** Fsync one durable file after its contents reach stable storage. */\nfunction syncDurableFile(filePath: string, exactMode?: number): void {\n const fd = openSync(filePath, 'r')\n try {\n if (exactMode !== undefined && process.platform !== 'win32') fchmodSync(fd, exactMode)\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n}\n\n/**\n * Append whole lines to a run file under the fence, creating `directory` first when given. Each\n * line is one O_APPEND write (well under PIPE_BUF), so concurrent writers never interleave; there\n * is no fsync, as for the observability logs that use it.\n */\nexport function appendRunLines(\n filePath: string,\n lines: readonly string[],\n options: { readonly directory?: string; readonly mode?: number } = {},\n): void {\n runFenced('appendRunLines', appendRunLinesFenced, filePath, lines, options)\n}\n\n/** The fenced line append the durable writer runs. @internal */\nexport function appendRunLinesFenced(\n filePath: string,\n lines: readonly string[],\n options: { readonly directory?: string; readonly mode?: number } = {},\n): void {\n fenceRunWrite(() => {\n if (options.directory !== undefined) mkdirSync(options.directory, { recursive: true })\n const fd = openSync(filePath, 'a', options.mode ?? 0o666)\n try {\n for (const line of lines) appendFileSync(fd, line)\n } finally {\n closeSync(fd)\n }\n })\n}\n\n/** Append one record with O_APPEND, then fsync the file and containing directory. */\nexport function appendDurableFile(\n filePath: string,\n content: string,\n options: DurableFileOptions = {},\n): void {\n runFenced('appendDurableFile', appendDurableFenced, filePath, content, options)\n}\n\n/** The fenced durable append the durable writer runs. @internal */\nexport function appendDurableFenced(\n filePath: string,\n content: string,\n options: DurableFileOptions = {},\n): void {\n fenceRunWrite(() => appendDurableFileUnchecked(filePath, content, options))\n}\n\nfunction appendDurableFileUnchecked(\n filePath: string,\n content: string,\n options: DurableFileOptions = {},\n): void {\n const flags =\n fsConstants.O_APPEND |\n fsConstants.O_CREAT |\n fsConstants.O_WRONLY |\n (typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0)\n const fd = openSync(filePath, flags, options.mode ?? 0o600)\n try {\n if (process.platform !== 'win32') fchmodSync(fd, options.mode ?? 0o600)\n const expectedBytes = Buffer.byteLength(content, 'utf8')\n const writtenBytes = writeSync(fd, content, undefined, 'utf8')\n if (writtenBytes !== expectedBytes) {\n throw new Error(\n `durable append wrote ${writtenBytes} of ${expectedBytes} bytes to '${filePath}'`,\n )\n }\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n syncDurableDirectory(dirname(filePath))\n}\n\n/** Reject a path that escapes its run directory or traverses a symbolic link. */\nexport function assertNoSymlinkDescendant(root: string, target: string, label = 'path'): void {\n const base = resolve(root)\n const exact = resolve(target)\n const rel = relative(base, exact)\n if (rel === '..' || rel.startsWith(`..${process.platform === 'win32' ? '\\\\' : '/'}`)) {\n throw new Error(`${label} path escapes its run directory`)\n }\n if (existsSync(base) && lstatSync(base).isSymbolicLink()) {\n throw new Error(`${label} path contains a symbolic link: ${base}`)\n }\n let current = base\n for (const part of rel.split(/[\\\\/]/u).filter(Boolean)) {\n current = join(current, part)\n if (!existsSync(current)) continue\n if (lstatSync(current).isSymbolicLink()) {\n throw new Error(`${label} path contains a symbolic link: ${current}`)\n }\n }\n}\n\n/** Write, fsync, atomically replace, and fsync one Runtime-owned state file.\n * preserveMode retains ordinary access permissions despite the current umask; a new\n * file keeps normal creation semantics. Callers still own path validation and write exclusion. */\nexport function writeAtomicDurableFile(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions & { readonly preserveMode?: boolean } = {},\n): void {\n if (typeof content === 'string')\n runFenced('writeAtomicDurableFile', writeAtomicFenced, filePath, content, options)\n else writeAtomicFenced(filePath, content, options)\n}\n\n/** `writeAtomicDurableFile` off the calling thread when the write is claimed. */\nexport function writeAtomicDurableFileAsync(\n filePath: string,\n content: string,\n options: DurableFileOptions & { readonly preserveMode?: boolean } = {},\n): Promise<void> {\n return runFencedAsync('writeAtomicDurableFile', writeAtomicFenced, filePath, content, options)\n}\n\n/** The fenced atomic replacement the durable writer runs. @internal */\nexport function writeAtomicFenced(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions & { readonly preserveMode?: boolean } = {},\n): void {\n fenceRunWrite(() => writeAtomicDurableFileUnchecked(filePath, content, options))\n}\n\nfunction writeAtomicDurableFileUnchecked(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions & { readonly preserveMode?: boolean } = {},\n): void {\n const temporaryPath = `${filePath}.${randomUUID()}.tmp`\n let operationFailed = false\n let operationError: unknown\n try {\n let mode = options.mode\n let exactMode = false\n if (options.preserveMode) {\n try {\n mode = statSync(filePath).mode & 0o777\n exactMode = true\n } catch (error) {\n if (!isNoEntryError(error)) throw error\n }\n }\n writeExclusiveDurableFile(temporaryPath, content, { mode }, exactMode)\n renameSync(temporaryPath, filePath)\n syncDurableDirectory(dirname(filePath))\n } catch (error) {\n operationFailed = true\n operationError = error\n }\n let cleanupError: unknown\n try {\n unlinkSync(temporaryPath)\n } catch (error) {\n if (!isNoEntryError(error)) cleanupError = error\n // A successful rename removes the temporary directory entry.\n }\n if (operationFailed) throw operationError\n if (cleanupError !== undefined) throw cleanupError\n}\n\nfunction writeExclusiveDurableFile(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions,\n exactMode = false,\n): void {\n const fd = openSync(filePath, 'wx', options.mode ?? 0o666)\n try {\n const text = typeof content === 'string' ? content : content(fstatSync(fd, { bigint: true }))\n writeFileSync(fd, text, 'utf8')\n } finally {\n closeSync(fd)\n }\n syncDurableFile(filePath, exactMode ? options.mode : undefined)\n}\n\nfunction isAlreadyExistsError(error: unknown): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'EEXIST'\n )\n}\n\nfunction isNoEntryError(error: unknown): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'ENOENT'\n )\n}\n"],"mappings":";;;;;;;;;AAcA,MAAM,SAAS,IAAI,kBAA6C;AAChE,MAAM,eAAe,IAAI,kBAAsE;AAG/F,IAAI,eAAe;;AAGnB,SAAgB,0BAAgC;CAC9C,eAAe;AACjB;;AAGA,SAAgB,wBAAiC;CAC/C,OAAO;AACT;;AAGA,SAAgB,uBAAkD;CAChE,OAAO,OAAO,SAAS;AACzB;;AAGA,SAAgB,kBAAqB,OAAsB,WAAuB;CAChF,OAAO,OAAO,IAAI,OAAO,SAAS;AACpC;;AAGA,SAAgB,yBAAuD;CACrE,IAAI,QAAQ,OAAO,SAAS;CAC5B,QAAW,cAA0B;EACnC,UAAU,OAAO,SAAS;EAC1B,OAAO,OAAO,IAAI,OAAO,SAAS;CACpC;AACF;;AAGA,SAAgB,eAAkB,MAAc,WAAuB;CAErE,MAAM,cAAc,GAAG,KAAK;CAC5B,IAAI,WAAW,WAAW,GACxB,MAAM,IAAI,MACR,mCAAmC,KAAK,YAAY,YAAY,gEAClE;CAEF,MAAM,WAAW,YAAY,IAAI,IAAI;CACrC,MAAM,UAAU,IAAI,WAAW,IAAI,kBAAkB,CAAC,CAAC;CACvD,SAAS;EACP,MAAM,cAAc,yBAAyB,EAAE,UAAU,GAAG,KAAK,WAAW,CAAC;EAC7E,IAAI,YAAY,UACd,IAAI;GACF,OAAO,UAAU;EACnB,UAAU;GACR,YAAY,KAAK,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QAAQ;EAClC,qBAAqB,QAAQ,QAAQ,CAAC;CACxC,SAAS,OAAO;EACd,kBAAkB;EAClB,iBAAiB;CACnB;CACA,IAAI;CACJ,IAAI;EACF,WAAW,aAAa;CAC1B,SAAS,OAAO;EACd,IAAI,CAAC,eAAe,KAAK,GAAG,eAAe;CAE7C;CACA,IAAI,iBAAiB,MAAM;CAC3B,IAAI,iBAAiB,KAAA,GAAW,MAAM;AACxC;AAEA,SAAS,0BACP,UACA,SACA,SACA,YAAY,OACN;CACN,MAAM,KAAK,SAAS,UAAU,MAAM,QAAQ,QAAQ,GAAK;CACzD,IAAI;EACF,MAAM,OAAO,OAAO,YAAY,WAAW,UAAU,QAAQ,UAAU,IAAI,EAAE,QAAQ,KAAK,CAAC,CAAC;EAC5F,cAAc,IAAI,MAAM,MAAM;CAChC,UAAU;EACR,UAAU,EAAE;CACd;CACA,gBAAgB,UAAU,YAAY,QAAQ,OAAO,KAAA,CAAS;AAChE;AAEA,SAAS,qBAAqB,OAAyB;CACrD,OACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS;AAE3C;AAEA,SAAS,eAAe,OAAyB;CAC/C,OACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS;AAE3C"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as closeStreamFile, c as openStreamFileFenced, d as syncStreamFileFenced, f as writeStreamLinesFenced } from "./supervisor-accounting-
|
|
3
|
-
import { i as prepareJsonlTailFenced, u as appendCommittedLine } from "./jsonl-file-
|
|
4
|
-
import { i as acquireRunLockFenced, o as releaseRunLockFenced } from "./run-lock-
|
|
5
|
-
import { n as makeRunDirectoryFenced, r as reopenSettleFenced } from "./run-reopen-
|
|
1
|
+
import { c as publishExclusiveFenced, f as writeAtomicFenced, i as appendRunLinesFenced, p as becomeDurableWriter, t as appendDurableFenced, w as runWithWriteClaim } from "./durable-file-pao7FijS.js";
|
|
2
|
+
import { a as closeStreamFile, c as openStreamFileFenced, d as syncStreamFileFenced, f as writeStreamLinesFenced } from "./supervisor-accounting-DuFyM-_h.js";
|
|
3
|
+
import { i as prepareJsonlTailFenced, u as appendCommittedLine } from "./jsonl-file-vE9H9UXa.js";
|
|
4
|
+
import { i as acquireRunLockFenced, o as releaseRunLockFenced } from "./run-lock-Ckakh1Uq.js";
|
|
5
|
+
import { n as makeRunDirectoryFenced, r as reopenSettleFenced } from "./run-reopen-BvF3Gjj9.js";
|
|
6
6
|
import { parentPort, workerData } from "node:worker_threads";
|
|
7
7
|
// src/durable/durable-writer-thread.ts
|
|
8
8
|
/**
|
package/dist/durable.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $d as
|
|
1
|
+
import { $d as PursuitProjection, $m as CoordinationRejectReason, Ab as QuestionEscalationOutcome, Ad as NextPursuitVersion, Bb as AuthorizedDownMessage, Bd as SupervisePursuitError, Ca as RootStreamReceipt, Db as EscalateQuestion, F as NodeId, Fd as SettledPursuitVersion, Gd as RunReopen, Gm as CoordinationAuthentication, Gp as RunParkingRecord, Hb as ContinuityMode, Hd as SupervisedPursuitResult, Hp as ParkedRun, Id as VersionJudge, Jd as PursuitNodeCost, Jm as CoordinationPublicAddress, Kd as PursuitObserverDelivery, Kp as readRunParking, Ld as VersionVerdict, Md as PursuitVersionChain, Nd as PursuitVersionStop, Pd as PursuitVersions, Qd as PursuitNodeUsage, Qm as CoordinationHttpAudit, Rd as assertPursuitVersions, Ub as DownMessageAuthorizationInput, Ud as superviseGraphPursuit, Up as RunParkedError, Vd as SupervisePursuitOptions, Vp as DeadlineCheckIn, Wd as supervisePursuit, Wp as RunParkingPolicy, Xd as PursuitNodeProjection, Xm as CoordinationTransportOptions, Yb as MapOnSettleRoute, Yd as PursuitNodePlatform, Ym as CoordinationReadAccess, Zd as PursuitNodeTiming, _S as readRunState, af as ObserverJournal, am as RootStreamRecord, cf as observerRecordDigest, dS as SpawnJournalReadOptions, dp as SeatSelection, ef as PursuitRunProjection, fS as SpawnJournalReadRecord, fp as SeatSelectionInput, gS as RunState, gb as WorkerWatchOptions, gf as AuthorizedSpawnContext, gm as ResolveDriveHarness, hf as AuthorizedSpawn, if as FileObserverJournal, iw as LoopTokenUsage, jd as NextPursuitVersionInput, kd as JudgedPursuitVersion, lf as PursuitFork, mS as readSpawnJournal, mm as DriveHarnessOwnerContext, mp as SelectSeat, nf as PursuitStatus, o_ as ToolLoopCompactionOptions, of as ObserverRecord, om as readRootStream, pS as SpawnJournalReadResult, q as RetainedPendingCause, qd as PursuitCostProvenance, rf as projectPursuit, sf as ObserverRecordKind, sm as readRootStreamReceipt, tf as PursuitRunTotals, uS as SpawnJournalCursor, uf as RUN_FORK_CORRELATION_KEYS, wa as SupervisedResult, wm as ManagerWakePolicy, yf as WorkerSlots, zd as SuperviseGraphPursuitOptions, zx as AnalyzeOnSettleRoute } from "./types-CFmKHKiN.js";
|
|
2
2
|
import { n as RuntimeDecisionKind, r as RuntimeDecisionPoint, t as RuntimeDecisionEvidenceRef } from "./runtime-hooks-DPghSHV7.js";
|
|
3
3
|
import { a as ChatTurnProducer, c as handleChatTurn, i as ChatTurnIdentity, n as ChatStreamEvent, o as ChatTurnResult, r as ChatTurnHooks, s as RunChatTurnInput, t as deriveExecutionId } from "./execution-handle-CujvqgCn.js";
|
|
4
4
|
import { AgentProfile } from "@tangle-network/agent-interface";
|
|
@@ -81,6 +81,9 @@ type RunEvidence = Awaited<ReturnType<typeof runEvidence>>;
|
|
|
81
81
|
* What each node of a run did, from the directory `superviseGraphPursuit` wrote: outcome and tokens
|
|
82
82
|
* from the observer journal, settled output from `blobs/`, tool calls and the final message from
|
|
83
83
|
* `streams/`. Over `totalChars` every cap halves, then the earliest nodes drop; size never throws.
|
|
84
|
+
* Tokens use the canonical node projection: settled descendant work plus the node's own
|
|
85
|
+
* inference. Missing accounting stays absent; an incomplete subtotal carries `tokensKnown: false`.
|
|
86
|
+
* Nested node totals overlap; use `projectPursuit().runs[].totals` for run-wide accounting.
|
|
84
87
|
*/
|
|
85
88
|
export declare function runEvidence(runDir: string, bounds?: RunEvidenceBounds): Promise<{
|
|
86
89
|
nodes: {
|
package/dist/durable.js
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
import { Fn as
|
|
2
|
-
import {
|
|
1
|
+
import { Fn as createFileObserverHooks, In as observerRecordDigest, Pn as FileObserverJournal, Pr as authoredProfileDigest, Y as FileSpawnJournal, cn as loadSpawnForest, l as readRootStream, u as readRootStreamReceipt, w as supervisorRunDir } from "./supervisor-accounting-DuFyM-_h.js";
|
|
2
|
+
import { c as readRunParking, r as RunParkedError } from "./supervisor-BlACe-uO.js";
|
|
3
3
|
import { n as handleChatTurn, t as deriveExecutionId } from "./execution-handle-Bd2_nUB6.js";
|
|
4
|
-
import { n as projectPursuit, t as discoverDurableSupervisionRun } from "./supervision-discovery-
|
|
4
|
+
import { n as projectPursuit, t as discoverDurableSupervisionRun } from "./supervision-discovery-DwRtZNdy.js";
|
|
5
5
|
import { a as applyExactAgentProfileDiff } from "./profile-Cxl_Ajl2.js";
|
|
6
6
|
import { f as RuntimeRunStateError, m as ValidationError } from "./errors-DG8yufqX.js";
|
|
7
|
-
import { o as failedItems, s as isFiniteNumber } from "./continuation-
|
|
8
|
-
import { c as errorMessage } from "./util-qsH5cC9S.js";
|
|
9
|
-
import { t as isNoEntError } from "./jsonl-file-
|
|
10
|
-
import { a as readFailureRecord, c as writeFailureRecord, i as parseSettleRecord, l as writeSettleRecord, n as SETTLE_RECORD_FILE, o as readSettleRecord, r as SettledRunDirectoryError, t as FAILURE_RECORD_FILE } from "./settle-record-
|
|
11
|
-
import { l as rootStreamToolSpans, s as ASSISTANT_REASONING_SPAN, t as supervise, u as runToolSpans, v as superviseRootProfile } from "./supervise-
|
|
7
|
+
import { o as failedItems, s as isFiniteNumber } from "./continuation-Bccak14N.js";
|
|
8
|
+
import { c as errorMessage, o as cloneTokenUsage } from "./util-qsH5cC9S.js";
|
|
9
|
+
import { t as isNoEntError } from "./jsonl-file-vE9H9UXa.js";
|
|
10
|
+
import { a as readFailureRecord, c as writeFailureRecord, i as parseSettleRecord, l as writeSettleRecord, n as SETTLE_RECORD_FILE, o as readSettleRecord, r as SettledRunDirectoryError, t as FAILURE_RECORD_FILE } from "./settle-record-BFhJigPW.js";
|
|
11
|
+
import { l as rootStreamToolSpans, s as ASSISTANT_REASONING_SPAN, t as supervise, u as runToolSpans, v as superviseRootProfile } from "./supervise-fmugf6Y2.js";
|
|
12
12
|
import { M as contentAddress, n as runtimeFailureCause } from "./failure-cause-DoCCGLDH.js";
|
|
13
|
-
import { a as readRunDirectoryLock, n as RunDirectoryLockedError, r as acquireRunDirectoryLock, s as runDirectoryHolderIsLive, t as RUN_DIRECTORY_LOCK_FILE } from "./run-lock-
|
|
13
|
+
import { a as readRunDirectoryLock, n as RunDirectoryLockedError, r as acquireRunDirectoryLock, s as runDirectoryHolderIsLive, t as RUN_DIRECTORY_LOCK_FILE } from "./run-lock-Ckakh1Uq.js";
|
|
14
14
|
import { u as defaultRedactor } from "./snapshot-BKI_w3JD.js";
|
|
15
|
-
import { t as FileResultBlobStore } from "./result-blob-store-
|
|
16
|
-
import { n as readSpawnJournal, t as readRunState } from "./run-state-
|
|
17
|
-
import { s as rootCoordinationOwner, u as FileCoordinationLog } from "./supervise-identity-
|
|
18
|
-
import { i as superviseAgentGraph, s as graphExecutionOptions } from "./graph-
|
|
15
|
+
import { t as FileResultBlobStore } from "./result-blob-store-UGXQYACQ.js";
|
|
16
|
+
import { n as readSpawnJournal, t as readRunState } from "./run-state-CZcFJjHn.js";
|
|
17
|
+
import { s as rootCoordinationOwner, u as FileCoordinationLog } from "./supervise-identity-7_7DUghQ.js";
|
|
18
|
+
import { i as superviseAgentGraph, s as graphExecutionOptions } from "./graph-CUUtx7qT.js";
|
|
19
19
|
import { a as withPursuitContext, t as composeRuntimeHooks } from "./runtime-hooks-CsW2pfFk.js";
|
|
20
|
-
import { i as reopenSettledRun, t as assertRunReopen } from "./run-reopen-
|
|
20
|
+
import { i as reopenSettledRun, t as assertRunReopen } from "./run-reopen-BvF3Gjj9.js";
|
|
21
21
|
import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, sha256Bytes } from "@tangle-network/agent-interface";
|
|
22
22
|
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
23
23
|
import { access, readFile, realpath } from "node:fs/promises";
|
|
@@ -1086,6 +1086,9 @@ const json = (value) => JSON.stringify(defaultRedactor(value ?? null), (_, item)
|
|
|
1086
1086
|
* What each node of a run did, from the directory `superviseGraphPursuit` wrote: outcome and tokens
|
|
1087
1087
|
* from the observer journal, settled output from `blobs/`, tool calls and the final message from
|
|
1088
1088
|
* `streams/`. Over `totalChars` every cap halves, then the earliest nodes drop; size never throws.
|
|
1089
|
+
* Tokens use the canonical node projection: settled descendant work plus the node's own
|
|
1090
|
+
* inference. Missing accounting stays absent; an incomplete subtotal carries `tokensKnown: false`.
|
|
1091
|
+
* Nested node totals overlap; use `projectPursuit().runs[].totals` for run-wide accounting.
|
|
1089
1092
|
*/
|
|
1090
1093
|
async function runEvidence(runDir, bounds = {}) {
|
|
1091
1094
|
const run = await discoverDurableSupervisionRun(runDir);
|
|
@@ -1107,7 +1110,10 @@ async function runEvidence(runDir, bounds = {}) {
|
|
|
1107
1110
|
args: json(span.args)
|
|
1108
1111
|
}]),
|
|
1109
1112
|
message: final === void 0 ? "" : JSON.parse(json(final)),
|
|
1110
|
-
...node.
|
|
1113
|
+
...node.usage === void 0 ? {} : { tokens: cloneTokenUsage({
|
|
1114
|
+
...node.usage,
|
|
1115
|
+
tokensKnown: node.usage.tokensKnown ? void 0 : false
|
|
1116
|
+
}) }
|
|
1111
1117
|
};
|
|
1112
1118
|
}));
|
|
1113
1119
|
let truncated = false;
|