opencode-copilot-delegate 0.2.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,34 @@
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
+
17
+ ## 0.3.0
18
+
19
+ ### Minor Changes
20
+
21
+ - 7dfb029: Eliminate head-of-line blocking and halve fork/exec cost in the orphan reaper
22
+
23
+ Two performance improvements to the plugin-init orphan-subprocess reaper, both surfaced in the `v0.1.x / v0.2.x runtime hardening follow-ups` tracking issue:
24
+
25
+ - **Streaming worker pool replaces chunked `Promise.all`**: under loaded conditions a single slow `ps` invocation (300-500ms is realistic) used to idle four sibling workers in the same chunk, blowing the soft init budget by 5-10x. The reaper now spawns up to `MAX_CONCURRENT_PROBES = 5` workers that drain a shared queue independently — a slow probe blocks only its own worker.
26
+ - **Combined `ps -p <pid> -o comm=,lstart=` query**: the two separate `comm` and `lstart` lookups (per entry, plus per task spawn) consolidate into a single `getPidIdentity(pid)` call. Halves fork/exec cost on the reap hot path, makes the concurrency-cap math match reality (5 workers ⇒ at most 5 concurrent `ps` subprocesses, not 10), and gets an atomic kernel snapshot of both identity legs.
27
+
28
+ Net wall-clock impact for a 10-entry orphan file with one slow `ps` probe: the chunked-of-5 worst case (~210ms) drops to roughly 200ms, but the streaming pool eliminates the artificial wave-boundary stall — the 9 fast probes complete in ~30ms instead of being trapped behind the slow one.
29
+
30
+ No public API changes. All callers and tests updated to use the combined `getPidIdentity` dependency.
31
+
3
32
  ## 0.2.0
4
33
 
5
34
  ### 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 psField(pid, field) {
9384
+ var DEFAULT_PS_TIMEOUT_MS = 1000;
9385
+ function runPs(args, timeoutMs = DEFAULT_PS_TIMEOUT_MS) {
9385
9386
  return new Promise((resolve) => {
9386
- const child = spawn2("ps", ["-p", String(pid), "-o", `${field}=`]);
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,11 +9411,23 @@ function psField(pid, field) {
9409
9411
  });
9410
9412
  });
9411
9413
  }
9412
- async function getPidComm(pid) {
9413
- return psField(pid, "comm");
9414
+ function parsePsIdentity(raw) {
9415
+ if (!raw)
9416
+ return null;
9417
+ const firstWs = raw.search(/\s/);
9418
+ if (firstWs === -1)
9419
+ return null;
9420
+ const comm = raw.slice(0, firstWs);
9421
+ const lstart = raw.slice(firstWs).trim();
9422
+ if (!comm || !lstart)
9423
+ return null;
9424
+ return { comm, lstart };
9414
9425
  }
9415
- async function getPidStartTime(pid) {
9416
- return psField(pid, "lstart");
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);
9417
9431
  }
9418
9432
  function parseLine(line) {
9419
9433
  const parts = line.split("\t");
@@ -9425,38 +9439,48 @@ function parseLine(line) {
9425
9439
  const pid = Number(pidStr);
9426
9440
  return { pid, comm: parts[1], lstart: parts[2] };
9427
9441
  }
9428
- async function processEntries(entries, killProcessTree2, getPidComm2, getPidStartTime2) {
9442
+ var MAX_CONCURRENT_PROBES = 5;
9443
+ async function processEntry(entry, killProcessTree2, getPidIdentity2, signal, psTimeoutMs) {
9444
+ if (signal?.aborted)
9445
+ return { reaped: false, skipped: true };
9446
+ try {
9447
+ process.kill(entry.pid, 0);
9448
+ } catch {
9449
+ return { reaped: false, skipped: true };
9450
+ }
9451
+ const live = await getPidIdentity2(entry.pid, psTimeoutMs);
9452
+ if (signal?.aborted)
9453
+ return { reaped: false, skipped: true };
9454
+ if (live === null || live.comm !== entry.comm || live.lstart !== entry.lstart) {
9455
+ return { reaped: false, skipped: true };
9456
+ }
9457
+ try {
9458
+ await killProcessTree2(entry.pid);
9459
+ return { reaped: true, skipped: false };
9460
+ } catch {
9461
+ return { reaped: false, skipped: true };
9462
+ }
9463
+ }
9464
+ async function processEntries(entries, killProcessTree2, getPidIdentity2, signal, psTimeoutMs) {
9429
9465
  let reaped = 0;
9430
9466
  let skipped = 0;
9431
- for (let i2 = 0;i2 < entries.length; i2 += 5) {
9432
- const chunk = entries.slice(i2, i2 + 5);
9433
- const results = await Promise.all(chunk.map(async (entry) => {
9434
- try {
9435
- process.kill(entry.pid, 0);
9436
- } catch {
9437
- return { reaped: false, skipped: true };
9438
- }
9439
- const [liveComm, liveLstart] = await Promise.all([
9440
- getPidComm2(entry.pid),
9441
- getPidStartTime2(entry.pid)
9442
- ]);
9443
- if (liveComm !== entry.comm || liveLstart !== entry.lstart) {
9444
- return { reaped: false, skipped: true };
9445
- }
9446
- try {
9447
- await killProcessTree2(entry.pid);
9448
- return { reaped: true, skipped: false };
9449
- } catch {
9450
- return { reaped: false, skipped: true };
9451
- }
9452
- }));
9453
- for (const r of results) {
9454
- if (r.reaped)
9467
+ const queue = [...entries];
9468
+ const workerCount = Math.min(MAX_CONCURRENT_PROBES, entries.length);
9469
+ const workers = Array.from({ length: workerCount }, async () => {
9470
+ while (true) {
9471
+ if (signal?.aborted)
9472
+ return;
9473
+ const entry = queue.shift();
9474
+ if (!entry)
9475
+ return;
9476
+ const result = await processEntry(entry, killProcessTree2, getPidIdentity2, signal, psTimeoutMs);
9477
+ if (result.reaped)
9455
9478
  reaped++;
9456
- else if (r.skipped)
9479
+ else if (result.skipped)
9457
9480
  skipped++;
9458
9481
  }
9459
- }
9482
+ });
9483
+ await Promise.all(workers);
9460
9484
  return { reaped, skipped };
9461
9485
  }
9462
9486
  async function readPidFileEntries(filePath) {
@@ -9489,7 +9513,7 @@ async function cleanupAfterReap(filePath, isCurrent, currentInstancePath) {
9489
9513
  return false;
9490
9514
  }
9491
9515
  }
9492
- async function reapOneFile(filePath, filePid, isCurrent, currentInstancePath, isPluginAlive, killProcessTree2, getPidComm2, getPidStartTime2) {
9516
+ async function reapOneFile(filePath, filePid, isCurrent, currentInstancePath, isPluginAlive, killProcessTree2, getPidIdentity2, signal, psTimeoutMs) {
9493
9517
  const empty = {
9494
9518
  reaped: 0,
9495
9519
  skipped: 0,
@@ -9503,18 +9527,22 @@ async function reapOneFile(filePath, filePid, isCurrent, currentInstancePath, is
9503
9527
  if (entries === null) {
9504
9528
  return empty;
9505
9529
  }
9506
- const { reaped, skipped } = await processEntries(entries, killProcessTree2, getPidComm2, getPidStartTime2);
9530
+ const { reaped, skipped } = await processEntries(entries, killProcessTree2, getPidIdentity2, signal, psTimeoutMs);
9531
+ if (signal?.aborted) {
9532
+ return { reaped, skipped, scanned: true, deleted: false };
9533
+ }
9507
9534
  const deleted = await cleanupAfterReap(filePath, isCurrent, currentInstancePath);
9508
9535
  return { reaped, skipped, scanned: true, deleted };
9509
9536
  }
9510
- async function reapOrphans(opts) {
9537
+ async function doReap(opts) {
9511
9538
  const {
9512
9539
  pidFileDir,
9513
9540
  currentInstancePath,
9514
9541
  killProcessTree: killProcessTree2,
9515
- getPidComm: getPidComm2,
9516
- getPidStartTime: getPidStartTime2,
9517
- isPluginAlive = defaultIsPluginAlive
9542
+ getPidIdentity: getPidIdentity2,
9543
+ isPluginAlive = defaultIsPluginAlive,
9544
+ signal,
9545
+ psTimeoutMs
9518
9546
  } = opts;
9519
9547
  let files;
9520
9548
  try {
@@ -9527,6 +9555,8 @@ async function reapOrphans(opts) {
9527
9555
  let scannedFiles = 0;
9528
9556
  let deletedFiles = 0;
9529
9557
  for (const file of files) {
9558
+ if (signal?.aborted)
9559
+ break;
9530
9560
  if (!file.endsWith(".pids"))
9531
9561
  continue;
9532
9562
  const filePath = join(pidFileDir, file);
@@ -9536,7 +9566,7 @@ async function reapOrphans(opts) {
9536
9566
  continue;
9537
9567
  }
9538
9568
  const filePid = Number(stem);
9539
- const outcome = await reapOneFile(filePath, filePid, filePid === process.pid, currentInstancePath, isPluginAlive, killProcessTree2, getPidComm2, getPidStartTime2);
9569
+ const outcome = await reapOneFile(filePath, filePid, filePid === process.pid, currentInstancePath, isPluginAlive, killProcessTree2, getPidIdentity2, signal, psTimeoutMs);
9540
9570
  reaped += outcome.reaped;
9541
9571
  skipped += outcome.skipped;
9542
9572
  if (outcome.scanned)
@@ -9546,6 +9576,33 @@ async function reapOrphans(opts) {
9546
9576
  }
9547
9577
  return { reaped, skipped, scannedFiles, deletedFiles };
9548
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
+ }
9549
9606
 
9550
9607
  // src/runtime/pid-file.ts
9551
9608
  import { randomBytes } from "crypto";
@@ -9648,9 +9705,9 @@ function createTask(input, taskId = `cpl_${randomUUID()}`) {
9648
9705
  taskId
9649
9706
  };
9650
9707
  if (task.pid > 0 && pidFilePath) {
9651
- Promise.all([getPidComm(task.pid), getPidStartTime(task.pid)]).then(([comm, lstart]) => {
9652
- if (comm && lstart) {
9653
- appendPidEntry(pidFilePath, task.pid, comm, lstart).catch(() => {});
9708
+ getPidIdentity(task.pid).then((identity3) => {
9709
+ if (identity3) {
9710
+ appendPidEntry(pidFilePath, task.pid, identity3.comm, identity3.lstart).catch(() => {});
9654
9711
  } else {
9655
9712
  console.warn(`[task-registry] ps lookup returned null for pid ${task.pid}; subprocess will not be tracked for orphan reaping`);
9656
9713
  }
@@ -10219,8 +10276,7 @@ var CopilotDelegate = async ({ client, directory }) => {
10219
10276
  pidFileDir,
10220
10277
  currentInstancePath,
10221
10278
  killProcessTree,
10222
- getPidComm,
10223
- getPidStartTime
10279
+ getPidIdentity
10224
10280
  });
10225
10281
  } catch {}
10226
10282
  return {
@@ -1,7 +1,9 @@
1
1
  export interface ReapDeps {
2
2
  killProcessTree: (pid: number) => Promise<void>;
3
- getPidComm: (pid: number) => Promise<string | null>;
4
- getPidStartTime: (pid: number) => Promise<string | null>;
3
+ getPidIdentity: (pid: number, timeoutMs?: number) => Promise<{
4
+ comm: string;
5
+ lstart: string;
6
+ } | null>;
5
7
  isPluginAlive: (pid: number) => boolean;
6
8
  }
7
9
  export interface ReapResult {
@@ -11,13 +13,61 @@ export interface ReapResult {
11
13
  deletedFiles: number;
12
14
  }
13
15
  export declare function defaultIsPluginAlive(pid: number): boolean;
14
- export declare function getPidComm(pid: number): Promise<string | null>;
15
- export declare function getPidStartTime(pid: number): Promise<string | null>;
16
- export declare function reapOrphans(opts: {
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;
41
+ /**
42
+ * Read both comm (kernel-tracked executable name) and lstart (process
43
+ * start time) for a PID via a single ps invocation.
44
+ *
45
+ * Halves the fork/exec cost of identity verification compared with two
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.
52
+ *
53
+ * Returns null on any failure mode (timeout, spawn error, non-zero exit,
54
+ * empty output, malformed output). Callers must treat null as "identity
55
+ * unverifiable; do not trust this PID."
56
+ */
57
+ export declare function getPidIdentity(pid: number, timeoutMs?: number): Promise<{
58
+ comm: string;
59
+ lstart: string;
60
+ } | null>;
61
+ interface ReapOpts {
17
62
  pidFileDir: string;
18
63
  currentInstancePath: string;
19
64
  killProcessTree: ReapDeps['killProcessTree'];
20
- getPidComm: ReapDeps['getPidComm'];
21
- getPidStartTime: ReapDeps['getPidStartTime'];
65
+ getPidIdentity: ReapDeps['getPidIdentity'];
22
66
  isPluginAlive?: ReapDeps['isPluginAlive'];
67
+ signal?: AbortSignal;
68
+ psTimeoutMs?: number;
69
+ }
70
+ export declare function reapOrphans(opts: Omit<ReapOpts, 'signal'> & {
71
+ reapTimeoutMs?: number;
23
72
  }): Promise<ReapResult>;
73
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-copilot-delegate",
3
- "version": "0.2.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",