pi-better-server 0.2.4 → 0.4.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/package.json +6 -3
- package/scripts/measure-shared-reads/daemon.mjs +7 -0
- package/scripts/measure-shared-reads/probe.mjs +10 -0
- package/scripts/measure-shared-reads.mjs +165 -0
- package/scripts/test-on-pi.sh +21 -3
- package/src/cli.ts +39 -2
- package/src/client.ts +9 -4
- package/src/daemon-owner.ts +48 -6
- package/src/handshake.ts +8 -7
- package/src/lifecycle-config.ts +4 -0
- package/src/paths.ts +1 -11
- package/src/protocol.ts +7 -0
- package/src/registry.ts +2 -1
- package/src/runtime/background-history.ts +241 -0
- package/src/runtime/background.ts +182 -0
- package/src/runtime/cancellation.ts +99 -0
- package/src/runtime/catalog-admission.ts +50 -0
- package/src/runtime/catalog.ts +133 -0
- package/src/runtime/client.ts +111 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -0
- package/src/runtime/domain/assignment-observation.mjs +120 -0
- package/src/runtime/domain/assignment-projection.d.mts +1 -0
- package/src/runtime/domain/assignment-projection.mjs +245 -0
- package/src/runtime/domain/background/conditions.mjs +93 -0
- package/src/runtime/domain/background/process-identity.mjs +110 -0
- package/src/runtime/domain/background/process.mjs +511 -0
- package/src/runtime/domain/background/registry.mjs +374 -0
- package/src/runtime/domain/background/snapshot.mjs +73 -0
- package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
- package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
- package/src/runtime/domain/background/supervisor/store.mjs +604 -0
- package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
- package/src/runtime/domain/background/supervisor/types.mjs +47 -0
- package/src/runtime/domain/background/terminal-publication.mjs +58 -0
- package/src/runtime/domain/background/types.mjs +3 -0
- package/src/runtime/domain/catalog/agent-session-settings.d.mts +30 -0
- package/src/runtime/domain/catalog/agent-session-settings.mjs +112 -0
- package/src/runtime/domain/catalog/catalog-overlay.d.mts +3 -0
- package/src/runtime/domain/catalog/catalog-overlay.mjs +9 -0
- package/src/runtime/domain/catalog/catalog-preferences.d.mts +17 -0
- package/src/runtime/domain/catalog/catalog-preferences.mjs +164 -0
- package/src/runtime/domain/catalog/catalog-schema.d.mts +265 -0
- package/src/runtime/domain/catalog/catalog-schema.mjs +1331 -0
- package/src/runtime/domain/catalog/catalog-skill-edits.d.mts +42 -0
- package/src/runtime/domain/catalog/catalog-skill-edits.mjs +95 -0
- package/src/runtime/domain/catalog/catalog-store.d.mts +126 -0
- package/src/runtime/domain/catalog/catalog-store.mjs +810 -0
- package/src/runtime/domain/catalog/roles/role.architect.md +13 -0
- package/src/runtime/domain/catalog/roles/role.developer.md +16 -0
- package/src/runtime/domain/catalog/roles/role.explorer.md +13 -0
- package/src/runtime/domain/catalog/roles/role.product-manager.md +13 -0
- package/src/runtime/domain/catalog/roles/role.researcher.md +13 -0
- package/src/runtime/domain/catalog/roles/role.reviewer.md +13 -0
- package/src/runtime/domain/catalog/roles/role.writer.md +12 -0
- package/src/runtime/domain/catalog/thinking.d.mts +8 -0
- package/src/runtime/domain/catalog/thinking.mjs +22 -0
- package/src/runtime/domain/coordinator/index.mjs +50 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
- package/src/runtime/domain/coordinator/src/discovery.mjs +94 -0
- package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
- package/src/runtime/domain/coordinator/src/operations.mjs +301 -0
- package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
- package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
- package/src/runtime/domain/coordinator/src/result-supervision.mjs +101 -0
- package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +367 -0
- package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
- package/src/runtime/domain/coordinator/src/store.mjs +245 -0
- package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
- package/src/runtime/domain/coordinator/src/types.mjs +24 -0
- package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
- package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
- package/src/runtime/domain/health-observation.d.mts +3 -0
- package/src/runtime/domain/health-observation.mjs +613 -0
- package/src/runtime/domain/health-surface.mjs +279 -0
- package/src/runtime/domain/log-cursor.mjs +148 -0
- package/src/runtime/domain/log-paths.mjs +13 -0
- package/src/runtime/domain/parse.d.mts +2 -0
- package/src/runtime/domain/parse.mjs +1173 -0
- package/src/runtime/domain/process-status.d.mts +1 -0
- package/src/runtime/domain/process-status.mjs +25 -0
- package/src/runtime/domain/session-store.d.mts +2 -0
- package/src/runtime/domain/session-store.mjs +489 -0
- package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
- package/src/runtime/domain/shared-harness-settings.mjs +126 -0
- package/src/runtime/domain/shared-log-utils.mjs +1223 -0
- package/src/runtime/domain/shared-stall-detector.mjs +37 -0
- package/src/runtime/domain/widget.d.mts +1 -0
- package/src/runtime/domain/widget.mjs +250 -0
- package/src/runtime/guardian.ts +189 -0
- package/src/runtime/health-config.ts +27 -0
- package/src/runtime/local-client.ts +34 -0
- package/src/runtime/mutation-store.ts +34 -0
- package/src/runtime/queries.ts +76 -0
- package/src/runtime/query-executor.ts +277 -0
- package/src/runtime/query-worker.mjs +119 -0
- package/src/runtime/read-model.ts +409 -0
- package/src/runtime/result-supervision.ts +63 -0
- package/src/runtime/root.ts +29 -0
- package/src/runtime/socket.ts +10 -0
- package/src/runtime/status-cli.ts +11 -0
- package/src/runtime/work-client.d.mts +14 -0
- package/src/runtime/work-client.mjs +102 -0
- package/src/server.ts +199 -14
- package/src/session-activity.ts +22 -2
- package/src/startup/activation.ts +32 -5
- package/src/startup/ensure.ts +13 -1
- package/src/startup/install.ts +2 -0
- package/src/version.ts +4 -0
|
@@ -0,0 +1,511 @@
|
|
|
1
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
2
|
+
import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, writeSync } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
/** Known Git for Windows locations; `bash -lc` needs a real bash, not the WSL shim. */
|
|
5
|
+
const WINDOWS_BASH_CANDIDATES = [
|
|
6
|
+
"C:\\Program Files\\Git\\bin\\bash.exe",
|
|
7
|
+
"C:\\Program Files (x86)\\Git\\bin\\bash.exe",
|
|
8
|
+
"C:\\Program Files\\Git\\usr\\bin\\bash.exe",
|
|
9
|
+
];
|
|
10
|
+
/**
|
|
11
|
+
* Resolve the shell used for `command` specs.
|
|
12
|
+
*
|
|
13
|
+
* POSIX keeps `/bin/bash`. Windows has no `/bin/bash`, and the `bash.exe` found
|
|
14
|
+
* on PATH is usually the WSL launcher in System32 or the WindowsApps alias,
|
|
15
|
+
* either of which would run the command inside WSL instead of Windows. Prefer
|
|
16
|
+
* an explicit override, then Git for Windows, then a non-WSL `bash.exe` on PATH.
|
|
17
|
+
*
|
|
18
|
+
* Resolved lazily at spawn time, not module load: env-injection extensions
|
|
19
|
+
* (e.g. pi-env) may apply settings.json `env` values after this module is
|
|
20
|
+
* evaluated, and those overrides must still take effect.
|
|
21
|
+
*
|
|
22
|
+
* Exposed for tests and reuse.
|
|
23
|
+
*/
|
|
24
|
+
export function resolveDefaultShell() {
|
|
25
|
+
const fromEnv = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
|
|
26
|
+
if (fromEnv)
|
|
27
|
+
return fromEnv;
|
|
28
|
+
if (process.platform !== "win32")
|
|
29
|
+
return "/bin/bash";
|
|
30
|
+
for (const candidate of WINDOWS_BASH_CANDIDATES) {
|
|
31
|
+
if (existsSync(candidate))
|
|
32
|
+
return candidate;
|
|
33
|
+
}
|
|
34
|
+
for (const dir of (process.env.PATH ?? "").split(";")) {
|
|
35
|
+
const trimmed = dir.trim();
|
|
36
|
+
if (!trimmed || /(^|[\\/])(system32|windowsapps)([\\/]|$)/i.test(trimmed))
|
|
37
|
+
continue;
|
|
38
|
+
const candidate = join(trimmed, "bash.exe");
|
|
39
|
+
if (existsSync(candidate))
|
|
40
|
+
return candidate;
|
|
41
|
+
}
|
|
42
|
+
// Nothing usable found: keep the POSIX default so the failure surfaces as a
|
|
43
|
+
// logged spawn error for the task instead of crashing the whole host process.
|
|
44
|
+
return "/bin/bash";
|
|
45
|
+
}
|
|
46
|
+
/** How long a timed-out process group has to exit on SIGTERM before SIGKILL. */
|
|
47
|
+
const TERMINATION_GRACE_MS = 2_000;
|
|
48
|
+
export function validateCommandSpec(spec) {
|
|
49
|
+
if (spec.shell === false) {
|
|
50
|
+
if (!spec.argv || spec.argv.length === 0 || !spec.argv[0]) {
|
|
51
|
+
throw new Error("argv with at least one element is required when shell:false");
|
|
52
|
+
}
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
if (!spec.command || spec.command.trim().length === 0) {
|
|
56
|
+
throw new Error("command is required unless shell:false with argv is provided");
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** Convert a Windows path to the `/c/...` form MSYS bash resolves in redirections. Exposed for tests and reuse. */
|
|
60
|
+
export function toMsysPath(path) {
|
|
61
|
+
const forward = path.replace(/\\/g, "/");
|
|
62
|
+
const drive = /^([A-Za-z]):(\/.+)$/.exec(forward);
|
|
63
|
+
return drive ? `/${drive[1].toLowerCase()}${drive[2]}` : forward;
|
|
64
|
+
}
|
|
65
|
+
/** Single-quote a value for safe literal use in a bash script line. Exposed for tests and reuse. */
|
|
66
|
+
export function bashSingleQuote(value) {
|
|
67
|
+
return `'${value.replace(/'/g, "'\\''")}'`;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Env var carrying the operator's own command into a gated launch (#619).
|
|
71
|
+
*
|
|
72
|
+
* The gate script `eval`s this value instead of concatenating it, so a command
|
|
73
|
+
* containing quotes, heredocs, or multiple lines is parsed exactly as bash would
|
|
74
|
+
* parse it alone. The value is also kept out of the spawned argv.
|
|
75
|
+
*/
|
|
76
|
+
export const STEP_GATE_COMMAND_ENV = "PI_BG_STEP_GATE_COMMAND";
|
|
77
|
+
/** Longest failing-step text recorded in task metadata; the log keeps it whole. */
|
|
78
|
+
export const STEP_GATE_COMMAND_CHARS = 160;
|
|
79
|
+
/**
|
|
80
|
+
* Bash script that runs an opt-in step gate around the operator's command (#619).
|
|
81
|
+
*
|
|
82
|
+
* The gate is a bash `errexit` contract, not shell parsing: `set -e` ends the
|
|
83
|
+
* command at the first unhandled failing step with that step's exit code, so a
|
|
84
|
+
* later command — in the same list, a function, a subshell, or a command
|
|
85
|
+
* substitution — can no longer turn a red gate green. A failure the command
|
|
86
|
+
* handles itself (`|| true`, `if`/`while`/`until` conditions, `!`, `&&`/`||`
|
|
87
|
+
* lists) is not a gate failure, and a discarded process-substitution status is
|
|
88
|
+
* not one either. `set -E` lets the ERR trap name a failure inside a shell
|
|
89
|
+
* function (functions run in the main shell); the trap records only main-shell
|
|
90
|
+
* failures (`BASH_SUBSHELL` 0), so a status bash itself discards is never claimed
|
|
91
|
+
* as the verdict — an unhandled command substitution still fails its assignment
|
|
92
|
+
* in the main shell. The EXIT trap writes the verdict to stderr, where the
|
|
93
|
+
* harness reads it back, and forces a failing step's code when the command
|
|
94
|
+
* disabled errexit and would have exited 0.
|
|
95
|
+
*
|
|
96
|
+
* Exposed for tests and reuse.
|
|
97
|
+
*/
|
|
98
|
+
export function stepGateScript(id) {
|
|
99
|
+
return [
|
|
100
|
+
"# Step gate (#619) from pi-better-background-tasks: bash errexit ends the command at its first unhandled failing step.",
|
|
101
|
+
"set -E",
|
|
102
|
+
"set -e",
|
|
103
|
+
`__pi_step_gate_id=${bashSingleQuote(id)}`,
|
|
104
|
+
"__pi_step_gate_first=0",
|
|
105
|
+
"__pi_step_gate_command=",
|
|
106
|
+
"__pi_step_gate_record() {",
|
|
107
|
+
" __pi_step_gate_status=$?",
|
|
108
|
+
" if [ \"${BASH_SUBSHELL:-0}\" -eq 0 ] && [ \"${__pi_step_gate_first:-0}\" -eq 0 ] && [ \"$__pi_step_gate_status\" -ne 0 ]; then",
|
|
109
|
+
" __pi_step_gate_first=$__pi_step_gate_status",
|
|
110
|
+
" __pi_step_gate_command=${BASH_COMMAND:-}",
|
|
111
|
+
" fi",
|
|
112
|
+
" return 0",
|
|
113
|
+
"}",
|
|
114
|
+
"__pi_step_gate_finish() {",
|
|
115
|
+
" __pi_step_gate_status=$?",
|
|
116
|
+
" if [ \"${__pi_step_gate_first:-0}\" -ne 0 ]; then",
|
|
117
|
+
" __pi_step_gate_text=${__pi_step_gate_command//$'\\n'/ }",
|
|
118
|
+
" printf '\\n--- step gate [%s]: first failing step exit=%s; shell exit=%s: %s ---\\n' \"$__pi_step_gate_id\" \"$__pi_step_gate_first\" \"$__pi_step_gate_status\" \"$__pi_step_gate_text\" >&2",
|
|
119
|
+
" if [ \"$__pi_step_gate_status\" -eq 0 ]; then exit \"$__pi_step_gate_first\"; fi",
|
|
120
|
+
" fi",
|
|
121
|
+
" exit \"$__pi_step_gate_status\"",
|
|
122
|
+
"}",
|
|
123
|
+
"trap '__pi_step_gate_record' ERR",
|
|
124
|
+
"trap '__pi_step_gate_finish' EXIT",
|
|
125
|
+
`if [ -z "\${${STEP_GATE_COMMAND_ENV}:-}" ]; then`,
|
|
126
|
+
" printf '\\n--- step gate [%s]: the gated command was not provided; nothing ran ---\\n' \"$__pi_step_gate_id\" >&2",
|
|
127
|
+
" exit 125",
|
|
128
|
+
"fi",
|
|
129
|
+
`eval "\${${STEP_GATE_COMMAND_ENV}}"`,
|
|
130
|
+
].join("\n");
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Read the gate's verdict marker from a task log (#619). Bash writes it as the last
|
|
134
|
+
* line of stderr, so log retention cannot turn a red gate green; a missing marker
|
|
135
|
+
* only costs the failing command's name, never the verdict carried by the exit code.
|
|
136
|
+
*
|
|
137
|
+
* Exposed for tests and reuse.
|
|
138
|
+
*/
|
|
139
|
+
export function parseStepGateFailure(logText, id) {
|
|
140
|
+
const marker = `--- step gate [${id}]: first failing step exit=`;
|
|
141
|
+
let found;
|
|
142
|
+
for (const rawLine of logText.split("\n")) {
|
|
143
|
+
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
|
|
144
|
+
if (!line.startsWith(marker) || !line.endsWith(" ---"))
|
|
145
|
+
continue;
|
|
146
|
+
const match = /^--- step gate \[[^\]]+\]: first failing step exit=(-?\d+); shell exit=(-?\d+): (.*) ---$/.exec(line);
|
|
147
|
+
if (!match)
|
|
148
|
+
continue;
|
|
149
|
+
const stepExitCode = Number(match[1]);
|
|
150
|
+
const shellExitCode = Number(match[2]);
|
|
151
|
+
if (!Number.isInteger(stepExitCode) || stepExitCode === 0)
|
|
152
|
+
continue;
|
|
153
|
+
// The marker is the newest evidence, and the shell writes only the first failing step.
|
|
154
|
+
found = {
|
|
155
|
+
stepExitCode,
|
|
156
|
+
shellExitCode: Number.isInteger(shellExitCode) ? shellExitCode : null,
|
|
157
|
+
command: boundedStepCommand(match[3]),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
return found;
|
|
161
|
+
}
|
|
162
|
+
function boundedStepCommand(value) {
|
|
163
|
+
const oneLine = value.replace(/\s+/g, " ").trim();
|
|
164
|
+
return oneLine.length > STEP_GATE_COMMAND_CHARS ? `${oneLine.slice(0, STEP_GATE_COMMAND_CHARS - 1)}…` : oneLine;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* On Windows, numeric fds above 2 are unusable as child stdio: Node spawns the
|
|
168
|
+
* process, but its output handles end up broken, every write fails, and shell
|
|
169
|
+
* tasks exit 1 having produced nothing. (POSIX inherits the fd normally.)
|
|
170
|
+
*
|
|
171
|
+
* Instead of handing the child a log fd, the shell opens and redirects into the
|
|
172
|
+
* log itself. Output stays durable — written by the detached task directly, so
|
|
173
|
+
* logging continues after pi exits — and the child runs with no inherited
|
|
174
|
+
* stdio. Raw argv specs get a bash trampoline (`exec`) that performs the same
|
|
175
|
+
* redirect before replacing itself with the target program.
|
|
176
|
+
*
|
|
177
|
+
* Exposed for tests and reuse.
|
|
178
|
+
*/
|
|
179
|
+
export function withWindowsLogRedirect(spec, logPath) {
|
|
180
|
+
const redirectLine = `exec >> ${bashSingleQuote(toMsysPath(logPath))} 2>&1`;
|
|
181
|
+
if (spec.shell === false) {
|
|
182
|
+
const argvText = spec.argv.map((arg) => bashSingleQuote(String(arg))).join(" ");
|
|
183
|
+
return {
|
|
184
|
+
...spec,
|
|
185
|
+
shell: true,
|
|
186
|
+
// The trampoline only redirects and execs an absolute program; sourcing
|
|
187
|
+
// the login profile (/etc/profile and friends) adds seconds of cold-start
|
|
188
|
+
// cost on a Windows runner and nothing the exec needs.
|
|
189
|
+
loginShell: false,
|
|
190
|
+
// The MSYS2 runtime rewrites POSIX-looking argv (e.g. `/c`, `/opt/x.sh`)
|
|
191
|
+
// when exec'ing native Windows binaries. Node spawn passed argv verbatim,
|
|
192
|
+
// so conversion is disabled to keep raw-argv semantics unchanged. The
|
|
193
|
+
// redirect target is unaffected: bash resolves it itself, already in
|
|
194
|
+
// `/c/...` form.
|
|
195
|
+
command: `${redirectLine}\nexport MSYS2_ARG_CONV_EXCL='*'\nexec ${argvText}`,
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
return { ...spec, command: `${redirectLine}\n${spec.command}` };
|
|
199
|
+
}
|
|
200
|
+
export function spawnCommand(spec, logPath, detached) {
|
|
201
|
+
validateCommandSpec(spec);
|
|
202
|
+
mkdirSync(dirname(logPath), { recursive: true });
|
|
203
|
+
const windows = process.platform === "win32";
|
|
204
|
+
const launchSpec = windows ? withWindowsLogRedirect(spec, logPath) : spec;
|
|
205
|
+
let fd;
|
|
206
|
+
let stdio;
|
|
207
|
+
if (windows) {
|
|
208
|
+
stdio = ["ignore", "ignore", "ignore"];
|
|
209
|
+
}
|
|
210
|
+
else {
|
|
211
|
+
fd = openSync(logPath, "a");
|
|
212
|
+
stdio = ["ignore", fd, fd];
|
|
213
|
+
}
|
|
214
|
+
const child = spawnArgs(launchSpec, detached, stdio);
|
|
215
|
+
const marker = `\n--- spawn ${new Date().toISOString()} pid=${child.pid ?? "unknown"} ---\n`;
|
|
216
|
+
try {
|
|
217
|
+
if (fd !== undefined) {
|
|
218
|
+
writeSync(fd, marker);
|
|
219
|
+
}
|
|
220
|
+
else {
|
|
221
|
+
// The detached child is already running; a throw here would orphan it
|
|
222
|
+
// with no task metadata, so the marker write is best effort.
|
|
223
|
+
appendFileSync(logPath, marker);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
// Log unavailable; the runtime close handler still records the failure.
|
|
228
|
+
}
|
|
229
|
+
finally {
|
|
230
|
+
if (fd !== undefined) {
|
|
231
|
+
try {
|
|
232
|
+
closeSync(fd);
|
|
233
|
+
}
|
|
234
|
+
catch { /* best effort */ }
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
// Spawn failures (ENOENT, bad cwd, permission denied) surface as an 'error'
|
|
238
|
+
// event. With no listener Node turns it into an uncaughtException that takes
|
|
239
|
+
// down the whole host process; log it here and let the runtime's 'close'
|
|
240
|
+
// handler finalize the task as failed.
|
|
241
|
+
child.on("error", (error) => {
|
|
242
|
+
try {
|
|
243
|
+
const code = error.code ?? "unknown";
|
|
244
|
+
appendFileSync(logPath, `\n--- spawn error ${new Date().toISOString()} code=${code} message=${error.message} ---\n`);
|
|
245
|
+
}
|
|
246
|
+
catch {
|
|
247
|
+
// Log unavailable; the runtime close handler still records the failure.
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
child.on("close", (code, signal) => {
|
|
251
|
+
try {
|
|
252
|
+
appendFileSync(logPath, `\n--- exit ${new Date().toISOString()} code=${code ?? "null"} signal=${signal ?? "null"} ---\n`);
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
// Log unavailable (swept tmp dir, ACL change): a throw here would crash
|
|
256
|
+
// the host; the runtime already finalized the task from meta.
|
|
257
|
+
}
|
|
258
|
+
});
|
|
259
|
+
return { child, pgid: detached && child.pid ? child.pid : undefined };
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Run one command to completion and collect its output.
|
|
263
|
+
*
|
|
264
|
+
* A timeout has to reach the whole process tree, not just the process spawned
|
|
265
|
+
* here. Two things make that necessary rather than tidy:
|
|
266
|
+
*
|
|
267
|
+
* - The command may not be what runs. Under the Linux write sandbox the spawned
|
|
268
|
+
* process is `bwrap`, which forks the real command instead of exec'ing it, so
|
|
269
|
+
* a signal to the spawned pid never reaches the command at all. (macOS
|
|
270
|
+
* `sandbox-exec` execs its target, which is why the same signal works there.)
|
|
271
|
+
* - `close` fires when the output pipes close, not when the child exits. A
|
|
272
|
+
* surviving grandchild keeps holding them, so signalling only the direct child
|
|
273
|
+
* leaves this promise pending indefinitely and the caller's deadline unenforced.
|
|
274
|
+
*
|
|
275
|
+
* So the child leads its own process group, and a timeout signals that group.
|
|
276
|
+
*/
|
|
277
|
+
export function runCommandOnce(spec, maxBufferBytes = 1024 * 1024, timeoutMs) {
|
|
278
|
+
validateCommandSpec(spec);
|
|
279
|
+
const startedAt = Date.now();
|
|
280
|
+
const child = spawnArgs(spec, true, ["ignore", "pipe", "pipe"]);
|
|
281
|
+
const cap = Math.max(1, Math.floor(maxBufferBytes));
|
|
282
|
+
const stdoutCapture = createCaptureBuffer();
|
|
283
|
+
const stderrCapture = createCaptureBuffer();
|
|
284
|
+
let timedOut = false;
|
|
285
|
+
child.stdout?.on("data", (chunk) => {
|
|
286
|
+
captureChunk(stdoutCapture, chunk, cap);
|
|
287
|
+
});
|
|
288
|
+
child.stderr?.on("data", (chunk) => {
|
|
289
|
+
captureChunk(stderrCapture, chunk, cap);
|
|
290
|
+
});
|
|
291
|
+
return new Promise((resolve, reject) => {
|
|
292
|
+
// The group outlives the leader as long as any member is alive, so the
|
|
293
|
+
// kernel keeps the id reserved and this stays addressable after the spawned
|
|
294
|
+
// process itself has been reaped.
|
|
295
|
+
const signalGroup = (signal) => {
|
|
296
|
+
if (child.pid === undefined)
|
|
297
|
+
return;
|
|
298
|
+
try {
|
|
299
|
+
stopProcessGroup(child.pid, undefined, signal);
|
|
300
|
+
}
|
|
301
|
+
catch (error) {
|
|
302
|
+
if (process.platform === "win32")
|
|
303
|
+
throw error;
|
|
304
|
+
// Nothing left in the group: the tree is already gone.
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
let escalation;
|
|
308
|
+
const timeout = timeoutMs === undefined ? undefined : setTimeout(() => {
|
|
309
|
+
timedOut = true;
|
|
310
|
+
try {
|
|
311
|
+
signalGroup("SIGTERM");
|
|
312
|
+
}
|
|
313
|
+
catch (error) {
|
|
314
|
+
settle();
|
|
315
|
+
reject(error);
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
// SIGTERM is a request. Whatever still holds the output pipes after the
|
|
319
|
+
// grace period is exactly what would keep this promise pending, so the
|
|
320
|
+
// group is killed outright rather than waited on.
|
|
321
|
+
escalation = setTimeout(() => {
|
|
322
|
+
try {
|
|
323
|
+
signalGroup("SIGKILL");
|
|
324
|
+
}
|
|
325
|
+
catch (error) {
|
|
326
|
+
settle();
|
|
327
|
+
reject(error);
|
|
328
|
+
}
|
|
329
|
+
}, TERMINATION_GRACE_MS);
|
|
330
|
+
escalation.unref();
|
|
331
|
+
}, Math.max(1, timeoutMs));
|
|
332
|
+
timeout?.unref();
|
|
333
|
+
const settle = () => {
|
|
334
|
+
if (timeout)
|
|
335
|
+
clearTimeout(timeout);
|
|
336
|
+
if (escalation)
|
|
337
|
+
clearTimeout(escalation);
|
|
338
|
+
};
|
|
339
|
+
child.on("error", (error) => {
|
|
340
|
+
settle();
|
|
341
|
+
reject(error);
|
|
342
|
+
});
|
|
343
|
+
child.on("close", (exitCode, signal) => {
|
|
344
|
+
settle();
|
|
345
|
+
const stdout = finishCapture(stdoutCapture);
|
|
346
|
+
const stderr = finishCapture(stderrCapture);
|
|
347
|
+
const captureTruncated = stdout.discardedBytes > 0 || stderr.discardedBytes > 0;
|
|
348
|
+
resolve({
|
|
349
|
+
exitCode,
|
|
350
|
+
signal,
|
|
351
|
+
stdout: stdout.text,
|
|
352
|
+
stderr: stderr.text,
|
|
353
|
+
startedAt,
|
|
354
|
+
endedAt: Date.now(),
|
|
355
|
+
...(timedOut ? { timedOut: true } : {}),
|
|
356
|
+
...(stdout.discardedBytes > 0 ? { stdoutDiscardedBytes: stdout.discardedBytes } : {}),
|
|
357
|
+
...(stderr.discardedBytes > 0 ? { stderrDiscardedBytes: stderr.discardedBytes } : {}),
|
|
358
|
+
...(captureTruncated ? { captureTruncated: true } : {}),
|
|
359
|
+
});
|
|
360
|
+
});
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
function createCaptureBuffer() {
|
|
364
|
+
return { chunks: [], storedBytes: 0, discardedBytes: 0, truncated: false };
|
|
365
|
+
}
|
|
366
|
+
function asBuffer(chunk) {
|
|
367
|
+
return Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
368
|
+
}
|
|
369
|
+
/** Largest UTF-8 prefix of `buffer` that fits in `maxBytes`. */
|
|
370
|
+
export function utf8PrefixLength(buffer, maxBytes) {
|
|
371
|
+
if (maxBytes <= 0)
|
|
372
|
+
return 0;
|
|
373
|
+
if (buffer.length <= maxBytes)
|
|
374
|
+
return buffer.length;
|
|
375
|
+
let end = maxBytes;
|
|
376
|
+
while (end > 0 && (buffer[end] & 0xc0) === 0x80)
|
|
377
|
+
end -= 1;
|
|
378
|
+
if (end === 0 && (buffer[0] & 0xc0) === 0x80)
|
|
379
|
+
return 0;
|
|
380
|
+
const lead = buffer[end];
|
|
381
|
+
const need = lead <= 0x7f ? 1
|
|
382
|
+
: (lead & 0xe0) === 0xc0 ? 2
|
|
383
|
+
: (lead & 0xf0) === 0xe0 ? 3
|
|
384
|
+
: (lead & 0xf8) === 0xf0 ? 4
|
|
385
|
+
: 1;
|
|
386
|
+
return end + need <= maxBytes ? end + need : end;
|
|
387
|
+
}
|
|
388
|
+
function captureChunk(target, chunk, maxBytes) {
|
|
389
|
+
const buffer = asBuffer(chunk);
|
|
390
|
+
if (target.truncated) {
|
|
391
|
+
target.discardedBytes += buffer.length;
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
const room = maxBytes - target.storedBytes;
|
|
395
|
+
if (buffer.length <= room) {
|
|
396
|
+
target.chunks.push(buffer);
|
|
397
|
+
target.storedBytes += buffer.length;
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
const take = utf8PrefixLength(buffer, room);
|
|
401
|
+
if (take > 0) {
|
|
402
|
+
target.chunks.push(buffer.subarray(0, take));
|
|
403
|
+
target.storedBytes += take;
|
|
404
|
+
}
|
|
405
|
+
target.discardedBytes += buffer.length - take;
|
|
406
|
+
target.truncated = true;
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Length of `buffer` without a trailing UTF-8 sequence that the cap cut short.
|
|
410
|
+
* Chunk boundaries can split a code point; once capture overflows, the bytes
|
|
411
|
+
* that would have completed it were discarded, so the dangling lead bytes are
|
|
412
|
+
* discarded too instead of decoding to U+FFFD.
|
|
413
|
+
*/
|
|
414
|
+
export function completeUtf8Length(buffer) {
|
|
415
|
+
let start = buffer.length - 1;
|
|
416
|
+
while (start >= 0 && buffer.length - start < 4 && (buffer[start] & 0xc0) === 0x80)
|
|
417
|
+
start -= 1;
|
|
418
|
+
if (start < 0)
|
|
419
|
+
return buffer.length;
|
|
420
|
+
const lead = buffer[start];
|
|
421
|
+
const need = lead <= 0x7f ? 1
|
|
422
|
+
: (lead & 0xe0) === 0xc0 ? 2
|
|
423
|
+
: (lead & 0xf0) === 0xe0 ? 3
|
|
424
|
+
: (lead & 0xf8) === 0xf0 ? 4
|
|
425
|
+
: 1;
|
|
426
|
+
return start + need > buffer.length ? start : buffer.length;
|
|
427
|
+
}
|
|
428
|
+
function finishCapture(target) {
|
|
429
|
+
const stored = Buffer.concat(target.chunks, target.storedBytes);
|
|
430
|
+
const keep = target.truncated ? completeUtf8Length(stored) : stored.length;
|
|
431
|
+
return {
|
|
432
|
+
text: stored.subarray(0, keep).toString("utf8"),
|
|
433
|
+
discardedBytes: target.discardedBytes + (stored.length - keep),
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Stop a task's process tree.
|
|
438
|
+
*
|
|
439
|
+
* POSIX signals the process group (`-target`), falling back to the direct pid
|
|
440
|
+
* when the group is already gone. Windows has no process groups in libuv, and
|
|
441
|
+
* `process.kill(pid)` would only terminate the spawned `bash.exe` while real
|
|
442
|
+
* work survives in grandchildren — so the tree is terminated with
|
|
443
|
+
* `taskkill /T /F` instead. Windows has no graceful signal delivery, so the
|
|
444
|
+
* requested signal is informational there.
|
|
445
|
+
*/
|
|
446
|
+
export function stopProcessGroup(pid, pgid, signal = "SIGTERM") {
|
|
447
|
+
if (process.platform === "win32") {
|
|
448
|
+
const result = spawnSync("taskkill", ["/T", "/F", "/PID", String(pid)], {
|
|
449
|
+
encoding: "utf8",
|
|
450
|
+
windowsHide: true,
|
|
451
|
+
});
|
|
452
|
+
if (result.error) {
|
|
453
|
+
const code = result.error.code;
|
|
454
|
+
throw new Error(`taskkill could not start for PID ${pid}${code ? ` (${code})` : ""}: ${result.error.message}`, {
|
|
455
|
+
cause: result.error,
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
if (result.status === 0)
|
|
459
|
+
return;
|
|
460
|
+
// A child can exit between the caller's liveness check and taskkill. That
|
|
461
|
+
// race is success; any still-live PID means the tree was not terminated.
|
|
462
|
+
if (!processExists(pid))
|
|
463
|
+
return;
|
|
464
|
+
const detail = String(result.stderr ?? result.stdout ?? "").replace(/\s+/g, " ").trim();
|
|
465
|
+
throw new Error(`taskkill failed with exit ${result.status ?? "unknown"} for PID ${pid}${detail ? `: ${detail}` : ""}`);
|
|
466
|
+
}
|
|
467
|
+
const target = pgid ?? pid;
|
|
468
|
+
try {
|
|
469
|
+
process.kill(-target, signal);
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
catch {
|
|
473
|
+
process.kill(pid, signal);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
export function processExists(pid) {
|
|
477
|
+
try {
|
|
478
|
+
process.kill(pid, 0);
|
|
479
|
+
return true;
|
|
480
|
+
}
|
|
481
|
+
catch {
|
|
482
|
+
return false;
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* The executable and argument vector a spec runs as.
|
|
487
|
+
*
|
|
488
|
+
* Shell specs become an explicit `bash -lc` invocation rather than a shell
|
|
489
|
+
* string, so every caller — spawning directly, or wrapping the same launch in an
|
|
490
|
+
* OS sandbox — starts from one definition of what actually executes.
|
|
491
|
+
*/
|
|
492
|
+
export function commandExecution(spec) {
|
|
493
|
+
if (spec.shell === false) {
|
|
494
|
+
const [command, ...args] = spec.argv;
|
|
495
|
+
return { execPath: command, execArgs: args };
|
|
496
|
+
}
|
|
497
|
+
return { execPath: resolveDefaultShell(), execArgs: [spec.loginShell === false ? "-c" : "-lc", spec.command] };
|
|
498
|
+
}
|
|
499
|
+
function spawnArgs(spec, detached, stdio) {
|
|
500
|
+
const env = { ...process.env, ...spec.env };
|
|
501
|
+
const { execPath, execArgs } = commandExecution(spec);
|
|
502
|
+
return spawn(execPath, execArgs, {
|
|
503
|
+
cwd: spec.cwd,
|
|
504
|
+
env,
|
|
505
|
+
detached,
|
|
506
|
+
stdio,
|
|
507
|
+
// A detached Windows child gets its own console window unless hidden; these
|
|
508
|
+
// tasks write to log files and must not flash terminals.
|
|
509
|
+
windowsHide: process.platform === "win32",
|
|
510
|
+
});
|
|
511
|
+
}
|