@tangle-network/agent-runtime 10.0.5 → 10.0.6
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 +10 -0
- package/dist/{activation-DvvM7gG5.js → activation-B3qLMoog.js} +2 -2
- package/dist/{activation-DvvM7gG5.js.map → activation-B3qLMoog.js.map} +1 -1
- package/dist/{activation-DyFt-GHq.d.ts → activation-CT-rr2-5.d.ts} +2 -2
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +3 -3
- package/dist/{delegate-YBqrrbq7.js → delegate-BFP1uCNY.js} +2 -2
- package/dist/{delegate-YBqrrbq7.js.map → delegate-BFP1uCNY.js.map} +1 -1
- package/dist/{driver-control-acknowledgers-CNNRjIo9.js → driver-control-acknowledgers-jdlf49OQ.js} +11 -10
- package/dist/driver-control-acknowledgers-jdlf49OQ.js.map +1 -0
- package/dist/durable-writer-thread.js +2 -2
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +11 -11
- package/dist/{failure-cause-DoCCGLDH.js → failure-cause-DvYGlOEV.js} +13 -5
- package/dist/{failure-cause-DoCCGLDH.js.map → failure-cause-DvYGlOEV.js.map} +1 -1
- package/dist/{graph-CUUtx7qT.js → graph-CiApRth2.js} +7 -7
- package/dist/graph-CiApRth2.js.map +1 -0
- package/dist/{improve-Cy8PZUdw.js → improve-LJaiGxdI.js} +5 -5
- package/dist/{improve-Cy8PZUdw.js.map → improve-LJaiGxdI.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/kernel.d.ts +2 -2
- package/dist/kernel.js +16 -16
- package/dist/{loop-runner-Icc1iBR-.d.ts → loop-runner-D6egvap-.d.ts} +2 -2
- package/dist/{loop-runner-BwkX4ViS.js → loop-runner-Dgow637w.js} +2 -2
- package/dist/{loop-runner-BwkX4ViS.js.map → loop-runner-Dgow637w.js.map} +1 -1
- 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/mcp/memory-bin.js +1 -1
- package/dist/profiles.d.ts +1 -1
- package/dist/{provision-supervisor-Dtn8RjHe.js → provision-supervisor-DLOeyFHV.js} +5 -5
- package/dist/{provision-supervisor-Dtn8RjHe.js.map → provision-supervisor-DLOeyFHV.js.map} +1 -1
- package/dist/{result-blob-store-UGXQYACQ.js → result-blob-store-BMMzqpHa.js} +2 -2
- package/dist/{result-blob-store-UGXQYACQ.js.map → result-blob-store-BMMzqpHa.js.map} +1 -1
- package/dist/{run-cancellation-BpUQZqBS.js → run-cancellation-Bv7ooTJa.js} +129 -54
- package/dist/run-cancellation-Bv7ooTJa.js.map +1 -0
- package/dist/{run-reopen-BvF3Gjj9.js → run-reopen-KAnkEJV4.js} +6 -6
- package/dist/{run-reopen-BvF3Gjj9.js.map → run-reopen-KAnkEJV4.js.map} +1 -1
- package/dist/{run-state-CZcFJjHn.js → run-state-Bcci4zIN.js} +5 -5
- package/dist/{run-state-CZcFJjHn.js.map → run-state-Bcci4zIN.js.map} +1 -1
- package/dist/{runtime-BvDaNyFf.js → runtime-DCo0OP4n.js} +16 -16
- package/dist/{runtime-BvDaNyFf.js.map → runtime-DCo0OP4n.js.map} +1 -1
- package/dist/{search-executor-DWQW-9WN.js → search-executor-Dn5YmHsg.js} +4 -4
- package/dist/{search-executor-DWQW-9WN.js.map → search-executor-Dn5YmHsg.js.map} +1 -1
- package/dist/{server-D5GpuQnT.js → server-DxpG9y6W.js} +4 -4
- package/dist/{server-D5GpuQnT.js.map → server-DxpG9y6W.js.map} +1 -1
- package/dist/{settle-record-BFhJigPW.js → settle-record-DMdeNy8A.js} +2 -2
- package/dist/{settle-record-BFhJigPW.js.map → settle-record-DMdeNy8A.js.map} +1 -1
- package/dist/{structural-rollout-D1pZn6Cu.js → structural-rollout-DOmjcEMD.js} +4 -4
- package/dist/{structural-rollout-D1pZn6Cu.js.map → structural-rollout-DOmjcEMD.js.map} +1 -1
- package/dist/{supervise-fmugf6Y2.js → supervise-D7jtypE-.js} +25 -21
- package/dist/supervise-D7jtypE-.js.map +1 -0
- package/dist/{supervise-identity-7_7DUghQ.js → supervise-identity-QavM_M4r.js} +2 -2
- package/dist/{supervise-identity-7_7DUghQ.js.map → supervise-identity-QavM_M4r.js.map} +1 -1
- package/dist/{supervision-discovery-DwRtZNdy.js → supervision-discovery-CFZnbNTB.js} +3 -3
- package/dist/{supervision-discovery-DwRtZNdy.js.map → supervision-discovery-CFZnbNTB.js.map} +1 -1
- package/dist/{supervisor-BlACe-uO.js → supervisor-BFs4u2Vo.js} +25 -16
- package/dist/supervisor-BFs4u2Vo.js.map +1 -0
- package/dist/{supervisor-accounting-DuFyM-_h.js → supervisor-accounting-CgipDzYg.js} +11 -3
- package/dist/{supervisor-accounting-DuFyM-_h.js.map → supervisor-accounting-CgipDzYg.js.map} +1 -1
- package/dist/{supervisor-root-contract-DCMw4u0V.js → supervisor-root-contract-Ca5xp0Vg.js} +3 -3
- package/dist/{supervisor-root-contract-DCMw4u0V.js.map → supervisor-root-contract-Ca5xp0Vg.js.map} +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +11 -11
- package/dist/{tool-server-DQCdu3am.js → tool-server-Cb7LBW4e.js} +2 -2
- package/dist/{tool-server-DQCdu3am.js.map → tool-server-Cb7LBW4e.js.map} +1 -1
- package/dist/{top-web-C5vhiOFA.js → top-web-oDO4xhNE.js} +7 -7
- package/dist/{top-web-C5vhiOFA.js.map → top-web-oDO4xhNE.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-CFmKHKiN.d.ts → types-CKsn_wgO.d.ts} +19 -3
- package/package.json +1 -1
- package/dist/driver-control-acknowledgers-CNNRjIo9.js.map +0 -1
- package/dist/graph-CUUtx7qT.js.map +0 -1
- package/dist/run-cancellation-BpUQZqBS.js.map +0 -1
- package/dist/supervise-fmugf6Y2.js.map +0 -1
- package/dist/supervisor-BlACe-uO.js.map +0 -1
|
@@ -1,32 +1,51 @@
|
|
|
1
|
-
import { a as assertNoSymlinkDescendant, u as writeAtomicDurableFile } from "./durable-file-pao7FijS.js";
|
|
2
|
-
import {
|
|
1
|
+
import { a as assertNoSymlinkDescendant, c as publishExclusiveFenced, d as writeAtomicDurableFileAsync, u as writeAtomicDurableFile, v as runFencedAlways } from "./durable-file-pao7FijS.js";
|
|
2
|
+
import { O as workerCancellationsDir, m as appendWorkerControlEventAsync, p as appendWorkerControlEvent } from "./supervisor-accounting-CgipDzYg.js";
|
|
3
3
|
import { existsSync, mkdirSync, readFileSync, watch } from "node:fs";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
// src/runtime/supervise/run-cancellation.ts
|
|
6
6
|
/** Apply a durable request through the run's existing abort controller. */
|
|
7
7
|
function applyRunCancellation(dir, abortRun, now, path = "turn-boundary") {
|
|
8
|
+
const applied = abortForRequest(dir, abortRun, now, path);
|
|
9
|
+
if (applied?.fresh) writeRunCancellation(dir, applied.record);
|
|
10
|
+
return applied?.record;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* `applyRunCancellation` without blocking the calling thread on the disk: the abort is issued at
|
|
14
|
+
* once, and the `cancel_requested` record reaches disk on the durable writer under the run's claim.
|
|
15
|
+
*/
|
|
16
|
+
async function applyRunCancellationAsync(dir, abortRun, now, path = "turn-boundary") {
|
|
17
|
+
const applied = abortForRequest(dir, abortRun, now, path);
|
|
18
|
+
if (applied?.fresh) await writeRunCancellationAsync(dir, applied.record);
|
|
19
|
+
return applied?.record;
|
|
20
|
+
}
|
|
21
|
+
/** Abort for the pending request, and the record it owes: the standing one, or a fresh one to write. */
|
|
22
|
+
function abortForRequest(dir, abortRun, now, path) {
|
|
8
23
|
const request = readRunCancelRequest(dir);
|
|
9
24
|
if (request === void 0) return void 0;
|
|
10
25
|
const prior = readRunCancellation(dir, request.operationId);
|
|
11
26
|
if (prior?.effect === "cancel_requested") abortRun(request.reason ?? "run cancel requested", request);
|
|
12
|
-
if (prior !== void 0) return
|
|
27
|
+
if (prior !== void 0) return {
|
|
28
|
+
record: prior,
|
|
29
|
+
fresh: false
|
|
30
|
+
};
|
|
13
31
|
abortRun(request.reason ?? "run cancel requested", request);
|
|
14
32
|
const observedAt = now();
|
|
15
33
|
const appliedAfterMs = Math.max(0, Date.parse(observedAt) - Date.parse(request.at));
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
34
|
+
return {
|
|
35
|
+
record: {
|
|
36
|
+
operationId: request.operationId,
|
|
37
|
+
effect: "cancel_requested",
|
|
38
|
+
path,
|
|
39
|
+
appliedAfterMs,
|
|
40
|
+
...request.deadlineMs === void 0 ? {} : { deadlineExceeded: appliedAfterMs > request.deadlineMs },
|
|
41
|
+
requestedAt: request.at,
|
|
42
|
+
observedAt,
|
|
43
|
+
...request.reason === void 0 ? {} : { reason: request.reason },
|
|
44
|
+
...request.operator === void 0 ? {} : { operator: request.operator },
|
|
45
|
+
detail: "root abort issued to the whole run; termination not yet proven"
|
|
46
|
+
},
|
|
47
|
+
fresh: true
|
|
27
48
|
};
|
|
28
|
-
writeRunCancellation(dir, record);
|
|
29
|
-
return record;
|
|
30
49
|
}
|
|
31
50
|
/** External drivers may remain silent indefinitely, so turn boundaries cannot observe control. */
|
|
32
51
|
function watchRunCancellation(dir, abortRun, createWatch = watch) {
|
|
@@ -39,37 +58,45 @@ function watchRunCancellation(dir, abortRun, createWatch = watch) {
|
|
|
39
58
|
aborted = true;
|
|
40
59
|
abortRun(reason, request);
|
|
41
60
|
};
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
if (
|
|
61
|
+
let inFlight;
|
|
62
|
+
const apply = (path) => {
|
|
63
|
+
if (failure !== void 0) return Promise.reject(failure);
|
|
64
|
+
if (!active) return Promise.resolve();
|
|
65
|
+
const applying = applyRunCancellationAsync(dir, abortOnce, () => (/* @__PURE__ */ new Date()).toISOString(), path).then(() => void 0);
|
|
66
|
+
const settled = applying.then(() => {
|
|
67
|
+
if (inFlight === settled) inFlight = void 0;
|
|
68
|
+
}, (error) => {
|
|
69
|
+
failure ??= error;
|
|
70
|
+
if (inFlight === settled) inFlight = void 0;
|
|
71
|
+
});
|
|
72
|
+
inFlight = settled;
|
|
73
|
+
return applying;
|
|
74
|
+
};
|
|
75
|
+
const check = async (path = "observer") => {
|
|
76
|
+
while (inFlight !== void 0) await inFlight;
|
|
77
|
+
await apply(path);
|
|
45
78
|
};
|
|
46
79
|
const fail = (error) => {
|
|
47
80
|
if (!active) return;
|
|
48
81
|
failure = error;
|
|
49
82
|
abortRun(`durable run cancellation observer failed: ${String(error)}`);
|
|
50
83
|
};
|
|
84
|
+
const poll = (path) => {
|
|
85
|
+
if (inFlight !== void 0) return;
|
|
86
|
+
apply(path).catch(fail);
|
|
87
|
+
};
|
|
51
88
|
let watcher;
|
|
52
89
|
try {
|
|
53
90
|
watcher = createWatch(workerCancellationsDir(dir), (_event, filename) => {
|
|
54
91
|
if (!active || filename !== null && filename !== "run.request.json") return;
|
|
55
|
-
|
|
56
|
-
check();
|
|
57
|
-
} catch (error) {
|
|
58
|
-
fail(error);
|
|
59
|
-
}
|
|
92
|
+
poll("observer");
|
|
60
93
|
});
|
|
61
94
|
} catch (error) {
|
|
62
95
|
const code = error.code;
|
|
63
96
|
if (code !== "EMFILE" && code !== "ENOSPC") throw error;
|
|
64
97
|
}
|
|
65
98
|
watcher?.on("error", fail);
|
|
66
|
-
const fallback = setInterval(() =>
|
|
67
|
-
try {
|
|
68
|
-
check("fallback");
|
|
69
|
-
} catch (error) {
|
|
70
|
-
fail(error);
|
|
71
|
-
}
|
|
72
|
-
}, 100);
|
|
99
|
+
const fallback = setInterval(() => poll("fallback"), 100);
|
|
73
100
|
fallback.unref();
|
|
74
101
|
return {
|
|
75
102
|
check,
|
|
@@ -122,13 +149,22 @@ function readRunCancellation(eventDir, operationId) {
|
|
|
122
149
|
* or {@link cancelRun}.
|
|
123
150
|
*/
|
|
124
151
|
function writeRunCancellation(eventDir, record) {
|
|
152
|
+
writeAtomicDurableFile(runCancellationTarget(eventDir), recordText(record), { mode: 384 });
|
|
153
|
+
}
|
|
154
|
+
/** `writeRunCancellation` without blocking the calling thread on the disk under a run claim. @internal */
|
|
155
|
+
function writeRunCancellationAsync(eventDir, record) {
|
|
156
|
+
return writeAtomicDurableFileAsync(runCancellationTarget(eventDir), recordText(record), { mode: 384 });
|
|
157
|
+
}
|
|
158
|
+
const recordText = (record) => `${JSON.stringify(record, null, 2)}\n`;
|
|
159
|
+
/** The acknowledgement file, its directory made and every path checked for symlinks. */
|
|
160
|
+
function runCancellationTarget(eventDir) {
|
|
125
161
|
const dir = workerCancellationsDir(eventDir);
|
|
126
162
|
assertNoSymlinkDescendant(eventDir, dir, "run cancel acknowledgement");
|
|
127
163
|
mkdirSync(dir, { recursive: true });
|
|
128
164
|
assertNoSymlinkDescendant(eventDir, dir, "run cancel acknowledgement");
|
|
129
165
|
const file = runCancellationFile(eventDir);
|
|
130
166
|
assertNoSymlinkDescendant(eventDir, file, "run cancel acknowledgement");
|
|
131
|
-
|
|
167
|
+
return file;
|
|
132
168
|
}
|
|
133
169
|
/**
|
|
134
170
|
* Request the cancellation of the WHOLE run, idempotently, and return the operation's current
|
|
@@ -153,6 +189,36 @@ function writeRunCancellation(eventDir, record) {
|
|
|
153
189
|
* or acknowledgement written before that rule is answered as it was.
|
|
154
190
|
*/
|
|
155
191
|
function cancelRun(eventDir, operationId, options = {}) {
|
|
192
|
+
const admission = admitRunCancel(eventDir, operationId, options);
|
|
193
|
+
if ("answer" in admission) return admission.answer;
|
|
194
|
+
if (admission.file !== void 0) {
|
|
195
|
+
writeAtomicDurableFile(admission.file, recordText(admission.request), { mode: 384 });
|
|
196
|
+
appendWorkerControlEvent(eventDir, "run", admission.event);
|
|
197
|
+
}
|
|
198
|
+
return queuedRunCancellation(admission.request);
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Request the cancellation of the whole run like {@link cancelRun}, without blocking the calling
|
|
202
|
+
* thread on the disk. The request file is published by the durable writer whether or not the
|
|
203
|
+
* caller holds a run claim (a coordinator outside the run holds none), so an event loop that stops
|
|
204
|
+
* runs keeps running while the file and its directory reach disk. Same admission, replay and
|
|
205
|
+
* conflict rules.
|
|
206
|
+
* @stable
|
|
207
|
+
*/
|
|
208
|
+
async function cancelRunAsync(eventDir, operationId, options = {}) {
|
|
209
|
+
const admission = admitRunCancel(eventDir, operationId, options);
|
|
210
|
+
if ("answer" in admission) return admission.answer;
|
|
211
|
+
if (admission.file !== void 0) {
|
|
212
|
+
if (!await runFencedAlways("publishExclusiveDurableFile", publishExclusiveFenced, admission.file, recordText(admission.request), { mode: 384 })) return cancelRunAsync(eventDir, operationId, options);
|
|
213
|
+
await appendWorkerControlEventAsync(eventDir, "run", admission.event);
|
|
214
|
+
}
|
|
215
|
+
return queuedRunCancellation(admission.request);
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* The admission of one run cancel: the standing acknowledgement, or the request to answer for,
|
|
219
|
+
* with the file and control event still to write when it is new.
|
|
220
|
+
*/
|
|
221
|
+
function admitRunCancel(eventDir, operationId, options) {
|
|
156
222
|
if (options.deadlineMs !== void 0 && (!Number.isFinite(options.deadlineMs) || options.deadlineMs < 0)) throw new Error("cancelRun: deadlineMs must be a finite nonnegative number");
|
|
157
223
|
const opId = operationId.trim();
|
|
158
224
|
if (!opId) throw new Error("cancelRun: operationId is empty");
|
|
@@ -170,7 +236,7 @@ function cancelRun(eventDir, operationId, options = {}) {
|
|
|
170
236
|
if (acknowledged !== void 0) {
|
|
171
237
|
if (pending === void 0 && options.source !== void 0) throw new Error(`cancelRun: operation '${opId}' cannot verify source without its admitted request`);
|
|
172
238
|
assertRunCancellationMatchesCandidate(acknowledged, candidate);
|
|
173
|
-
return acknowledged;
|
|
239
|
+
return { answer: acknowledged };
|
|
174
240
|
}
|
|
175
241
|
if (pending === void 0 && (options.operator === void 0 || options.operator.trim() === "")) throw new Error("cancelRun: operator is required; name who stops the run");
|
|
176
242
|
const source = options.source ?? "human";
|
|
@@ -182,26 +248,35 @@ function cancelRun(eventDir, operationId, options = {}) {
|
|
|
182
248
|
...options.deadlineMs === void 0 ? {} : { deadlineMs: options.deadlineMs },
|
|
183
249
|
...options.operator === void 0 ? {} : { operator: options.operator }
|
|
184
250
|
};
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
assertNoSymlinkDescendant(eventDir, dir, "run cancel request");
|
|
188
|
-
mkdirSync(dir, { recursive: true });
|
|
189
|
-
assertNoSymlinkDescendant(eventDir, dir, "run cancel request");
|
|
190
|
-
const file = runCancelRequestFile(eventDir);
|
|
191
|
-
assertNoSymlinkDescendant(eventDir, file, "run cancel request");
|
|
192
|
-
writeAtomicDurableFile(file, `${JSON.stringify(request, null, 2)}\n`, { mode: 384 });
|
|
193
|
-
appendWorkerControlEvent(eventDir, "run", {
|
|
194
|
-
kind: "run-cancel-request",
|
|
195
|
-
operationId: opId,
|
|
196
|
-
source,
|
|
197
|
-
queued: true,
|
|
198
|
-
...options.reason === void 0 ? {} : { reason: options.reason },
|
|
199
|
-
...options.deadlineMs === void 0 ? {} : { deadlineMs: options.deadlineMs },
|
|
200
|
-
...options.operator === void 0 ? {} : { operator: options.operator }
|
|
201
|
-
});
|
|
202
|
-
}
|
|
203
|
-
return {
|
|
251
|
+
const event = {
|
|
252
|
+
kind: "run-cancel-request",
|
|
204
253
|
operationId: opId,
|
|
254
|
+
source,
|
|
255
|
+
queued: true,
|
|
256
|
+
...options.reason === void 0 ? {} : { reason: options.reason },
|
|
257
|
+
...options.deadlineMs === void 0 ? {} : { deadlineMs: options.deadlineMs },
|
|
258
|
+
...options.operator === void 0 ? {} : { operator: options.operator }
|
|
259
|
+
};
|
|
260
|
+
if (pending !== void 0) return {
|
|
261
|
+
request,
|
|
262
|
+
event
|
|
263
|
+
};
|
|
264
|
+
const dir = workerCancellationsDir(eventDir);
|
|
265
|
+
assertNoSymlinkDescendant(eventDir, dir, "run cancel request");
|
|
266
|
+
mkdirSync(dir, { recursive: true });
|
|
267
|
+
assertNoSymlinkDescendant(eventDir, dir, "run cancel request");
|
|
268
|
+
const file = runCancelRequestFile(eventDir);
|
|
269
|
+
assertNoSymlinkDescendant(eventDir, file, "run cancel request");
|
|
270
|
+
return {
|
|
271
|
+
request,
|
|
272
|
+
file,
|
|
273
|
+
event
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
/** The answer to a request no runtime has acknowledged yet. */
|
|
277
|
+
function queuedRunCancellation(request) {
|
|
278
|
+
return {
|
|
279
|
+
operationId: request.operationId,
|
|
205
280
|
effect: "unknown",
|
|
206
281
|
requestedAt: request.at,
|
|
207
282
|
observedAt: request.at,
|
|
@@ -224,6 +299,6 @@ function assertRunCancellationMatchesCandidate(existing, candidate) {
|
|
|
224
299
|
function isRunCancelRequest(value) {
|
|
225
300
|
return typeof value.operationId === "string" && value.operationId.length > 0 && typeof value.at === "string" && typeof value.source === "string" && (value.deadlineMs === void 0 || Number.isFinite(value.deadlineMs) && value.deadlineMs >= 0) && (value.reason === void 0 || typeof value.reason === "string") && (value.operator === void 0 || typeof value.operator === "string");
|
|
226
301
|
}
|
|
227
|
-
export {
|
|
302
|
+
export { readRunCancelRequest as a, runCancellationFile as c, writeRunCancellationAsync as d, cancelRunAsync as i, watchRunCancellation as l, applyRunCancellationAsync as n, readRunCancellation as o, cancelRun as r, runCancelRequestFile as s, applyRunCancellation as t, writeRunCancellation as u };
|
|
228
303
|
|
|
229
|
-
//# sourceMappingURL=run-cancellation-
|
|
304
|
+
//# sourceMappingURL=run-cancellation-Bv7ooTJa.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-cancellation-Bv7ooTJa.js","names":[],"sources":["../src/runtime/supervise/run-cancellation.ts"],"sourcesContent":["import { existsSync, mkdirSync, readFileSync, watch } from 'node:fs'\nimport { join } from 'node:path'\nimport { runFencedAlways } from '../../durable/durable-writer'\nimport type { RetainedRunEffect } from '../retained-run-types'\nimport {\n assertNoSymlinkDescendant,\n publishExclusiveFenced,\n writeAtomicDurableFile,\n writeAtomicDurableFileAsync,\n} from './durable-file'\nimport {\n appendWorkerControlEvent,\n appendWorkerControlEventAsync,\n workerCancellationsDir,\n} from './run-layout'\n\ntype CancellationPath = 'observer' | 'turn-boundary' | 'fallback'\n\n/** Apply a durable request through the run's existing abort controller. */\nexport function applyRunCancellation(\n dir: string,\n abortRun: (reason: string, request?: RunCancelRequest) => void,\n now: () => string,\n path: CancellationPath = 'turn-boundary',\n): RunCancellation | undefined {\n const applied = abortForRequest(dir, abortRun, now, path)\n if (applied?.fresh) writeRunCancellation(dir, applied.record)\n return applied?.record\n}\n\n/**\n * `applyRunCancellation` without blocking the calling thread on the disk: the abort is issued at\n * once, and the `cancel_requested` record reaches disk on the durable writer under the run's claim.\n */\nexport async function applyRunCancellationAsync(\n dir: string,\n abortRun: (reason: string, request?: RunCancelRequest) => void,\n now: () => string,\n path: CancellationPath = 'turn-boundary',\n): Promise<RunCancellation | undefined> {\n const applied = abortForRequest(dir, abortRun, now, path)\n if (applied?.fresh) await writeRunCancellationAsync(dir, applied.record)\n return applied?.record\n}\n\n/** Abort for the pending request, and the record it owes: the standing one, or a fresh one to write. */\nfunction abortForRequest(\n dir: string,\n abortRun: (reason: string, request?: RunCancelRequest) => void,\n now: () => string,\n path: CancellationPath,\n): { readonly record: RunCancellation; readonly fresh: boolean } | undefined {\n const request = readRunCancelRequest(dir)\n if (request === undefined) return undefined\n const prior = readRunCancellation(dir, request.operationId)\n // A request acknowledged only as `cancel_requested` is still owed by this run: the process\n // that issued the abort died before the run settled. Abort again; the record stands.\n if (prior?.effect === 'cancel_requested') {\n abortRun(request.reason ?? 'run cancel requested', request)\n }\n if (prior !== undefined) return { record: prior, fresh: false }\n abortRun(request.reason ?? 'run cancel requested', request)\n const observedAt = now()\n const appliedAfterMs = Math.max(0, Date.parse(observedAt) - Date.parse(request.at))\n const record: RunCancellation = {\n operationId: request.operationId,\n effect: 'cancel_requested',\n path,\n appliedAfterMs,\n ...(request.deadlineMs === undefined\n ? {}\n : { deadlineExceeded: appliedAfterMs > request.deadlineMs }),\n requestedAt: request.at,\n observedAt,\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n ...(request.operator === undefined ? {} : { operator: request.operator }),\n detail: 'root abort issued to the whole run; termination not yet proven',\n }\n return { record, fresh: true }\n}\n\n/** External drivers may remain silent indefinitely, so turn boundaries cannot observe control. */\nexport function watchRunCancellation(\n dir: string,\n abortRun: (reason: string, request?: RunCancelRequest) => void,\n createWatch: typeof watch = watch,\n) {\n mkdirSync(workerCancellationsDir(dir), { recursive: true })\n let active = true\n let failure: unknown\n // One observer aborts its run once: a request this process already applied, or one a dead\n // process acknowledged, is not re-issued on every poll.\n let aborted = false\n const abortOnce = (reason: string, request?: RunCancelRequest): void => {\n if (aborted) return\n aborted = true\n abortRun(reason, request)\n }\n // One application at a time. The abort is immediate; its record goes to the durable writer, so a\n // saturated disk delays the record, never this event loop. A poll that finds one in flight skips.\n let inFlight: Promise<void> | undefined\n const apply = (path: 'observer' | 'fallback'): Promise<void> => {\n if (failure !== undefined) return Promise.reject(failure)\n if (!active) return Promise.resolve()\n const applying = applyRunCancellationAsync(\n dir,\n abortOnce,\n () => new Date().toISOString(),\n path,\n ).then(() => undefined)\n const settled = applying.then(\n () => {\n if (inFlight === settled) inFlight = undefined\n },\n (error: unknown) => {\n // Kept even after close, so the settle path's check() throws it instead of reading no record.\n failure ??= error\n if (inFlight === settled) inFlight = undefined\n },\n )\n inFlight = settled\n return applying\n }\n // A caller's check waits for the application in flight, so a closed observer's last record lands\n // before the run's settle record is written, and a failure it met is thrown here.\n const check = async (path: 'observer' | 'fallback' = 'observer'): Promise<void> => {\n while (inFlight !== undefined) await inFlight\n await apply(path)\n }\n const fail = (error: unknown): void => {\n if (!active) return\n failure = error\n abortRun(`durable run cancellation observer failed: ${String(error)}`)\n }\n const poll = (path: 'observer' | 'fallback'): void => {\n if (inFlight !== undefined) return\n apply(path).catch(fail)\n }\n // The watcher is an optimization over the poll loop below (instant pickup instead of ≤100 ms).\n // Creating it can fail for reasons that say NOTHING about this run: the host's inotify budget is\n // exhausted (EMFILE — a shared box with many agents held ~110 of the 128 default user instances\n // when this was measured), or the kernel caps watches (ENOSPC). Degrading to poll-only keeps\n // every durable behavior; failing the run would make a neighboring process's resource use kill\n // runs that never touched the limit. Any other creation error still fails loudly.\n let watcher: ReturnType<typeof watch> | undefined\n try {\n watcher = createWatch(workerCancellationsDir(dir), (_event, filename) => {\n if (!active || (filename !== null && filename !== 'run.request.json')) return\n poll('observer')\n })\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'EMFILE' && code !== 'ENOSPC') throw error\n }\n watcher?.on('error', fail)\n // Filesystem notifications are advisory. Scan the same durable inbox when one is dropped —\n // and carry the whole observer alone whenever the watcher above could not be created.\n const fallback = setInterval(() => poll('fallback'), 100)\n fallback.unref()\n return {\n check,\n close(): void {\n active = false\n watcher?.close()\n clearInterval(fallback)\n },\n }\n}\n\n/** One durable run-scoped cancel request: cancel the WHOLE run, not one worker. */\nexport interface RunCancelRequest {\n /** Caller-minted stable operation identifier — the idempotency key of the whole operation. */\n readonly operationId: string\n /** ISO timestamp of the write. */\n readonly at: string\n /** Who asked — 'human', a brain label, a tool name. Provenance, not authorization. */\n readonly source: string\n /** Requested observation target, measured by the acknowledgement's deadlineExceeded field.\n * The observer always cascades eagerly. This does not guarantee scheduler latency or cleanup. */\n readonly deadlineMs?: number\n /** Who stops the run. `cancelRun` requires it on every new request; it is optional here only\n * so a request written before that rule still reads. The settle record carries it. */\n readonly operator?: 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 cancelled state with confirmed teardown.\n * - `'not_live'` — the run was not live to cancel: it settled on its own despite the\n * request, or it ended before the request was applied.\n */\nexport interface RunCancellation {\n /** Runtime path that issued the cascade. */\n readonly path?: 'observer' | 'turn-boundary' | 'fallback'\n /** Runtime clock elapsed between request timestamp and cascade application. */\n readonly appliedAfterMs?: number\n /** Whether application exceeded the requested deadlineMs; absent when no target was requested. */\n readonly deadlineExceeded?: boolean\n readonly operationId: string\n readonly effect: RetainedRunEffect\n /** ISO timestamp of the original request. */\n readonly requestedAt: string\n /** ISO timestamp of the runtime's most recent observation of this operation. */\n readonly observedAt: string\n /** The caller's reason, carried verbatim from the request. */\n readonly reason?: string\n /** The caller's operator identity, carried verbatim from the request. */\n readonly operator?: string\n /** The runtime's explanation of how it arrived at `effect`. */\n readonly detail?: string\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 writeAtomicDurableFile(runCancellationTarget(eventDir), recordText(record), { mode: 0o600 })\n}\n\n/** `writeRunCancellation` without blocking the calling thread on the disk under a run claim. @internal */\nexport function writeRunCancellationAsync(\n eventDir: string,\n record: RunCancellation,\n): Promise<void> {\n return writeAtomicDurableFileAsync(runCancellationTarget(eventDir), recordText(record), {\n mode: 0o600,\n })\n}\n\nconst recordText = (record: RunCancellation | RunCancelRequest): string =>\n `${JSON.stringify(record, null, 2)}\\n`\n\n/** The acknowledgement file, its directory made and every path checked for symlinks. */\nfunction runCancellationTarget(eventDir: string): string {\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 return file\n}\n\n/**\n * Request the cancellation of the WHOLE run, idempotently, and return the operation's current\n * durable state.\n *\n * The run-scoped twin of {@link cancelWorker}: write the request into the run's cancellation\n * directory, where the run's own root manager applies it — aborting the root through the one\n * cascade controller the run already has, so every live worker comes down with it. This function\n * never applies the cancellation itself; writing a request file is not an acknowledgement.\n *\n * Idempotency is a lookup: when an acknowledgement for `operationId` already exists it is returned\n * AS-IS and nothing is written. A retry that changes the source, reason, deadline, or operator\n * fails closed. A request the runtime has not answered yet returns `effect: 'unknown'` (never a\n * success); call again with the same `operationId` — or {@link readRunCancellation} — to read the\n * acknowledged result after a reconnect.\n *\n * A run carries ONE run-scoped operation: a second request under a different `operationId` throws\n * rather than silently replacing the pending one, because both would claim the same single abort.\n * Reopening a settled run (`supervisePursuit`'s `reopen`) moves that operation aside.\n *\n * A NEW request must name its `operator`, so every stop says who made it. A replay of a request\n * or acknowledgement written before that rule is answered as it was.\n */\nexport function cancelRun(\n eventDir: string,\n operationId: string,\n // Inline, as published through 10.0.5: the archive admission reads a named type here as a new\n // shape, which would make this patch a major.\n options: {\n readonly reason?: string\n readonly source?: string\n readonly deadlineMs?: number\n readonly operator?: string\n } = {},\n): RunCancellation {\n const admission = admitRunCancel(eventDir, operationId, options)\n if ('answer' in admission) return admission.answer\n if (admission.file !== undefined) {\n writeAtomicDurableFile(admission.file, recordText(admission.request), { mode: 0o600 })\n appendWorkerControlEvent(eventDir, 'run', admission.event)\n }\n return queuedRunCancellation(admission.request)\n}\n\n/**\n * Request the cancellation of the whole run like {@link cancelRun}, without blocking the calling\n * thread on the disk. The request file is published by the durable writer whether or not the\n * caller holds a run claim (a coordinator outside the run holds none), so an event loop that stops\n * runs keeps running while the file and its directory reach disk. Same admission, replay and\n * conflict rules.\n * @stable\n */\nexport async function cancelRunAsync(\n eventDir: string,\n operationId: string,\n options: CancelRunOptions = {},\n): Promise<RunCancellation> {\n const admission = admitRunCancel(eventDir, operationId, options)\n if ('answer' in admission) return admission.answer\n if (admission.file !== undefined) {\n // Published only if no request is there yet: an overlapping call admitted against the same empty\n // inbox loses here, and is admitted again against the winner, which it replays or conflicts with.\n const published = await runFencedAlways(\n 'publishExclusiveDurableFile',\n publishExclusiveFenced,\n admission.file,\n recordText(admission.request),\n { mode: 0o600 },\n )\n if (!published) return cancelRunAsync(eventDir, operationId, options)\n await appendWorkerControlEventAsync(eventDir, 'run', admission.event)\n }\n return queuedRunCancellation(admission.request)\n}\n\n/** Options of {@link cancelRun} and {@link cancelRunAsync}. */\nexport interface CancelRunOptions {\n readonly reason?: string\n readonly source?: string\n readonly deadlineMs?: number\n readonly operator?: string\n}\n\n/**\n * The admission of one run cancel: the standing acknowledgement, or the request to answer for,\n * with the file and control event still to write when it is new.\n */\nfunction admitRunCancel(\n eventDir: string,\n operationId: string,\n options: CancelRunOptions,\n):\n | { readonly answer: RunCancellation }\n | {\n readonly request: RunCancelRequest\n readonly file?: string\n readonly event: Record<string, unknown>\n } {\n if (\n options.deadlineMs !== undefined &&\n (!Number.isFinite(options.deadlineMs) || options.deadlineMs < 0)\n ) {\n throw new Error('cancelRun: deadlineMs must be a finite nonnegative number')\n }\n const opId = operationId.trim()\n if (!opId) throw new Error('cancelRun: operationId is empty')\n const pending = readRunCancelRequest(eventDir)\n if (pending !== undefined && pending.operationId !== opId) {\n throw new Error(\n `cancelRun: run cancel '${pending.operationId}' is already pending for this run; ` +\n `read it with readRunCancellation instead of issuing '${opId}'`,\n )\n }\n const candidate = {\n operationId: opId,\n source: options.source ?? 'human',\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n ...(options.operator === undefined ? {} : { operator: options.operator }),\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 { answer: acknowledged }\n }\n // A new request names who stops the run. A replay of a request written before this rule keeps\n // its absent operator: it was admitted above against the file it replays.\n if (pending === undefined && (options.operator === undefined || options.operator.trim() === '')) {\n throw new Error('cancelRun: operator is required; name who stops the run')\n }\n const source = options.source ?? 'human'\n const request: RunCancelRequest = pending ?? {\n operationId: opId,\n at: new Date().toISOString(),\n source,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n ...(options.operator === undefined ? {} : { operator: options.operator }),\n }\n const event = {\n kind: 'run-cancel-request',\n operationId: opId,\n source,\n queued: true,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n ...(options.operator === undefined ? {} : { operator: options.operator }),\n }\n if (pending !== undefined) return { request, event }\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 return { request, file, event }\n}\n\n/** The answer to a request no runtime has acknowledged yet. */\nfunction queuedRunCancellation(request: RunCancelRequest): RunCancellation {\n return {\n operationId: request.operationId,\n effect: 'unknown',\n requestedAt: request.at,\n observedAt: request.at,\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n ...(request.operator === undefined ? {} : { operator: request.operator }),\n detail: 'request queued; no runtime acknowledger has answered yet',\n }\n}\n\ntype RunCancelRequestCandidate = Omit<RunCancelRequest, 'at'>\n\nfunction assertSameRunCancelRequest(\n existing: RunCancelRequest,\n candidate: RunCancelRequestCandidate,\n): void {\n if (existing.operationId !== candidate.operationId) {\n throw new Error(`cancelRun: operation '${candidate.operationId}' has an id collision`)\n }\n if (existing.source !== candidate.source) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(source '${existing.source}' != '${candidate.source}')`,\n )\n }\n if (existing.deadlineMs !== candidate.deadlineMs) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request (deadlineMs differs)`,\n )\n }\n if (existing.reason !== candidate.reason) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(reason differs)`,\n )\n }\n if (existing.operator !== candidate.operator) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(operator '${existing.operator}' != '${candidate.operator}')`,\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 // An acknowledgement written before acknowledgements carried the operator (0.251.0) names none\n // even when its admitted request does. The request comparator has already held the candidate\n // to that request, so a legacy record matches any candidate operator; a record that names one\n // must name the same one.\n if (existing.operator !== undefined && existing.operator !== candidate.operator) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its acknowledgement ` +\n `(operator '${existing.operator}' != '${candidate.operator}')`,\n )\n }\n}\n\nfunction isRunCancelRequest(value: Partial<RunCancelRequest>): value is RunCancelRequest {\n return (\n typeof value.operationId === 'string' &&\n value.operationId.length > 0 &&\n typeof value.at === 'string' &&\n typeof value.source === 'string' &&\n (value.deadlineMs === undefined ||\n (Number.isFinite(value.deadlineMs) && value.deadlineMs >= 0)) &&\n (value.reason === undefined || typeof value.reason === 'string') &&\n (value.operator === undefined || typeof value.operator === 'string')\n )\n}\n"],"mappings":";;;;;;AAmBA,SAAgB,qBACd,KAC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IAAI,SAAS,eAAe,UAAU,YACpC,MAAM,IAAI,MACR,yBAAyB,UAAU,YAAY,2DACjD;CAEF,IAAI,SAAS,WAAW,UAAU,QAChC,MAAM,IAAI,MACR,yBAAyB,UAAU,YAAY,uDAEjD;CAEF,IAAI,SAAS,aAAa,UAAU,UAClC,MAAM,IAAI,MACR,yBAAyB,UAAU,YAAY,mDAC/B,SAAS,SAAS,QAAQ,UAAU,SAAS,GAC/D;AAEJ;AAEA,SAAS,sCACP,UACA,WACM;CACN,IAAI,SAAS,WAAW,UAAU,QAChC,MAAM,IAAI,MACR,yBAAyB,UAAU,YAAY,sDAEjD;CAMF,IAAI,SAAS,aAAa,KAAA,KAAa,SAAS,aAAa,UAAU,UACrE,MAAM,IAAI,MACR,yBAAyB,UAAU,YAAY,kDAC/B,SAAS,SAAS,QAAQ,UAAU,SAAS,GAC/D;AAEJ;AAEA,SAAS,mBAAmB,OAA6D;CACvF,OACE,OAAO,MAAM,gBAAgB,YAC7B,MAAM,YAAY,SAAS,KAC3B,OAAO,MAAM,OAAO,YACpB,OAAO,MAAM,WAAW,aACvB,MAAM,eAAe,KAAA,KACnB,OAAO,SAAS,MAAM,UAAU,KAAK,MAAM,cAAc,OAC3D,MAAM,WAAW,KAAA,KAAa,OAAO,MAAM,WAAW,cACtD,MAAM,aAAa,KAAA,KAAa,OAAO,MAAM,aAAa;AAE/D"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { _ as runFenced, l as syncDurableDirectory, o as publishExclusiveDurableFile, x as fenceRunWrite } from "./durable-file-pao7FijS.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { n as assertResumeLimits } from "./supervisor-root-contract-
|
|
6
|
-
import { n as SETTLE_RECORD_FILE, s as settleRecordDigest } from "./settle-record-
|
|
2
|
+
import { c as runCancellationFile, s as runCancelRequestFile } from "./run-cancellation-Bv7ooTJa.js";
|
|
3
|
+
import { O as workerCancellationsDir, X as FileSpawnJournal } from "./supervisor-accounting-CgipDzYg.js";
|
|
4
|
+
import { it as assertValidBudget } from "./failure-cause-DvYGlOEV.js";
|
|
5
|
+
import { n as assertResumeLimits } from "./supervisor-root-contract-Ca5xp0Vg.js";
|
|
6
|
+
import { n as SETTLE_RECORD_FILE, s as settleRecordDigest } from "./settle-record-DMdeNy8A.js";
|
|
7
7
|
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync } from "node:fs";
|
|
8
8
|
import { join, resolve } from "node:path";
|
|
9
9
|
import { readFile } from "node:fs/promises";
|
|
@@ -131,4 +131,4 @@ function makeRunDirectoryFenced(dir) {
|
|
|
131
131
|
}
|
|
132
132
|
export { reopenSettledRun as i, makeRunDirectoryFenced as n, reopenSettleFenced as r, assertRunReopen as t };
|
|
133
133
|
|
|
134
|
-
//# sourceMappingURL=run-reopen-
|
|
134
|
+
//# sourceMappingURL=run-reopen-KAnkEJV4.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-reopen-BvF3Gjj9.js","names":[],"sources":["../src/durable/run-reopen.ts"],"sourcesContent":["import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync } from 'node:fs'\nimport { readFile } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport {\n publishExclusiveDurableFile,\n syncDurableDirectory,\n} from '../runtime/supervise/durable-file'\nimport { runCancellationFile, runCancelRequestFile } from '../runtime/supervise/run-cancellation'\nimport { workerCancellationsDir } from '../runtime/supervise/run-layout'\nimport { assertValidBudget } from '../runtime/supervise/spend-validation'\nimport { assertResumeLimits } from '../runtime/supervise/supervisor-root-contract'\nimport type { Budget, SpawnEvent, SpawnJournal, SupervisorOpts } from '../runtime/supervise/types'\nimport { runFenced } from './durable-writer'\nimport type { FileObserverJournal } from './observer-journal'\nimport { fenceRunWrite } from './run-fence'\nimport { SETTLE_RECORD_FILE, settleRecordDigest } from './settle-record'\nimport { FileSpawnJournal } from './spawn-journal/journal-store'\n\n/*\n * Reopening a settled run under its own run id.\n *\n * A wrong settle used to be final: `supervisePursuit` refuses a directory that holds `result.json`,\n * and `fork` and `versions` each start a new run id in a new directory. Magnetar used 21 run ids\n * from 2026-10-16 to 10-21 for one solve; 16 of those runs settled, 11 of them in under 5 hours.\n *\n * A reopen archives the settled segment and resumes the same journal. Before it writes anything it\n * checks the resume limits (`assertResumeLimits`): a reopen refused for its budget or reservation\n * policy leaves `result.json`, the cancel files and the journal as they were. The profile's identity\n * and materialization are checked by `supervise` itself, after these steps. Every step is\n * idempotent, so a later call with the same `operationId` finishes a reopen that crashed partway:\n * 1. copy `result.json` byte for byte to `settles/<n>.json`;\n * 2. append one `reopened` spawn-journal row naming the operator, the reason and the archive;\n * 3. append one observer event, so the pursuit projection shows one lineage;\n * 4. move the run's cancel request and acknowledgement aside under this reopen's and that\n * request's operation ids, so a new `cancelRun` is accepted (one run carries one run-scoped\n * cancel operation) and no later reopen overwrites an earlier segment's cancel;\n * 5. last, remove `result.json`.\n * The caller then runs `supervise` with `resume: true`: settled children replay by key, the pool\n * is restored from the journal, and the next settle writes `result.json` again.\n */\n\n/** `supervisePursuit`'s `reopen` option: reopen this settled run under its own run id. */\nexport interface RunReopen {\n /** Who reopens the run. Required and non-empty. */\n readonly operator: string\n /** Why. Required and non-empty. */\n readonly reason: string\n /** Idempotency key: calling again with it finishes a reopen that crashed partway. */\n readonly operationId: string\n /**\n * The budget the reopened run is held to, recorded on its `reopened` row, which a later resume\n * must then match. Omit and the call's `budget` must equal the recorded one: the root's, or the\n * last budget a reopen recorded. A run that settled `budget-exhausted` and reopens without a\n * larger budget pauses at once (with `driverRetry.pauseRootStops`) or settles\n * `budget-exhausted` again. A deadline is measured from the original root instant, so a run\n * whose recorded deadline has passed settles `deadline` at once unless this budget drops the\n * deadline or moves it.\n */\n readonly budget?: Budget\n}\n\n/** The directory that holds a run's archived settle records. */\nexport const SETTLE_ARCHIVE_DIR = 'settles'\n\n/** Refuse a reopen that names no operator or reason, or that is combined with a fork or versions. */\nexport function assertRunReopen(\n reopen: RunReopen,\n opts: { readonly fork?: unknown; readonly versions?: unknown },\n): void {\n if (reopen.operator.trim().length === 0) {\n throw new TypeError('supervisePursuit: reopen.operator must be non-empty')\n }\n if (reopen.reason.trim().length === 0) {\n throw new TypeError('supervisePursuit: reopen.reason must be non-empty')\n }\n if (reopen.operationId.trim().length === 0) {\n throw new TypeError('supervisePursuit: reopen.operationId must be non-empty')\n }\n if (reopen.budget !== undefined) assertValidBudget(reopen.budget, 'reopen.budget')\n if (opts.fork !== undefined || opts.versions !== undefined) {\n throw new TypeError(\n 'supervisePursuit: reopen continues this run under its own id; fork and versions start new runs',\n )\n }\n}\n\n/**\n * Archive the settled segment of the run at `runDir` and clear it for a resume. Runs under the\n * directory lock. Throws when there is nothing to reopen, or when `operationId` already reopened a\n * segment that has since settled again.\n */\nexport async function reopenSettledRun(input: {\n readonly runDir: string\n readonly runId: string\n readonly reopen: RunReopen\n readonly journal: SpawnJournal | undefined\n /** The call's budget and reservation policy, checked against the recorded ones before any write. */\n readonly limits: Pick<SupervisorOpts, 'budget' | 'reservationPolicy'>\n readonly observer: FileObserverJournal\n readonly pursuitId: string\n readonly now: () => number\n}): Promise<void> {\n const { runDir, runId, reopen, observer, pursuitId, now } = input\n const operationId = reopen.operationId.trim()\n const settlePath = resolve(runDir, SETTLE_RECORD_FILE)\n const journal = input.journal ?? new FileSpawnJournal(resolve(runDir, 'spawn-journal.jsonl'))\n const events = (await journal.loadTree(runId)) ?? []\n const reopened = events.filter(\n (event): event is Extract<SpawnEvent, { kind: 'reopened' }> =>\n event.kind === 'reopened' && event.id === runId,\n )\n const mine = reopened.find((event) => event.operationId === operationId)\n const settled = await readBytes(settlePath)\n if (settled === undefined) {\n // Removing result.json is the last step, so a recorded reopen without it is complete.\n if (mine !== undefined) return\n throw new Error(\n `supervisePursuit: ${runDir} holds no ${SETTLE_RECORD_FILE}; nothing to reopen; resume it`,\n )\n }\n assertResumeLimits(\n events,\n {\n runId,\n budget: reopen.budget ?? input.limits.budget,\n ...(input.limits.reservationPolicy === undefined\n ? {}\n : { reservationPolicy: input.limits.reservationPolicy }),\n },\n mine === undefined ? reopen.budget : undefined,\n )\n const result = JSON.parse(settled) as { readonly kind?: unknown; readonly reason?: unknown }\n const digest = settleRecordDigest(result)\n if (mine !== undefined && mine.prior.digest !== digest) {\n throw new Error(\n `supervisePursuit: reopen '${operationId}' already reopened run '${runId}', which has settled again; reopen it under a new operationId`,\n )\n }\n const archivedAs = mine?.prior.archivedAs ?? (await archiveName(runDir, settled))\n const archivePath = resolve(runDir, archivedAs)\n if (\n !publishExclusiveDurableFile(archivePath, settled) &&\n (await readBytes(archivePath)) !== settled\n ) {\n throw new Error(\n `supervisePursuit: ${archivePath} already holds a different settle record; reopen refused`,\n )\n }\n const at = new Date(now()).toISOString()\n if (mine === undefined) {\n await journal.appendEvent(runId, {\n kind: 'reopened',\n id: runId,\n operator: reopen.operator,\n reason: reopen.reason,\n operationId,\n prior: {\n kind: String(result.kind),\n ...(typeof result.reason === 'string' ? { reason: result.reason } : {}),\n digest,\n archivedAs,\n },\n ...(reopen.budget === undefined ? {} : { budget: reopen.budget }),\n seq: reopened.length,\n at,\n })\n }\n const eventId = `${runId}:pursuit:reopened:${operationId}`\n if (!(await observer.read()).some((record) => record.event?.id === eventId)) {\n await observer.appendEvent({\n id: eventId,\n pursuitId,\n runId,\n target: 'agent.run',\n phase: 'event',\n timestamp: now(),\n payload: { reopened: { operator: reopen.operator, reason: reopen.reason, archivedAs } },\n })\n }\n runFenced('reopenSettle', reopenSettleFenced, runDir, operationId, settlePath)\n}\n\n/** Set the settled run's cancellation aside and remove its settle record, under the fence. @internal */\nexport function reopenSettleFenced(runDir: string, operationId: string, settlePath: string): void {\n fenceRunWrite(() => {\n setCancellationAside(runDir, operationId)\n unlinkSync(settlePath)\n syncDurableDirectory(runDir)\n })\n}\n\n/** The next free `settles/<n>.json`, or the archive that already holds these bytes (a reopen that\n * crashed after archiving and before its journal row). */\nasync function archiveName(runDir: string, settled: string): Promise<string> {\n const dir = resolve(runDir, SETTLE_ARCHIVE_DIR)\n runFenced('makeRunDirectory', makeRunDirectoryFenced, dir)\n const numbers = readdirSync(dir)\n .map((name) => /^(\\d+)\\.json$/u.exec(name)?.[1])\n .filter((n): n is string => n !== undefined)\n .map(Number)\n .sort((a, b) => a - b)\n for (const n of numbers) {\n if ((await readBytes(join(dir, `${n}.json`))) === settled)\n return `${SETTLE_ARCHIVE_DIR}/${n}.json`\n }\n return `${SETTLE_ARCHIVE_DIR}/${(numbers.at(-1) ?? 0) + 1}.json`\n}\n\n/** Move the settled run's cancel request and acknowledgement aside under the reopen's and the\n * request's operation ids, so the reopened run accepts a new `cancelRun`. Idempotent: an absent\n * file is skipped. A reopen's operation id names one segment, so a later segment cancelled under\n * the same cancel operation id lands beside this one instead of over it. */\nfunction setCancellationAside(runDir: string, reopenOperationId: string): void {\n const requestFile = runCancelRequestFile(runDir)\n const ackFile = runCancellationFile(runDir)\n if (!existsSync(requestFile) && !existsSync(ackFile)) return\n const source = existsSync(requestFile) ? requestFile : ackFile\n const { operationId } = JSON.parse(readFileSync(source, 'utf8')) as {\n readonly operationId: string\n }\n const reopenedDir = join(workerCancellationsDir(runDir), 'reopened')\n const aside = join(\n reopenedDir,\n encodeURIComponent(reopenOperationId),\n encodeURIComponent(operationId),\n )\n mkdirSync(aside, { recursive: true })\n if (existsSync(ackFile)) renameSync(ackFile, join(aside, 'run.json'))\n if (existsSync(requestFile)) renameSync(requestFile, join(aside, 'run.request.json'))\n syncDurableDirectory(aside)\n syncDurableDirectory(join(reopenedDir, encodeURIComponent(reopenOperationId)))\n syncDurableDirectory(reopenedDir)\n syncDurableDirectory(workerCancellationsDir(runDir))\n}\n\nasync function readBytes(path: string): Promise<string | undefined> {\n try {\n return await readFile(path, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n throw error\n }\n}\n\n/** Create a directory inside the run under the fence. @internal */\nexport function make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W,GAAG,WAAW,aAAa,KAAK,OAAO,kBAAkB,CAAC;CACpF,qBAAqB,KAAK;CAC1B,qBAAqB,KAAK,aAAa,mBAAmB,iBAAiB,CAAC,CAAC;CAC7E,qBAAqB,WAAW;CAChC,qBAAqB,uBAAuB,MAAM,CAAC;AACrD;AAEA,eAAe,UAAU,MAA2C;CAClE,IAAI;EACF,OAAO,MAAM,SAAS,MAAM,MAAM;CACpC,SAAS,OAAO;EACd,IAAK,MAAgC,SAAS,UAAU,OAAO,KAAA;EAC/D,MAAM;CACR;AACF;;AAGA,SAAgB,uBAAuB,KAAmB;CACxD,oBAAoB,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC,CAAC;AACzD"}
|
|
1
|
+
{"version":3,"file":"run-reopen-KAnkEJV4.js","names":[],"sources":["../src/durable/run-reopen.ts"],"sourcesContent":["import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync } from 'node:fs'\nimport { readFile } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport {\n publishExclusiveDurableFile,\n syncDurableDirectory,\n} from '../runtime/supervise/durable-file'\nimport { runCancellationFile, runCancelRequestFile } from '../runtime/supervise/run-cancellation'\nimport { workerCancellationsDir } from '../runtime/supervise/run-layout'\nimport { assertValidBudget } from '../runtime/supervise/spend-validation'\nimport { assertResumeLimits } from '../runtime/supervise/supervisor-root-contract'\nimport type { Budget, SpawnEvent, SpawnJournal, SupervisorOpts } from '../runtime/supervise/types'\nimport { runFenced } from './durable-writer'\nimport type { FileObserverJournal } from './observer-journal'\nimport { fenceRunWrite } from './run-fence'\nimport { SETTLE_RECORD_FILE, settleRecordDigest } from './settle-record'\nimport { FileSpawnJournal } from './spawn-journal/journal-store'\n\n/*\n * Reopening a settled run under its own run id.\n *\n * A wrong settle used to be final: `supervisePursuit` refuses a directory that holds `result.json`,\n * and `fork` and `versions` each start a new run id in a new directory. Magnetar used 21 run ids\n * from 2026-10-16 to 10-21 for one solve; 16 of those runs settled, 11 of them in under 5 hours.\n *\n * A reopen archives the settled segment and resumes the same journal. Before it writes anything it\n * checks the resume limits (`assertResumeLimits`): a reopen refused for its budget or reservation\n * policy leaves `result.json`, the cancel files and the journal as they were. The profile's identity\n * and materialization are checked by `supervise` itself, after these steps. Every step is\n * idempotent, so a later call with the same `operationId` finishes a reopen that crashed partway:\n * 1. copy `result.json` byte for byte to `settles/<n>.json`;\n * 2. append one `reopened` spawn-journal row naming the operator, the reason and the archive;\n * 3. append one observer event, so the pursuit projection shows one lineage;\n * 4. move the run's cancel request and acknowledgement aside under this reopen's and that\n * request's operation ids, so a new `cancelRun` is accepted (one run carries one run-scoped\n * cancel operation) and no later reopen overwrites an earlier segment's cancel;\n * 5. last, remove `result.json`.\n * The caller then runs `supervise` with `resume: true`: settled children replay by key, the pool\n * is restored from the journal, and the next settle writes `result.json` again.\n */\n\n/** `supervisePursuit`'s `reopen` option: reopen this settled run under its own run id. */\nexport interface RunReopen {\n /** Who reopens the run. Required and non-empty. */\n readonly operator: string\n /** Why. Required and non-empty. */\n readonly reason: string\n /** Idempotency key: calling again with it finishes a reopen that crashed partway. */\n readonly operationId: string\n /**\n * The budget the reopened run is held to, recorded on its `reopened` row, which a later resume\n * must then match. Omit and the call's `budget` must equal the recorded one: the root's, or the\n * last budget a reopen recorded. A run that settled `budget-exhausted` and reopens without a\n * larger budget pauses at once (with `driverRetry.pauseRootStops`) or settles\n * `budget-exhausted` again. A deadline is measured from the original root instant, so a run\n * whose recorded deadline has passed settles `deadline` at once unless this budget drops the\n * deadline or moves it.\n */\n readonly budget?: Budget\n}\n\n/** The directory that holds a run's archived settle records. */\nexport const SETTLE_ARCHIVE_DIR = 'settles'\n\n/** Refuse a reopen that names no operator or reason, or that is combined with a fork or versions. */\nexport function assertRunReopen(\n reopen: RunReopen,\n opts: { readonly fork?: unknown; readonly versions?: unknown },\n): void {\n if (reopen.operator.trim().length === 0) {\n throw new TypeError('supervisePursuit: reopen.operator must be non-empty')\n }\n if (reopen.reason.trim().length === 0) {\n throw new TypeError('supervisePursuit: reopen.reason must be non-empty')\n }\n if (reopen.operationId.trim().length === 0) {\n throw new TypeError('supervisePursuit: reopen.operationId must be non-empty')\n }\n if (reopen.budget !== undefined) assertValidBudget(reopen.budget, 'reopen.budget')\n if (opts.fork !== undefined || opts.versions !== undefined) {\n throw new TypeError(\n 'supervisePursuit: reopen continues this run under its own id; fork and versions start new runs',\n )\n }\n}\n\n/**\n * Archive the settled segment of the run at `runDir` and clear it for a resume. Runs under the\n * directory lock. Throws when there is nothing to reopen, or when `operationId` already reopened a\n * segment that has since settled again.\n */\nexport async function reopenSettledRun(input: {\n readonly runDir: string\n readonly runId: string\n readonly reopen: RunReopen\n readonly journal: SpawnJournal | undefined\n /** The call's budget and reservation policy, checked against the recorded ones before any write. */\n readonly limits: Pick<SupervisorOpts, 'budget' | 'reservationPolicy'>\n readonly observer: FileObserverJournal\n readonly pursuitId: string\n readonly now: () => number\n}): Promise<void> {\n const { runDir, runId, reopen, observer, pursuitId, now } = input\n const operationId = reopen.operationId.trim()\n const settlePath = resolve(runDir, SETTLE_RECORD_FILE)\n const journal = input.journal ?? new FileSpawnJournal(resolve(runDir, 'spawn-journal.jsonl'))\n const events = (await journal.loadTree(runId)) ?? []\n const reopened = events.filter(\n (event): event is Extract<SpawnEvent, { kind: 'reopened' }> =>\n event.kind === 'reopened' && event.id === runId,\n )\n const mine = reopened.find((event) => event.operationId === operationId)\n const settled = await readBytes(settlePath)\n if (settled === undefined) {\n // Removing result.json is the last step, so a recorded reopen without it is complete.\n if (mine !== undefined) return\n throw new Error(\n `supervisePursuit: ${runDir} holds no ${SETTLE_RECORD_FILE}; nothing to reopen; resume it`,\n )\n }\n assertResumeLimits(\n events,\n {\n runId,\n budget: reopen.budget ?? input.limits.budget,\n ...(input.limits.reservationPolicy === undefined\n ? {}\n : { reservationPolicy: input.limits.reservationPolicy }),\n },\n mine === undefined ? reopen.budget : undefined,\n )\n const result = JSON.parse(settled) as { readonly kind?: unknown; readonly reason?: unknown }\n const digest = settleRecordDigest(result)\n if (mine !== undefined && mine.prior.digest !== digest) {\n throw new Error(\n `supervisePursuit: reopen '${operationId}' already reopened run '${runId}', which has settled again; reopen it under a new operationId`,\n )\n }\n const archivedAs = mine?.prior.archivedAs ?? (await archiveName(runDir, settled))\n const archivePath = resolve(runDir, archivedAs)\n if (\n !publishExclusiveDurableFile(archivePath, settled) &&\n (await readBytes(archivePath)) !== settled\n ) {\n throw new Error(\n `supervisePursuit: ${archivePath} already holds a different settle record; reopen refused`,\n )\n }\n const at = new Date(now()).toISOString()\n if (mine === undefined) {\n await journal.appendEvent(runId, {\n kind: 'reopened',\n id: runId,\n operator: reopen.operator,\n reason: reopen.reason,\n operationId,\n prior: {\n kind: String(result.kind),\n ...(typeof result.reason === 'string' ? { reason: result.reason } : {}),\n digest,\n archivedAs,\n },\n ...(reopen.budget === undefined ? {} : { budget: reopen.budget }),\n seq: reopened.length,\n at,\n })\n }\n const eventId = `${runId}:pursuit:reopened:${operationId}`\n if (!(await observer.read()).some((record) => record.event?.id === eventId)) {\n await observer.appendEvent({\n id: eventId,\n pursuitId,\n runId,\n target: 'agent.run',\n phase: 'event',\n timestamp: now(),\n payload: { reopened: { operator: reopen.operator, reason: reopen.reason, archivedAs } },\n })\n }\n runFenced('reopenSettle', reopenSettleFenced, runDir, operationId, settlePath)\n}\n\n/** Set the settled run's cancellation aside and remove its settle record, under the fence. @internal */\nexport function reopenSettleFenced(runDir: string, operationId: string, settlePath: string): void {\n fenceRunWrite(() => {\n setCancellationAside(runDir, operationId)\n unlinkSync(settlePath)\n syncDurableDirectory(runDir)\n })\n}\n\n/** The next free `settles/<n>.json`, or the archive that already holds these bytes (a reopen that\n * crashed after archiving and before its journal row). */\nasync function archiveName(runDir: string, settled: string): Promise<string> {\n const dir = resolve(runDir, SETTLE_ARCHIVE_DIR)\n runFenced('makeRunDirectory', makeRunDirectoryFenced, dir)\n const numbers = readdirSync(dir)\n .map((name) => /^(\\d+)\\.json$/u.exec(name)?.[1])\n .filter((n): n is string => n !== undefined)\n .map(Number)\n .sort((a, b) => a - b)\n for (const n of numbers) {\n if ((await readBytes(join(dir, `${n}.json`))) === settled)\n return `${SETTLE_ARCHIVE_DIR}/${n}.json`\n }\n return `${SETTLE_ARCHIVE_DIR}/${(numbers.at(-1) ?? 0) + 1}.json`\n}\n\n/** Move the settled run's cancel request and acknowledgement aside under the reopen's and the\n * request's operation ids, so the reopened run accepts a new `cancelRun`. Idempotent: an absent\n * file is skipped. A reopen's operation id names one segment, so a later segment cancelled under\n * the same cancel operation id lands beside this one instead of over it. */\nfunction setCancellationAside(runDir: string, reopenOperationId: string): void {\n const requestFile = runCancelRequestFile(runDir)\n const ackFile = runCancellationFile(runDir)\n if (!existsSync(requestFile) && !existsSync(ackFile)) return\n const source = existsSync(requestFile) ? requestFile : ackFile\n const { operationId } = JSON.parse(readFileSync(source, 'utf8')) as {\n readonly operationId: string\n }\n const reopenedDir = join(workerCancellationsDir(runDir), 'reopened')\n const aside = join(\n reopenedDir,\n encodeURIComponent(reopenOperationId),\n encodeURIComponent(operationId),\n )\n mkdirSync(aside, { recursive: true })\n if (existsSync(ackFile)) renameSync(ackFile, join(aside, 'run.json'))\n if (existsSync(requestFile)) renameSync(requestFile, join(aside, 'run.request.json'))\n syncDurableDirectory(aside)\n syncDurableDirectory(join(reopenedDir, encodeURIComponent(reopenOperationId)))\n syncDurableDirectory(reopenedDir)\n syncDurableDirectory(workerCancellationsDir(runDir))\n}\n\nasync function readBytes(path: string): Promise<string | undefined> {\n try {\n return await readFile(path, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n throw error\n }\n}\n\n/** Create a directory inside the run under the fence. @internal */\nexport function makeRunDirectoryFenced(dir: string): void {\n fenceRunWrite(() => mkdirSync(dir, { recursive: true }))\n}\n"],"mappings":";;;;;;;;;;;AA8DA,MAAa,qBAAqB;;AAGlC,SAAgB,gBACd,QACA,MACM;CACN,IAAI,OAAO,SAAS,K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AuB,MAAM,CAAC;AACrD;AAEA,eAAe,UAAU,MAA2C;CAClE,IAAI;EACF,OAAO,MAAM,SAAS,MAAM,MAAM;CACpC,SAAS,OAAO;EACd,IAAK,MAAgC,SAAS,UAAU,OAAO,KAAA;EAC/D,MAAM;CACR;AACF;;AAGA,SAAgB,uBAAuB,KAAmB;CACxD,oBAAoB,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC,CAAC;AACzD"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { c as readRunParking } from "./supervisor-
|
|
1
|
+
import { a as readRunCancelRequest } from "./run-cancellation-Bv7ooTJa.js";
|
|
2
|
+
import { c as readRunParking } from "./supervisor-BFs4u2Vo.js";
|
|
3
3
|
import { s as runDirectoryHolderIsLive } from "./run-lock-Ckakh1Uq.js";
|
|
4
|
-
import { a as readFailureRecord, o as readSettleRecord } from "./settle-record-
|
|
4
|
+
import { a as readFailureRecord, o as readSettleRecord } from "./settle-record-DMdeNy8A.js";
|
|
5
5
|
import { o as readCommittedJsonLines, t as isNoEntError } from "./jsonl-file-vE9H9UXa.js";
|
|
6
|
-
import {
|
|
6
|
+
import { Q as spawnJournalRecordEvents } from "./supervisor-accounting-CgipDzYg.js";
|
|
7
7
|
import { isRecord } from "@tangle-network/agent-core";
|
|
8
8
|
import { createHash } from "node:crypto";
|
|
9
9
|
import { join } from "node:path";
|
|
@@ -177,4 +177,4 @@ async function readRunState(runDir) {
|
|
|
177
177
|
}
|
|
178
178
|
export { readSpawnJournal as n, readRunState as t };
|
|
179
179
|
|
|
180
|
-
//# sourceMappingURL=run-state-
|
|
180
|
+
//# sourceMappingURL=run-state-Bcci4zIN.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-state-CZcFJjHn.js","names":[],"sources":["../src/durable/spawn-journal/read.ts","../src/durable/run-state.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport type { BigIntStats } from 'node:fs'\nimport { type FileHandle, open, stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { isRecord } from '@tangle-network/agent-core'\nimport type { NodeId, SpawnEvent } from '../../runtime/supervise/types'\nimport { isNoEntError, readCommittedJsonLines } from '../jsonl-file'\nimport { spawnJournalRecordEvents } from './record-events'\n\n/** Serializable checkpoint of a committed byte boundary, bound to one file and its bytes. */\nexport interface SpawnJournalCursor {\n readonly file: string\n readonly offset: number\n readonly boundary: string\n}\n\n/** Physical groups expand to event records; the owning tree is preserved for every event. */\nexport type SpawnJournalReadRecord =\n | { readonly kind: 'begin'; readonly root: NodeId; readonly at: string }\n | { readonly kind: 'event'; readonly root: NodeId; readonly event: SpawnEvent }\n\nexport interface SpawnJournalReadOptions {\n /** Read-only projections may skip malformed physical rows; execution readers stay strict. */\n readonly invalid?: 'throw' | 'skip'\n readonly after?: SpawnJournalCursor\n /** Initial opening-and-tail window, or an incremental page's byte budget. A crossing record\n * is read whole, so one large record can exceed this budget. Omit for complete history. */\n readonly tailBytes?: number\n}\n\nexport interface SpawnJournalReadResult {\n readonly records: ReadonlyArray<SpawnJournalReadRecord>\n /** Absent only when the journal does not exist. Treat as opaque and persist unchanged. */\n readonly cursor?: SpawnJournalCursor\n /** The supplied cursor no longer matches; this page starts over. */\n readonly reset: boolean\n /** An initial opening-and-tail window omitted records between its two windows. */\n readonly truncated: boolean\n /** Bytes after the committed cursor in this snapshot, including an incomplete final write. */\n readonly remainingBytes: number\n}\n\n/** Read a fixed journal prefix, with historical envelopes and framing owned by Runtime.\n * Missing journals return an empty page. Malformed committed records fail by default; incomplete final\n * writes remain unread for the next call. Cursors detect replacement, truncation and edits at\n * their sampled opening/boundary; they are not integrity proofs against arbitrary file edits.\n */\nexport async function readSpawnJournal(\n runDir: string,\n options: SpawnJournalReadOptions = {},\n): Promise<SpawnJournalReadResult> {\n const { after, tailBytes } = options\n if (tailBytes !== undefined && (!Number.isSafeInteger(tailBytes) || tailBytes < 1)) {\n throw new RangeError('readSpawnJournal: tailBytes must be a positive safe integer')\n }\n const path = join(runDir, 'spawn-journal.jsonl')\n let handle: FileHandle\n try {\n handle = await open(path, 'r')\n } catch (error) {\n if (isNoEntError(error)) {\n return { records: [], reset: after !== undefined, truncated: false, remainingBytes: 0 }\n }\n throw error\n }\n try {\n const snapshot = await handle.stat({ bigint: true })\n if (!snapshot.isFile()) throw new Error(`${path}: expected a regular file`)\n const size = Number(snapshot.size)\n const file = identity(snapshot)\n const resumed =\n after !== undefined &&\n after.file === file &&\n Number.isSafeInteger(after.offset) &&\n after.offset >= 0 &&\n after.offset <= size &&\n after.boundary === (await boundary(handle, after.offset))\n let offset = resumed ? after.offset : 0\n const records: SpawnJournalReadRecord[] = []\n const read = async (start: number, end: number, firstOnly = false): Promise<void> => {\n offset = start\n for await (const record of readCommittedJsonLines<unknown>(path, {\n handle,\n start,\n end,\n strictUtf8: true,\n invalid: options.invalid,\n onCommit: (committed) => {\n offset = committed\n },\n })) {\n if (\n !isRecord(record) ||\n typeof record.root !== 'string' ||\n (record.kind === 'begin' && typeof record.at !== 'string')\n ) {\n if (options.invalid === 'skip') continue\n throw new Error(`${path}: spawn journal record has no root or begin timestamp`)\n }\n if (record.kind === 'begin') {\n records.push({ kind: 'begin', root: record.root, at: record.at as string })\n } else {\n const events = spawnJournalRecordEvents(record, options.invalid)\n if (\n events.some(\n (event) =>\n !isRecord(event) || typeof event.kind !== 'string' || typeof event.id !== 'string',\n )\n ) {\n if (options.invalid === 'skip') continue\n throw new Error(`${path}: spawn journal record has no event identity`)\n }\n for (const event of events) records.push({ kind: 'event', root: record.root, event })\n }\n if (firstOnly) break\n }\n }\n let truncated = false\n if (!resumed && tailBytes !== undefined && size > tailBytes) {\n await read(0, size, true)\n const openingEnd = offset\n const tailStart = await lineBoundary(handle, size - tailBytes, size, -1)\n truncated = tailStart > openingEnd\n await read(Math.max(openingEnd, tailStart), size)\n // A long torn tail must not hide the latest committed activity before it.\n if (offset === tailStart && tailStart > openingEnd) {\n const previous = await lineBoundary(handle, tailStart - 1, size, -1)\n truncated = previous > openingEnd\n await read(Math.max(openingEnd, previous), tailStart)\n }\n } else {\n const end =\n resumed && tailBytes !== undefined && size - offset > tailBytes\n ? await lineBoundary(handle, offset + tailBytes, size, 1)\n : size\n await read(offset, end)\n }\n if (identity(await stat(path, { bigint: true })) !== file || (await handle.stat()).size < size)\n throw new Error(`${path}: journal changed while reading its committed prefix`)\n return {\n records,\n cursor: { file, offset, boundary: await boundary(handle, offset) },\n reset: after !== undefined && !resumed,\n truncated,\n remainingBytes: size - offset,\n }\n } finally {\n await handle.close()\n }\n}\n\nfunction identity(info: BigIntStats): string {\n return `${info.dev}:${info.ino}:${info.birthtimeNs}`\n}\n\nasync function bytes(handle: FileHandle, start: number, length: number): Promise<Buffer> {\n const buffer = Buffer.alloc(length)\n const { bytesRead } = await handle.read(buffer, 0, length, start)\n if (bytesRead !== length) throw new Error('spawn journal changed while reading its boundary')\n return buffer\n}\n\nasync function boundary(handle: FileHandle, offset: number): Promise<string> {\n const length = Math.min(offset, 128)\n return createHash('sha256')\n .update(await bytes(handle, 0, length))\n .update(await bytes(handle, offset - length, length))\n .digest('hex')\n}\n\n/** Include the record crossing a tail window or incremental page boundary. */\nasync function lineBoundary(\n handle: FileHandle,\n position: number,\n size: number,\n direction: -1 | 1,\n): Promise<number> {\n while (position > 0 && position < size) {\n const start = direction === -1 ? Math.max(0, position - 65_536) : position\n const end = direction === -1 ? position : Math.min(size, position + 65_536)\n const part = await bytes(handle, start, end - start)\n const newline = direction === -1 ? part.lastIndexOf(10) : part.indexOf(10)\n if (newline !== -1) return start + newline + 1\n position = direction === -1 ? start : end\n }\n return position\n}\n","import type { RuntimeFailureCause } from '../runtime/failure-cause'\nimport { type RunCancelRequest, readRunCancelRequest } from '../runtime/supervise/run-cancellation'\nimport { readRunParking } from '../runtime/supervise/run-parking'\nimport type { SupervisedResult } from '../runtime/supervise/types'\nimport { runDirectoryHolderIsLive } from './run-lock'\nimport { readFailureRecord, readSettleRecord } from './settle-record'\nimport { readSpawnJournal } from './spawn-journal/read'\n\n/** Runtime evidence only. Product-specific launch, checks and trace completeness belong to callers. */\nexport interface RunState {\n /** Absent when a recorded holder cannot be verified on this host. */\n readonly phase?: 'running' | 'parked' | 'cancelling' | 'settled' | 'down'\n /** A persisted typed root failure; legacy failure messages do not establish a code. */\n readonly failureCode?: RuntimeFailureCause['code']\n readonly settle?: SupervisedResult<unknown>\n readonly cancelRequest?: RunCancelRequest\n /** Absent when holder liveness is unknown. This is advisory, never ownership authorization. */\n readonly holderLive?: boolean\n /** Latest explicit Runtime timestamp observed, as ISO UTC; never a filesystem mtime. */\n readonly lastActivityAt?: string\n}\n\n/** Compose maintained record readers. Terminal settlement outranks cancellation and parking;\n * a request remains cancelling until settlement. An unheld run with evidence is down.\n * No Runtime evidence (including a missing or empty directory) returns undefined. Reads are\n * advisory snapshots across independently published files, not a transaction or a resume gate.\n */\nexport async function readRunState(runDir: string): Promise<RunState | undefined> {\n const [settle, failure, parking, holder, journal] = await Promise.all([\n readSettleRecord(runDir),\n readFailureRecord(runDir),\n readRunParking(runDir),\n runDirectoryHolderIsLive(runDir),\n readSpawnJournal(runDir, { tailBytes: 65_536 }),\n ])\n const cancelRequest = readRunCancelRequest(runDir)\n if (\n !settle &&\n !failure &&\n !parking &&\n !holder.holder &&\n !cancelRequest &&\n journal.records.length === 0\n ) {\n return undefined\n }\n const holderLive = holder.unknown ? undefined : holder.live\n const phase = settle\n ? 'settled'\n : cancelRequest\n ? 'cancelling'\n : parking\n ? 'parked'\n : holderLive === true\n ? 'running'\n : holderLive === false\n ? 'down'\n : undefined\n const root = settle?.tree.nodes?.find((node) => node.id === settle.tree.root)\n const failureCode =\n (settle?.kind === 'no-winner' && settle.reason === 'driver-failed'\n ? settle.error?.failure?.code\n : undefined) ?? root?.failure?.code\n let latest: number | undefined\n const observe = (at: string | number | undefined): void => {\n const timestamp = at === undefined ? undefined : new Date(at).getTime()\n if (timestamp !== undefined && Number.isFinite(timestamp)) {\n latest = latest === undefined ? timestamp : Math.max(latest, timestamp)\n }\n }\n observe(failure?.at)\n observe(parking?.since)\n observe(cancelRequest?.at)\n observe(holder.holder?.startedAt)\n for (const record of journal.records)\n observe(record.kind === 'begin' ? record.at : record.event.at)\n for (const node of settle?.tree.nodes ?? []) {\n observe(node.spawnedAt)\n observe(node.settledAt)\n }\n const lastActivityAt = latest === undefined ? undefined : new Date(latest).toISOString()\n return {\n ...(phase === undefined ? {} : { phase }),\n ...(failureCode === undefined ? {} : { failureCode }),\n ...(settle === undefined ? {} : { settle }),\n ...(cancelRequest === undefined ? {} : { cancelRequest }),\n ...(holderLive === undefined ? {} : { holderLive }),\n ...(lastActivityAt === undefined ? {} : { lastActivityAt }),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA+CA,eAAsB,iBACpB,QACA,UAAmC,CAAC,GACH;CACjC,MAAM,EAAE,OAAO,cAAc;CAC7B,IAAI,cAAc,KAAA,MAAc,CAAC,OAAO,cAAc,SAAS,KAAK,YAAY,IAC9E,MAAM,IAAI,WAAW,6DAA6D;CAEpF,MAAM,OAAO,KAAK,QAAQ,qBAAqB;CAC/C,IAAI;CACJ,IAAI;EACF,SAAS,MAAM,KAAK,MAAM,GAAG;CAC/B,SAAS,OAAO;EACd,IAAI,aAAa,KAAK,GACpB,OAAO;GAAE,SAAS,CAAC;GAAG,OAAO,UAAU,KAAA;GAAW,WAAW;GAAO,gBAAgB;EAAE;EAExF,MAAM;CACR;CACA,IAAI;EACF,MAAM,WAAW,MAAM,OAAO,KAAK,EAAE,QAAQ,KAAK,CAAC;EACnD,IAAI,CAAC,SAAS,OAAO,GAAG,MAAM,IAAI,MAAM,GAAG,KAAK,0BAA0B;EAC1E,MAAM,OAAO,OAAO,SAAS,IAAI;EACjC,MAAM,OAAO,SAAS,QAAQ;EAC9B,MAAM,UACJ,UAAU,KAAA,KACV,MAAM,SAAS,QACf,OAAO,cAAc,MAAM,MAAM,KACjC,MAAM,UAAU,KAChB,MAAM,UAAU,QAChB,MAA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C,CAAC,QAAQ;EACtE,IAAI,cAAc,KAAA,KAAa,OAAO,SAAS,SAAS,GACtD,SAAS,WAAW,KAAA,IAAY,YAAY,KAAK,IAAI,QAAQ,SAAS;CAE1E;CACA,QAAQ,SAAS,EAAE;CACnB,QAAQ,SAAS,KAAK;CACtB,QAAQ,eAAe,EAAE;CACzB,QAAQ,OAAO,QAAQ,SAAS;CAChC,KAAK,MAAM,UAAU,QAAQ,SAC3B,QAAQ,OAAO,SAAS,UAAU,OAAO,KAAK,OAAO,MAAM,EAAE;CAC/D,KAAK,MAAM,QAAQ,QAAQ,KAAK,SAAS,CAAC,GAAG;EAC3C,QAAQ,KAAK,SAAS;EACtB,QAAQ,KAAK,SAAS;CACxB;CACA,MAAM,iBAAiB,WAAW,KAAA,IAAY,KAAA,IAAY,IAAI,KAAK,MAAM,CAAC,CAAC,YAAY;CACvF,OAAO;EACL,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM;EACvC,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY;EACnD,GAAI,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO;EACzC,GAAI,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc;EACvD,GAAI,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW;EACjD,GAAI,mBAAmB,KAAA,IAAY,CAAC,IAAI,EAAE,eAAe;CAC3D;AACF"}
|
|
1
|
+
{"version":3,"file":"run-state-Bcci4zIN.js","names":[],"sources":["../src/durable/spawn-journal/read.ts","../src/durable/run-state.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport type { BigIntStats } from 'node:fs'\nimport { type FileHandle, open, stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { isRecord } from '@tangle-network/agent-core'\nimport type { NodeId, SpawnEvent } from '../../runtime/supervise/types'\nimport { isNoEntError, readCommittedJsonLines } from '../jsonl-file'\nimport { spawnJournalRecordEvents } from './record-events'\n\n/** Serializable checkpoint of a committed byte boundary, bound to one file and its bytes. */\nexport interface SpawnJournalCursor {\n readonly file: string\n readonly offset: number\n readonly boundary: string\n}\n\n/** Physical groups expand to event records; the owning tree is preserved for every event. */\nexport type SpawnJournalReadRecord =\n | { readonly kind: 'begin'; readonly root: NodeId; readonly at: string }\n | { readonly kind: 'event'; readonly root: NodeId; readonly event: SpawnEvent }\n\nexport interface SpawnJournalReadOptions {\n /** Read-only projections may skip malformed physical rows; execution readers stay strict. */\n readonly invalid?: 'throw' | 'skip'\n readonly after?: SpawnJournalCursor\n /** Initial opening-and-tail window, or an incremental page's byte budget. A crossing record\n * is read whole, so one large record can exceed this budget. Omit for complete history. */\n readonly tailBytes?: number\n}\n\nexport interface SpawnJournalReadResult {\n readonly records: ReadonlyArray<SpawnJournalReadRecord>\n /** Absent only when the journal does not exist. Treat as opaque and persist unchanged. */\n readonly cursor?: SpawnJournalCursor\n /** The supplied cursor no longer matches; this page starts over. */\n readonly reset: boolean\n /** An initial opening-and-tail window omitted records between its two windows. */\n readonly truncated: boolean\n /** Bytes after the committed cursor in this snapshot, including an incomplete final write. */\n readonly remainingBytes: number\n}\n\n/** Read a fixed journal prefix, with historical envelopes and framing owned by Runtime.\n * Missing journals return an empty page. Malformed committed records fail by default; incomplete final\n * writes remain unread for the next call. Cursors detect replacement, truncation and edits at\n * their sampled opening/boundary; they are not integrity proofs against arbitrary file edits.\n */\nexport async function readSpawnJournal(\n runDir: string,\n options: SpawnJournalReadOptions = {},\n): Promise<SpawnJournalReadResult> {\n const { after, tailBytes } = options\n if (tailBytes !== undefined && (!Number.isSafeInteger(tailBytes) || tailBytes < 1)) {\n throw new RangeError('readSpawnJournal: tailBytes must be a positive safe integer')\n }\n const path = join(runDir, 'spawn-journal.jsonl')\n let handle: FileHandle\n try {\n handle = await open(path, 'r')\n } catch (error) {\n if (isNoEntError(error)) {\n return { records: [], reset: after !== undefined, truncated: false, remainingBytes: 0 }\n }\n throw error\n }\n try {\n const snapshot = await handle.stat({ bigint: true })\n if (!snapshot.isFile()) throw new Error(`${path}: expected a regular file`)\n const size = Number(snapshot.size)\n const file = identity(snapshot)\n const resumed =\n after !== undefined &&\n after.file === file &&\n Number.isSafeInteger(after.offset) &&\n after.offset >= 0 &&\n after.offset <= size &&\n after.boundary === (await boundary(handle, after.offset))\n let offset = resumed ? after.offset : 0\n const records: SpawnJournalReadRecord[] = []\n const read = async (start: number, end: number, firstOnly = false): Promise<void> => {\n offset = start\n for await (const record of readCommittedJsonLines<unknown>(path, {\n handle,\n start,\n end,\n strictUtf8: true,\n invalid: options.invalid,\n onCommit: (committed) => {\n offset = committed\n },\n })) {\n if (\n !isRecord(record) ||\n typeof record.root !== 'string' ||\n (record.kind === 'begin' && typeof record.at !== 'string')\n ) {\n if (options.invalid === 'skip') continue\n throw new Error(`${path}: spawn journal record has no root or begin timestamp`)\n }\n if (record.kind === 'begin') {\n records.push({ kind: 'begin', root: record.root, at: record.at as string })\n } else {\n const events = spawnJournalRecordEvents(record, options.invalid)\n if (\n events.some(\n (event) =>\n !isRecord(event) || typeof event.kind !== 'string' || typeof event.id !== 'string',\n )\n ) {\n if (options.invalid === 'skip') continue\n throw new Error(`${path}: spawn journal record has no event identity`)\n }\n for (const event of events) records.push({ kind: 'event', root: record.root, event })\n }\n if (firstOnly) break\n }\n }\n let truncated = false\n if (!resumed && tailBytes !== undefined && size > tailBytes) {\n await read(0, size, true)\n const openingEnd = offset\n const tailStart = await lineBoundary(handle, size - tailBytes, size, -1)\n truncated = tailStart > openingEnd\n await read(Math.max(openingEnd, tailStart), size)\n // A long torn tail must not hide the latest committed activity before it.\n if (offset === tailStart && tailStart > openingEnd) {\n const previous = await lineBoundary(handle, tailStart - 1, size, -1)\n truncated = previous > openingEnd\n await read(Math.max(openingEnd, previous), tailStart)\n }\n } else {\n const end =\n resumed && tailBytes !== undefined && size - offset > tailBytes\n ? await lineBoundary(handle, offset + tailBytes, size, 1)\n : size\n await read(offset, end)\n }\n if (identity(await stat(path, { bigint: true })) !== file || (await handle.stat()).size < size)\n throw new Error(`${path}: journal changed while reading its committed prefix`)\n return {\n records,\n cursor: { file, offset, boundary: await boundary(handle, offset) },\n reset: after !== undefined && !resumed,\n truncated,\n remainingBytes: size - offset,\n }\n } finally {\n await handle.close()\n }\n}\n\nfunction identity(info: BigIntStats): string {\n return `${info.dev}:${info.ino}:${info.birthtimeNs}`\n}\n\nasync function bytes(handle: FileHandle, start: number, length: number): Promise<Buffer> {\n const buffer = Buffer.alloc(length)\n const { bytesRead } = await handle.read(buffer, 0, length, start)\n if (bytesRead !== length) throw new Error('spawn journal changed while reading its boundary')\n return buffer\n}\n\nasync function boundary(handle: FileHandle, offset: number): Promise<string> {\n const length = Math.min(offset, 128)\n return createHash('sha256')\n .update(await bytes(handle, 0, length))\n .update(await bytes(handle, offset - length, length))\n .digest('hex')\n}\n\n/** Include the record crossing a tail window or incremental page boundary. */\nasync function lineBoundary(\n handle: FileHandle,\n position: number,\n size: number,\n direction: -1 | 1,\n): Promise<number> {\n while (position > 0 && position < size) {\n const start = direction === -1 ? Math.max(0, position - 65_536) : position\n const end = direction === -1 ? position : Math.min(size, position + 65_536)\n const part = await bytes(handle, start, end - start)\n const newline = direction === -1 ? part.lastIndexOf(10) : part.indexOf(10)\n if (newline !== -1) return start + newline + 1\n position = direction === -1 ? start : end\n }\n return position\n}\n","import type { RuntimeFailureCause } from '../runtime/failure-cause'\nimport { type RunCancelRequest, readRunCancelRequest } from '../runtime/supervise/run-cancellation'\nimport { readRunParking } from '../runtime/supervise/run-parking'\nimport type { SupervisedResult } from '../runtime/supervise/types'\nimport { runDirectoryHolderIsLive } from './run-lock'\nimport { readFailureRecord, readSettleRecord } from './settle-record'\nimport { readSpawnJournal } from './spawn-journal/read'\n\n/** Runtime evidence only. Product-specific launch, checks and trace completeness belong to callers. */\nexport interface RunState {\n /** Absent when a recorded holder cannot be verified on this host. */\n readonly phase?: 'running' | 'parked' | 'cancelling' | 'settled' | 'down'\n /** A persisted typed root failure; legacy failure messages do not establish a code. */\n readonly failureCode?: RuntimeFailureCause['code']\n readonly settle?: SupervisedResult<unknown>\n readonly cancelRequest?: RunCancelRequest\n /** Absent when holder liveness is unknown. This is advisory, never ownership authorization. */\n readonly holderLive?: boolean\n /** Latest explicit Runtime timestamp observed, as ISO UTC; never a filesystem mtime. */\n readonly lastActivityAt?: string\n}\n\n/** Compose maintained record readers. Terminal settlement outranks cancellation and parking;\n * a request remains cancelling until settlement. An unheld run with evidence is down.\n * No Runtime evidence (including a missing or empty directory) returns undefined. Reads are\n * advisory snapshots across independently published files, not a transaction or a resume gate.\n */\nexport async function readRunState(runDir: string): Promise<RunState | undefined> {\n const [settle, failure, parking, holder, journal] = await Promise.all([\n readSettleRecord(runDir),\n readFailureRecord(runDir),\n readRunParking(runDir),\n runDirectoryHolderIsLive(runDir),\n readSpawnJournal(runDir, { tailBytes: 65_536 }),\n ])\n const cancelRequest = readRunCancelRequest(runDir)\n if (\n !settle &&\n !failure &&\n !parking &&\n !holder.holder &&\n !cancelRequest &&\n journal.records.length === 0\n ) {\n return undefined\n }\n const holderLive = holder.unknown ? undefined : holder.live\n const phase = settle\n ? 'settled'\n : cancelRequest\n ? 'cancelling'\n : parking\n ? 'parked'\n : holderLive === true\n ? 'running'\n : holderLive === false\n ? 'down'\n : undefined\n const root = settle?.tree.nodes?.find((node) => node.id === settle.tree.root)\n const failureCode =\n (settle?.kind === 'no-winner' && settle.reason === 'driver-failed'\n ? settle.error?.failure?.code\n : undefined) ?? root?.failure?.code\n let latest: number | undefined\n const observe = (at: string | number | undefined): void => {\n const timestamp = at === undefined ? undefined : new Date(at).getTime()\n if (timestamp !== undefined && Number.isFinite(timestamp)) {\n latest = latest === undefined ? timestamp : Math.max(latest, timestamp)\n }\n }\n observe(failure?.at)\n observe(parking?.since)\n observe(cancelRequest?.at)\n observe(holder.holder?.startedAt)\n for (const record of journal.records)\n observe(record.kind === 'begin' ? record.at : record.event.at)\n for (const node of settle?.tree.nodes ?? []) {\n observe(node.spawnedAt)\n observe(node.settledAt)\n }\n const lastActivityAt = latest === undefined ? undefined : new Date(latest).toISOString()\n return {\n ...(phase === undefined ? {} : { phase }),\n ...(failureCode === undefined ? {} : { failureCode }),\n ...(settle === undefined ? {} : { settle }),\n ...(cancelRequest === undefined ? {} : { cancelRequest }),\n ...(holderLive === undefined ? {} : { holderLive }),\n ...(lastActivityAt === undefined ? {} : { lastActivityAt }),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA+CA,eAAsB,iBACpB,QACA,UAAmC,CAAC,GACH;CACjC,MAAM,EAAE,OAAO,cAAc;CAC7B,IAAI,cAAc,KAAA,MAAc,CAAC,OAAO,cAAc,SAAS,KAAK,YAAY,IAC9E,MAAM,IAAI,WAAW,6DAA6D;CAEpF,MAAM,OAAO,KAAK,QAAQ,qBAAqB;CAC/C,IAAI;CACJ,IAAI;EACF,SAAS,MAAM,KAAK,MAAM,GAAG;CAC/B,SAAS,OAAO;EACd,IAAI,aAAa,KAAK,GACpB,OAAO;GAAE,SAAS,CAAC;GAAG,OAAO,UAAU,KAAA;GAAW,WAAW;GAAO,gBAAgB;EAAE;EAExF,MAAM;CACR;CACA,IAAI;EACF,MAAM,WAAW,MAAM,OAAO,KAAK,EAAE,QAAQ,KAAK,CAAC;EACnD,IAAI,CAAC,SAAS,OAAO,GAAG,MAAM,IAAI,MAAM,GAAG,KAAK,0BAA0B;EAC1E,MAAM,OAAO,OAAO,SAAS,IAAI;EACjC,MAAM,OAAO,SAAS,QAAQ;EAC9B,MAAM,UACJ,UAAU,KAAA,KACV,MAAM,SAAS,QACf,OAAO,cAAc,MAAM,MAAM,KACjC,MAAM,UAAU,KAChB,MAAM,UAAU,QAChB,MAAM,aAAc,MAAM,SAAS,QAAQ,MAAM,MAAM;EACzD,IAAI,SAAS,UAAU,MAAM,SAAS;EACtC,MAAM,UAAoC,CAAC;EAC3C,MAAM,OAAO,OAAO,OAAe,KAAa,YAAY,UAAyB;GACnF,SAAS;GACT,WAAW,MAA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AK;CACtB,QAAQ,eAAe,EAAE;CACzB,QAAQ,OAAO,QAAQ,SAAS;CAChC,KAAK,MAAM,UAAU,QAAQ,SAC3B,QAAQ,OAAO,SAAS,UAAU,OAAO,KAAK,OAAO,MAAM,EAAE;CAC/D,KAAK,MAAM,QAAQ,QAAQ,KAAK,SAAS,CAAC,GAAG;EAC3C,QAAQ,KAAK,SAAS;EACtB,QAAQ,KAAK,SAAS;CACxB;CACA,MAAM,iBAAiB,WAAW,KAAA,IAAY,KAAA,IAAY,IAAI,KAAK,MAAM,CAAC,CAAC,YAAY;CACvF,OAAO;EACL,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM;EACvC,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY;EACnD,GAAI,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO;EACzC,GAAI,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc;EACvD,GAAI,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW;EACjD,GAAI,mBAAmB,KAAA,IAAY,CAAC,IAAI,EAAE,eAAe;CAC3D;AACF"}
|
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
import { A as readPromptOptions, F as defaultSelectWinner, H as routerBrain, M as createSandboxLineage, O as runAgentRounds, St as verdictFromJudgeScore, Y as createWorktreeCliExecutor, b as InMemorySpawnJournal, bt as gateOnDeliverable, k as assertBoxlessPromptOptions, n as createSupervisor, v as withDriverExecutor, vt as CheckUnavailableError, w as createExecutor, x as createExecutorRegistry, xt as mapExecutorResult, y as InMemoryResultBlobStore } from "./supervisor-
|
|
2
|
-
import {
|
|
3
|
-
import "./run-state-
|
|
4
|
-
import {
|
|
5
|
-
import "./result-blob-store-
|
|
6
|
-
import { E as validateFlowGraph, I as kernelPromptRegistry, b as coordinationControlToolNames, k as validateGraphTopology, m as runBrainLoop, t as supervise } from "./supervise-
|
|
1
|
+
import { A as readPromptOptions, F as defaultSelectWinner, H as routerBrain, M as createSandboxLineage, O as runAgentRounds, St as verdictFromJudgeScore, Y as createWorktreeCliExecutor, b as InMemorySpawnJournal, bt as gateOnDeliverable, k as assertBoxlessPromptOptions, n as createSupervisor, v as withDriverExecutor, vt as CheckUnavailableError, w as createExecutor, x as createExecutorRegistry, xt as mapExecutorResult, y as InMemoryResultBlobStore } from "./supervisor-BFs4u2Vo.js";
|
|
2
|
+
import { At as recordValue, P as contentAddress, St as notifySandboxEventObserver, r as runtimeFailureCauseSchema, vt as createSandboxTurnEventCollector } from "./failure-cause-DvYGlOEV.js";
|
|
3
|
+
import "./run-state-Bcci4zIN.js";
|
|
4
|
+
import { B as isTraceAnalysisStore, Kt as coordinationProfileToolPrefix, cr as harnessTranscriptArtifact, gn as insideCursorNamespace, hr as readBoundHarnessSessions, ni as executableAgentProfileSnapshot, ot as rollingDispatch, ri as executableAgentSpecSnapshot, tt as settledToIteration } from "./supervisor-accounting-CgipDzYg.js";
|
|
5
|
+
import "./result-blob-store-BMMzqpHa.js";
|
|
6
|
+
import { E as validateFlowGraph, I as kernelPromptRegistry, b as coordinationControlToolNames, k as validateGraphTopology, m as runBrainLoop, t as supervise } from "./supervise-D7jtypE-.js";
|
|
7
7
|
import { T as zeroSpend, a as cloneSpend, c as errorMessage, d as isAbortError, f as isAsyncIterable, h as randomSuffix, i as chargedTokens, l as fnv1a32Hex, n as addSpend, p as mapWithConcurrency, u as hasCompleteCacheBreakdown, v as sleep, y as stringifySafe } from "./util-qsH5cC9S.js";
|
|
8
8
|
import { a as captureMaterializedWorkspace, b as sha256Bytes$1, m as canonicalCandidateDigest$1, v as immutableCandidateValue } from "./output-artifacts-AqkZ8lO2.js";
|
|
9
9
|
import { i as ConfigError, m as ValidationError, n as AnalystError, s as PlannerError } from "./errors-DG8yufqX.js";
|
|
10
|
-
import { c as runIsolatedCheck, l as createIsolatedCheckCpuSession } from "./graph-
|
|
10
|
+
import { c as runIsolatedCheck, l as createIsolatedCheckCpuSession } from "./graph-CiApRth2.js";
|
|
11
11
|
import { a as concreteProfileModel, c as profileModelExecutionSettings, i as concreteModelId, l as profileProviderModel, o as enforceTokenLimits, p as canonicalObservedModelParts, t as assertExecutableAgentProfile, y as harnessRunsAgent } from "./model-policy-DTbTFyOG.js";
|
|
12
12
|
import { i as redactProtectedValue, r as redactProtectedReason } from "./protected-redaction-DilFZch5.js";
|
|
13
13
|
import { o as armDeadlineTimer } from "./deadline-CySmJ_0S.js";
|
|
14
|
-
import { D as runAgentic, E as refine, M as renderReport, N as profileChatClient, O as sample, j as observe, k as ObservationError, v as loadAuthoredStrategy, x as strategyAuthorContract, y as requestStrategySource } from "./structural-rollout-
|
|
14
|
+
import { D as runAgentic, E as refine, M as renderReport, N as profileChatClient, O as sample, j as observe, k as ObservationError, v as loadAuthoredStrategy, x as strategyAuthorContract, y as requestStrategySource } from "./structural-rollout-DOmjcEMD.js";
|
|
15
15
|
import { _ as runAbortable, a as readCommittedJsonFile, c as withJsonlFileLock, l as appendCommittedJsonLine, o as readCommittedJsonLines, s as upsertCommittedJsonLine, t as isNoEntError } from "./jsonl-file-vE9H9UXa.js";
|
|
16
16
|
import { n as detachedSnapshot, t as detachedFrozen } from "./snapshot-BKI_w3JD.js";
|
|
17
17
|
import { y as markPutStreamVerified } from "./workspace-streams-C7PGLAUd.js";
|
|
18
|
-
import "./provision-supervisor-
|
|
18
|
+
import "./provision-supervisor-DLOeyFHV.js";
|
|
19
19
|
import { i as notifyRuntimeHookEvent } from "./runtime-hooks-CsW2pfFk.js";
|
|
20
|
-
import { a as reconcileInterruptedSearchCalls, c as searchExecutor, r as dedicatedLane, x as runtimeShipDecision } from "./search-executor-
|
|
21
|
-
import "./delegate-
|
|
20
|
+
import { a as reconcileInterruptedSearchCalls, c as searchExecutor, r as dedicatedLane, x as runtimeShipDecision } from "./search-executor-Dn5YmHsg.js";
|
|
21
|
+
import "./delegate-BFP1uCNY.js";
|
|
22
22
|
import "./continuation-Bccak14N.js";
|
|
23
23
|
import { S as graphRouteWhenSchema, _ as compileGraphParameters, a as graphRegistry, d as recordGraphRun, g as bindGraphParameters, h as assertGraphTriggerBindings, i as graphFromStored, j as assertJsonData, l as lookupGraph, m as taskShapeDigest, o as graphRunsFor, r as graphDigest, t as digestOfGraph, v as graphTriggerBindingsSchema, x as graphFileSchema, y as graphCheckNodeSchema } from "./graph-registry-CRskE_Yp.js";
|
|
24
|
-
import { d as foldCoordinationRecords } from "./supervise-identity-
|
|
25
|
-
import { p as createInMemoryRunContext, s as downMessageRefusalReasons } from "./driver-control-acknowledgers-
|
|
24
|
+
import { d as foldCoordinationRecords } from "./supervise-identity-QavM_M4r.js";
|
|
25
|
+
import { p as createInMemoryRunContext, s as downMessageRefusalReasons } from "./driver-control-acknowledgers-jdlf49OQ.js";
|
|
26
26
|
import { u as writeAtomicDurableFile } from "./durable-file-pao7FijS.js";
|
|
27
|
-
import "./run-cancellation-
|
|
27
|
+
import "./run-cancellation-Bv7ooTJa.js";
|
|
28
28
|
import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, sameAgentRunControlRef, sha256Bytes, sha256DigestSchema, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
|
|
29
29
|
import { CODING_HARNESSES, DEFAULT_TRACE_ANALYST_KINDS, InMemoryTraceStore, OUTPUT_VALUE, benjaminiHochberg, buildTrajectory, computeFindingId as computeFindingId$1, confidenceInterval, createTraceAnalyst, expandProfileAxes, makeFinding as makeFinding$1, meanConfidenceInterval, pairedBootstrap, paretoFrontier, wilcoxonSignedRank, wilson } from "@tangle-network/agent-eval";
|
|
30
30
|
import { createAgentRunOutcomeTracker } from "@tangle-network/sandbox/runtime";
|
|
@@ -7387,7 +7387,7 @@ async function expandProfile(node, options) {
|
|
|
7387
7387
|
...selected.reasoningEffort === void 0 ? {} : { reasoningEffort: selected.reasoningEffort }
|
|
7388
7388
|
};
|
|
7389
7389
|
}
|
|
7390
|
-
if (node.needs) {
|
|
7390
|
+
if (node.needs && (connections.length > 0 || node.profile?.connections !== void 0)) {
|
|
7391
7391
|
const seen = /* @__PURE__ */ new Set();
|
|
7392
7392
|
profile.connections = [...node.profile?.connections ?? [], ...connections].filter((connection) => {
|
|
7393
7393
|
let key;
|
|
@@ -9975,4 +9975,4 @@ function tail(s) {
|
|
|
9975
9975
|
}
|
|
9976
9976
|
export { strategyTournament as $, completionAuthorizes as $t, searchPresets as A, readHarnessTranscriptSessions as At, graphFromSessionFacts as B, resolveMcpServerLaunch as Bt, withUntrackedArtifacts as C, createScopeAnalyst as Ct, SEARCH_SPEC_CORRELATION_KEY as D, inProcessSandboxClient as Dt, createFencedSqlRunContext as E, observationFromRegistry as Et, loadProfile as F, materializeLocalMcp as Ft, readGraphStrings as G, loopDispatch as Gt, graphWorkspace as H, secretEnvOfMcpServer as Ht, pickBestProfile as I, createMcpEnvironment as It, graphDesignerExtraTools as J, checkProgramDigest as Jt, setGraphProfile as K, superviseDispatch as Kt, profileRegistry as L, sanitizeMcpToolSchema as Lt, connectRemoteSupervisor as M, resolveSandboxClient as Mt, connectRemoteSupervisorControl as N, McpSpawnFault as Nt, assertSearchSpec as O, HarvestError as Ot, bestProfileFor as P, connectStdioMcp as Pt, runStrategyEvolution as Q, readDeclaredCheck as Qt, profileRunsForName as R, envKeyProvider as Rt, copyUntrackedIntoClone as S, buildSteerContext as St, validateStoredGraph as T, measurePairedCommands as Tt, loadGraphFile as U, inlineSandboxClient as Ut, GraphFileResolutionError as V, resolveSecretEnv as Vt, readGraphProfile as W, loopCampaignDispatch as Wt, chatWorkerSeam as X, declaredCheckDigest as Xt, chatTransportExecutor as Y, declaredCheckDeliverable as Yt, createChatSessionStore as Z, declaredCheckJudge as Zt, NOTE_MAX_CHARS as _, pipeline as _t, localShell as a, renderLeaderboardHtml as an, createPrivateCasArtifactPort as at, composeWorkerEvidence as b, widen as bt, createVerifierEnvironment as c, renderPairwiseMarkdown as cn, definePersona as ct, harvestSurfaceDiffs as d, InMemoryCorpus as dt, deterministicCompletion as en, SandboxRunAbortError as et, analystsFromRegistry as f, renderCorpusToInstructions as ft, EVIDENCE_MAX_CHARS as g, panel as gt, runCoderChecks as h, loopUntil as ht, jjWorkspace as i, pairwiseSignificance as in, runBenchmark as it, searchSpecDigest as j, defineLeaderboard as jt, compileSearchSpec as k, harvestCorpus as kt, boxSurfaceReader as l, SqlRunOwnershipError as ln, runPersonified as lt, worktreeFanout as m, flatWidenGate as mt, makeFinding$1 as n, stopSentinel as nn, createS3PrivateCasStore as nt, runInWorkspace as o, renderLeaderboardMarkdown as on, equalKOnCost as ot, failuresAnalyst as p, fanout as pt, setGraphStrings as q, assertDeclaredCheck as qt, gitWorkspace as r, leaderboard as rn, printBenchmarkReport as rt, createWaterfallCollector as s, renderLeaderboardSvg as sn, trajectoryReport as st, computeFindingId$1 as t, sentinelCompletion as tn, openSandboxRun as tt, fsSurfaceReader as u, openSqlRunStore as un, FileCorpus as ut, VERIFY_TAIL_CHARS as v, selectValidWinner as vt, analyzeTrace as w, registryScopeAnalyst as wt, settledWorkerOut as x, assertTraceDerivedFindings as xt, closingWorkerNote as y, verify as yt, recordProfileRun as z, mcpSecretEnvMetadataKey as zt };
|
|
9977
9977
|
|
|
9978
|
-
//# sourceMappingURL=runtime-
|
|
9978
|
+
//# sourceMappingURL=runtime-DCo0OP4n.js.map
|