opencode-model-router 1.13.0 → 1.15.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.
@@ -0,0 +1,711 @@
1
+ /**
2
+ * The single process layer for verification: every command runs through
3
+ * `runShell` (a shell string) or `runArgv` (argv, no shell), which share one
4
+ * implementation of the deadline, abort, output cap and tree kill.
5
+ *
6
+ * `child_process.exec` with `timeout` (or `signal`) only signals the shell it
7
+ * spawned. Test commands are process trees — `cmd /c npm test` -> npm -> vitest
8
+ * -> one worker per core — so killing the shell orphans everything below it,
9
+ * and the "aborted" baseline keeps every core busy until the suite finishes on
10
+ * its own. On a timeout or abort this kills the whole tree instead: `taskkill
11
+ * /T` on Windows, the process group on POSIX.
12
+ *
13
+ * Lifecycle guarantees (G4, docs/qa/verification-resource-budget/phase-1.2.md):
14
+ * - The promise always resolves, never rejects, and settles at most
15
+ * KILL_GRACE_MS after a kill even when a descendant that escaped the kill
16
+ * still holds the output pipes (they are then force-closed).
17
+ * - A deadline or abort that arrives after the direct child exited still
18
+ * reaches what it left running (POSIX: its process group; Windows: a
19
+ * creation-time-bounded sweep of its children, see `armSweeper`), without
20
+ * ever signalling a PID that may have been recycled.
21
+ * - `timedOut` is true when the deadline or abort fired while something still
22
+ * held the run (the command, a descendant it left running, or the held
23
+ * pipes), so a kill was attempted. A case that cannot be told apart counts as
24
+ * a kill (fail-closed): on Windows, the grace settling the run while a sweep
25
+ * that pinned trees is still reporting, even if the leftover exited on its
26
+ * own during the grace (QA-1.2-24, QA-1.2-28). An abort that finds nothing
27
+ * left running is a no-op: the natural result stands.
28
+ * - POSIX: when a run settles, whatever the command left in its process group
29
+ * (a background job, an unref'd child) is killed, so a normal exit leaves
30
+ * nothing running outside the slot either (QA-G-5). A `setsid` escapee is
31
+ * not reached. Windows sweeps only for a deadline or abort (the sweep costs a
32
+ * PowerShell start per run), so there a normal exit's leftovers survive
33
+ * (a documented limit, docs/VERIFICATION.md "Process limits").
34
+ * - Runs still in flight when opencode exits are killed from one
35
+ * `process.once("exit")` hook: on POSIX their process groups (QA-1.2-6), on
36
+ * Windows the tree of each direct child that has not exited (QA-1.2-18).
37
+ * libuv's kill-on-close job does not do this on Windows: its job allows
38
+ * silent breakaway, so it holds only the processes libuv spawned itself. It
39
+ * ends the direct child (cmd.exe) but not the tree below it (npm, vitest).
40
+ * Not covered: death by an unhandled signal (the host's SIGTERM/SIGHUP/Ctrl-C
41
+ * policy), which skips `exit` hooks and remains opencode's concern, and on
42
+ * Windows what an already-exited direct child left running (only the sweep
43
+ * reaches that).
44
+ */
45
+ import { execFile, spawn, spawnSync, type ChildProcess } from "node:child_process";
46
+ import { constants as osConstants, setPriority, tmpdir } from "node:os";
47
+ import { join } from "node:path";
48
+ import type { ArgvSeam, ExecOptions, ExecSeam } from "./types";
49
+
50
+ export interface ShellResult {
51
+ code: number;
52
+ stdout: string;
53
+ stderr: string;
54
+ /**
55
+ * True when the deadline or the abort signal fired while something still
56
+ * held the run and a kill was attempted. Fail-closed: a leftover that exited
57
+ * on its own during the kill grace, while a sweep that pinned trees was still
58
+ * reporting, also counts (see the header's G4 bullet).
59
+ */
60
+ timedOut: boolean;
61
+ }
62
+
63
+ export interface RunOptions extends ExecOptions {
64
+ /**
65
+ * Deadline in ms. Callers must bound every run with `timeoutMs` or `signal`;
66
+ * when both are absent the run gets DEFAULT_TIMEOUT_MS (120 s, the same
67
+ * default as `DeterministicDeps.timeoutMs`). `Infinity` explicitly means no
68
+ * deadline, `NaN` counts as absent, values <= 0 expire at once, and values
69
+ * above the 2^31-1 ms timer limit (~24.8 days) are clamped to it.
70
+ */
71
+ timeoutMs?: number;
72
+ /**
73
+ * Per-stream cap in characters (UTF-16 code units). Output past it is
74
+ * dropped and a `[stdout truncated at <n> chars]` line is appended to stderr.
75
+ * Default 10 MB.
76
+ */
77
+ maxBuffer?: number;
78
+ }
79
+
80
+ export const DEFAULT_TIMEOUT_MS = 120_000;
81
+ /** After a kill, the longest the result waits for the output pipes to close. */
82
+ export const KILL_GRACE_MS = 2000;
83
+ const MAX_TIMER_MS = 2 ** 31 - 1;
84
+ const DEFAULT_MAX_BUFFER = 10 * 1024 * 1024;
85
+ /** Windows: pipes still open this long after the child exited arm the orphan sweeper. */
86
+ const SWEEP_ARM_MS = 200;
87
+ /**
88
+ * Windows: the most the sweeper's kill phase may take before it is abandoned.
89
+ * It only bounds a hung sweeper: by then the kill grace has already settled the
90
+ * run, so a late kill costs the run nothing, while a short limit turned a slow
91
+ * sweep under normal-priority CPU saturation into no kill at all (QA-1.2-14).
92
+ * On a saturated 4-core CI runner, the first sweep of the job (a cold
93
+ * PowerShell start and the first CIM query) killed 28.7 s after the kill was
94
+ * requested, 1.3 s inside the former 30 s limit (phase 3.1, CI round 3).
95
+ * Exported for tests.
96
+ */
97
+ export const SWEEP_TIMEOUT_MS = 60_000;
98
+ /** Windows: the most `taskkill /T` on a live direct child may take. */
99
+ const TASKKILL_TIMEOUT_MS = 5000;
100
+ /**
101
+ * Windows: the most the exit hook's single `taskkill /T` may delay opencode's
102
+ * exit, and only when a verification is in flight: with none, the hook spawns
103
+ * nothing, and an idle taskkill takes well under a second. Under normal-priority
104
+ * CPU saturation taskkill took up to 3.4 s, and a 2 s limit left part of a tree
105
+ * running (QA-1.2-21); this is the last chance to reach those trees. A load that
106
+ * slows taskkill past this limit can still leave part of a tree (a G4 known limit).
107
+ */
108
+ const EXIT_TASKKILL_TIMEOUT_MS = 10_000;
109
+ /** Printed by the sweeper once pinning is done; its absence means the sweep did not run. */
110
+ const SWEEP_MARKER = "pinned";
111
+ /** Windows: clock tolerance between Date.now() and the kernel's creation times. */
112
+ const SWEEP_CLOCK_SLACK_MS = 50;
113
+
114
+ const isWin = process.platform === "win32";
115
+ /**
116
+ * Windows tools by absolute path: a bare name is looked up in the working
117
+ * directory before PATH (libuv), and that directory is the user's project.
118
+ */
119
+ const SYSTEM32 = process.env.SystemRoot ? join(process.env.SystemRoot, "System32") : undefined;
120
+ const TASKKILL = SYSTEM32 ? join(SYSTEM32, "taskkill.exe") : "taskkill.exe";
121
+ const DEFAULT_POWERSHELL = SYSTEM32 ? join(SYSTEM32, "WindowsPowerShell", "v1.0", "powershell.exe") : "powershell.exe";
122
+
123
+ /** Run `command` through the platform shell (`cmd.exe` / `/bin/sh`). */
124
+ export function runShell(command: string, opts: RunOptions = {}): Promise<ShellResult> {
125
+ // POSIX low priority: `nice -n 10 -- /bin/sh -c <command>` is exactly what
126
+ // `shell: true` would spawn, just prefixed, so the command string keeps its
127
+ // shell semantics and is never re-quoted. niceness is inherited by every
128
+ // descendant from birth, so there is no startup race on POSIX.
129
+ if (opts.lowPriority && !isWin) return run("nice", ["-n", "10", "--", "/bin/sh", "-c", command], false, opts);
130
+ return run(command, [], true, opts);
131
+ }
132
+
133
+ /**
134
+ * Windows: a batch file name, in any case and with the trailing dots and
135
+ * spaces that Windows strips from a file name.
136
+ */
137
+ const BATCH_FILE = /\.(cmd|bat)[. ]*$/i;
138
+ /** What Node itself returns for a batch file spawned without a shell. */
139
+ const BATCH_REFUSED = "exec failed: Error: spawn EINVAL (batch files must run through runShell)";
140
+
141
+ /**
142
+ * Spawn `file` with `args` and no shell: arguments reach the child
143
+ * byte-for-byte. On Windows a `.cmd`/`.bat` target is refused before anything
144
+ * is spawned, as a spawn error (`code: 1`, `spawn EINVAL` on stderr) — run
145
+ * batch files through `runShell` instead.
146
+ *
147
+ * CreateProcess runs a batch file through cmd.exe, which re-parses the
148
+ * arguments, so `"&calc&"` would run `calc` (BatBadBut, CVE-2024-27980). Node
149
+ * refuses such a spawn with EINVAL; Bun, which opencode loads the plugin in,
150
+ * does not, so the check is made here for both runtimes (QA-1.2-17). A bare
151
+ * name cannot reach a batch file: the runtime resolves it with `.com` and
152
+ * `.exe` only (a bare `probe` beside `probe.cmd` is ENOENT under both), and
153
+ * the argv adapters pass absolute `.js`/`.exe` targets.
154
+ */
155
+ export function runArgv(file: string, args: readonly string[], opts: RunOptions = {}): Promise<ShellResult> {
156
+ if (isWin && BATCH_FILE.test(file)) return Promise.resolve({ code: 1, stdout: "", stderr: BATCH_REFUSED, timedOut: false });
157
+ // `--` keeps a target whose name starts with "-" from being read as a nice option.
158
+ if (opts.lowPriority && !isWin) return run("nice", ["-n", "10", "--", file, ...args], false, opts, file);
159
+ return run(file, [...args], false, opts);
160
+ }
161
+
162
+ // Compile-time proof that both entry points satisfy the injection seams.
163
+ export const execSeam: ExecSeam = runShell;
164
+ export const argvSeam: ArgvSeam = runArgv;
165
+
166
+ /**
167
+ * @param niceTarget set when `file` is `nice` wrapping this argv target: nice
168
+ * reports a target it cannot exec as exit 127/126 instead of a spawn error.
169
+ */
170
+ function run(file: string, args: string[], shell: boolean, opts: RunOptions, niceTarget?: string): Promise<ShellResult> {
171
+ if (opts.signal?.aborted) return Promise.resolve({ code: 1, stdout: "", stderr: "", timedOut: true });
172
+ const deadline = deadlineOf(opts);
173
+ return new Promise((resolve) => {
174
+ const limit = opts.maxBuffer === undefined || Number.isNaN(opts.maxBuffer) ? DEFAULT_MAX_BUFFER : Math.max(0, opts.maxBuffer);
175
+ const out = capture(limit);
176
+ const err = capture(limit);
177
+ const notes: string[] = [];
178
+ let killRequested = false;
179
+ /** The deadline or abort ended something: the command, a leftover descendant or the pipes. */
180
+ let killed = false;
181
+ let exited = false;
182
+ let exitCode: number | null = null;
183
+ let exitedAt = 0;
184
+ let closed = false;
185
+ let closeCode: number | null = null;
186
+ let settled = false;
187
+ let groupGone = false;
188
+ let sweeper: Sweeper | undefined;
189
+ let swept = false;
190
+ let sweepPending = false;
191
+ let timer: ReturnType<typeof setTimeout> | undefined;
192
+ let grace: ReturnType<typeof setTimeout> | undefined;
193
+ let armTimer: ReturnType<typeof setTimeout> | undefined;
194
+ const spawnedAt = Date.now();
195
+ let child: ChildProcess;
196
+ try {
197
+ child = spawn(file, args, {
198
+ cwd: opts.cwd,
199
+ env: mergeEnv(opts.env),
200
+ shell,
201
+ windowsHide: true,
202
+ // Its own process group on POSIX, so the whole tree can be signalled at once.
203
+ detached: !isWin,
204
+ stdio: ["ignore", "pipe", "pipe"],
205
+ });
206
+ } catch (e) {
207
+ resolve({ code: 1, stdout: "", stderr: `exec failed: ${String(e)}`, timedOut: false });
208
+ return;
209
+ }
210
+ const pid = child.pid;
211
+ if (opts.lowPriority && isWin && pid) {
212
+ // Windows low priority (Spike A, docs/qa/verification-resource-budget/phase-1.2.md):
213
+ // lower the direct child right after spawn; descendants inherit the class
214
+ // when they are created. The `start /BELOWNORMAL` wrapper was rejected
215
+ // because it loses exit codes of `.cmd` targets such as npm.cmd.
216
+ // Startup race: anything the child spawns before this call runs at normal
217
+ // priority. The window is the few microseconds between CreateProcess and
218
+ // this line, before the child has even loaded its runtime, so in practice
219
+ // no grandchild exists yet — but it is not a guarantee.
220
+ try {
221
+ setPriority(pid, osConstants.priority.PRIORITY_BELOW_NORMAL);
222
+ } catch (e) {
223
+ // The child may already have exited; the run itself is unaffected.
224
+ notes.push(`[low priority not applied: ${String(e)}]`);
225
+ }
226
+ }
227
+ // After the priority call, which must follow the spawn as closely as possible.
228
+ const trackToken = Symbol("run");
229
+ if (pid) track(pid, trackToken);
230
+ // A StringDecoder per stream, so a multi-byte character split across two
231
+ // chunks is not turned into U+FFFD.
232
+ child.stdout?.setEncoding("utf8");
233
+ child.stderr?.setEncoding("utf8");
234
+ // Output past the cap is dropped rather than failing the run; the verdict
235
+ // is parsed from the summary lines, which runners print last only when the
236
+ // run completes, so truncation degrades to "unknown output", never a pass.
237
+ child.stdout?.on("data", (s: string) => out.push(s));
238
+ child.stderr?.on("data", (s: string) => err.push(s));
239
+
240
+ const finish = (code: number | null, error?: unknown) => {
241
+ if (settled) return;
242
+ settled = true;
243
+ clearTimeout(timer);
244
+ clearTimeout(grace);
245
+ clearTimeout(armTimer);
246
+ opts.signal?.removeEventListener("abort", kill);
247
+ // Windows keeps the child tracked until its `exit`: one that outlived
248
+ // the grace is exactly what the exit hook must still end.
249
+ if (!isWin && pid) {
250
+ // QA-G-5: a run that ended normally may have left background members
251
+ // in its group (`cmd &`, an unref'd child). They would keep running
252
+ // outside the slot, so they are ended with the run. The same guards
253
+ // as the late kill: the group was not seen empty and the entry is
254
+ // still ours (QA-1.2-27). A `setsid` escapee is not in the group.
255
+ if (!groupGone && ownsTracked(pid, trackToken) && groupAlive(pid)) signalGroup(pid, "SIGKILL");
256
+ untrack(pid, trackToken);
257
+ }
258
+ // A sweep that is killing must finish, but must not keep opencode alive
259
+ // (QA-1.2-19); one that is only armed is released.
260
+ if (sweeper && sweepPending) sweeper.unref();
261
+ else sweeper?.dispose();
262
+ let finalCode = killed ? code || 1 : code ?? 1;
263
+ let stderr = err.text;
264
+ if (niceTarget && !killed && (code === 126 || code === 127) && stderr.startsWith("nice:")) {
265
+ // The same contract as a direct spawn: code 1 and the errno in stderr.
266
+ stderr = `exec failed: spawn ${niceTarget} ${code === 127 ? "ENOENT" : "EACCES"} (${stderr.trim()})`;
267
+ finalCode = 1;
268
+ }
269
+ if (error) stderr += String(error);
270
+ if (out.truncated) notes.push(`[stdout truncated at ${limit} chars]`);
271
+ if (err.truncated) notes.push(`[stderr truncated at ${limit} chars]`);
272
+ for (const note of notes) stderr += `${stderr && !stderr.endsWith("\n") ? "\n" : ""}${note}\n`;
273
+ resolve({ code: finalCode, stdout: out.text, stderr, timedOut: killed });
274
+ };
275
+
276
+ const onSwept = (pids: number[], unavailable?: string) => {
277
+ sweepPending = false;
278
+ // Reported only while the run is still pending; after the grace settled
279
+ // it there is no result left to carry the note.
280
+ if (unavailable && !settled) notes.push(`[orphan sweep unavailable: ${unavailable}]`);
281
+ if (pids.length > 0) {
282
+ killed = true;
283
+ notes.push(`[killed ${pids.length} process tree(s) left running by the exited command: pid ${pids.join(", ")}]`);
284
+ }
285
+ if (closed) finish(closeCode);
286
+ };
287
+ /** Windows only: kill what the exited child left running (at most once per run). */
288
+ const sweep = () => {
289
+ if (swept || !pid) return;
290
+ swept = true;
291
+ sweeper ??= armSweeper(pid, spawnedAt, exitedAt);
292
+ sweepPending = true;
293
+ sweeper.kill(onSwept);
294
+ };
295
+
296
+ const onGrace = () => {
297
+ if (settled) return;
298
+ if (!closed) {
299
+ // Something that survived the kill still holds the pipes: stop waiting
300
+ // for it so neither the run nor its slot outlives the deadline.
301
+ child.stdout?.destroy();
302
+ child.stderr?.destroy();
303
+ if (!exited) child.kill("SIGKILL");
304
+ killed = true;
305
+ const holder = exited ? "a descendant still held them" : "the process did not exit";
306
+ notes.push(`[output streams force-closed ${KILL_GRACE_MS} ms after the kill: ${holder}]`);
307
+ } else if (sweepPending && sweeper && sweeper.pinnedCount() > 0) {
308
+ // The pipes closed while the sweep had not reported yet (QA-1.2-24):
309
+ // with trees pinned, its kill may be what closed them, so the result
310
+ // must not read as a natural exit. A sweep that has pinned nothing
311
+ // cannot have killed anything, and the natural result stands (QA-1.2-10).
312
+ killed = true;
313
+ notes.push("[orphan sweep still reporting at settle: it may have ended what held the pipes]");
314
+ }
315
+ finish(closed ? closeCode : exitCode);
316
+ };
317
+
318
+ const kill = () => {
319
+ if (killRequested || settled) return;
320
+ killRequested = true;
321
+ grace = setTimeout(onGrace, KILL_GRACE_MS);
322
+ grace.unref();
323
+ if (!exited) {
324
+ // Also taken when the OS already ended the child but libuv has not
325
+ // delivered `exit` yet: indistinguishable here, so it counts as a kill.
326
+ killed = true;
327
+ killTree(child);
328
+ return;
329
+ }
330
+ // The direct child already exited, so its PID may be recycled: never
331
+ // `taskkill` it. Only what it left running can remain.
332
+ if (isWin) {
333
+ sweep();
334
+ } else if (pid && !groupGone && ownsTracked(pid, trackToken) && signalGroup(pid, "SIGKILL")) {
335
+ // A group id is not reused while any member is alive, and `groupGone`
336
+ // stops us once the group was seen empty. If the group emptied later
337
+ // and a new run's group took the id, that run overwrote our entry, so
338
+ // the ownership check skips its group (QA-1.2-27).
339
+ killed = true;
340
+ notes.push("[killed the process group left running by the exited command]");
341
+ }
342
+ };
343
+
344
+ if (deadline !== undefined) timer = setTimeout(kill, deadline);
345
+ opts.signal?.addEventListener("abort", kill, { once: true });
346
+
347
+ child.on("exit", (code) => {
348
+ exited = true;
349
+ exitCode = code;
350
+ exitedAt = Date.now();
351
+ // Windows: libuv has closed the child's handle, so its PID may be recycled from here on.
352
+ if (isWin && pid) untrack(pid, trackToken);
353
+ if (!isWin && pid && !groupAlive(pid)) {
354
+ groupGone = true;
355
+ untrack(pid, trackToken);
356
+ }
357
+ if (isWin && pid) {
358
+ // Pipes still open shortly after exit mean a descendant holds them.
359
+ // Arm the sweeper now (pinning its candidates) so a later deadline or
360
+ // abort does not pay PowerShell's startup inside the G4 window; a kill
361
+ // that raced the exit (taskkill found no process) is completed here too.
362
+ armTimer = setTimeout(() => {
363
+ if (closed || settled) return;
364
+ if (killRequested) sweep();
365
+ else sweeper ??= armSweeper(pid, spawnedAt, exitedAt);
366
+ }, SWEEP_ARM_MS);
367
+ }
368
+ });
369
+ child.on("error", (e) => finish(1, e));
370
+ child.on("close", (code) => {
371
+ closed = true;
372
+ closeCode = code;
373
+ clearTimeout(armTimer);
374
+ // A sweep in flight decides whether the kill ended anything.
375
+ if (sweepPending) return;
376
+ finish(code);
377
+ });
378
+ });
379
+ }
380
+
381
+ /** The timer to arm, or undefined for none. Exported for tests. */
382
+ export function deadlineOf(opts: RunOptions): number | undefined {
383
+ const t = opts.timeoutMs;
384
+ if (t === undefined || Number.isNaN(t)) return opts.signal ? undefined : DEFAULT_TIMEOUT_MS;
385
+ if (t === Infinity) return undefined;
386
+ // setTimeout treats anything above 2^31-1 as 1 ms, which would kill at once.
387
+ return Math.min(Math.max(t, 0), MAX_TIMER_MS);
388
+ }
389
+
390
+ /**
391
+ * Overrides merged over process.env. Windows environment names are
392
+ * case-insensitive and Node keeps only one of two keys that differ in case
393
+ * (the first in sort order, not the override), so an inherited key that
394
+ * matches an override case-insensitively is dropped first.
395
+ */
396
+ function mergeEnv(overrides: Record<string, string> | undefined): NodeJS.ProcessEnv {
397
+ if (!overrides) return process.env;
398
+ const env: NodeJS.ProcessEnv = { ...process.env };
399
+ for (const [key, value] of Object.entries(overrides)) {
400
+ if (isWin) {
401
+ const upper = key.toUpperCase();
402
+ for (const existing of Object.keys(env)) if (existing.toUpperCase() === upper) delete env[existing];
403
+ }
404
+ env[key] = value;
405
+ }
406
+ return env;
407
+ }
408
+
409
+ interface Capture {
410
+ text: string;
411
+ truncated: boolean;
412
+ push(s: string): void;
413
+ }
414
+
415
+ function capture(limit: number): Capture {
416
+ const c: Capture = {
417
+ text: "",
418
+ truncated: false,
419
+ push(s) {
420
+ if (c.truncated) return;
421
+ const room = limit - c.text.length;
422
+ if (s.length <= room) {
423
+ c.text += s;
424
+ return;
425
+ }
426
+ let cut = Math.max(room, 0);
427
+ // Do not keep half of a surrogate pair.
428
+ const last = s.charCodeAt(cut - 1);
429
+ if (cut > 0 && last >= 0xd800 && last <= 0xdbff) cut--;
430
+ c.text += s.slice(0, cut);
431
+ c.truncated = true;
432
+ },
433
+ };
434
+ return c;
435
+ }
436
+
437
+ function killTree(child: ChildProcess): void {
438
+ const pid = child.pid;
439
+ if (!pid) {
440
+ // The spawn failed and its `error` (which settles the run) is still to be
441
+ // emitted on a later tick. Node throws EINVAL for a kill of a process that
442
+ // never started; it must not escape the abort listener or the timer.
443
+ try {
444
+ child.kill("SIGKILL");
445
+ } catch {
446
+ // Nothing is running; the pending `error` settles the run.
447
+ }
448
+ return;
449
+ }
450
+ if (isWin) {
451
+ execFile(TASKKILL, ["/pid", String(pid), "/T", "/F"], { windowsHide: true, timeout: TASKKILL_TIMEOUT_MS }, (err) => {
452
+ // taskkill fails when the child exited meanwhile; the direct kill is then
453
+ // a no-op and the exit handler sweeps what it left running.
454
+ if (err) child.kill();
455
+ });
456
+ return;
457
+ }
458
+ // No group (already reaped or never detached): fall back to the direct child.
459
+ if (!signalGroup(pid, "SIGKILL")) child.kill("SIGKILL");
460
+ }
461
+
462
+ // Runs still in flight are killed when opencode exits.
463
+ // - POSIX (QA-1.2-6): the process group of each run. Detached children lead
464
+ // their own group and session, so a terminal hang-up or Ctrl-C that ends
465
+ // opencode never reaches them.
466
+ // - Windows (QA-1.2-18): the tree of each direct child that has not exited.
467
+ // libuv's kill-on-close job ends the direct child only. Until the child's
468
+ // `exit`, libuv holds its process handle, so its PID cannot be recycled.
469
+ // Each entry is owned by the run that tracked it (QA-1.2-23): POSIX untracks a
470
+ // group both at `exit` and at settle, and its id may be recycled in between by
471
+ // a new run's group. That run overwrites the entry, and the old run's second
472
+ // untrack must not delete it, so only the owner's token deletes an entry.
473
+ // The same token keeps a run's late kill off a recycled id taken by another
474
+ // run of this process (QA-1.2-27). Not fixable without pidfd: if a group
475
+ // empties after `exit` and its id is recycled by an unrelated group (not one
476
+ // of our runs), the late kill or this hook can signal that group (it needs a
477
+ // `setsid` escapee holding the pipes plus PID wrap-around).
478
+ const tracked = new Map<number, symbol>();
479
+ let exitHookInstalled = false;
480
+
481
+ function track(pid: number, token: symbol): void {
482
+ tracked.set(pid, token);
483
+ if (exitHookInstalled) return;
484
+ exitHookInstalled = true;
485
+ process.once("exit", killTrackedProcesses);
486
+ }
487
+
488
+ function untrack(pid: number, token: symbol): void {
489
+ if (ownsTracked(pid, token)) tracked.delete(pid);
490
+ }
491
+
492
+ /** The entry for `pid` is still the one `token`'s run tracked. */
493
+ function ownsTracked(pid: number, token: symbol): boolean {
494
+ return tracked.get(pid) === token;
495
+ }
496
+
497
+ /** The tracking helpers, for unit tests only (QA-1.2-23, QA-1.2-27). */
498
+ export const trackingForTests = {
499
+ track,
500
+ untrack,
501
+ ownsTracked,
502
+ isTracked: (pid: number): boolean => tracked.has(pid),
503
+ };
504
+
505
+ /** The `exit` hook: synchronous, as `exit` listeners must be. */
506
+ function killTrackedProcesses(): void {
507
+ const pids = [...tracked.keys()];
508
+ tracked.clear();
509
+ if (!isWin) {
510
+ for (const pgid of pids) signalGroup(pgid, "SIGKILL");
511
+ return;
512
+ }
513
+ if (pids.length === 0) return;
514
+ // One taskkill for every tree, so the hook delays opencode's exit by at most
515
+ // EXIT_TASKKILL_TIMEOUT_MS however many runs are in flight. A tree that is
516
+ // already gone only makes taskkill report it as not found.
517
+ spawnSync(TASKKILL, [...pids.flatMap((pid) => ["/pid", String(pid)]), "/T", "/F"], {
518
+ windowsHide: true,
519
+ stdio: "ignore",
520
+ timeout: EXIT_TASKKILL_TIMEOUT_MS,
521
+ });
522
+ }
523
+
524
+ function signalGroup(pgid: number, signal: NodeJS.Signals): boolean {
525
+ try {
526
+ process.kill(-pgid, signal);
527
+ return true;
528
+ } catch {
529
+ return false;
530
+ }
531
+ }
532
+
533
+ function groupAlive(pgid: number): boolean {
534
+ try {
535
+ process.kill(-pgid, 0);
536
+ return true;
537
+ } catch (e) {
538
+ return (e as NodeJS.ErrnoException).code === "EPERM";
539
+ }
540
+ }
541
+
542
+ interface Sweeper {
543
+ /**
544
+ * Kill the pinned trees; `done` receives the root PIDs taskkill ended and,
545
+ * when the sweep could not run, why. Never throws.
546
+ */
547
+ kill(done: (pids: number[], unavailable?: string) => void): void;
548
+ /** How many trees the sweeper reported pinned; 0 until its marker arrives. */
549
+ pinnedCount(): number;
550
+ /** Release the pins without killing anything. */
551
+ dispose(): void;
552
+ /**
553
+ * The run settled while the kill is in flight: let the sweeper finish, but
554
+ * stop it (its process handle and pipes) from keeping opencode alive.
555
+ */
556
+ unref(): void;
557
+ }
558
+
559
+ /** Node's child pipes are `net.Socket`s with `unref`; another runtime's may lack it. */
560
+ function unrefStream(stream: object | null): void {
561
+ if (stream && "unref" in stream && typeof stream.unref === "function") stream.unref();
562
+ }
563
+
564
+ let powershell = DEFAULT_POWERSHELL;
565
+
566
+ /** Test-only: run the sweeper with another executable; undefined restores the default. */
567
+ export function setSweeperExecutableForTests(file: string | undefined): void {
568
+ powershell = file ?? DEFAULT_POWERSHELL;
569
+ }
570
+
571
+ /**
572
+ * Windows: find and kill what an exited child left running, without ever
573
+ * targeting a recycled PID (QA-1.2-1). `taskkill /T` on the dead PID finds
574
+ * nothing, and a recycled PID must never be targeted, so the processes are
575
+ * found by their creation time instead:
576
+ *
577
+ * 1. Roots are processes whose ParentProcessId is the child's PID and whose
578
+ * creation time lies in [spawnedAt, exitedAt] (± clock slack). The child's
579
+ * PID stays bound to the child until libuv closes its handle, just before
580
+ * `exit` is emitted, so a process with that parent created in the window
581
+ * was created by the child; the children of a later owner of the PID are
582
+ * created after `exitedAt` and are excluded.
583
+ * 2. Each root is pinned by an open handle and its start time re-checked, so
584
+ * its own PID cannot be recycled between the query and the kill.
585
+ * 3. On `kill`, each live root is ended with `taskkill /T /F` (its tree). A
586
+ * pinned root that exited meanwhile is swept the same way, using its exact
587
+ * lifetime as the window.
588
+ *
589
+ * Descendants whose parent died before being pinned (a detached grandchild of
590
+ * a short-lived middle process) cannot be attributed safely; the kill grace
591
+ * period bounds the run in that case.
592
+ *
593
+ * The sweeper is Windows PowerShell 5.1 (always installed; pwsh 7 is not, and
594
+ * wmic is gone from current Windows 11) at normal priority, spawned directly —
595
+ * not through `run` — with its own kill timeout; every failure degrades to
596
+ * "nothing killed". The script is passed with single quotes only, so Node's
597
+ * argument quoting cannot alter it.
598
+ *
599
+ * It needs PowerShell in FullLanguage mode: under Constrained Language Mode
600
+ * (AppLocker/WDAC) the .NET calls it relies on fail, so it exits 3 at once.
601
+ * After pinning it prints `pinned <n>`. When a kill was requested and that
602
+ * marker is missing (spawn error, non-zero exit, no marker, or the
603
+ * SWEEP_TIMEOUT_MS limit), `kill` reports why, and the run appends
604
+ * `[orphan sweep unavailable: <reason>]` to stderr if it has not settled yet
605
+ * (QA-1.2-15). A failure after the run settled has no result to report to.
606
+ */
607
+ function armSweeper(pid: number, spawnedAt: number, exitedAt: number): Sweeper {
608
+ const from = Math.floor(spawnedAt - SWEEP_CLOCK_SLACK_MS);
609
+ const to = Math.ceil(exitedAt + SWEEP_CLOCK_SLACK_MS);
610
+ const script = [
611
+ "$ErrorActionPreference = 'Stop'",
612
+ "if ($ExecutionContext.SessionState.LanguageMode -ne 'FullLanguage') { exit 3 }",
613
+ "function Ms($d) { ([DateTimeOffset]$d).ToUnixTimeMilliseconds() }",
614
+ "function Pin($ppid, $from, $to) { foreach ($c in @(Get-CimInstance -ClassName Win32_Process -Filter ('ParentProcessId=' + $ppid))) { try { $t = Ms $c.CreationDate; if ($t -ge $from -and $t -le $to) { $p = [Diagnostics.Process]::GetProcessById([int]$c.ProcessId); $null = $p.Handle; $s = Ms $p.StartTime; if ($s -ge $from -and $s -le $to) { $p } } } catch { $null = $_ } } }",
615
+ "function Stop-Trees($roots) { foreach ($p in $roots) { if (-not $p.HasExited) { & taskkill.exe /pid $p.Id /T /F *> $null; if ($LASTEXITCODE -eq 0) { [Console]::Out.WriteLine([string]$p.Id) } } else { Stop-Trees @(Pin $p.Id (Ms $p.StartTime) (Ms $p.ExitTime)) } } }",
616
+ `$roots = @(Pin ${pid} ${from} ${to})`,
617
+ `[Console]::Out.WriteLine('${SWEEP_MARKER} ' + $roots.Count)`,
618
+ "if ($roots.Count -eq 0) { exit 0 }",
619
+ "if ([Console]::In.ReadLine() -eq 'kill') { Stop-Trees $roots }",
620
+ ].join("; ");
621
+ let output = "";
622
+ let ended = false;
623
+ /** Why the sweep could not run, once known. */
624
+ let failure: string | undefined;
625
+ const waiters: Array<() => void> = [];
626
+ const end = () => {
627
+ if (ended) return;
628
+ ended = true;
629
+ for (const w of waiters.splice(0)) w();
630
+ };
631
+ const lines = () => output.split(/\r?\n/);
632
+ const killedPids = () => lines().filter((l) => /^\d+$/.test(l)).map(Number);
633
+ const pinned = () => lines().some((l) => l.startsWith(`${SWEEP_MARKER} `));
634
+ const pinnedCount = () => {
635
+ const marker = lines().find((l) => l.startsWith(`${SWEEP_MARKER} `));
636
+ const n = marker === undefined ? 0 : Number(marker.slice(SWEEP_MARKER.length + 1));
637
+ return Number.isInteger(n) && n > 0 ? n : 0;
638
+ };
639
+ /** Undefined when the sweep ran; otherwise the reason it did not. */
640
+ const unavailable = () => failure ?? (pinned() ? undefined : "no marker");
641
+ let ps: ChildProcess | undefined;
642
+ try {
643
+ ps = spawn(powershell, ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], {
644
+ // QA-G-9: not the host's cwd (the user's project). PowerShell writes its
645
+ // module analysis cache relative to its cwd when LocalAppData is missing.
646
+ cwd: tmpdir(),
647
+ windowsHide: true,
648
+ stdio: ["pipe", "pipe", "ignore"],
649
+ });
650
+ ps.stdout?.setEncoding("utf8");
651
+ ps.stdout?.on("data", (s: string) => { output += s; });
652
+ // EPIPE: the sweeper exited before reading (it found nothing to pin).
653
+ ps.stdin?.on("error", end);
654
+ ps.on("error", (e) => {
655
+ failure ??= `spawn error: ${e.message}`;
656
+ end();
657
+ });
658
+ ps.on("close", (code, signal) => {
659
+ if (code !== 0 && !pinned()) failure ??= code === null ? `killed by ${signal}` : `exit ${code}`;
660
+ end();
661
+ });
662
+ } catch (e) {
663
+ failure = `spawn error: ${String(e)}`;
664
+ ps = undefined;
665
+ end();
666
+ }
667
+ return {
668
+ kill(done) {
669
+ let called = false;
670
+ let limit: ReturnType<typeof setTimeout> | undefined;
671
+ const report = () => {
672
+ if (called) return;
673
+ called = true;
674
+ clearTimeout(limit);
675
+ done(killedPids(), unavailable());
676
+ };
677
+ if (ended || !ps) {
678
+ report();
679
+ return;
680
+ }
681
+ const sweeperProcess = ps;
682
+ waiters.push(report);
683
+ limit = setTimeout(() => {
684
+ if (!pinned()) failure ??= `timed out after ${SWEEP_TIMEOUT_MS} ms`;
685
+ sweeperProcess.kill();
686
+ report();
687
+ }, SWEEP_TIMEOUT_MS);
688
+ // With `unref()` below, a hung sweeper never keeps opencode alive after
689
+ // the run settled (QA-1.2-19). Being a direct child, it sits in libuv's
690
+ // kill-on-close job and dies with opencode.
691
+ limit.unref();
692
+ // Written, not ended: ending a Windows pipe makes libuv flush it
693
+ // (FlushFileBuffers), which blocks until the sweeper reads, and that
694
+ // pending shutdown would keep opencode alive however much is unref'd
695
+ // (QA-1.2-19). The sweeper's exit closes the pipe.
696
+ sweeperProcess.stdin?.write("kill\n");
697
+ },
698
+ pinnedCount,
699
+ dispose() {
700
+ if (ended || !ps) return;
701
+ ps.stdin?.end();
702
+ ps.kill();
703
+ },
704
+ unref() {
705
+ if (ended || !ps) return;
706
+ ps.unref();
707
+ unrefStream(ps.stdin);
708
+ unrefStream(ps.stdout);
709
+ },
710
+ };
711
+ }