opencode-copilot-delegate 0.3.0 → 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/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # opencode-copilot-delegate
2
2
 
3
+ ## 0.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - f3f21c7: Configurable orphan-reaper timeouts and parser extraction
8
+
9
+ Three medium-priority improvements to the plugin-init orphan-subprocess reaper, all from the runtime hardening backlog:
10
+
11
+ - **Configurable per-probe `ps` timeout with degradation warning**: `getPidIdentity` and the underlying `runPs` helper now accept an optional `timeoutMs` parameter (default 1000). On loaded systems where legitimate `ps` responses can exceed 1s, callers can pass a longer timeout to avoid identity-gate misses that leave orphans alive. When the timeout fires, `runPs` emits a `console.warn` so operators can detect probe degradation and tune the budget up.
12
+ - **Overall `reapOrphans` timeout with cooperative cancellation**: `reapOrphans` now accepts an optional `reapTimeoutMs` parameter (default 15000). When the timeout fires, the reap aborts via `AbortSignal`: in-flight workers cooperate by skipping their next mutating step (kill, truncate, unlink) so no dangerous side effects can occur after `reapOrphans` returns. The call resolves with an empty result and emits a `console.warn`. Prevents pathological cases (NFS `readdir` hang, all probes timing out simultaneously) from blocking plugin init indefinitely, and prevents lingering reap workers from wiping current-instance pid file entries that live tasks have appended after the timeout fired.
13
+ - **Parser extraction**: the comm/lstart parsing logic is lifted out of `getPidIdentity` into a new exported `parsePsIdentity(raw)` pure function with full edge-case coverage (empty input, single-token input, leading-whitespace input, the 15/16-char `comm` boundary, and multi-whitespace separator).
14
+
15
+ All new parameters are additive optionals; existing callers continue to work without modification. Behavior at default settings is unchanged for normal-load operation, but the new overall reap timeout introduces a conditional control-flow branch (warn + empty return) that activates only under pathological conditions where a reap exceeds the 15s default budget.
16
+
3
17
  ## 0.3.0
4
18
 
5
19
  ### Minor Changes
package/dist/index.js CHANGED
@@ -9381,15 +9381,17 @@ function defaultIsPluginAlive(pid) {
9381
9381
  return isErrnoException(e) && e.code === "EPERM";
9382
9382
  }
9383
9383
  }
9384
- function runPs(args) {
9384
+ var DEFAULT_PS_TIMEOUT_MS = 1000;
9385
+ function runPs(args, timeoutMs = DEFAULT_PS_TIMEOUT_MS) {
9385
9386
  return new Promise((resolve) => {
9386
9387
  const child = spawn2("ps", args);
9387
9388
  let stdout = "";
9388
9389
  let timedOut = false;
9389
9390
  const timeout = setTimeout(() => {
9390
9391
  timedOut = true;
9392
+ console.warn(`[orphan-reaper] ps invocation exceeded ${timeoutMs}ms timeout: ps ${args.join(" ")}`);
9391
9393
  child.kill("SIGTERM");
9392
- }, 1000);
9394
+ }, timeoutMs);
9393
9395
  child.stdout?.on("data", (chunk) => {
9394
9396
  stdout += chunk.toString("utf-8");
9395
9397
  });
@@ -9409,9 +9411,8 @@ function runPs(args) {
9409
9411
  });
9410
9412
  });
9411
9413
  }
9412
- async function getPidIdentity(pid) {
9413
- const raw = await runPs(["-p", String(pid), "-o", "comm=,lstart="]);
9414
- if (raw === null)
9414
+ function parsePsIdentity(raw) {
9415
+ if (!raw)
9415
9416
  return null;
9416
9417
  const firstWs = raw.search(/\s/);
9417
9418
  if (firstWs === -1)
@@ -9422,6 +9423,12 @@ async function getPidIdentity(pid) {
9422
9423
  return null;
9423
9424
  return { comm, lstart };
9424
9425
  }
9426
+ async function getPidIdentity(pid, timeoutMs = DEFAULT_PS_TIMEOUT_MS) {
9427
+ const raw = await runPs(["-p", String(pid), "-o", "comm=,lstart="], timeoutMs);
9428
+ if (raw === null)
9429
+ return null;
9430
+ return parsePsIdentity(raw);
9431
+ }
9425
9432
  function parseLine(line) {
9426
9433
  const parts = line.split("\t");
9427
9434
  if (parts.length !== 3)
@@ -9433,13 +9440,17 @@ function parseLine(line) {
9433
9440
  return { pid, comm: parts[1], lstart: parts[2] };
9434
9441
  }
9435
9442
  var MAX_CONCURRENT_PROBES = 5;
9436
- async function processEntry(entry, killProcessTree2, getPidIdentity2) {
9443
+ async function processEntry(entry, killProcessTree2, getPidIdentity2, signal, psTimeoutMs) {
9444
+ if (signal?.aborted)
9445
+ return { reaped: false, skipped: true };
9437
9446
  try {
9438
9447
  process.kill(entry.pid, 0);
9439
9448
  } catch {
9440
9449
  return { reaped: false, skipped: true };
9441
9450
  }
9442
- const live = await getPidIdentity2(entry.pid);
9451
+ const live = await getPidIdentity2(entry.pid, psTimeoutMs);
9452
+ if (signal?.aborted)
9453
+ return { reaped: false, skipped: true };
9443
9454
  if (live === null || live.comm !== entry.comm || live.lstart !== entry.lstart) {
9444
9455
  return { reaped: false, skipped: true };
9445
9456
  }
@@ -9450,17 +9461,19 @@ async function processEntry(entry, killProcessTree2, getPidIdentity2) {
9450
9461
  return { reaped: false, skipped: true };
9451
9462
  }
9452
9463
  }
9453
- async function processEntries(entries, killProcessTree2, getPidIdentity2) {
9464
+ async function processEntries(entries, killProcessTree2, getPidIdentity2, signal, psTimeoutMs) {
9454
9465
  let reaped = 0;
9455
9466
  let skipped = 0;
9456
9467
  const queue = [...entries];
9457
9468
  const workerCount = Math.min(MAX_CONCURRENT_PROBES, entries.length);
9458
9469
  const workers = Array.from({ length: workerCount }, async () => {
9459
9470
  while (true) {
9471
+ if (signal?.aborted)
9472
+ return;
9460
9473
  const entry = queue.shift();
9461
9474
  if (!entry)
9462
9475
  return;
9463
- const result = await processEntry(entry, killProcessTree2, getPidIdentity2);
9476
+ const result = await processEntry(entry, killProcessTree2, getPidIdentity2, signal, psTimeoutMs);
9464
9477
  if (result.reaped)
9465
9478
  reaped++;
9466
9479
  else if (result.skipped)
@@ -9500,7 +9513,7 @@ async function cleanupAfterReap(filePath, isCurrent, currentInstancePath) {
9500
9513
  return false;
9501
9514
  }
9502
9515
  }
9503
- async function reapOneFile(filePath, filePid, isCurrent, currentInstancePath, isPluginAlive, killProcessTree2, getPidIdentity2) {
9516
+ async function reapOneFile(filePath, filePid, isCurrent, currentInstancePath, isPluginAlive, killProcessTree2, getPidIdentity2, signal, psTimeoutMs) {
9504
9517
  const empty = {
9505
9518
  reaped: 0,
9506
9519
  skipped: 0,
@@ -9514,17 +9527,22 @@ async function reapOneFile(filePath, filePid, isCurrent, currentInstancePath, is
9514
9527
  if (entries === null) {
9515
9528
  return empty;
9516
9529
  }
9517
- const { reaped, skipped } = await processEntries(entries, killProcessTree2, getPidIdentity2);
9530
+ const { reaped, skipped } = await processEntries(entries, killProcessTree2, getPidIdentity2, signal, psTimeoutMs);
9531
+ if (signal?.aborted) {
9532
+ return { reaped, skipped, scanned: true, deleted: false };
9533
+ }
9518
9534
  const deleted = await cleanupAfterReap(filePath, isCurrent, currentInstancePath);
9519
9535
  return { reaped, skipped, scanned: true, deleted };
9520
9536
  }
9521
- async function reapOrphans(opts) {
9537
+ async function doReap(opts) {
9522
9538
  const {
9523
9539
  pidFileDir,
9524
9540
  currentInstancePath,
9525
9541
  killProcessTree: killProcessTree2,
9526
9542
  getPidIdentity: getPidIdentity2,
9527
- isPluginAlive = defaultIsPluginAlive
9543
+ isPluginAlive = defaultIsPluginAlive,
9544
+ signal,
9545
+ psTimeoutMs
9528
9546
  } = opts;
9529
9547
  let files;
9530
9548
  try {
@@ -9537,6 +9555,8 @@ async function reapOrphans(opts) {
9537
9555
  let scannedFiles = 0;
9538
9556
  let deletedFiles = 0;
9539
9557
  for (const file of files) {
9558
+ if (signal?.aborted)
9559
+ break;
9540
9560
  if (!file.endsWith(".pids"))
9541
9561
  continue;
9542
9562
  const filePath = join(pidFileDir, file);
@@ -9546,7 +9566,7 @@ async function reapOrphans(opts) {
9546
9566
  continue;
9547
9567
  }
9548
9568
  const filePid = Number(stem);
9549
- const outcome = await reapOneFile(filePath, filePid, filePid === process.pid, currentInstancePath, isPluginAlive, killProcessTree2, getPidIdentity2);
9569
+ const outcome = await reapOneFile(filePath, filePid, filePid === process.pid, currentInstancePath, isPluginAlive, killProcessTree2, getPidIdentity2, signal, psTimeoutMs);
9550
9570
  reaped += outcome.reaped;
9551
9571
  skipped += outcome.skipped;
9552
9572
  if (outcome.scanned)
@@ -9556,6 +9576,33 @@ async function reapOrphans(opts) {
9556
9576
  }
9557
9577
  return { reaped, skipped, scannedFiles, deletedFiles };
9558
9578
  }
9579
+ var DEFAULT_REAP_TIMEOUT_MS = 15000;
9580
+ async function reapOrphans(opts) {
9581
+ const reapTimeoutMs = opts.reapTimeoutMs ?? DEFAULT_REAP_TIMEOUT_MS;
9582
+ const empty = {
9583
+ reaped: 0,
9584
+ skipped: 0,
9585
+ scannedFiles: 0,
9586
+ deletedFiles: 0
9587
+ };
9588
+ const controller = new AbortController;
9589
+ let timeoutId;
9590
+ const timeoutPromise = new Promise((resolve) => {
9591
+ timeoutId = setTimeout(() => {
9592
+ console.warn(`[orphan-reaper] reapOrphans exceeded ${reapTimeoutMs}ms budget; returning empty result`);
9593
+ controller.abort();
9594
+ resolve(empty);
9595
+ }, reapTimeoutMs);
9596
+ });
9597
+ const reapPromise = doReap({ ...opts, signal: controller.signal });
9598
+ reapPromise.catch(() => {});
9599
+ try {
9600
+ return await Promise.race([reapPromise, timeoutPromise]);
9601
+ } finally {
9602
+ if (timeoutId)
9603
+ clearTimeout(timeoutId);
9604
+ }
9605
+ }
9559
9606
 
9560
9607
  // src/runtime/pid-file.ts
9561
9608
  import { randomBytes } from "crypto";
@@ -1,6 +1,6 @@
1
1
  export interface ReapDeps {
2
2
  killProcessTree: (pid: number) => Promise<void>;
3
- getPidIdentity: (pid: number) => Promise<{
3
+ getPidIdentity: (pid: number, timeoutMs?: number) => Promise<{
4
4
  comm: string;
5
5
  lstart: string;
6
6
  } | null>;
@@ -13,27 +13,61 @@ export interface ReapResult {
13
13
  deletedFiles: number;
14
14
  }
15
15
  export declare function defaultIsPluginAlive(pid: number): boolean;
16
+ /**
17
+ * Parse `ps -p <pid> -o comm=,lstart=` output into `{ comm, lstart }`.
18
+ *
19
+ * Output format: `<comm><whitespace><lstart>` where `comm` is a single
20
+ * non-whitespace token (kernel-tracked process name field, capped at 15
21
+ * chars on Linux and 16 chars on macOS) and `lstart` is the multi-word
22
+ * date string that follows (e.g., `Tue Apr 28 23:45:30 2026`).
23
+ *
24
+ * Splitting on the first whitespace is safe because the kernel `comm`
25
+ * field never contains whitespace. If a future refactor adds different
26
+ * `-o` fields or runs on a platform that emits padded output, this parse
27
+ * fails safe: a truncated comm won't match the recorded one, so the
28
+ * identity gate skips rather than kills.
29
+ *
30
+ * Callers must trim their input first (e.g., via `runPs`'s built-in
31
+ * trim). Leading whitespace yields an empty comm and the parser returns
32
+ * null \u2014 the safe behavior, but a poor signal for the caller.
33
+ *
34
+ * Returns null on empty input, single-token input (no lstart), and any
35
+ * other malformed shape.
36
+ */
37
+ export declare function parsePsIdentity(raw: string): {
38
+ comm: string;
39
+ lstart: string;
40
+ } | null;
16
41
  /**
17
42
  * Read both comm (kernel-tracked executable name) and lstart (process
18
43
  * start time) for a PID via a single ps invocation.
19
44
  *
20
45
  * Halves the fork/exec cost of identity verification compared with two
21
- * separate `ps -o comm=` and `ps -o lstart=` calls. The combined output
22
- * format is `<comm> <lstart>` where comm is a single token and lstart is
23
- * a multi-word date string (e.g., `Tue Apr 28 23:45:30 2026`).
46
+ * separate `ps -o comm=` and `ps -o lstart=` calls.
47
+ *
48
+ * `timeoutMs` controls the underlying ps timeout (default 1s). On loaded
49
+ * systems where legitimate ps responses can exceed 1s, callers can pass
50
+ * a longer timeout; the timeout-fire path emits a `console.warn` for
51
+ * operator visibility.
24
52
  *
25
53
  * Returns null on any failure mode (timeout, spawn error, non-zero exit,
26
54
  * empty output, malformed output). Callers must treat null as "identity
27
55
  * unverifiable; do not trust this PID."
28
56
  */
29
- export declare function getPidIdentity(pid: number): Promise<{
57
+ export declare function getPidIdentity(pid: number, timeoutMs?: number): Promise<{
30
58
  comm: string;
31
59
  lstart: string;
32
60
  } | null>;
33
- export declare function reapOrphans(opts: {
61
+ interface ReapOpts {
34
62
  pidFileDir: string;
35
63
  currentInstancePath: string;
36
64
  killProcessTree: ReapDeps['killProcessTree'];
37
65
  getPidIdentity: ReapDeps['getPidIdentity'];
38
66
  isPluginAlive?: ReapDeps['isPluginAlive'];
67
+ signal?: AbortSignal;
68
+ psTimeoutMs?: number;
69
+ }
70
+ export declare function reapOrphans(opts: Omit<ReapOpts, 'signal'> & {
71
+ reapTimeoutMs?: number;
39
72
  }): Promise<ReapResult>;
73
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-copilot-delegate",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "OpenCode plugin that delegates tasks to GitHub Copilot CLI as background subprocesses",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",