pi-durable-subagents 1.5.1 → 1.6.1
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 +41 -0
- package/README.md +69 -14
- package/dist/agent/capabilities.js +19 -11
- package/dist/agent/child/live.js +10 -2
- package/dist/agent/child.js +1 -1
- package/dist/agent/exact/capture.js +22 -2
- package/dist/agent/exact/child.js +8 -1
- package/dist/agent/exact/session.js +4 -2
- package/dist/agent/extension.js +13 -0
- 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/main.js +7 -2
- 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 +47 -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/digest.js +2 -2
- 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/observe.js +6 -1
- package/dist/orchestrator/executor/session.js +10 -4
- package/dist/orchestrator/executor/sweep.js +34 -1
- package/dist/orchestrator/executor/usage.js +19 -5
- 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 +262 -29
- 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/types.js +1 -0
- package/dist/ui/data.js +7 -6
- package/dist/ui/session.js +6 -5
- package/package.json +3 -3
|
@@ -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 {
|
|
@@ -124,10 +125,15 @@ export function evidence(entries, exec) {
|
|
|
124
125
|
if (value.trim())
|
|
125
126
|
text = value;
|
|
126
127
|
}
|
|
127
|
-
usage.input += m.usage?.input ?? 0;
|
|
128
|
+
usage.input += (m.usage?.input ?? 0) + (m.usage?.cacheRead ?? 0) + (m.usage?.cacheWrite ?? 0);
|
|
128
129
|
usage.output += m.usage?.output ?? 0;
|
|
129
130
|
usage.costUsd += m.usage?.cost?.total ?? 0;
|
|
130
131
|
}
|
|
132
|
+
else if (e.type === "usage" && e.usage) {
|
|
133
|
+
usage.input += (e.usage.input ?? 0) + (e.usage.cacheRead ?? 0) + (e.usage.cacheWrite ?? 0);
|
|
134
|
+
usage.output += e.usage.output ?? 0;
|
|
135
|
+
usage.costUsd += e.usage.cost?.total ?? 0;
|
|
136
|
+
}
|
|
131
137
|
// P28: an ask cut off by shutdown or abort while its question waited keeps an unknown outcome, like one with no result.
|
|
132
138
|
if (m?.role === "toolResult" && m.toolCallId && !(asked.has(m.toolCallId) && cutAskResult(m)))
|
|
133
139
|
tools.delete(m.toolCallId);
|
|
@@ -1,7 +1,40 @@
|
|
|
1
1
|
import { JT, attentionEntries, isEntry } from "../../types.js";
|
|
2
2
|
import { Containment as PlatformContainment } from "../../platform/containment.js";
|
|
3
|
+
import { readBeginIdentitySync, readGroupRecordSync } from "../../platform/job.js";
|
|
3
4
|
import { ProcessTable } from "../../platform/proctable.js";
|
|
5
|
+
import { isWinStart, sameCreation } from "../../platform/windows.js";
|
|
4
6
|
import { fenceAgent } from "./ended.js";
|
|
7
|
+
/** Read verified Windows Job Object owner and wrapper identities from a gate's durable `jobDir`. */
|
|
8
|
+
export function gateJobProcesses(jobDir, tag) {
|
|
9
|
+
if (typeof jobDir !== "string" || !jobDir)
|
|
10
|
+
return [];
|
|
11
|
+
const out = [];
|
|
12
|
+
const add = (pid, start, ppid = 0) => {
|
|
13
|
+
if (!pid || !Number.isInteger(pid) || pid <= 0 || !isWinStart(start))
|
|
14
|
+
return;
|
|
15
|
+
if (out.some(k => k.pid === pid && (k.start === start || sameCreation(k.start, start))))
|
|
16
|
+
return;
|
|
17
|
+
out.push({ pid, ppid, start, ...(tag ? { tag } : {}) });
|
|
18
|
+
};
|
|
19
|
+
const group = readGroupRecordSync(jobDir), began = readBeginIdentitySync(jobDir);
|
|
20
|
+
add(group?.group?.pid, group?.group?.start);
|
|
21
|
+
add(began?.pid, began?.start);
|
|
22
|
+
add(group?.pid, group?.start, group?.group?.pid ?? began?.pid ?? 0);
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
/** Merge durable Windows gate job identities with journaled `gate-tracked` entries, deduplicated by `(pid, start)`. */
|
|
26
|
+
export function gateJobTracked(jobDir, id, recorded) {
|
|
27
|
+
const fromJob = gateJobProcesses(jobDir, id);
|
|
28
|
+
if (!fromJob.length)
|
|
29
|
+
return [...recorded];
|
|
30
|
+
const out = [...fromJob];
|
|
31
|
+
for (const p of recorded) {
|
|
32
|
+
if (out.some(k => k.pid === p.pid && (k.start === p.start || sameCreation(k.start, p.start))))
|
|
33
|
+
continue;
|
|
34
|
+
out.push(p);
|
|
35
|
+
}
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
5
38
|
/** C2, F4: Real observers share snapshots; injected tables retain serialized access. */
|
|
6
39
|
export function serialContainment(table) {
|
|
7
40
|
if (!table || table instanceof ProcessTable)
|
|
@@ -131,7 +164,7 @@ export async function sweepExecutions(journals, containment, hooks = {}) {
|
|
|
131
164
|
for (const e of gates) {
|
|
132
165
|
const id = String(e.id);
|
|
133
166
|
if (e.type === "gate-intent" && !gated.has(id) && (failed.has(id) || hooks.failing?.(id)))
|
|
134
|
-
targets.push({ journal, exec: id, call: String(e.call), fenced: false, failed: true, tracked: tracked.get(id) ?? [] });
|
|
167
|
+
targets.push({ journal, exec: id, call: String(e.call), fenced: false, failed: true, tracked: gateJobTracked(e.jobDir, id, tracked.get(id) ?? []) });
|
|
135
168
|
}
|
|
136
169
|
const ordered = [
|
|
137
170
|
...execs.map(e => ({ exec: String(e.exec), call: String(e.call), order: e.seq, fenced: false })),
|
|
@@ -2,22 +2,36 @@
|
|
|
2
2
|
import { contentHash } from "../../kernel/ids.js";
|
|
3
3
|
import { budgets } from "../../kernel/guards.js";
|
|
4
4
|
import { CT } from "../../types.js";
|
|
5
|
+
function normalizeUsage(raw) {
|
|
6
|
+
return {
|
|
7
|
+
input: (raw.input ?? 0) + (raw.cacheRead ?? 0) + (raw.cacheWrite ?? 0),
|
|
8
|
+
output: raw.output ?? 0,
|
|
9
|
+
costUsd: raw.cost?.total ?? 0,
|
|
10
|
+
};
|
|
11
|
+
}
|
|
5
12
|
/** P31: Use the provider message identity, or native timestamp/content identity when pi omits an id. */
|
|
6
13
|
export function messageUsage(message) {
|
|
7
14
|
if (message.role !== "assistant" || !message.usage)
|
|
8
15
|
return;
|
|
9
16
|
const raw = message.usage;
|
|
10
|
-
return { id: String(message.id ?? message.timestamp ?? contentHash(message)), usage:
|
|
11
|
-
|
|
12
|
-
|
|
17
|
+
return { id: String(message.id ?? message.timestamp ?? contentHash(message)), usage: normalizeUsage(raw) };
|
|
18
|
+
}
|
|
19
|
+
/** P31: Extract usage from either an assistant message entry or a standalone pi `usage` entry (e.g. `cache_warm`). */
|
|
20
|
+
export function entryUsage(entry) {
|
|
21
|
+
if (entry.message)
|
|
22
|
+
return messageUsage(entry.message);
|
|
23
|
+
if (entry.type === "usage" && entry.usage) {
|
|
24
|
+
return { id: String(entry.id ?? entry.timestamp ?? contentHash(entry)), usage: normalizeUsage(entry.usage) };
|
|
25
|
+
}
|
|
26
|
+
return undefined;
|
|
13
27
|
}
|
|
14
|
-
/** P31: Charge only messages in segments opened by this call, excluding inherited context. */
|
|
28
|
+
/** P31: Charge only messages and usage entries in segments opened by this call, excluding inherited context. */
|
|
15
29
|
export function sessionUsage(entries, call) {
|
|
16
30
|
let own = false;
|
|
17
31
|
return entries.flatMap(e => {
|
|
18
32
|
if (e.type === "custom" && e.customType === CT.exec)
|
|
19
33
|
own = typeof e.data?.exec === "string" && e.data.exec.startsWith(`${call}#`);
|
|
20
|
-
const u = own &&
|
|
34
|
+
const u = own && entryUsage(e);
|
|
21
35
|
return u ? [u] : [];
|
|
22
36
|
});
|
|
23
37
|
}
|
|
@@ -12,7 +12,7 @@ export function toolPath(cwd, input) {
|
|
|
12
12
|
path = path.slice(1);
|
|
13
13
|
if (path === "~")
|
|
14
14
|
path = homedir();
|
|
15
|
-
else if (path.startsWith("~/"))
|
|
15
|
+
else if (path.startsWith("~/") || path.startsWith("~\\"))
|
|
16
16
|
path = join(homedir(), path.slice(2));
|
|
17
17
|
else if (/^file:\/\//.test(path))
|
|
18
18
|
path = fileURLToPath(path);
|
|
@@ -48,8 +48,10 @@ export async function main(options = {}) {
|
|
|
48
48
|
}
|
|
49
49
|
ledgers = { home, config, orch: await openJournal(orchLedger(home)) };
|
|
50
50
|
// Which version runs is visible to every pi session (status; a notice when it differs from the one pi loaded).
|
|
51
|
-
// `start` (Linux) tells this process from a later one given the same pid after a crash.
|
|
52
|
-
|
|
51
|
+
// `start` (Linux and Windows) tells this process from a later one given the same pid after a crash.
|
|
52
|
+
let start = await captureStart(process.pid).catch(() => '');
|
|
53
|
+
if (!start && process.platform === 'win32')
|
|
54
|
+
start = await captureStart(process.pid).catch(() => '');
|
|
53
55
|
// Partial writes of earlier starts (a full disk, say): best effort, never fails the start.
|
|
54
56
|
removeStaleTemps(binDir(home), 10 * 60_000);
|
|
55
57
|
// Subagents reach `pi-durable-subagents hold …` through this shim, written before the start is recorded (executor puts its directory first on PATH).
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// Pi-side ledger state: only projections used by readers, never decoded ledger history or run bodies.
|
|
2
|
+
import { fileIdentityKey } from "../kernel/fsx.js";
|
|
2
3
|
import { forgetJournalSnapshot, readJournalFold } from "../kernel/journal.js";
|
|
3
4
|
import { orchLedger, journalPath } from "../paths.js";
|
|
4
5
|
import { JT } from "../types.js";
|
|
@@ -123,7 +124,7 @@ export function readerLedger(home) {
|
|
|
123
124
|
return record;
|
|
124
125
|
}
|
|
125
126
|
readers.delete(path);
|
|
126
|
-
return { dev: 0, ino: 0, size: 0, length: 0, seen: 0, state: emptyReaderLedger() };
|
|
127
|
+
return { dev: "0", ino: "0", size: 0, length: 0, seen: 0, state: emptyReaderLedger() };
|
|
127
128
|
}
|
|
128
129
|
catch (error) {
|
|
129
130
|
readers.delete(path);
|
|
@@ -177,4 +178,4 @@ export function awaitingRuns(home, wid, key, revision) {
|
|
|
177
178
|
}
|
|
178
179
|
return out.length ? out : undefined;
|
|
179
180
|
}
|
|
180
|
-
export const readerLedgerIdentity = (record) =>
|
|
181
|
+
export const readerLedgerIdentity = (record) => fileIdentityKey(record);
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import { join } from "node:path";
|
|
8
8
|
import { rmSync } from "node:fs";
|
|
9
9
|
import { readCache, writeCache } from "../kernel/cache.js";
|
|
10
|
+
import { isFileId, isFileSize } from "../kernel/fsx.js";
|
|
10
11
|
import { journalExpectation } from "../kernel/journal.js";
|
|
11
12
|
import { cacheDir, journalPath } from "../paths.js";
|
|
12
13
|
import { JT, isEntry } from "../types.js";
|
|
@@ -111,7 +112,7 @@ export function readSettled(home, wid) {
|
|
|
111
112
|
const record = readCache(settledPath(home, wid));
|
|
112
113
|
if (!record || record.v !== SETTLED_VERSION || record.recovery !== RECOVERY_VERSION || record.wid !== wid)
|
|
113
114
|
return undefined;
|
|
114
|
-
if (!record.journal ||
|
|
115
|
+
if (!record.journal || !isFileId(record.journal.dev) || !isFileId(record.journal.ino) || !isFileSize(record.journal.size) || !record.done || typeof record.revision !== "number" || !Array.isArray(record.sweep) || !Array.isArray(record.resumed))
|
|
115
116
|
return undefined;
|
|
116
117
|
// Version 2 records held fenced tags with obsolete pid/start lineage. Keep their tags only; no rebuild is needed.
|
|
117
118
|
const tags = [];
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
// Read-only status snapshots (P25: `status` is always a fresh snapshot). Pure readers of committed journals:
|
|
2
2
|
// never depend on orchestrator memory, so the UI, the CLI and the main agent see the same durable state.
|
|
3
3
|
import { initiatorSummary, restartLine } from "./restart.js";
|
|
4
|
-
import { existsSync, readFileSync, readdirSync
|
|
4
|
+
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { FANOUT_BODIES } from "../compat/fanout.js";
|
|
7
|
+
import { fileIdentityKey, isFileId, isFileSize, statIdentitySync } from "../kernel/fsx.js";
|
|
7
8
|
import { crc32, forgetJournalSnapshot, forgetJournalSnapshotsIf, journalAppends, readJournalRecord, readJournalSnapshot, readJournalUncached } from "../kernel/journal.js";
|
|
8
9
|
import { readCache, writeCache } from "../kernel/cache.js";
|
|
9
10
|
import { digestDir, journalPath, pinnedDir, workflowDir } from "../paths.js";
|
|
@@ -16,6 +17,7 @@ import { packageVersion } from "../version.js";
|
|
|
16
17
|
import { worktreeCalls, worktreeLabel, isWorktreeConflict } from "./executor/worktree.js";
|
|
17
18
|
import { leaseCalls, leaseLines, leaseState } from "../platform/lease.js";
|
|
18
19
|
import { labelsOf } from "../events/derive.js";
|
|
20
|
+
import { probeKernelPid, winProcessAlive } from "../platform/windows.js";
|
|
19
21
|
import { PENDING_NOTE, generationRids, UNDELIVERED_FOLLOW_UP } from "./notes.js";
|
|
20
22
|
import { readStats } from "./stats.js";
|
|
21
23
|
export function answerForwardedNote(c, now = Date.now()) {
|
|
@@ -693,7 +695,9 @@ function digestOf(wf, entries, complete) {
|
|
|
693
695
|
function storedDigest(home, wid, dev, ino, size) {
|
|
694
696
|
const stored = readCache(join(digestDir(home), `${wid}.json`));
|
|
695
697
|
const d = stored?.digest, wf = d?.snapshot;
|
|
696
|
-
if (!(digestVersion() && stored?.v === digestVersion() && stored.home === home &&
|
|
698
|
+
if (!(digestVersion() && stored?.v === digestVersion() && stored.home === home &&
|
|
699
|
+
isFileId(stored.dev) && isFileId(stored.ino) && isFileSize(stored.size) &&
|
|
700
|
+
stored.dev === dev && stored.ino === ino && stored.size === size &&
|
|
697
701
|
d?.settled && Array.isArray(d.settled.attention) && d.settled.tasks && wf?.wid === wid && Array.isArray(wf.calls) &&
|
|
698
702
|
Array.isArray(wf.attention) && wf.counts && FINAL_STATUS.has(wf.status) && !wf.active && !wf.followUps))
|
|
699
703
|
return undefined;
|
|
@@ -735,7 +739,7 @@ export function workflowDigest(home, wid, ledger) {
|
|
|
735
739
|
return memo.digest;
|
|
736
740
|
let dev, ino, size;
|
|
737
741
|
try {
|
|
738
|
-
({ dev, ino, size } =
|
|
742
|
+
({ dev, ino, size } = statIdentitySync(path));
|
|
739
743
|
}
|
|
740
744
|
catch (error) {
|
|
741
745
|
if (error.code !== "ENOENT")
|
|
@@ -797,7 +801,7 @@ function settledFacts(home, wid) {
|
|
|
797
801
|
}
|
|
798
802
|
let dev, ino, size;
|
|
799
803
|
try {
|
|
800
|
-
({ dev, ino, size } =
|
|
804
|
+
({ dev, ino, size } = statIdentitySync(path));
|
|
801
805
|
}
|
|
802
806
|
catch (error) {
|
|
803
807
|
if (error.code !== "ENOENT")
|
|
@@ -1020,13 +1024,13 @@ function firstOrigin(home, wid) {
|
|
|
1020
1024
|
if (known && "origin" in known)
|
|
1021
1025
|
return known.origin;
|
|
1022
1026
|
const identity = () => { try {
|
|
1023
|
-
const st =
|
|
1024
|
-
return { ino: st.ino, size: st.size,
|
|
1027
|
+
const st = statIdentitySync(path);
|
|
1028
|
+
return { dev: st.dev, ino: st.ino, size: st.size, ctimeNs: st.stats.ctimeNs, mode: st.stats.mode };
|
|
1025
1029
|
}
|
|
1026
1030
|
catch {
|
|
1027
1031
|
return undefined;
|
|
1028
1032
|
} };
|
|
1029
|
-
const same = (a, b) => !!a && !!b && a.ino === b.ino && a.size === b.size && a.
|
|
1033
|
+
const same = (a, b) => !!a && !!b && a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.ctimeNs === b.ctimeNs && a.mode === b.mode;
|
|
1030
1034
|
// The identity is taken before the read, and a failure is kept only when the file did not change during the read:
|
|
1031
1035
|
// a chmod between the failed read and a later sample would otherwise be recorded as the failure's identity.
|
|
1032
1036
|
const before = identity();
|
|
@@ -1196,7 +1200,7 @@ export function allWorkflows(home) {
|
|
|
1196
1200
|
return snapshotsOf(home, workflowIds(home));
|
|
1197
1201
|
}
|
|
1198
1202
|
export function ledgerIdentity(record) {
|
|
1199
|
-
return record ?
|
|
1203
|
+
return record ? fileIdentityKey(record) : "";
|
|
1200
1204
|
}
|
|
1201
1205
|
function snapshotWithLedger(home, wid, ix, mark) {
|
|
1202
1206
|
const pendingRevision = (ix.revisions.get(wid) ?? 0) > (digests.get(pathsOf(home, wid).journal)?.digest.snapshot.rev ?? 0);
|
|
@@ -1416,17 +1420,18 @@ export function orchestratorView(state, loaded = packageVersion(), now = Date.no
|
|
|
1416
1420
|
const starting = orchestratorStarting(state), phase = starting ? `, starting ${age(now - starting.since)}` : "";
|
|
1417
1421
|
return { orchestrator: `${o.version} (pid ${o.pid}${phase})${note}`, ...(o.version === loaded ? {} : { versionNote: versionNote(o.version, loaded) }) };
|
|
1418
1422
|
}
|
|
1419
|
-
/** Whether the recorded orchestrator still runs. On Linux its start time also tells it from a later process
|
|
1420
|
-
* same pid after a crash (elsewhere the pid alone is checked). */
|
|
1421
|
-
export function processAlive(pid, start) {
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1423
|
+
/** Whether the recorded orchestrator still runs. On Linux and Windows its start time also tells it from a later process
|
|
1424
|
+
* given the same pid after a crash (elsewhere the pid alone is checked). */
|
|
1425
|
+
export function processAlive(pid, start, options = {}) {
|
|
1426
|
+
const platform = options.platform ?? process.platform;
|
|
1427
|
+
if (platform === "win32")
|
|
1428
|
+
return winProcessAlive(pid, start, options);
|
|
1429
|
+
const probe = (options.probePid ?? probeKernelPid)(pid);
|
|
1430
|
+
if (probe === "dead")
|
|
1431
|
+
return false;
|
|
1432
|
+
if (!start)
|
|
1433
|
+
return true;
|
|
1434
|
+
if (platform !== "linux")
|
|
1430
1435
|
return true;
|
|
1431
1436
|
try {
|
|
1432
1437
|
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
import { readFileSync, readdirSync } from "node:fs";
|
|
5
5
|
import { rename, rm, writeFile } from "node:fs/promises";
|
|
6
6
|
import { join } from "node:path";
|
|
7
|
+
import { replacePath } from "../kernel/fsx.js";
|
|
7
8
|
export const STATS_EVERY_MS = 10_000;
|
|
8
9
|
export const statsPath = (home) => join(home, "orchestrator-stats.json");
|
|
9
10
|
/** The summed rchar of this process's live threads, or undefined where there is none (see OrchestratorStats.readBytes). */
|
|
@@ -32,7 +33,7 @@ export async function writeStats(home, stats) {
|
|
|
32
33
|
const path = statsPath(home), temp = join(home, `.orchestrator-stats.${process.pid}.tmp`);
|
|
33
34
|
try {
|
|
34
35
|
await writeFile(temp, JSON.stringify(stats));
|
|
35
|
-
await
|
|
36
|
+
await replacePath(temp, path);
|
|
36
37
|
}
|
|
37
38
|
catch (error) {
|
|
38
39
|
await rm(temp, { force: true });
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// revised {rid,revision,snapshot} commit publications; old pins remain immutable.
|
|
6
6
|
// pruned {rid,wid,endedAt,bytes} (written by the engine) is decisive: the wid is gone, its create-intent and
|
|
7
7
|
// created entries stay for identity (A1), and recovery finishes removing w/<wid> and its staging dirs.
|
|
8
|
-
import { lstat, open, readdir, readFile,
|
|
8
|
+
import { lstat, open, readdir, readFile, stat, rm } from 'node:fs/promises';
|
|
9
9
|
import { createReadStream, readFileSync } from 'node:fs';
|
|
10
10
|
import { createHash } from 'node:crypto';
|
|
11
11
|
import { basename, extname, join, relative } from 'node:path';
|
|
@@ -16,6 +16,7 @@ import { contentHash, ulid } from "../kernel/ids.js";
|
|
|
16
16
|
import { openJournal, openLazyJournal, syncDirectory } from "../kernel/journal.js";
|
|
17
17
|
import { readSettled, settledPath } from "./settled.js";
|
|
18
18
|
import { publishFile } from "../kernel/mailbox.js";
|
|
19
|
+
import { replacePath } from "../kernel/fsx.js";
|
|
19
20
|
import { digestDir, factsDir, journalPath, pinnedDir, workflowDir } from "../paths.js";
|
|
20
21
|
import { JT } from "../types.js";
|
|
21
22
|
import { pinOrigin } from "./origin.js";
|
|
@@ -55,7 +56,7 @@ async function replaceFile(dir, name, text) {
|
|
|
55
56
|
await file.close();
|
|
56
57
|
}
|
|
57
58
|
try {
|
|
58
|
-
await
|
|
59
|
+
await replacePath(temp, join(dir, name));
|
|
59
60
|
}
|
|
60
61
|
catch (error) {
|
|
61
62
|
await rm(temp, { force: true });
|
package/dist/platform/cmdline.js
CHANGED
|
@@ -2,6 +2,7 @@ import { execFile } from "node:child_process";
|
|
|
2
2
|
import { readFile } from "node:fs/promises";
|
|
3
3
|
import { promisify } from "node:util";
|
|
4
4
|
import { PS } from "./proctable.js";
|
|
5
|
+
import { winCommandLine } from "./windows.js";
|
|
5
6
|
const exec = promisify(execFile);
|
|
6
7
|
/** EX1: A diagnostic argv, never evidence of identity or death. Unreadable processes have an empty command. */
|
|
7
8
|
export async function commandLine(pid, signal) {
|
|
@@ -10,6 +11,8 @@ export async function commandLine(pid, signal) {
|
|
|
10
11
|
return (await readFile(`/proc/${pid}/cmdline`, { encoding: "utf8", signal })).replace(/\0/g, " ").trimEnd().slice(0, 200);
|
|
11
12
|
if (process.platform === "darwin")
|
|
12
13
|
return (await exec(PS, ["-o", "command=", "-p", String(pid)], { signal, timeout: 450, maxBuffer: 1024 * 1024 })).stdout.trim().slice(0, 200);
|
|
14
|
+
if (process.platform === "win32")
|
|
15
|
+
return winCommandLine(pid, signal);
|
|
13
16
|
}
|
|
14
17
|
catch { /* Diagnostics must not prevent a fence. */ }
|
|
15
18
|
return "";
|
package/dist/platform/command.js
CHANGED
|
@@ -1,17 +1,39 @@
|
|
|
1
|
-
// Command calls (CallSpec.command): the launcher.
|
|
2
|
-
// wrapper that runs it, then records its exit status atomically in the attempt directory (`exit.tmp`, renamed
|
|
3
|
-
// and exits with the same status.
|
|
4
|
-
//
|
|
5
|
-
//
|
|
1
|
+
// Command calls (CallSpec.command): the launcher. On Unix a command runs detached in its own session under a tiny
|
|
2
|
+
// /bin/sh wrapper that runs it, then records its exit status atomically in the attempt directory (`exit.tmp`, renamed
|
|
3
|
+
// to `exit`) and exits with the same status. Windows has no /bin/sh: the same wrapper is a short Node program (Node is
|
|
4
|
+
// already the runtime), and a string command runs through the command's `ComSpec` (cmd.exe by default). Its output (stdout and stderr, interleaved) is
|
|
5
|
+
// appended to `output.log` in the same directory through a descriptor the orchestrator opens, passes and closes: no
|
|
6
|
+
// pipe leads back into the orchestrator and no node process stays resident for the life of the command, so it outlives
|
|
7
|
+
// the orchestrator that started it. On Windows that descriptor is not this process's: the attempt's group owner opens
|
|
8
|
+
// its own two append handles for the log (platform/job.ts), so nothing here opens or holds `output.log` while the owner
|
|
9
|
+
// compiles and starts.
|
|
10
|
+
//
|
|
11
|
+
// On Windows the wrapper also runs inside a Windows Job Object of its own (platform/job.ts): the wrapper is the group's
|
|
12
|
+
// root, created suspended and assigned before its first instruction, and the group's only handle dies with the owner --
|
|
13
|
+
// a small .NET Framework winexe compiled per launch with the framework's own csc.exe. A command attempt therefore cannot
|
|
14
|
+
// leave descendants behind, and a scan that finds the wrapper gone finds the group closed: no second attempt starts
|
|
15
|
+
// while processes of the first can still act. The attempt's `exec` tag goes into the owner's own command line as well,
|
|
16
|
+
// so the attempt is findable while the owner is still starting. The owner is the expensive part of a start, so it is
|
|
17
|
+
// staged (prepareCommand) before the attempt's durable intent: `proceed` is checked before the compilation and again
|
|
18
|
+
// immediately before the spawn, and a stop, retirement or exit during the compilation cancels it -- nothing recorded,
|
|
19
|
+
// nothing started, so that cut is unambiguously prelaunch.
|
|
6
20
|
import { spawn } from "node:child_process";
|
|
7
21
|
import { closeSync, openSync } from "node:fs";
|
|
8
|
-
import { mkdir,
|
|
22
|
+
import { mkdir, open, writeFile } from "node:fs/promises";
|
|
9
23
|
import { constants } from "node:os";
|
|
10
24
|
import { join } from "node:path";
|
|
25
|
+
import { retryWinSharing } from "../kernel/fsx.js";
|
|
11
26
|
import { captureStart } from "./proctable.js";
|
|
12
|
-
import { findOnPath } from "./launch.js";
|
|
27
|
+
import { execTarget, findOnPath } from "./launch.js";
|
|
28
|
+
import { prepareJob, spawnInJob } from "./job.js";
|
|
29
|
+
import { DWORD_MAX, comspec, envValue, helperEnv, IS_WINDOWS, mergeEnv, normalizeEnv, systemRoot, winTagArg } from "./windows.js";
|
|
13
30
|
export const COMMAND_LOG = "output.log";
|
|
14
31
|
export const COMMAND_EXIT = "exit";
|
|
32
|
+
/** What the Windows wrapper reads: the command, its cwd and its complete environment (a command line can be long and
|
|
33
|
+
* contain anything, so it is a file, not argv). */
|
|
34
|
+
export const COMMAND_SPEC = "command.json";
|
|
35
|
+
/** The Windows wrapper itself, written into the attempt directory before each spawn (Node runs a file, not a URL). */
|
|
36
|
+
export const COMMAND_WRAPPER = "wrapper.mjs";
|
|
15
37
|
/** The output a result carries: the last bytes of `output.log`. */
|
|
16
38
|
export const OUTPUT_TAIL_BYTES = 16 * 1024;
|
|
17
39
|
/** The wrapper: `$1` is the attempt directory, `$2` the absolute `mv`, the rest the command's argv. Its own steps use
|
|
@@ -21,16 +43,133 @@ export const OUTPUT_TAIL_BYTES = 16 * 1024;
|
|
|
21
43
|
* it), and its end, however it comes, never skips recording the status. A program named by a path that does not exist
|
|
22
44
|
* is 127 before `exec`: some shells (bash 3.2, the macOS /bin/sh) report 126 for it instead. */
|
|
23
45
|
const WRAPPER = 'd="$1"; m="$2"; shift 2; ( case "$1" in (*/*) [ -e "$1" ] || { printf "%s: %s: not found\\n" "$0" "$1" >&2; exit 127; } ;; esac; exec "$@" ); s="$?"; printf "%s\\n" "$s" > "$d/exit.tmp" && "$m" -f "$d/exit.tmp" "$d/exit"; exit "$s"';
|
|
46
|
+
/** Windows wrapper: `argv[2]` is the attempt directory (its command.json holds the command, cwd and environment).
|
|
47
|
+
* It runs the child with inherited output descriptors, records the status and exits with it. It merges the environment
|
|
48
|
+
* by Windows name, not by spelling: `Path`/`PATH`, `ComSpec`/`COMSPEC` and `PATHEXT`/`PathExt` are one variable each, the
|
|
49
|
+
* command's own definition wins (the wrapper process's only fills in a name the command lacks), and the block the child
|
|
50
|
+
* gets never carries a name twice. The string command runs through the command's `ComSpec`, not this process's. */
|
|
51
|
+
const WIN_WRAPPER = `import { spawn } from "node:child_process";
|
|
52
|
+
import { readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
53
|
+
import { join } from "node:path";
|
|
54
|
+
const dir = process.argv[2];
|
|
55
|
+
const SHARING = new Set(["EACCES", "EBUSY", "EPERM"]);
|
|
56
|
+
const WAIT = new Int32Array(new SharedArrayBuffer(4));
|
|
57
|
+
function retrySharing(fn, deadline) {
|
|
58
|
+
for (let attempt = 0; ; attempt++) {
|
|
59
|
+
try { return fn(); }
|
|
60
|
+
catch (error) {
|
|
61
|
+
if (!SHARING.has(error && error.code) || attempt >= 25) throw error;
|
|
62
|
+
const left = deadline - Date.now();
|
|
63
|
+
if (left <= 0) throw error;
|
|
64
|
+
Atomics.wait(WAIT, 0, 0, Math.min(left, Math.min(100, 10 * (attempt + 1))));
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const spec = JSON.parse(retrySharing(() => readFileSync(join(dir, "${COMMAND_SPEC}"), "utf8"), Date.now() + 2500));
|
|
69
|
+
try { unlinkSync(join(dir, "${COMMAND_SPEC}")); } catch { /* already gone */ }
|
|
70
|
+
// The status of the attempt is the kernel's 32-bit exit code. Node hands a Windows status back as a number whose bit
|
|
71
|
+
// pattern is that code -- on some paths as a signed int32 (0xC0000005 reads -1073741819) -- and a negative number is not
|
|
72
|
+
// an exit record at all, so every status is normalized to its DWORD here before it is written. process.exit takes an
|
|
73
|
+
// integer and the OS keeps its low 32 bits, so the same DWORD reaches the caller as this wrapper's own exit status: the
|
|
74
|
+
// record and the observed outcome cannot disagree.
|
|
75
|
+
function dword(code) { return code >>> 0; }
|
|
76
|
+
// Publish the exit record atomically (temp file then rename) with bounded retries on Windows transient sharing errors
|
|
77
|
+
// (antivirus/indexer/concurrent reader). Never fall back to a direct write to "exit" so readers never see partial data.
|
|
78
|
+
function record(status) {
|
|
79
|
+
const deadline = Date.now() + 2500;
|
|
80
|
+
try {
|
|
81
|
+
retrySharing(() => writeFileSync(join(dir, "exit.tmp"), String(status)), deadline);
|
|
82
|
+
retrySharing(() => renameSync(join(dir, "exit.tmp"), join(dir, "exit")), deadline);
|
|
83
|
+
} catch {
|
|
84
|
+
try { unlinkSync(join(dir, "exit.tmp")); } catch { /* never lose the command's own result */ }
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function value(env, name) { const lower = name.toLowerCase(); let found; for (const key of Object.keys(env)) if (key.toLowerCase() === lower) found = env[key]; return found; }
|
|
88
|
+
function put(env, name, val) { const lower = name.toLowerCase(); for (const key of Object.keys(env)) if (key.toLowerCase() === lower) delete env[key]; env[name] = val; }
|
|
89
|
+
const shell = value(spec.env, "ComSpec") || value(process.env, "ComSpec") || "cmd.exe";
|
|
90
|
+
// The command's block by name: one PATH (also when the call spelled it Path), one ComSpec, one PATHEXT.
|
|
91
|
+
const env = {};
|
|
92
|
+
for (const key of Object.keys(spec.env)) put(env, key, spec.env[key]);
|
|
93
|
+
put(env, "ComSpec", shell);
|
|
94
|
+
put(env, "PATHEXT", value(spec.env, "PATHEXT") || value(process.env, "PATHEXT") || ".COM;.EXE;.BAT;.CMD");
|
|
95
|
+
const options = { cwd: spec.cwd, env, stdio: ["ignore", "inherit", "inherit"], windowsHide: true, ...(spec.verbatim ? { windowsVerbatimArguments: true } : {}) };
|
|
96
|
+
let child;
|
|
97
|
+
try { child = typeof spec.command === "string" ? spawn(spec.command, { ...options, shell }) : spawn(spec.command[0], spec.command.slice(1), options); }
|
|
98
|
+
catch (error) { const status = error && error.code === "ENOENT" ? 127 : 126; record(status); process.exit(status); }
|
|
99
|
+
child.once("error", error => { const status = error && error.code === "ENOENT" ? 127 : 126; record(status); process.exit(status); });
|
|
100
|
+
child.once("exit", (code, signal) => { const status = code === null ? (signal ? 128 : 1) : dword(code); record(status); process.exit(status); });
|
|
101
|
+
`;
|
|
102
|
+
/** The wrapper's source (it is written into the attempt directory as `COMMAND_WRAPPER`): exported so its own environment
|
|
103
|
+
* merge and exit record can be exercised on a host that is not Windows. */
|
|
104
|
+
export const COMMAND_WRAPPER_SOURCE = WIN_WRAPPER;
|
|
24
105
|
/** `mv` for the wrapper: from this process's PATH, else /bin or /usr/bin; resolved once. */
|
|
25
106
|
let mvPath;
|
|
26
107
|
export function resolveMv(PATH = process.env.PATH) {
|
|
27
108
|
mvPath ??= findOnPath("mv", PATH) ?? findOnPath("mv", "/bin:/usr/bin") ?? "/bin/mv";
|
|
28
109
|
return mvPath;
|
|
29
110
|
}
|
|
30
|
-
/** The argv the wrapper runs: an argv as given (a program, never shell syntax), a string through
|
|
31
|
-
export const commandArgv = (command) => typeof command === "string" ? ["/bin/sh", "-c", command] : [...command];
|
|
111
|
+
/** The argv the wrapper runs: an argv as given (a program, never shell syntax), a string through the platform shell. */
|
|
112
|
+
export const commandArgv = (command) => typeof command === "string" ? [IS_WINDOWS ? comspec() : "/bin/sh", "-c", command] : [...command];
|
|
113
|
+
/** Whether `error` is a preparation cancelled by a stop, a retirement or the orchestrator's exit (never a failure of the
|
|
114
|
+
* attempt, and never sealed as one). */
|
|
115
|
+
export { prepareCancelled } from "./job.js";
|
|
116
|
+
/** The Windows plan of one command start: the child's environment as one block (Windows names one variable whatever their
|
|
117
|
+
* case: one `PATH`, one `ComSpec`, one `PATHEXT`), the command the wrapper runs (an argv whose program is a .cmd/.bat shim
|
|
118
|
+
* unwrapped to the program it names) and the wrapper's own argv. Shared by the staging and the start, so both describe the
|
|
119
|
+
* same attempt. */
|
|
120
|
+
function windowsPlan(spec) {
|
|
121
|
+
const inherited = normalizeEnv(spec.env);
|
|
122
|
+
const env = mergeEnv(inherited, { ComSpec: envValue(inherited, "ComSpec") || comspec(inherited),
|
|
123
|
+
PATHEXT: envValue(inherited, "PATHEXT") || ".COM;.EXE;.BAT;.CMD" });
|
|
124
|
+
let command;
|
|
125
|
+
let verbatim;
|
|
126
|
+
if (typeof spec.command === "string")
|
|
127
|
+
command = spec.command;
|
|
128
|
+
else {
|
|
129
|
+
const target = execTarget(spec.command[0], spec.command.slice(1), { env });
|
|
130
|
+
command = [target.command, ...target.args];
|
|
131
|
+
verbatim = target.verbatim;
|
|
132
|
+
}
|
|
133
|
+
return { env, command, ...(verbatim ? { verbatim } : {}), args: [join(spec.dir, COMMAND_WRAPPER), spec.dir, ...(spec.exec ? [winTagArg("DSA_EXEC", spec.exec)] : [])] };
|
|
134
|
+
}
|
|
135
|
+
/** Stage what a Windows command start needs, before its durable intent: the command spec and the wrapper the child runs,
|
|
136
|
+
* then the group owner compiled (bounded and cancellable: `signal` ends the compiler, removes what it wrote and rejects
|
|
137
|
+
* with a cancelled preparation). Nothing is started, so a crash here leaves no intent and no process: the attempt is
|
|
138
|
+
* unambiguously prelaunch. POSIX prepares nothing (the wrapper is /bin/sh). */
|
|
139
|
+
export async function prepareCommand(spec) {
|
|
140
|
+
if (!IS_WINDOWS)
|
|
141
|
+
return undefined;
|
|
142
|
+
// A command line can be long and contain anything: pass it through a file, not argv.
|
|
143
|
+
await mkdir(spec.dir, { recursive: true });
|
|
144
|
+
const plan = windowsPlan(spec);
|
|
145
|
+
await writeFile(join(spec.dir, COMMAND_SPEC), JSON.stringify({ command: plan.command, cwd: spec.cwd, env: plan.env, ...(plan.verbatim ? { verbatim: true } : {}) }));
|
|
146
|
+
await writeFile(join(spec.dir, COMMAND_WRAPPER), COMMAND_WRAPPER_SOURCE);
|
|
147
|
+
return prepareJob(spec.dir, { exe: process.execPath, env: helperEnv({ SystemRoot: systemRoot() }), cwd: spec.cwd, log: join(spec.dir, COMMAND_LOG),
|
|
148
|
+
args: plan.args, ...(spec.exec ? { exec: spec.exec } : {}) }, { ...(spec.signal ? { signal: spec.signal } : {}) });
|
|
149
|
+
}
|
|
32
150
|
export async function spawnCommand(spec) {
|
|
33
151
|
await mkdir(spec.dir, { recursive: true });
|
|
152
|
+
if (IS_WINDOWS) {
|
|
153
|
+
// The log belongs to the attempt's group owner: it opens its own append handles for it (platform/job.ts), so this
|
|
154
|
+
// process opens none -- an unused descriptor would only be held open across the compilation and the handshake.
|
|
155
|
+
// A staged preparation (prepareCommand) already wrote command.json, the wrapper and the compiled owner: rewriting
|
|
156
|
+
// them would only risk a spec the owner was not prepared for, so the start reads what it staged.
|
|
157
|
+
const plan = windowsPlan(spec);
|
|
158
|
+
if (!spec.prepared) {
|
|
159
|
+
await writeFile(join(spec.dir, COMMAND_SPEC), JSON.stringify({ command: plan.command, cwd: spec.cwd, env: plan.env, ...(plan.verbatim ? { verbatim: true } : {}) }));
|
|
160
|
+
await writeFile(join(spec.dir, COMMAND_WRAPPER), COMMAND_WRAPPER_SOURCE);
|
|
161
|
+
}
|
|
162
|
+
// An already revoked permission never prepares or starts; the executor's stage checks again immediately before the
|
|
163
|
+
// spawn (spawnInJob), so a stop or retirement that arrived while the owner compiled still starts nothing.
|
|
164
|
+
if (spec.proceed && !spec.proceed())
|
|
165
|
+
return undefined;
|
|
166
|
+
// Start the internal Node wrapper with OS defaults. It reads the command's environment from command.json.
|
|
167
|
+
return await spawnInJob(spec.dir, { exe: process.execPath, env: helperEnv({ SystemRoot: systemRoot() }), cwd: spec.cwd, log: join(spec.dir, COMMAND_LOG),
|
|
168
|
+
args: plan.args, ...(spec.exec ? { exec: spec.exec } : {}) }, { ...(spec.proceed ? { proceed: spec.proceed } : {}),
|
|
169
|
+
...(spec.prepared ? { prepared: spec.prepared } : {}), ...(spec.signal ? { signal: spec.signal } : {}) });
|
|
170
|
+
}
|
|
171
|
+
// POSIX: the wrapper's stdout and stderr are this descriptor, which it inherits and this process closes after the
|
|
172
|
+
// spawn: the command's log is never a pipe held by a process that has to outlive it.
|
|
34
173
|
const fd = openSync(join(spec.dir, COMMAND_LOG), "a");
|
|
35
174
|
try {
|
|
36
175
|
const mv = resolveMv(), argv = commandArgv(spec.command);
|
|
@@ -48,32 +187,57 @@ export async function spawnCommand(spec) {
|
|
|
48
187
|
closeSync(fd);
|
|
49
188
|
}
|
|
50
189
|
}
|
|
51
|
-
|
|
52
|
-
|
|
190
|
+
async function readExitFile(path) {
|
|
191
|
+
const file = await open(path, "r");
|
|
192
|
+
try {
|
|
193
|
+
const [text, info] = await Promise.all([file.readFile("utf8"), file.stat()]);
|
|
194
|
+
return { text, at: info.mtimeMs };
|
|
195
|
+
}
|
|
196
|
+
finally {
|
|
197
|
+
await file.close();
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
/** The status the wrapper recorded, or undefined while there is none (the command runs, or ended without one). The record
|
|
201
|
+
* is one exit status: on Windows the whole DWORD (a status above 0x7fffffff included), on POSIX 0..255. Anything outside
|
|
202
|
+
* that is not a status a wrapper wrote -- a negative number a Node version reported, a corrupt or foreign file -- and is
|
|
203
|
+
* not read as one. On Windows, transient sharing conflicts (`EACCES`, `EBUSY`, `EPERM`) are retried boundedly. */
|
|
204
|
+
export async function readExitRecord(dir, options = {}) {
|
|
53
205
|
const path = join(dir, COMMAND_EXIT);
|
|
54
|
-
|
|
206
|
+
const reader = options.read ?? readExitFile;
|
|
207
|
+
let recorded, at;
|
|
55
208
|
try {
|
|
56
|
-
|
|
209
|
+
({ text: recorded, at } = await retryWinSharing(() => reader(path), {
|
|
210
|
+
timeoutMs: 2_000,
|
|
211
|
+
maxAttempts: 20,
|
|
212
|
+
...options,
|
|
213
|
+
}));
|
|
57
214
|
}
|
|
58
215
|
catch (error) {
|
|
59
216
|
if (error.code === "ENOENT")
|
|
60
217
|
return undefined;
|
|
61
218
|
throw error;
|
|
62
219
|
}
|
|
63
|
-
|
|
64
|
-
|
|
220
|
+
// A wrapper writes one decimal status (and a newline): anything else in the file -- nothing, a sign, an exponent,
|
|
221
|
+
// text -- is not a status of this attempt.
|
|
222
|
+
const text = recorded.trim();
|
|
223
|
+
if (!/^\d{1,10}$/.test(text))
|
|
224
|
+
return undefined;
|
|
225
|
+
const status = Number(text);
|
|
226
|
+
return status <= DWORD_MAX ? { status, at } : undefined;
|
|
65
227
|
}
|
|
66
228
|
const signalNames = new Map(Object.entries(constants.signals).map(([name, n]) => [n, name]));
|
|
67
|
-
/** How an exit status reads.
|
|
68
|
-
* that itself exits with a status above 128 (`exit 130`) therefore reads as killed by that signal
|
|
69
|
-
* told apart from the status alone (the shell convention).
|
|
229
|
+
/** How an exit status reads. On POSIX the wrapper sees the status of a shell: a command killed by signal N exits 128+N,
|
|
230
|
+
* and a command that itself exits with a status above 128 (`exit 130`) therefore reads as killed by that signal -- the two
|
|
231
|
+
* cannot be told apart from the status alone (the shell convention). A status that is not 128 plus a known signal number
|
|
232
|
+
* reads as the status itself: a Windows DWORD, a status above 0x7fffffff included, always does. */
|
|
70
233
|
export function exitMeaning(status) {
|
|
71
234
|
const name = status > 128 ? signalNames.get(status - 128) : undefined;
|
|
72
235
|
return name ? { exitCode: null, signal: name } : { exitCode: status, signal: null };
|
|
73
236
|
}
|
|
74
237
|
/** The last `bytes` of a file, starting on a UTF-8 character boundary ("" when it is missing). */
|
|
75
|
-
export async function readTail(path, bytes = OUTPUT_TAIL_BYTES) {
|
|
76
|
-
const file = await open(path, "r")
|
|
238
|
+
export async function readTail(path, bytes = OUTPUT_TAIL_BYTES, options = {}) {
|
|
239
|
+
const file = await retryWinSharing(() => open(path, "r"), { timeoutMs: 1_000, maxAttempts: 15, ...options })
|
|
240
|
+
.catch((error) => { if (error.code === "ENOENT")
|
|
77
241
|
return undefined; throw error; });
|
|
78
242
|
if (!file)
|
|
79
243
|
return "";
|