pi-better-background-tasks 0.18.0 → 0.20.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/README.md +25 -13
- package/package.json +1 -1
- package/runtime-client/artifacts/darwin-arm64.gz +0 -0
- package/runtime-client/artifacts/darwin-arm64.json +1 -1
- package/runtime-client/artifacts/darwin-x64.gz +0 -0
- package/runtime-client/artifacts/darwin-x64.json +1 -1
- package/runtime-client/artifacts/linux-arm64.gz +0 -0
- package/runtime-client/artifacts/linux-arm64.json +1 -1
- package/runtime-client/artifacts/linux-x64.gz +0 -0
- package/runtime-client/artifacts/linux-x64.json +1 -1
- package/runtime-client/src/runtime/client.mjs +30 -3
- package/runtime-client/src/runtime/root.mjs +5 -2
- package/runtime-client/src/runtime/work-client.mjs +150 -7
- package/src/adapter-contract.ts +1 -1
- package/src/goal-provider.ts +31 -16
- package/src/index.ts +25 -9
- package/src/managed-authority.ts +5 -3
- package/src/managed-client.ts +20 -7
- package/src/managed-frontend.ts +135 -19
- package/src/navigator-provider.ts +19 -5
- package/src/observed-wait-client.ts +10 -0
- package/src/observed-waits.ts +321 -53
- package/src/process-identity.ts +18 -2
- package/src/process.ts +48 -14
- package/src/registry.ts +53 -5
- package/src/review-settings.ts +18 -0
- package/src/runtime.ts +27 -82
- package/src/sandbox.ts +14 -11
- package/src/shared-callback-batcher.ts +11 -2
- package/src/shared-navigator-panels.ts +26 -4
- package/src/shared-navigator.ts +244 -40
- package/src/shared-operation-coordinator/assignment-observation.mjs +43 -35
- package/src/shared-operation-coordinator/src/assignment-changes.ts +73 -0
- package/src/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
- package/src/shared-operation-coordinator/src/background-requests.ts +14 -3
- package/src/shared-operation-coordinator/src/discovery.ts +5 -3
- package/src/shared-operation-coordinator/src/operations.ts +50 -2
- package/src/shared-operation-coordinator/src/outbox.ts +9 -0
- package/src/shared-operation-coordinator/src/result-supervision.ts +12 -0
- package/src/shared-operation-coordinator/src/rows.ts +2 -0
- package/src/shared-operation-coordinator/src/schema.ts +40 -24
- package/src/shared-operation-coordinator/src/store.ts +40 -8
- package/src/shared-operation-coordinator/src/subagent-launch.ts +24 -1
- package/src/shared-operation-coordinator/src/types.ts +5 -1
- package/src/shared-sandbox-core.ts +1 -1
- package/src/shared-work-client.mjs +150 -7
- package/src/stall.ts +7 -4
- package/src/supervised-progress.ts +43 -0
- package/src/supervisor/README.md +1 -4
- package/src/supervisor/emit-runner.mjs +1 -0
- package/src/supervisor/generated/process-identity.mjs +20 -2
- package/src/supervisor/generated/process.mjs +52 -14
- package/src/supervisor/generated/runner.mjs +47 -4
- package/src/supervisor/generated/store.mjs +3 -3
- package/src/supervisor/generated/watch-fingerprint.mjs +69 -0
- package/src/supervisor/runner.ts +38 -3
- package/src/supervisor/store.ts +3 -3
- package/src/supervisor/supervisor.ts +6 -3
- package/src/task-diagnostics.ts +1 -1
- package/src/tools.ts +67 -54
- package/src/types.ts +7 -3
- package/src/watch-fingerprint.ts +70 -0
- package/src/work-observation.ts +46 -19
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
// Do not edit: change the source and re-run the emitter (a drift test enforces this).
|
|
3
3
|
|
|
4
4
|
import { spawn, spawnSync } from "node:child_process";
|
|
5
|
-
import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, writeSync } from "node:fs";
|
|
6
|
-
import {
|
|
5
|
+
import { accessSync, appendFileSync, closeSync, constants, existsSync, mkdirSync, openSync, readFileSync, writeSync } from "node:fs";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import { dirname, join, win32 } from "node:path";
|
|
7
8
|
/** Known Git for Windows locations; `bash -lc` needs a real bash, not the WSL shim. */
|
|
8
9
|
const WINDOWS_BASH_CANDIDATES = [
|
|
9
10
|
"C:\\Program Files\\Git\\bin\\bash.exe",
|
|
@@ -16,7 +17,8 @@ const WINDOWS_BASH_CANDIDATES = [
|
|
|
16
17
|
* POSIX keeps `/bin/bash`. Windows has no `/bin/bash`, and the `bash.exe` found
|
|
17
18
|
* on PATH is usually the WSL launcher in System32 or the WindowsApps alias,
|
|
18
19
|
* either of which would run the command inside WSL instead of Windows. Prefer
|
|
19
|
-
* an explicit override, then Git for Windows,
|
|
20
|
+
* an explicit override, then Pi's shellPath, Git for Windows, and a non-WSL
|
|
21
|
+
* `bash.exe` on PATH.
|
|
20
22
|
*
|
|
21
23
|
* Resolved lazily at spawn time, not module load: env-injection extensions
|
|
22
24
|
* (e.g. pi-env) may apply settings.json `env` values after this module is
|
|
@@ -24,27 +26,62 @@ const WINDOWS_BASH_CANDIDATES = [
|
|
|
24
26
|
*
|
|
25
27
|
* Exposed for tests and reuse.
|
|
26
28
|
*/
|
|
27
|
-
export function resolveDefaultShell() {
|
|
29
|
+
export function resolveDefaultShell(shellPath) {
|
|
28
30
|
const fromEnv = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
|
|
29
31
|
if (fromEnv)
|
|
30
32
|
return fromEnv;
|
|
31
33
|
if (process.platform !== "win32")
|
|
32
34
|
return "/bin/bash";
|
|
33
|
-
|
|
35
|
+
const configured = shellPath ?? readWindowsShellSetting();
|
|
36
|
+
const tried = [];
|
|
37
|
+
if (configured?.trim()) {
|
|
38
|
+
const candidate = /^~[\\/]/.test(configured) ? win32.join(homedir(), configured.slice(2)) : configured;
|
|
39
|
+
tried.push(candidate);
|
|
40
|
+
try {
|
|
41
|
+
accessSync(candidate, constants.F_OK);
|
|
42
|
+
return candidate;
|
|
43
|
+
}
|
|
44
|
+
catch { /* An unavailable setting leaves standard Windows discovery enabled. */ }
|
|
45
|
+
}
|
|
46
|
+
const gitCandidates = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"]]
|
|
47
|
+
.filter((directory) => Boolean(directory))
|
|
48
|
+
.map(directory => win32.join(directory, "Git", "bin", "bash.exe"));
|
|
49
|
+
for (const candidate of new Set([...gitCandidates, ...WINDOWS_BASH_CANDIDATES])) {
|
|
50
|
+
tried.push(candidate);
|
|
34
51
|
if (existsSync(candidate))
|
|
35
52
|
return candidate;
|
|
36
53
|
}
|
|
37
|
-
for (const dir of (process.env.PATH ?? "").split(";")) {
|
|
54
|
+
for (const dir of (process.env.PATH ?? process.env.Path ?? "").split(";")) {
|
|
38
55
|
const trimmed = dir.trim();
|
|
39
56
|
if (!trimmed || /(^|[\\/])(system32|windowsapps)([\\/]|$)/i.test(trimmed))
|
|
40
57
|
continue;
|
|
41
|
-
const candidate = join(trimmed, "bash.exe");
|
|
58
|
+
const candidate = win32.join(trimmed, "bash.exe");
|
|
59
|
+
tried.push(candidate);
|
|
42
60
|
if (existsSync(candidate))
|
|
43
61
|
return candidate;
|
|
44
62
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
63
|
+
throw new Error("No Bash executable found for Windows Background tasks. Set Pi's shellPath in settings.json or "
|
|
64
|
+
+ "PI_BETTER_BACKGROUND_TASKS_SHELL to a working bash.exe. Searched:\n " + [...new Set(tried)].join("\n "));
|
|
65
|
+
}
|
|
66
|
+
function readWindowsShellSetting() {
|
|
67
|
+
const agentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
|
|
68
|
+
try {
|
|
69
|
+
const settings = JSON.parse(readFileSync(join(agentDir, "settings.json"), "utf8"));
|
|
70
|
+
return typeof settings?.shellPath === "string" ? settings.shellPath : undefined;
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/** Capture effective session settings before dispatching a Windows launch. */
|
|
77
|
+
export function resolveWindowsLaunchShell(pi) {
|
|
78
|
+
if (process.platform !== "win32")
|
|
79
|
+
return undefined;
|
|
80
|
+
const override = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
|
|
81
|
+
if (override)
|
|
82
|
+
return override;
|
|
83
|
+
const settings = pi.getSettings?.();
|
|
84
|
+
return resolveDefaultShell(typeof settings?.shellPath === "string" ? settings.shellPath : undefined);
|
|
48
85
|
}
|
|
49
86
|
/** How long a timed-out process group has to exit on SIGTERM before SIGKILL. */
|
|
50
87
|
const TERMINATION_GRACE_MS = 2_000;
|
|
@@ -62,8 +99,8 @@ export function validateCommandSpec(spec) {
|
|
|
62
99
|
/** Convert a Windows path to the `/c/...` form MSYS bash resolves in redirections. Exposed for tests and reuse. */
|
|
63
100
|
export function toMsysPath(path) {
|
|
64
101
|
const forward = path.replace(/\\/g, "/");
|
|
65
|
-
const drive = /^([A-Za-z]):(\/.+)$/.exec(forward);
|
|
66
|
-
return drive ? `/${drive
|
|
102
|
+
const [, drive, rest] = /^([A-Za-z]):(\/.+)$/.exec(forward) ?? [];
|
|
103
|
+
return drive && rest ? `/${drive.toLowerCase()}${rest}` : forward;
|
|
67
104
|
}
|
|
68
105
|
/** Single-quote a value for safe literal use in a bash script line. Exposed for tests and reuse. */
|
|
69
106
|
export function bashSingleQuote(value) {
|
|
@@ -147,7 +184,7 @@ export function parseStepGateFailure(logText, id) {
|
|
|
147
184
|
if (!line.startsWith(marker) || !line.endsWith(" ---"))
|
|
148
185
|
continue;
|
|
149
186
|
const match = /^--- step gate \[[^\]]+\]: first failing step exit=(-?\d+); shell exit=(-?\d+): (.*) ---$/.exec(line);
|
|
150
|
-
if (!match)
|
|
187
|
+
if (!match || match[3] === undefined)
|
|
151
188
|
continue;
|
|
152
189
|
const stepExitCode = Number(match[1]);
|
|
153
190
|
const shellExitCode = Number(match[2]);
|
|
@@ -497,7 +534,8 @@ export function commandExecution(spec) {
|
|
|
497
534
|
const [command, ...args] = spec.argv;
|
|
498
535
|
return { execPath: command, execArgs: args };
|
|
499
536
|
}
|
|
500
|
-
|
|
537
|
+
const resolved = process.platform === "win32" ? spec.resolvedWindowsShell : undefined;
|
|
538
|
+
return { execPath: resolved ?? resolveDefaultShell(), execArgs: [spec.loginShell === false ? "-c" : "-lc", spec.command] };
|
|
501
539
|
}
|
|
502
540
|
function spawnArgs(spec, detached, stdio) {
|
|
503
541
|
const env = { ...process.env, ...spec.env };
|
|
@@ -32,14 +32,15 @@
|
|
|
32
32
|
*/
|
|
33
33
|
import { spawn } from "node:child_process";
|
|
34
34
|
import { closeSync, openSync, realpathSync } from "node:fs";
|
|
35
|
-
import { resolve } from "node:path";
|
|
35
|
+
import { join, resolve } from "node:path";
|
|
36
36
|
import { setTimeout as delay } from "node:timers/promises";
|
|
37
37
|
import { fileURLToPath } from "node:url";
|
|
38
|
+
import { watchOutcomeFingerprint } from "./watch-fingerprint.mjs";
|
|
38
39
|
import { evaluateCondition, validateCondition } from "./conditions.mjs";
|
|
39
40
|
import { completeUtf8Length, stopProcessGroup, utf8PrefixLength } from "./process.mjs";
|
|
40
41
|
import { readProcessStartToken } from "./process-identity.mjs";
|
|
41
42
|
import { processGroupAlive } from "./identity.mjs";
|
|
42
|
-
import { appendEvent, appendStreamBytes, claimLaunch, ensureSupervisorTaskDir, readLaunchRecord, readStopRequest, writeCommandRecord, writeTerminalRecord, } from "./store.mjs";
|
|
43
|
+
import { appendEvent, appendStreamBytes, claimLaunch, ensureSupervisorTaskDir, readLaunchRecord, readStopRequest, writeCommandRecord, writeTerminalRecord, writeTextAtomic, } from "./store.mjs";
|
|
43
44
|
import { DEFAULT_TERMINAL_TAIL_BYTES, DEFAULT_WATCH_INTERVAL_MS, SUPERVISOR_GROUP_CLEANUP_DEADLINE_MS, SUPERVISOR_POLL_MS, SUPERVISOR_RECORD_VERSION, SUPERVISOR_RUNNER_VERSION, SUPERVISOR_TERMINATION_GRACE_MS, } from "./types.mjs";
|
|
44
45
|
/** How long the runner waits for `close` after the child reported `exit`. */
|
|
45
46
|
const PIPE_CLOSE_GRACE_MS = 1_000;
|
|
@@ -117,6 +118,39 @@ function streamChunk(sink, chunk, maxBytes) {
|
|
|
117
118
|
sink.tailBytes = keep.length;
|
|
118
119
|
}
|
|
119
120
|
}
|
|
121
|
+
/** Coalesce stream bursts while retaining the timestamp of the last byte, including discarded output. */
|
|
122
|
+
function progressRecorder(directory) {
|
|
123
|
+
const path = join(directory, "progress.json");
|
|
124
|
+
let pending;
|
|
125
|
+
let timer;
|
|
126
|
+
let lastWrite = 0;
|
|
127
|
+
const flush = () => {
|
|
128
|
+
timer = undefined;
|
|
129
|
+
if (!pending)
|
|
130
|
+
return;
|
|
131
|
+
try {
|
|
132
|
+
writeTextAtomic(path, JSON.stringify(pending));
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
process.stderr.write(`Could not record Background progress: ${String(error)}\n`);
|
|
136
|
+
}
|
|
137
|
+
lastWrite = Date.now();
|
|
138
|
+
};
|
|
139
|
+
return (observedAt, fingerprint) => {
|
|
140
|
+
if (fingerprint !== undefined && pending?.fingerprint === fingerprint)
|
|
141
|
+
return;
|
|
142
|
+
pending = { observedAt, fingerprint };
|
|
143
|
+
if (timer)
|
|
144
|
+
return;
|
|
145
|
+
const remaining = lastWrite + 1000 - Date.now();
|
|
146
|
+
if (remaining <= 0)
|
|
147
|
+
flush();
|
|
148
|
+
else {
|
|
149
|
+
timer = setTimeout(flush, remaining);
|
|
150
|
+
timer.unref();
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
}
|
|
120
154
|
function startToken(pid) {
|
|
121
155
|
return pid === undefined ? undefined : readProcessStartToken(pid);
|
|
122
156
|
}
|
|
@@ -389,15 +423,21 @@ function runChild(ctx, plan) {
|
|
|
389
423
|
};
|
|
390
424
|
child.stdout?.on("data", (chunk) => {
|
|
391
425
|
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
392
|
-
if (plan.mode === "stream")
|
|
426
|
+
if (plan.mode === "stream") {
|
|
393
427
|
streamChunk(ctx.stdout, buffer, plan.maxBytes);
|
|
428
|
+
if (buffer.length)
|
|
429
|
+
ctx.progress(Date.now());
|
|
430
|
+
}
|
|
394
431
|
else
|
|
395
432
|
captureChunk(stdoutCapture, buffer, plan.maxBytes);
|
|
396
433
|
});
|
|
397
434
|
child.stderr?.on("data", (chunk) => {
|
|
398
435
|
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
399
|
-
if (plan.mode === "stream")
|
|
436
|
+
if (plan.mode === "stream") {
|
|
400
437
|
streamChunk(ctx.stderr, buffer, plan.maxBytes);
|
|
438
|
+
if (buffer.length)
|
|
439
|
+
ctx.progress(Date.now());
|
|
440
|
+
}
|
|
401
441
|
else
|
|
402
442
|
captureChunk(stderrCapture, buffer, plan.maxBytes);
|
|
403
443
|
});
|
|
@@ -596,6 +636,7 @@ async function runWatch(ctx) {
|
|
|
596
636
|
if (ctx.finalized)
|
|
597
637
|
return;
|
|
598
638
|
ctx.checks += 1;
|
|
639
|
+
ctx.progress(outcome.endedAt, watchOutcomeFingerprint({ ...asCommandResult(outcome), ...(outcome.spawnError ? { error: outcome.spawnError } : {}) }));
|
|
599
640
|
// Per-check output keeps the streams apart: stdout bytes in stdout.log, stderr in stderr.log.
|
|
600
641
|
streamChunk(ctx.stdout, Buffer.from(outcome.stdout), ctx.launch.maxLogBytes);
|
|
601
642
|
streamChunk(ctx.stderr, Buffer.from(outcome.stderr), ctx.launch.maxLogBytes);
|
|
@@ -823,9 +864,11 @@ function main() {
|
|
|
823
864
|
checks: 0,
|
|
824
865
|
stdout,
|
|
825
866
|
stderr,
|
|
867
|
+
progress: progressRecorder(paths.dir),
|
|
826
868
|
stopRequested: false,
|
|
827
869
|
finalized: false,
|
|
828
870
|
};
|
|
871
|
+
ctx.progress(ctx.startedAt);
|
|
829
872
|
appendEvent(paths.events, `claimed runner_pid=${process.pid} runner_version=${SUPERVISOR_RUNNER_VERSION} kind=${launch.kind} cwd=${launch.command.cwd}`);
|
|
830
873
|
const onSignal = (signal) => {
|
|
831
874
|
appendEvent(paths.events, `runner received ${signal}`);
|
|
@@ -328,13 +328,13 @@ function readText(path) {
|
|
|
328
328
|
catch (error) {
|
|
329
329
|
if (error.code === "ENOENT")
|
|
330
330
|
return { missing: true };
|
|
331
|
-
return { missing:
|
|
331
|
+
return { missing: false, error: error instanceof Error ? error.message : String(error) };
|
|
332
332
|
}
|
|
333
333
|
}
|
|
334
334
|
function readJsonRecord(path, problem) {
|
|
335
335
|
const read = readText(path);
|
|
336
|
-
if (read.
|
|
337
|
-
return { missing:
|
|
336
|
+
if (read.value === undefined)
|
|
337
|
+
return { missing: read.missing, error: read.error };
|
|
338
338
|
let parsed;
|
|
339
339
|
try {
|
|
340
340
|
parsed = JSON.parse(read.value);
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// Generated by src/supervisor/emit-runner.mjs from the TypeScript source.
|
|
2
|
+
// Do not edit: change the source and re-run the emitter (a drift test enforces this).
|
|
3
|
+
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
/** Version tag of the watch outcome fingerprint. A value from another version is adopted, never compared. */
|
|
6
|
+
export const WATCH_FINGERPRINT_VERSION = "v1";
|
|
7
|
+
/** OSC and CSI control sequences are display markup, not content. */
|
|
8
|
+
const TERMINAL_ESCAPE = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b\[[0-?]*[ -/]*[@-~]/g;
|
|
9
|
+
/**
|
|
10
|
+
* Text as the terminal would settle it. Redraw frames and control sequences are
|
|
11
|
+
* display churn: repainting the same visible line is not a new observation.
|
|
12
|
+
*/
|
|
13
|
+
function settledTerminalText(text) {
|
|
14
|
+
return text
|
|
15
|
+
.replace(TERMINAL_ESCAPE, "")
|
|
16
|
+
.split("\n")
|
|
17
|
+
.map((line) => {
|
|
18
|
+
// A CR immediately before LF ends the line; any other CR overwrites it in place.
|
|
19
|
+
const body = line.endsWith("\r") ? line.slice(0, -1) : line;
|
|
20
|
+
return (body.split("\r").at(-1) ?? "").replace(/[ \t]+$/, "");
|
|
21
|
+
})
|
|
22
|
+
.join("\n")
|
|
23
|
+
.replace(/\n+$/, "");
|
|
24
|
+
}
|
|
25
|
+
/** Objects compare by content regardless of key order, so reordered keys are not progress. */
|
|
26
|
+
function canonicalJsonText(value) {
|
|
27
|
+
if (Array.isArray(value))
|
|
28
|
+
return `[${value.map(canonicalJsonText).join(",")}]`;
|
|
29
|
+
if (value && typeof value === "object") {
|
|
30
|
+
const record = value;
|
|
31
|
+
const entries = Object.keys(record).sort()
|
|
32
|
+
.map((key) => `${JSON.stringify(key)}:${canonicalJsonText(record[key])}`);
|
|
33
|
+
return `{${entries.join(",")}}`;
|
|
34
|
+
}
|
|
35
|
+
return JSON.stringify(value) ?? "null";
|
|
36
|
+
}
|
|
37
|
+
/** stdout compares as JSON content when it parses, and as settled text otherwise. */
|
|
38
|
+
function canonicalWatchStdout(stdout) {
|
|
39
|
+
const settled = settledTerminalText(stdout);
|
|
40
|
+
try {
|
|
41
|
+
return `json:${canonicalJsonText(JSON.parse(settled))}`;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return `text:${settled}`;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* What a poll observed, independent of when it ran. Exit status, signal, error,
|
|
49
|
+
* stdout content, and stderr content are included; poll metadata (start time,
|
|
50
|
+
* end time, duration, check count) is deliberately not, so it can never hide a
|
|
51
|
+
* watch that reports the same outcome forever. Watch stdout may carry its own
|
|
52
|
+
* timestamps: projecting meaningful fields is the caller's job, not this
|
|
53
|
+
* fingerprint's guess.
|
|
54
|
+
*/
|
|
55
|
+
export function watchOutcomeFingerprint(result) {
|
|
56
|
+
// A runner may report why the check itself could not run; that is part of the
|
|
57
|
+
// observed outcome, not poll metadata.
|
|
58
|
+
const reported = result.error;
|
|
59
|
+
const error = typeof reported === "string" ? settledTerminalText(reported) : null;
|
|
60
|
+
const payload = JSON.stringify([
|
|
61
|
+
result.exitCode,
|
|
62
|
+
result.signal ?? null,
|
|
63
|
+
result.timedOut === true,
|
|
64
|
+
error,
|
|
65
|
+
canonicalWatchStdout(result.stdout),
|
|
66
|
+
settledTerminalText(result.stderr),
|
|
67
|
+
]);
|
|
68
|
+
return `${WATCH_FINGERPRINT_VERSION}:${createHash("sha256").update(payload).digest("hex")}`;
|
|
69
|
+
}
|
package/src/supervisor/runner.ts
CHANGED
|
@@ -30,9 +30,10 @@
|
|
|
30
30
|
|
|
31
31
|
import { spawn } from "node:child_process";
|
|
32
32
|
import { closeSync, openSync, realpathSync } from "node:fs";
|
|
33
|
-
import { resolve } from "node:path";
|
|
33
|
+
import { join, resolve } from "node:path";
|
|
34
34
|
import { setTimeout as delay } from "node:timers/promises";
|
|
35
35
|
import { fileURLToPath } from "node:url";
|
|
36
|
+
import { watchOutcomeFingerprint } from "../watch-fingerprint.ts";
|
|
36
37
|
import { evaluateCondition, validateCondition } from "../conditions.ts";
|
|
37
38
|
import { completeUtf8Length, stopProcessGroup, utf8PrefixLength } from "../process.ts";
|
|
38
39
|
import { readProcessStartToken } from "../process-identity.ts";
|
|
@@ -47,6 +48,7 @@ import {
|
|
|
47
48
|
supervisorPaths,
|
|
48
49
|
writeCommandRecord,
|
|
49
50
|
writeTerminalRecord,
|
|
51
|
+
writeTextAtomic,
|
|
50
52
|
} from "./store.ts";
|
|
51
53
|
import {
|
|
52
54
|
DEFAULT_TERMINAL_TAIL_BYTES,
|
|
@@ -88,6 +90,7 @@ interface RunnerContext {
|
|
|
88
90
|
checks: number;
|
|
89
91
|
stdout: StreamSink;
|
|
90
92
|
stderr: StreamSink;
|
|
93
|
+
progress: (observedAt: number, fingerprint?: string) => void;
|
|
91
94
|
stopRequested: boolean;
|
|
92
95
|
finalized: boolean;
|
|
93
96
|
command?: { pid: number; pgid?: number; pidStartTime?: string; startedAt: number; attempt: number };
|
|
@@ -212,6 +215,29 @@ function streamChunk(sink: StreamSink, chunk: Buffer, maxBytes: number): void {
|
|
|
212
215
|
}
|
|
213
216
|
}
|
|
214
217
|
|
|
218
|
+
/** Coalesce stream bursts while retaining the timestamp of the last byte, including discarded output. */
|
|
219
|
+
function progressRecorder(directory: string) {
|
|
220
|
+
const path = join(directory, "progress.json");
|
|
221
|
+
let pending: { observedAt: number; fingerprint?: string } | undefined;
|
|
222
|
+
let timer: NodeJS.Timeout | undefined;
|
|
223
|
+
let lastWrite = 0;
|
|
224
|
+
const flush = () => {
|
|
225
|
+
timer = undefined;
|
|
226
|
+
if (!pending) return;
|
|
227
|
+
try { writeTextAtomic(path, JSON.stringify(pending)); }
|
|
228
|
+
catch (error) { process.stderr.write(`Could not record Background progress: ${String(error)}\n`); }
|
|
229
|
+
lastWrite = Date.now();
|
|
230
|
+
};
|
|
231
|
+
return (observedAt: number, fingerprint?: string) => {
|
|
232
|
+
if (fingerprint !== undefined && pending?.fingerprint === fingerprint) return;
|
|
233
|
+
pending = { observedAt, fingerprint };
|
|
234
|
+
if (timer) return;
|
|
235
|
+
const remaining = lastWrite + 1000 - Date.now();
|
|
236
|
+
if (remaining <= 0) flush();
|
|
237
|
+
else { timer = setTimeout(flush, remaining); timer.unref(); }
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
215
241
|
function startToken(pid: number | undefined): string | undefined {
|
|
216
242
|
return pid === undefined ? undefined : readProcessStartToken(pid);
|
|
217
243
|
}
|
|
@@ -482,12 +508,18 @@ function runChild(ctx: RunnerContext, plan: ChildPlan): Promise<ChildOutcome> {
|
|
|
482
508
|
|
|
483
509
|
child.stdout?.on("data", (chunk: Buffer | string) => {
|
|
484
510
|
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
485
|
-
if (plan.mode === "stream")
|
|
511
|
+
if (plan.mode === "stream") {
|
|
512
|
+
streamChunk(ctx.stdout, buffer, plan.maxBytes);
|
|
513
|
+
if (buffer.length) ctx.progress(Date.now());
|
|
514
|
+
}
|
|
486
515
|
else captureChunk(stdoutCapture, buffer, plan.maxBytes);
|
|
487
516
|
});
|
|
488
517
|
child.stderr?.on("data", (chunk: Buffer | string) => {
|
|
489
518
|
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
490
|
-
if (plan.mode === "stream")
|
|
519
|
+
if (plan.mode === "stream") {
|
|
520
|
+
streamChunk(ctx.stderr, buffer, plan.maxBytes);
|
|
521
|
+
if (buffer.length) ctx.progress(Date.now());
|
|
522
|
+
}
|
|
491
523
|
else captureChunk(stderrCapture, buffer, plan.maxBytes);
|
|
492
524
|
});
|
|
493
525
|
child.on("error", (error) => {
|
|
@@ -704,6 +736,7 @@ async function runWatch(ctx: RunnerContext): Promise<void> {
|
|
|
704
736
|
});
|
|
705
737
|
if (ctx.finalized) return;
|
|
706
738
|
ctx.checks += 1;
|
|
739
|
+
ctx.progress(outcome.endedAt, watchOutcomeFingerprint({ ...asCommandResult(outcome), ...(outcome.spawnError ? { error: outcome.spawnError } : {}) }));
|
|
707
740
|
// Per-check output keeps the streams apart: stdout bytes in stdout.log, stderr in stderr.log.
|
|
708
741
|
streamChunk(ctx.stdout, Buffer.from(outcome.stdout), ctx.launch.maxLogBytes);
|
|
709
742
|
streamChunk(ctx.stderr, Buffer.from(outcome.stderr), ctx.launch.maxLogBytes);
|
|
@@ -936,9 +969,11 @@ function main(): number {
|
|
|
936
969
|
checks: 0,
|
|
937
970
|
stdout,
|
|
938
971
|
stderr,
|
|
972
|
+
progress: progressRecorder(paths.dir),
|
|
939
973
|
stopRequested: false,
|
|
940
974
|
finalized: false,
|
|
941
975
|
};
|
|
976
|
+
ctx.progress(ctx.startedAt);
|
|
942
977
|
appendEvent(paths.events, `claimed runner_pid=${process.pid} runner_version=${SUPERVISOR_RUNNER_VERSION} kind=${launch.kind} cwd=${launch.command.cwd}`);
|
|
943
978
|
|
|
944
979
|
const onSignal = (signal: NodeJS.Signals): void => {
|
package/src/supervisor/store.ts
CHANGED
|
@@ -397,16 +397,16 @@ function readText(path: string): RecordRead<string> {
|
|
|
397
397
|
return { value: readFileSync(path, "utf8"), missing: false };
|
|
398
398
|
} catch (error) {
|
|
399
399
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return { missing: true };
|
|
400
|
-
return { missing:
|
|
400
|
+
return { missing: false, error: error instanceof Error ? error.message : String(error) };
|
|
401
401
|
}
|
|
402
402
|
}
|
|
403
403
|
|
|
404
404
|
function readJsonRecord<T>(path: string, problem: (value: unknown) => string | undefined): RecordRead<T> {
|
|
405
405
|
const read = readText(path);
|
|
406
|
-
if (read.
|
|
406
|
+
if (read.value === undefined) return { missing: read.missing, error: read.error };
|
|
407
407
|
let parsed: unknown;
|
|
408
408
|
try {
|
|
409
|
-
parsed = JSON.parse(read.value
|
|
409
|
+
parsed = JSON.parse(read.value);
|
|
410
410
|
} catch (error) {
|
|
411
411
|
return { missing: false, error: `invalid JSON: ${error instanceof Error ? error.message : String(error)}` };
|
|
412
412
|
}
|
|
@@ -527,13 +527,16 @@ class Supervisor implements LocalSupervisor {
|
|
|
527
527
|
options: SupervisorInspectOptions,
|
|
528
528
|
): { status: SupervisorTaskStatus; terminal: boolean; result?: SupervisorTerminalRecord; lost?: SupervisorLostRecord } {
|
|
529
529
|
return withStateFence(this.directory, launch.taskId, () => {
|
|
530
|
-
const result = readTerminalRecord(this.directory, launch.taskId)
|
|
530
|
+
const { value: result, error: resultError } = readTerminalRecord(this.directory, launch.taskId);
|
|
531
|
+
if (resultError) throw new Error(`Unreadable supervisor result record for ${launch.taskId}: ${resultError}`);
|
|
531
532
|
if (result) return { status: result.status as SupervisorTaskStatus, terminal: true, result };
|
|
532
533
|
|
|
533
|
-
const existingLost = readLostRecord(this.directory, launch.taskId)
|
|
534
|
+
const { value: existingLost, error: lostError } = readLostRecord(this.directory, launch.taskId);
|
|
535
|
+
if (lostError) throw new Error(`Unreadable supervisor loss record for ${launch.taskId}: ${lostError}`);
|
|
534
536
|
if (existingLost) return { status: "lost" as const, terminal: true, lost: existingLost };
|
|
535
537
|
|
|
536
|
-
const claim = readClaimRecord(this.directory, launch.taskId)
|
|
538
|
+
const { value: claim, error: claimError } = readClaimRecord(this.directory, launch.taskId);
|
|
539
|
+
if (claimError) throw new Error(`Unreadable supervisor claim record for ${launch.taskId}: ${claimError}`);
|
|
537
540
|
if (claim) {
|
|
538
541
|
if (identityAlive(claim.pid, claim.pidStartTime, claim.claimedAt, this.readToken)) {
|
|
539
542
|
return { status: "running" as const, terminal: false };
|
package/src/task-diagnostics.ts
CHANGED
|
@@ -52,7 +52,7 @@ export function inspectTaskProcess(
|
|
|
52
52
|
({ availability: "unavailable", reason, ...(identity ? { identity } : {}), limit: LIMIT });
|
|
53
53
|
if (access === "confined") return unavailable("Process activity adapter is unavailable under Main confinement; no unconfined process probe was run. Process access Read does not bypass kernel rules.");
|
|
54
54
|
if (access !== "read") return { availability: "blocked", reason: access === "off"
|
|
55
|
-
? "
|
|
55
|
+
? "An active Main or Background tasks profile denies process reads. Check Process access in /sandbox; this does not describe task confinement."
|
|
56
56
|
: "Current process-access policy is unavailable; no process probe was run.", limit: LIMIT };
|
|
57
57
|
if (meta.ssh) return unavailable("Remote activity is unavailable; no remote diagnostic command was run.");
|
|
58
58
|
if (meta.kind !== "process") return unavailable("Watch poll PID is not retained; last completed check is progress evidence only.");
|