pi-durable-subagents 1.5.1 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/README.md +69 -14
- package/dist/agent/capabilities.js +5 -4
- package/dist/agent/child/live.js +2 -1
- package/dist/agent/exact/capture.js +3 -2
- package/dist/agent/main/snapshots.js +10 -9
- package/dist/agent/main.js +2 -1
- package/dist/cli/chaos/stack.js +53 -21
- package/dist/cli/control.js +4 -3
- package/dist/cli/doctor.js +3 -1
- package/dist/cli/drill/index.js +35 -17
- package/dist/cli/hold.js +221 -16
- package/dist/cli/restart.js +14 -2
- package/dist/cli/service.js +77 -2
- package/dist/cli/smoke.js +10 -6
- package/dist/compat/agents.js +46 -13
- package/dist/events/log.js +33 -11
- package/dist/kernel/cache.js +3 -2
- package/dist/kernel/fsx.js +203 -0
- package/dist/kernel/ids.js +11 -0
- package/dist/kernel/journal.js +42 -25
- package/dist/kernel/mailbox.js +7 -4
- package/dist/orchestrator/engine.js +49 -46
- package/dist/orchestrator/evaluator-client.js +11 -3
- package/dist/orchestrator/executor/command.js +21 -6
- package/dist/orchestrator/executor/effects/gate.js +291 -56
- package/dist/orchestrator/executor/effects/index.js +3 -4
- package/dist/orchestrator/executor/effects/output.js +9 -5
- package/dist/orchestrator/executor/effects/prepare.js +34 -32
- package/dist/orchestrator/executor/effects/worktree-path.js +102 -0
- package/dist/orchestrator/executor/ended.js +7 -3
- package/dist/orchestrator/executor/index.js +216 -62
- package/dist/orchestrator/executor/memory.js +15 -0
- package/dist/orchestrator/executor/session.js +4 -3
- package/dist/orchestrator/executor/sweep.js +34 -1
- package/dist/orchestrator/executor/worktree.js +1 -1
- package/dist/orchestrator/main.js +4 -2
- package/dist/orchestrator/reader-ledger.js +3 -2
- package/dist/orchestrator/settled.js +2 -1
- package/dist/orchestrator/snapshot.js +24 -19
- package/dist/orchestrator/stats.js +2 -1
- package/dist/orchestrator/store.js +3 -2
- package/dist/platform/cmdline.js +3 -0
- package/dist/platform/command.js +184 -20
- package/dist/platform/containment.js +204 -40
- package/dist/platform/job.js +1404 -0
- package/dist/platform/launch.js +157 -23
- package/dist/platform/lease.js +351 -32
- package/dist/platform/lock.js +464 -16
- package/dist/platform/proctable.js +31 -2
- package/dist/platform/windows.js +642 -0
- package/dist/requests.js +1 -1
- package/dist/ui/data.js +7 -6
- package/dist/ui/session.js +6 -5
- package/package.json +3 -3
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// P32: the spelling of a call's worktree path and branch, and the identity of a path as the file system holds it.
|
|
2
|
+
// A call key is an opaque name inside its workflow's directory (`.dsa/<wid>`): a key that is path-like (a Win32
|
|
3
|
+
// separator, a traversal part, an absolute, drive-qualified or UNC spelling) is refused, and every other key keeps its
|
|
4
|
+
// own spelling, so POSIX journals name exactly what they always named. Win32 cannot spell some names (`tasks:0`, `CON`,
|
|
5
|
+
// `x.`, `a*b`), so on Windows such a key lives under `.keys/<hash>`: a literal key may not begin with `.keys`, so the
|
|
6
|
+
// encoded namespace is disjoint from every literal spelling, even where the file system ignores case. The rules are pure
|
|
7
|
+
// functions of the key and the platform, so the Windows decisions are testable anywhere.
|
|
8
|
+
import { realpathSync } from "node:fs";
|
|
9
|
+
import { basename, dirname, join, posix, win32 } from "node:path";
|
|
10
|
+
import { contentHash } from "../../../kernel/ids.js";
|
|
11
|
+
/** The one directory under `.dsa/<wid>` that only encoded keys name; no literal key starts with it on Windows. */
|
|
12
|
+
export const encodedDir = ".keys";
|
|
13
|
+
/** Win32 reserves these names for devices, with or without an extension and in any case. */
|
|
14
|
+
const device = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i;
|
|
15
|
+
/** Reject a key that is not an opaque name inside its workflow's directory. A key never names a path: `a:0` is a name
|
|
16
|
+
* Win32 cannot spell (it is encoded), while `C:\x`, `C:/x`, `\\server\share`, `/abs` and `..` are paths and are
|
|
17
|
+
* refused, so no key can ever resolve outside `.dsa/<wid>`. */
|
|
18
|
+
export function checkKey(key) {
|
|
19
|
+
if (key.includes("\\") || /^[A-Za-z]:([\\/]|$)/.test(key))
|
|
20
|
+
throw new Error("Invalid worktree key");
|
|
21
|
+
if (key.split("/").some(part => !part || part === "." || part === ".."))
|
|
22
|
+
throw new Error("Invalid worktree key");
|
|
23
|
+
}
|
|
24
|
+
/** Whether Win32 can create a directory spelled exactly like `part`: no character it forbids, no trailing dot or space
|
|
25
|
+
* (Win32 drops those), and not a reserved device name. */
|
|
26
|
+
export function win32Name(part) {
|
|
27
|
+
return Boolean(part) && part !== "." && part !== ".." && !/[<>:"|?*\\/\x00-\x1f]/.test(part) && !/[. ]$/.test(part) && !device.test(part);
|
|
28
|
+
}
|
|
29
|
+
/** Whether a key keeps its own spelling on `platform`: always on POSIX (journals name what they always named), and on
|
|
30
|
+
* Windows when every part is a Win32 name and the first part is not the encoded namespace's. */
|
|
31
|
+
export function literalKey(key, platform = process.platform) {
|
|
32
|
+
if (platform !== "win32")
|
|
33
|
+
return true;
|
|
34
|
+
const parts = key.split("/");
|
|
35
|
+
return parts.every(win32Name) && parts[0].toLowerCase() !== encodedDir;
|
|
36
|
+
}
|
|
37
|
+
/** The spelling of a key's worktree relative to `.dsa/<wid>`: its own, or — where the platform cannot spell it — the
|
|
38
|
+
* encoded namespace with the key's hash (deterministic, one-to-one, and outside every literal name). */
|
|
39
|
+
export function keyDir(key, platform = process.platform) {
|
|
40
|
+
checkKey(key);
|
|
41
|
+
return literalKey(key, platform) ? key : `${encodedDir}/${contentHash(key)}`;
|
|
42
|
+
}
|
|
43
|
+
/** The branch of a key's worktree: `dsa/<wid>/<key>`, or — for a key a ref cannot spell (`:`) or one whose path is
|
|
44
|
+
* encoded — the hashed namespace, so no two keys share a branch. */
|
|
45
|
+
export function keyBranch(wid, key, platform = process.platform) {
|
|
46
|
+
checkKey(key);
|
|
47
|
+
return key.includes(":") || !literalKey(key, platform) ? `dsa-colon/${wid}/${contentHash(key)}` : `dsa/${wid}/${key}`;
|
|
48
|
+
}
|
|
49
|
+
/** The identity of a path as the file system holds it: the native spelling its nearest existing ancestor has (on Windows
|
|
50
|
+
* the long form `C:\Users\runneradmin\...` under its on-disk case, on macOS `/private/var` for `/var`) extended by the
|
|
51
|
+
* parts that do not exist yet, so a worktree Git has not created still compares. */
|
|
52
|
+
export function nativePath(path) {
|
|
53
|
+
let dir = path, rest = "";
|
|
54
|
+
for (;;) {
|
|
55
|
+
try {
|
|
56
|
+
return join(realpathSync.native(dir), rest);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
const up = dirname(dir);
|
|
60
|
+
if (up === dir)
|
|
61
|
+
return path;
|
|
62
|
+
rest = join(basename(dir), rest);
|
|
63
|
+
dir = up;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/** How Win32 spells one path: `\\?\C:\x` and `\\?\UNC\s\share\x` are the extended forms of `C:\x` and `\\s\share\x`,
|
|
68
|
+
* either separator is the same one, `.` and repeated separators collapse, a trailing separator is not part of the name,
|
|
69
|
+
* and case does not tell two names apart. */
|
|
70
|
+
export function win32Spelling(path) {
|
|
71
|
+
const plain = path.replace(/^\\\\\?\\UNC\\/i, "\\\\").replace(/^\\\\\?\\/i, "").replace(/\//g, "\\");
|
|
72
|
+
const trimmed = win32.normalize(plain).replace(/\\+$/, "");
|
|
73
|
+
return (/^[A-Za-z]:$/.test(trimmed) ? `${trimmed}\\` : trimmed).toLowerCase();
|
|
74
|
+
}
|
|
75
|
+
/** Whether two spellings name one path here: the same spelling, or — on Windows — the same Win32 spelling of the native
|
|
76
|
+
* form each names (an 8.3 alias, another case, a `/` from `git worktree list`, a symlinked directory). */
|
|
77
|
+
export function sameWorktree(a, b) {
|
|
78
|
+
if (a === b)
|
|
79
|
+
return true;
|
|
80
|
+
const na = nativePath(a), nb = nativePath(b);
|
|
81
|
+
return na === nb || (process.platform === "win32" && win32Spelling(na) === win32Spelling(nb));
|
|
82
|
+
}
|
|
83
|
+
/** Whether `target` is inside `base`, both already in the file system's own spelling. It is not when there is no
|
|
84
|
+
* relative part at all (the same directory), when that part leaves `base` (`..`), or when it is absolute — which is
|
|
85
|
+
* what Win32 `relative` yields for another drive or share, so a cross-drive target is never inside. */
|
|
86
|
+
export function insidePath(base, target, platform = process.platform) {
|
|
87
|
+
const path = platform === "win32" ? win32 : posix;
|
|
88
|
+
if (platform === "win32") {
|
|
89
|
+
if (!win32.isAbsolute(base) || !win32.isAbsolute(target))
|
|
90
|
+
return false;
|
|
91
|
+
base = win32Spelling(base);
|
|
92
|
+
target = win32Spelling(target);
|
|
93
|
+
}
|
|
94
|
+
const within = path.relative(base, target);
|
|
95
|
+
return Boolean(within) && within !== ".." && !within.startsWith(`..${path.sep}`) && !path.isAbsolute(within) &&
|
|
96
|
+
path.resolve(base, within) === target;
|
|
97
|
+
}
|
|
98
|
+
/** Whether `path` is inside `root` by the identity the file system gives each (a spelling through a symlink, a junction
|
|
99
|
+
* or an 8.3 alias is still inside), and on Windows never across drives or shares. */
|
|
100
|
+
export function inside(root, path) {
|
|
101
|
+
return insidePath(nativePath(root), nativePath(path));
|
|
102
|
+
}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { commandLine } from "../../platform/cmdline.js";
|
|
2
|
+
import { scannedCommand } from "../../platform/windows.js";
|
|
2
3
|
/** EX1 / WK8: Agent fences only. The direct child's tracked identity is retained across recovery (old journals: first tracked). */
|
|
3
|
-
export async function fenceAgent(containment, journal, exec, tracked, child) {
|
|
4
|
+
export async function fenceAgent(containment, journal, exec, tracked, child, opts = {}) {
|
|
5
|
+
const read = opts.readCommand ?? commandLine;
|
|
4
6
|
const options = { beforeKill: async (targets, signal) => {
|
|
5
7
|
const identities = journal.entries().filter(e => e.type === "tracked" && e.exec === exec);
|
|
6
8
|
const direct = child ?? identities.find(e => e.child === true) ?? identities[0];
|
|
@@ -11,8 +13,10 @@ export async function fenceAgent(containment, journal, exec, tracked, child) {
|
|
|
11
13
|
: targets.filter(p => pids.has(p.ppid));
|
|
12
14
|
if (!others.length || signal.aborted)
|
|
13
15
|
return;
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
+
const procs = await Promise.all(others.slice(0, 20).map(async (p) => {
|
|
17
|
+
const scanned = scannedCommand(p);
|
|
18
|
+
return { pid: p.pid, command: scanned !== undefined ? scanned : await read(p.pid, signal) };
|
|
19
|
+
}));
|
|
16
20
|
// The timeout cancels command reads and prevents an outstanding read from appending after the kill/seal.
|
|
17
21
|
if (signal.aborted)
|
|
18
22
|
return;
|
|
@@ -12,8 +12,14 @@
|
|
|
12
12
|
// pi or its interpreter missing or not executable); the call stays queued and launches again after a backoff.
|
|
13
13
|
// Command calls (CallSpec.command) record no exec/tracked/fenced entries (nothing that handles agent executions picks them
|
|
14
14
|
// up): command-intent{call,id,n} before the spawn (id = command:<call>#<n> is the attempt and its process tag DSA_EXEC;
|
|
15
|
-
// n is 1, or 2 for the single rerun)
|
|
16
|
-
//
|
|
15
|
+
// n is 1, or 2 for the single rerun). The expensive part of a start -- on Windows the compilation of the job host, bounded
|
|
16
|
+
// and cancellable -- is staged *before* that intent (under the writer lock a writer call holds), so a crash, a stop or a
|
|
17
|
+
// retirement during it leaves no intent and nothing that can act: that cut is unambiguously prelaunch, and an interrupted
|
|
18
|
+
// compilation is never a failure of the attempt. An intent with no command-started is still ambiguous for a journal an
|
|
19
|
+
// earlier version wrote (its compilation ran after the intent) and recovery keeps treating it so; command-started{call,id,pid,start,dir,group?,uncertain?} follows the spawn (the wrapper's identity, the
|
|
20
|
+
// attempt directory, and on Windows {pid,start} of the job host that owns the attempt's kernel group; its ts starts the
|
|
21
|
+
// wall-clock timeout; `uncertain` means the start could not be confirmed -- the host was adopted with pid/start of the
|
|
22
|
+
// host itself, and only a scan that finds it gone may let another attempt start); command-spawn-failed{call,id,error}: the command could not
|
|
17
23
|
// start (it seals failed, never reruns); command-timeout{call,id}: the deadline passed, recorded before the process tree
|
|
18
24
|
// is ended (as stop-intent is for a stop), so a crash during that fence still seals timeout; command-withdrawn{call,id}:
|
|
19
25
|
// the intent was recorded but no process started (a retirement or the orchestrator's exit came first): a later start
|
|
@@ -29,8 +35,10 @@ import { fileURLToPath } from "node:url";
|
|
|
29
35
|
import { CT, JT, askFields, attentionEntries, isCommandCall, isEntry } from "../../types.js";
|
|
30
36
|
import { binDir, callDir, callInbox, callSession, journalPath, outboxRoot } from "../../paths.js";
|
|
31
37
|
import { readJournalSnapshot, syncDirectory } from "../../kernel/journal.js";
|
|
38
|
+
import { isWinSharingError } from "../../kernel/fsx.js";
|
|
32
39
|
import { Outbox } from "../../kernel/mailbox.js";
|
|
33
|
-
import { contentHash, forwardRid } from "../../kernel/ids.js";
|
|
40
|
+
import { contentHash, fileId, forwardRid } from "../../kernel/ids.js";
|
|
41
|
+
import { execTarget } from "../../platform/launch.js";
|
|
34
42
|
import { capacity, seal } from "../../kernel/guards.js";
|
|
35
43
|
import { buildPiArgs, DEFAULT_TOOLS } from "../../compat/pi-args.js";
|
|
36
44
|
import { parseModel, plainModel, resolveModel, sameModel } from "../../compat/model.js";
|
|
@@ -56,8 +64,9 @@ import { gateRetired } from "./effects/gate.js";
|
|
|
56
64
|
import { WorktreeIndex, isWorktreeConflict, worktreeCalls, worktreeLabel, worktreePair, worktreeRoots } from "./worktree.js";
|
|
57
65
|
import { failedModel, modelFailures, MODEL_RETRY_MS, parentPinned, spillCandidates } from "./pool.js";
|
|
58
66
|
import { PENDING_NOTE, UNDELIVERED_FOLLOW_UP } from "../notes.js";
|
|
59
|
-
import { COMMAND_LOG, exitMeaning, readExitRecord, readTail, spawnCommand } from "../../platform/command.js";
|
|
67
|
+
import { COMMAND_LOG, exitMeaning, prepareCancelled, prepareCommand as stageCommand, readExitRecord, readTail, spawnCommand } from "../../platform/command.js";
|
|
60
68
|
import { captureStart } from "../../platform/proctable.js";
|
|
69
|
+
import { IS_WINDOWS, sameCreation } from "../../platform/windows.js";
|
|
61
70
|
import { heldIn } from "../snapshot.js";
|
|
62
71
|
import { COMMAND_INTENT, COMMAND_SPAWN_FAILED, COMMAND_STARTED, COMMAND_TIMEOUT, COMMAND_WITHDRAWN, commandDirName, commandEnvironment, commandId, retiredCommandAttempts } from "./command.js";
|
|
63
72
|
const MEM_RECORD_MS = 30000;
|
|
@@ -188,6 +197,10 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
188
197
|
const { home, config, orch } = ledgers;
|
|
189
198
|
const containment = options.containment ?? serialContainment(), effects = options.effects ?? createEffects(ledgers);
|
|
190
199
|
const piCommand = options.pi ?? "pi";
|
|
200
|
+
// The command start's pre-intent preparation: the Windows owner compilation (cancellable), nothing on POSIX.
|
|
201
|
+
const prepareStart = options.prepareCommand ?? stageCommand;
|
|
202
|
+
const readCommandExit = options.readExitRecord ?? readExitRecord;
|
|
203
|
+
const isWin = (options.platform ?? (IS_WINDOWS ? "win32" : process.platform)) === "win32";
|
|
191
204
|
const active = new Map(), completed = new Map(), journals = new Map();
|
|
192
205
|
let queue = Promise.resolve(), closed = false;
|
|
193
206
|
let suspending;
|
|
@@ -197,12 +210,26 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
197
210
|
// F2: a sweep error is transient: report it and retry at the next K1; it never blocks dispatch.
|
|
198
211
|
/** The sweep state of settled journals not decoded (recover with `settled`). */
|
|
199
212
|
const seeds = new WeakMap();
|
|
200
|
-
const
|
|
213
|
+
const sweep = () => {
|
|
201
214
|
if (!sweeping)
|
|
202
|
-
sweeping = sweepExecutions([...journals.values()].filter(j => !j.closed), containment, { failing: exec => failing.has(exec), fenced: swept,
|
|
215
|
+
sweeping = sweepExecutions([...journals.values()].filter(j => !j.closed), containment, { failing: exec => failing.has(exec), fenced: swept, seeded: journal => seeds.get(journal),
|
|
216
|
+
// A sweep's own failure never schedules another sweep: the interval is its retry.
|
|
217
|
+
failed: (journal, exec, call, error) => fenceFailed(journal, exec, call, error, false) })
|
|
203
218
|
.catch(error => console.error(`durable-subagents: sweep failed, retrying in K1: ${String(error)}`)).finally(() => { sweeping = undefined; });
|
|
204
|
-
}
|
|
219
|
+
};
|
|
220
|
+
const sweepTimer = setInterval(sweep, options.sweepMs ?? 30000);
|
|
205
221
|
sweepTimer.unref();
|
|
222
|
+
// F1: a failed fence parks its call, and the sweep is the only retry. A transient stall (a PowerShell/CIM scan that
|
|
223
|
+
// misses the Windows budget) must not keep the call parked for a whole sweep interval: one prompt sweep is requested
|
|
224
|
+
// per fence failure that did not come from a sweep, so a probe that keeps failing is retried at the interval, as before.
|
|
225
|
+
let sweepSoon;
|
|
226
|
+
const sweepNow = () => {
|
|
227
|
+
if (sweepSoon || sweeping || closed)
|
|
228
|
+
return;
|
|
229
|
+
sweepSoon = setTimeout(() => { sweepSoon = undefined; if (!closed)
|
|
230
|
+
sweep(); }, 0);
|
|
231
|
+
sweepSoon.unref();
|
|
232
|
+
};
|
|
206
233
|
const waiters = new Set();
|
|
207
234
|
const inbox = (call) => { const a = address(call); return callInbox(home, a.wid, a.key, a.gen); };
|
|
208
235
|
const outbox = Outbox.open(outboxRoot(home), "orch", inbox);
|
|
@@ -282,13 +309,16 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
282
309
|
await resolveFenceAttention(journal, exec);
|
|
283
310
|
});
|
|
284
311
|
}
|
|
285
|
-
/** F1: A fence timeout is recorded once with one unknown attention item for the origin; any failure parks the exec.
|
|
286
|
-
|
|
312
|
+
/** F1: A fence timeout is recorded once with one unknown attention item for the origin; any failure parks the exec.
|
|
313
|
+
* `prompt` asks for one immediate sweep, which is the only retry of a parked call (a sweep never asks itself). */
|
|
314
|
+
async function fenceFailed(journal, exec, call, error, prompt = true) {
|
|
287
315
|
if (!failing.has(exec))
|
|
288
316
|
console.error(`durable-subagents: fence of ${exec} failed: ${String(error)}`);
|
|
289
317
|
failing.add(exec);
|
|
290
318
|
if (/Fence timeout/.test(String(error)))
|
|
291
319
|
await serial(() => recordFenceFailure(journal, exec, call, error));
|
|
320
|
+
if (prompt)
|
|
321
|
+
sweepNow();
|
|
292
322
|
}
|
|
293
323
|
async function parked(a, journal, exec) {
|
|
294
324
|
a.parking = exec;
|
|
@@ -377,7 +407,8 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
377
407
|
fresh.add(rid);
|
|
378
408
|
if (!fresh.size)
|
|
379
409
|
return;
|
|
380
|
-
|
|
410
|
+
// Windows refuses FlushFileBuffers on a read-only handle; open read/write there (the session is ours to flush).
|
|
411
|
+
const a = address(call), file = await open(callSession(home, a.wid, a.key, a.gen), process.platform === "win32" ? "r+" : "r");
|
|
381
412
|
try {
|
|
382
413
|
await file.sync();
|
|
383
414
|
}
|
|
@@ -387,7 +418,7 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
387
418
|
const sender = await outbox, dir = inbox(call);
|
|
388
419
|
for (const rid of fresh) {
|
|
389
420
|
await sender.markResolved(rid);
|
|
390
|
-
await unlink(join(dir, `${rid}.json`)).catch(ignoreMissing);
|
|
421
|
+
await unlink(join(dir, `${fileId(rid)}.json`)).catch(ignoreMissing);
|
|
391
422
|
done.add(rid);
|
|
392
423
|
}
|
|
393
424
|
}
|
|
@@ -1284,37 +1315,78 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1284
1315
|
}
|
|
1285
1316
|
// ---- Command calls: no model, slot, usage, hibernation or budget; the process outlives the orchestrator. ----
|
|
1286
1317
|
const commandTick = () => Math.min(config.k?.trackerMs ?? 1000, 1000);
|
|
1318
|
+
/** Attempts whose process table read failed (logged once: a broken observer would otherwise fill the log). */
|
|
1319
|
+
const unobserved = new Set();
|
|
1287
1320
|
const hasStopIntent = (journal, call) => entriesFor(journal, call).some(e => e.type === "stop-intent");
|
|
1288
|
-
/** The
|
|
1289
|
-
|
|
1290
|
-
|
|
1321
|
+
/** The attempt's known identities (from its latest command-started): the wrapper and, on Windows, the job host that
|
|
1322
|
+
* owns its kernel group (whose descendants are the whole attempt), for scans and fences. */
|
|
1323
|
+
const commandKnown = (started) => {
|
|
1324
|
+
if (!started)
|
|
1325
|
+
return [];
|
|
1326
|
+
const known = [];
|
|
1327
|
+
if (started.start)
|
|
1328
|
+
known.push({ pid: Number(started.pid), ppid: 0, start: String(started.start) });
|
|
1329
|
+
const group = started.group;
|
|
1330
|
+
if (group && typeof group.start === "string" && group.start)
|
|
1331
|
+
known.push({ pid: Number(group.pid), ppid: 0, start: group.start });
|
|
1332
|
+
return known;
|
|
1333
|
+
};
|
|
1334
|
+
/** The processes of an attempt: tagged with its id, the wrapper while it lives, and their live descendants. A scan that
|
|
1335
|
+
* fails transiently is not an empty result (`undefined`): an attempt is never called gone because the observer failed. */
|
|
1291
1336
|
async function commandProcesses(id, known) {
|
|
1292
|
-
|
|
1337
|
+
try {
|
|
1338
|
+
return (await containment.scan(new Map([[id, known]]), { fresh: true })).get(id) ?? [];
|
|
1339
|
+
}
|
|
1340
|
+
catch (error) {
|
|
1341
|
+
if (closed)
|
|
1342
|
+
throw error;
|
|
1343
|
+
return undefined;
|
|
1344
|
+
}
|
|
1293
1345
|
}
|
|
1294
|
-
/**
|
|
1295
|
-
*
|
|
1346
|
+
/** The same, for a decision that may not proceed on an unobserved attempt: retried until the table answers (the fence
|
|
1347
|
+
* retries a failed retirement the same way; the orchestrator's exit ends it). */
|
|
1348
|
+
async function observedCommandProcesses(id, known) {
|
|
1349
|
+
for (;;) {
|
|
1350
|
+
const live = await commandProcesses(id, known);
|
|
1351
|
+
if (live) {
|
|
1352
|
+
unobserved.delete(id);
|
|
1353
|
+
return live;
|
|
1354
|
+
}
|
|
1355
|
+
if (!unobserved.has(id)) {
|
|
1356
|
+
unobserved.add(id);
|
|
1357
|
+
console.error(`durable-subagents: the processes of ${id} could not be observed; retrying`);
|
|
1358
|
+
}
|
|
1359
|
+
if (closed)
|
|
1360
|
+
throw shutdownError();
|
|
1361
|
+
await delay(commandTick());
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
/** End an attempt's whole process tree: on POSIX, SIGTERM with a grace period before the fence; on Windows, directly
|
|
1365
|
+
* through the handle-verified fence (`process.kill` on Windows is an unverified bare-PID TerminateProcess). */
|
|
1296
1366
|
async function endCommand(id, known) {
|
|
1297
|
-
let live = await
|
|
1367
|
+
let live = await observedCommandProcesses(id, known);
|
|
1298
1368
|
if (!live.length)
|
|
1299
1369
|
return;
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1370
|
+
if (!IS_WINDOWS) {
|
|
1371
|
+
for (const p of live) {
|
|
1372
|
+
if (!p.start || await captureStart(p.pid).catch(() => "") !== p.start)
|
|
1373
|
+
continue;
|
|
1374
|
+
try {
|
|
1375
|
+
process.kill(p.pid, "SIGTERM");
|
|
1376
|
+
}
|
|
1377
|
+
catch (error) {
|
|
1378
|
+
if (error.code !== "ESRCH")
|
|
1379
|
+
throw error;
|
|
1380
|
+
}
|
|
1305
1381
|
}
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1382
|
+
const graceUntil = Date.now() + COMMAND_GRACE_MS;
|
|
1383
|
+
while (Date.now() < graceUntil) {
|
|
1384
|
+
await delay(100);
|
|
1385
|
+
live = await observedCommandProcesses(id, known);
|
|
1386
|
+
if (!live.length)
|
|
1387
|
+
return;
|
|
1309
1388
|
}
|
|
1310
1389
|
}
|
|
1311
|
-
const graceUntil = Date.now() + COMMAND_GRACE_MS;
|
|
1312
|
-
while (Date.now() < graceUntil) {
|
|
1313
|
-
await delay(100);
|
|
1314
|
-
live = await commandProcesses(id, known);
|
|
1315
|
-
if (!live.length)
|
|
1316
|
-
return;
|
|
1317
|
-
}
|
|
1318
1390
|
for (;;) {
|
|
1319
1391
|
try {
|
|
1320
1392
|
await containment.fence(id, [...known, ...live]);
|
|
@@ -1418,8 +1490,9 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1418
1490
|
const intentWithdrawn = (journal, call, id, seq) => entriesFor(journal, call).some(e => e.type === COMMAND_WITHDRAWN && e.id === id && e.seq > seq);
|
|
1419
1491
|
/** Start the attempt whose intent is recorded; records command-started, or command-spawn-failed when it cannot start.
|
|
1420
1492
|
* Rechecked synchronously right before the spawn: a stop means no process (the watch seals it stopped), a retirement or the orchestrator's exit
|
|
1421
|
-
* withdraws the intent (nothing started; the next start decides again).
|
|
1422
|
-
|
|
1493
|
+
* withdraws the intent (nothing started; the next start decides again). `prepared` is the start's staged preparation: when
|
|
1494
|
+
* no process is started it is released (nothing started and the intent is withdrawn or the stop seals it). */
|
|
1495
|
+
async function launchCommand(a, id, dir, prepared) {
|
|
1423
1496
|
const t = a.ticket;
|
|
1424
1497
|
let spawned;
|
|
1425
1498
|
try {
|
|
@@ -1436,11 +1509,13 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1436
1509
|
refused = "withdrawn";
|
|
1437
1510
|
return refused === undefined;
|
|
1438
1511
|
};
|
|
1439
|
-
const result = await spawnCommand({ command: t.spec.command, cwd: t.cwd, dir, proceed,
|
|
1440
|
-
env: commandEnvironment(home, id, t.callId, t.spec.env) });
|
|
1512
|
+
const result = await spawnCommand({ command: t.spec.command, cwd: t.cwd, dir, proceed, exec: id,
|
|
1513
|
+
...(prepared ? { prepared } : {}), env: commandEnvironment(home, id, t.callId, t.spec.env) });
|
|
1441
1514
|
if (!result) {
|
|
1442
1515
|
if (refused === "withdrawn")
|
|
1443
1516
|
await serial(() => t.journal.append(COMMAND_WITHDRAWN, { call: t.callId, id }));
|
|
1517
|
+
// Nothing of the attempt exists: what the preparation staged is of no use.
|
|
1518
|
+
await prepared?.release().catch(() => { });
|
|
1444
1519
|
return undefined;
|
|
1445
1520
|
}
|
|
1446
1521
|
spawned = result;
|
|
@@ -1449,7 +1524,8 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1449
1524
|
await serial(() => t.journal.append(COMMAND_SPAWN_FAILED, { call: t.callId, id, error: String(error instanceof Error ? error.message : error).slice(0, 300) }));
|
|
1450
1525
|
return undefined;
|
|
1451
1526
|
}
|
|
1452
|
-
await serial(() => t.journal.append(COMMAND_STARTED, { call: t.callId, id, pid: spawned.pid, start: spawned.start, dir
|
|
1527
|
+
await serial(() => t.journal.append(COMMAND_STARTED, { call: t.callId, id, pid: spawned.pid, start: spawned.start, dir,
|
|
1528
|
+
...(spawned.group ? { group: spawned.group } : {}), ...(spawned.uncertain ? { uncertain: spawned.uncertain } : {}) }));
|
|
1453
1529
|
return spawned;
|
|
1454
1530
|
}
|
|
1455
1531
|
/** Run, adopt or settle a command call (see the journal records at the top). One attempt runs at a time; a lost first
|
|
@@ -1461,14 +1537,64 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1461
1537
|
const dirOf = (n) => join(callDir(home, t.wid, t.key, t.gen), commandDirName(n));
|
|
1462
1538
|
const fail = (error) => sealCommand(journal, t, commandId(call, 1), { status: "failed", error });
|
|
1463
1539
|
const latest = () => { const e = own().findLast(e => e.type === COMMAND_INTENT); return e && !intentWithdrawn(journal, call, String(e.id), e.seq) ? e : undefined; };
|
|
1464
|
-
/**
|
|
1540
|
+
/** Stage the expensive part of attempt `id`'s start (the Windows owner compilation) *before* the durable intent, under
|
|
1541
|
+
* whatever fence the call already holds (the writer lock): a crash here leaves no `command-intent`, so the attempt is
|
|
1542
|
+
* unambiguously prelaunch -- nothing started, nothing to adopt, nothing to rerun. The preparation is bounded and
|
|
1543
|
+
* cancellable: a stop, retirement, suspension or exit during it ends the compiler, removes what it wrote and is never
|
|
1544
|
+
* recorded as a failure of the attempt (a stop seals stopped; anything else ends the run and the call resumes on
|
|
1545
|
+
* recovery). A preparation that fails for its own reason is fail-closed, as the compilation always was -- but only
|
|
1546
|
+
* while the start is still permitted: once the start was revoked (a stop, a suspension, a retirement or the exit
|
|
1547
|
+
* aborted it), the revocation decides the attempt and a rejection on the way out is never sealed failed. */
|
|
1548
|
+
const start = async (a, id, dir) => {
|
|
1549
|
+
const blocked = commandBlocked(a);
|
|
1550
|
+
if (blocked)
|
|
1551
|
+
return { blocked };
|
|
1552
|
+
let prepared;
|
|
1553
|
+
try {
|
|
1554
|
+
prepared = await prepareStart({ command: t.spec.command, cwd: t.cwd, dir, exec: id,
|
|
1555
|
+
env: commandEnvironment(home, id, call, t.spec.env), signal: a.controller.signal });
|
|
1556
|
+
}
|
|
1557
|
+
catch (error) {
|
|
1558
|
+
// The revocation is the cause, so it decides the attempt: the rejection cannot be told apart from one the abort
|
|
1559
|
+
// produced (a cancelled publication, a compiler this process ended), and sealing it failed would report a failure
|
|
1560
|
+
// of an attempt the run is only suspending, retiring or stopping (or that a stop already decided).
|
|
1561
|
+
if (!prepareCancelled(error) && !a.controller.signal.aborted)
|
|
1562
|
+
return { failure: String(error instanceof Error ? error.message : error) };
|
|
1563
|
+
// Interrupted, and nothing was recorded: a stop decides the attempt, anything else ends this run. Without a blocked
|
|
1564
|
+
// state the run is being torn down anyway (a suspension or a retirement), so it is never retried here.
|
|
1565
|
+
return { blocked: commandBlocked(a) ?? "shutdown" };
|
|
1566
|
+
}
|
|
1567
|
+
// An abort that arrived while the last step of the preparation ran: nothing may follow it.
|
|
1568
|
+
if (a.controller.signal.aborted) {
|
|
1569
|
+
await prepared?.release().catch(() => { });
|
|
1570
|
+
return { blocked: commandBlocked(a) ?? "shutdown" };
|
|
1571
|
+
}
|
|
1572
|
+
return { ready: true, ...(prepared ? { prepared } : {}) };
|
|
1573
|
+
};
|
|
1574
|
+
/** Start attempt `n`: the staged preparation (before the intent), the intent, then the process; undefined when it did
|
|
1575
|
+
* not start (and the run goes on). */
|
|
1465
1576
|
const begin = async (n) => {
|
|
1577
|
+
const id = commandId(call, n), dir = dirOf(n);
|
|
1578
|
+
const staged = await start(a, id, dir);
|
|
1579
|
+
if ("blocked" in staged) {
|
|
1580
|
+
if (staged.blocked === "stopped")
|
|
1581
|
+
return undefined;
|
|
1582
|
+
throw shutdownError();
|
|
1583
|
+
}
|
|
1584
|
+
if ("failure" in staged) {
|
|
1585
|
+
await sealCommand(journal, t, id, { status: "failed", error: `Command could not start: ${staged.failure}` });
|
|
1586
|
+
return {};
|
|
1587
|
+
}
|
|
1466
1588
|
const intent = await commandIntent(a, n);
|
|
1467
|
-
if (intent === "stopped")
|
|
1589
|
+
if (intent === "stopped") {
|
|
1590
|
+
await staged.prepared?.release().catch(() => { });
|
|
1468
1591
|
return undefined;
|
|
1469
|
-
|
|
1592
|
+
}
|
|
1593
|
+
if (intent === "shutdown" || intent === "held") {
|
|
1594
|
+
await staged.prepared?.release().catch(() => { });
|
|
1470
1595
|
throw shutdownError();
|
|
1471
|
-
|
|
1596
|
+
}
|
|
1597
|
+
return { spawned: await launchCommand(a, String(intent.id), dir, staged.prepared) };
|
|
1472
1598
|
};
|
|
1473
1599
|
let spawned;
|
|
1474
1600
|
for (;;) {
|
|
@@ -1531,22 +1657,34 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1531
1657
|
watcher = undefined;
|
|
1532
1658
|
}
|
|
1533
1659
|
void spawned?.exited.then(() => a.wake());
|
|
1660
|
+
const readExit = async () => {
|
|
1661
|
+
try {
|
|
1662
|
+
return await readCommandExit(dir);
|
|
1663
|
+
}
|
|
1664
|
+
catch (error) {
|
|
1665
|
+
if (isWin && isWinSharingError(error))
|
|
1666
|
+
return undefined;
|
|
1667
|
+
throw error;
|
|
1668
|
+
}
|
|
1669
|
+
};
|
|
1670
|
+
const settleExit = async (exit, known, deadline) => {
|
|
1671
|
+
// Processes the command left behind (background ones included) end with it, as a call's processes always do.
|
|
1672
|
+
if (!closed)
|
|
1673
|
+
await endCommand(id, known);
|
|
1674
|
+
// An exit after the deadline (seen late: the orchestrator was down) is a timeout, with the record's data.
|
|
1675
|
+
const late = deadline !== undefined && exit.at > deadline;
|
|
1676
|
+
return await sealCommand(journal, t, id, { status: late ? "timeout" : exit.status === 0 ? "ok" : "failed", ...exitResult(exit.status),
|
|
1677
|
+
...(late ? { error: `Command timed out after ${t.spec.timeoutMs} ms` } : {}), at: exit.at }, dir);
|
|
1678
|
+
};
|
|
1534
1679
|
try {
|
|
1535
1680
|
for (;;) {
|
|
1536
1681
|
const started = entriesFor(journal, call).findLast(e => e.type === COMMAND_STARTED && e.id === id), known = commandKnown(started);
|
|
1537
1682
|
// The timeout is wall clock from the start (command-started, else the intent: a crash before the started record),
|
|
1538
1683
|
// downtime included.
|
|
1539
1684
|
const deadline = t.spec.timeoutMs !== undefined ? (started ?? intent).ts + t.spec.timeoutMs : undefined;
|
|
1540
|
-
const exit = await
|
|
1541
|
-
if (exit)
|
|
1542
|
-
|
|
1543
|
-
if (!closed)
|
|
1544
|
-
await endCommand(id, known);
|
|
1545
|
-
// An exit after the deadline (seen late: the orchestrator was down) is a timeout, with the record's data.
|
|
1546
|
-
const late = deadline !== undefined && exit.at > deadline;
|
|
1547
|
-
return await sealCommand(journal, t, id, { status: late ? "timeout" : exit.status === 0 ? "ok" : "failed", ...exitResult(exit.status),
|
|
1548
|
-
...(late ? { error: `Command timed out after ${t.spec.timeoutMs} ms` } : {}), at: exit.at }, dir);
|
|
1549
|
-
}
|
|
1685
|
+
const exit = await readExit();
|
|
1686
|
+
if (exit)
|
|
1687
|
+
return await settleExit(exit, known, deadline);
|
|
1550
1688
|
if (closed)
|
|
1551
1689
|
throw shutdownError();
|
|
1552
1690
|
if (a.retired || retiredCall(journal, call)) {
|
|
@@ -1563,13 +1701,16 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1563
1701
|
await endCommand(id, known);
|
|
1564
1702
|
return await sealCommand(journal, t, id, { status: "timeout" }, dir);
|
|
1565
1703
|
}
|
|
1566
|
-
const
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1704
|
+
const observedStart = started?.start ? await captureStart(Number(started.pid)).catch(() => "") : "";
|
|
1705
|
+
const wrapper = !!started?.start && (IS_WINDOWS ? sameCreation(observedStart, String(started.start)) : observedStart === started.start);
|
|
1706
|
+
// A failed observation is not a loss: the attempt stays tracked and is watched again (never started over).
|
|
1707
|
+
const live = wrapper ? undefined : await commandProcesses(id, known);
|
|
1708
|
+
if (!wrapper && live !== undefined && !live.length) {
|
|
1709
|
+
// The wrapper may have written its record just before it ended (or a Windows scanner may briefly hold it).
|
|
1710
|
+
const late = await readExit();
|
|
1570
1711
|
if (!late)
|
|
1571
1712
|
return "lost";
|
|
1572
|
-
|
|
1713
|
+
return await settleExit(late, known, deadline);
|
|
1573
1714
|
}
|
|
1574
1715
|
const wait = Math.max(1, Math.min(commandTick(), deadline !== undefined ? deadline - Date.now() : Infinity));
|
|
1575
1716
|
await new Promise(resolve => { const timer = setTimeout(resolve, wait); a.wake = () => { clearTimeout(timer); resolve(); }; });
|
|
@@ -1881,10 +2022,13 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1881
2022
|
const exactTools = t.exactMode?.mode === "exact" ? [...new Set([...(t.spec.tools ?? t.agent.tools ?? DEFAULT_TOOLS),
|
|
1882
2023
|
...(t.spec.schema === undefined ? ["ask"] : ["ask", "report"])])] : undefined;
|
|
1883
2024
|
let child;
|
|
2025
|
+
// The child's environment: the orchestrator's node follows binDir, so a `#!/usr/bin/env node` pi still runs under a
|
|
2026
|
+
// PATH without node (a service's). execTarget resolves a bare `pi` on this PATH too, not on the orchestrator's: the
|
|
2027
|
+
// shim it must run may be the call's own.
|
|
2028
|
+
const childEnv = { DSA_HOME: home, PATH: [binDir(home), dirname(process.execPath), process.env.PATH].filter(Boolean).join(delimiter), DSA_EXEC: exec, DSA_CALL: t.callId, DSA_INBOX: inbox(t.callId), DSA_JOURNAL: journal.path, DSA_ASK_REQUIRE_DECISION: String(config.askRequireDecision ?? false), ...(Object.keys(patterns).length ? { DSA_EXHAUSTED_PATTERNS: JSON.stringify(patterns) } : {}), ...(t.spec.schema !== undefined ? { DSA_SCHEMA: schema } : {}), ...(t.spec.budget ? { DSA_BUDGET: JSON.stringify(t.spec.budget) } : {}), ...(model.provider && model.id ? { DSA_MODEL: `${model.provider}/${model.id}` } : {}), ...(exactTools && t.exactCapture ? { DSA_EXACT_CAPTURE: t.exactCapture.path, DSA_EXACT_TOOLS: JSON.stringify(exactTools) } : {}) };
|
|
1884
2029
|
try {
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
env: { DSA_HOME: home, PATH: [binDir(home), dirname(process.execPath), process.env.PATH].filter(Boolean).join(delimiter), DSA_EXEC: exec, DSA_CALL: t.callId, DSA_INBOX: inbox(t.callId), DSA_JOURNAL: journal.path, DSA_ASK_REQUIRE_DECISION: String(config.askRequireDecision ?? false), ...(Object.keys(patterns).length ? { DSA_EXHAUSTED_PATTERNS: JSON.stringify(patterns) } : {}), ...(t.spec.schema !== undefined ? { DSA_SCHEMA: schema } : {}), ...(t.spec.budget ? { DSA_BUDGET: JSON.stringify(t.spec.budget) } : {}), ...(model.provider && model.id ? { DSA_MODEL: `${model.provider}/${model.id}` } : {}), ...(exactTools && t.exactCapture ? { DSA_EXACT_CAPTURE: t.exactCapture.path, DSA_EXACT_TOOLS: JSON.stringify(exactTools) } : {}) } });
|
|
2030
|
+
const target = execTarget(piCommand, [...buildPiArgs(t.agent, t.spec, { sessionPath: session, systemPromptPath: prompt, continuation: decision.continuation, controlTools: t.spec.schema === undefined ? ["ask"] : ["ask", "report"], ...(model.id ? { model } : {}), ...(t.exactMode?.mode === "exact" ? { thinking: (await readPinnedCapture(t.exactCapture?.path))?.thinking ?? false } : {}) }), "-e", extension], { env: childEnv });
|
|
2031
|
+
child = await containment.spawn({ exec, command: target.command, args: target.args, cwd, env: childEnv, ...(target.verbatim ? { windowsVerbatimArguments: true } : {}) });
|
|
1888
2032
|
}
|
|
1889
2033
|
catch (error) {
|
|
1890
2034
|
const environment = environmentSpawnError(error);
|
|
@@ -2359,8 +2503,14 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
2359
2503
|
// executions were fenced and released, its session read, its forwards, attention and inbox settled.
|
|
2360
2504
|
// A retired command call's processes, if any still run (an orchestrator ended during its retirement), end now.
|
|
2361
2505
|
if (entriesOf(journal, COMMAND_INTENT).length)
|
|
2362
|
-
for (const r of retiredCommandAttempts(journal.entries()))
|
|
2363
|
-
|
|
2506
|
+
for (const r of retiredCommandAttempts(journal.entries())) {
|
|
2507
|
+
const known = [];
|
|
2508
|
+
if (r.start)
|
|
2509
|
+
known.push({ pid: r.pid, ppid: 0, start: r.start });
|
|
2510
|
+
if (r.group?.start)
|
|
2511
|
+
known.push({ pid: Number(r.group.pid), ppid: 0, start: r.group.start });
|
|
2512
|
+
await endCommand(r.id, known);
|
|
2513
|
+
}
|
|
2364
2514
|
const complete = completeCalls(journal, wid), execs = entriesOf(journal, JT.exec).filter(e => !complete.has(String(e.call)));
|
|
2365
2515
|
for (const e of execs) {
|
|
2366
2516
|
// F1: an exec whose fence fails stays unfenced and holding; its call parks until a sweep retires it.
|
|
@@ -2521,6 +2671,10 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
2521
2671
|
return;
|
|
2522
2672
|
closed = true;
|
|
2523
2673
|
clearInterval(sweepTimer);
|
|
2674
|
+
if (sweepSoon) {
|
|
2675
|
+
clearTimeout(sweepSoon);
|
|
2676
|
+
sweepSoon = undefined;
|
|
2677
|
+
}
|
|
2524
2678
|
try {
|
|
2525
2679
|
await this.suspend();
|
|
2526
2680
|
// Command watchers end at once (their processes keep running; the next start adopts them), also when an
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { readFile } from "node:fs/promises";
|
|
2
2
|
import { execFile } from "node:child_process";
|
|
3
|
+
import { freemem } from "node:os";
|
|
3
4
|
import { promisify } from "node:util";
|
|
5
|
+
import { powershell } from "../../platform/windows.js";
|
|
4
6
|
/** P29: Observe available memory in MB; capability errors refuse dispatch instead of bypassing V1. */
|
|
5
7
|
export async function availableMemory() {
|
|
6
8
|
if (process.platform === "linux") {
|
|
@@ -17,5 +19,18 @@ export async function availableMemory() {
|
|
|
17
19
|
throw new Error("P29: vm_stat unavailable");
|
|
18
20
|
return pages * page / 1024 / 1024;
|
|
19
21
|
}
|
|
22
|
+
// Windows: free commit (commit limit - committed), not free physical memory. Windows keeps most physical memory in
|
|
23
|
+
// standby/cache, so `os.freemem()` reports a few hundred MB on a healthy 16 GB machine and admission would wait
|
|
24
|
+
// forever; commit headroom is what another child can still allocate. FreeVirtualMemory is KB.
|
|
25
|
+
if (process.platform === "win32") {
|
|
26
|
+
try {
|
|
27
|
+
const stdout = await powershell("$s = [wmisearcher]'SELECT FreeVirtualMemory FROM Win32_OperatingSystem'; foreach ($os in $s.Get()) { $os.FreeVirtualMemory }", { timeout: 5000 });
|
|
28
|
+
const kb = Number(stdout.trim());
|
|
29
|
+
if (kb > 0)
|
|
30
|
+
return kb / 1024;
|
|
31
|
+
}
|
|
32
|
+
catch { /* fall through to the physical free memory */ }
|
|
33
|
+
return freemem() / 1024 / 1024;
|
|
34
|
+
}
|
|
20
35
|
throw new Error(`P29 capability unavailable: ${process.platform}`);
|
|
21
36
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { open } from "node:fs/promises";
|
|
3
|
+
import { statHandleIdentity } from "../../kernel/fsx.js";
|
|
3
4
|
import { ASK_CUT, CT } from "../../types.js";
|
|
4
5
|
// A child session is append-only while observed (pi appends whole lines), so a cached state is extended by parsing only
|
|
5
6
|
// the bytes appended since the last read. A different inode, a shorter file or a changed first 4 KiB (pi rewrites a
|
|
@@ -19,7 +20,7 @@ export async function readSessionState(path) {
|
|
|
19
20
|
return EMPTY;
|
|
20
21
|
}
|
|
21
22
|
try {
|
|
22
|
-
const { ino, size } = await file
|
|
23
|
+
const { dev, ino, size } = await statHandleIdentity(file);
|
|
23
24
|
const head = Buffer.alloc(Math.min(HEAD, size));
|
|
24
25
|
for (let read = 0; read < head.length;) {
|
|
25
26
|
const { bytesRead } = await file.read(head, read, head.length - read, read);
|
|
@@ -28,7 +29,7 @@ export async function readSessionState(path) {
|
|
|
28
29
|
read += bytesRead;
|
|
29
30
|
}
|
|
30
31
|
let cached = cache.get(path);
|
|
31
|
-
if (cached && (cached.ino !== ino || size < cached.size || digest(head.subarray(0, cached.headLength)) !== cached.head))
|
|
32
|
+
if (cached && (cached.dev !== dev || cached.ino !== ino || size < cached.size || digest(head.subarray(0, cached.headLength)) !== cached.head))
|
|
32
33
|
cached = undefined;
|
|
33
34
|
if (cached && cached.size === size)
|
|
34
35
|
return cached.state;
|
|
@@ -57,7 +58,7 @@ export async function readSessionState(path) {
|
|
|
57
58
|
const state = prior && !entries.length && !corrupt.length ? prior.state : {
|
|
58
59
|
entries: prior ? prior.state.entries.concat(entries) : entries, corrupt: prior ? prior.state.corrupt.concat(corrupt) : corrupt
|
|
59
60
|
};
|
|
60
|
-
cache.set(path, { ino, size, length: from + offset, lines, head: digest(head), headLength: head.length, state });
|
|
61
|
+
cache.set(path, { dev, ino, size, length: from + offset, lines, head: digest(head), headLength: head.length, state });
|
|
61
62
|
return state;
|
|
62
63
|
}
|
|
63
64
|
finally {
|