opencode-copilot-delegate 0.1.0 → 0.3.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 +29 -0
- package/README.md +1 -1
- package/dist/index.js +354 -20
- package/dist/lib/errno.d.ts +9 -0
- package/dist/runtime/orphan-reaper.d.ts +39 -0
- package/dist/runtime/pid-file.d.ts +3 -0
- package/dist/runtime/subprocess.d.ts +1 -0
- package/dist/runtime/task-registry.d.ts +1 -0
- package/dist/runtime/task-status.d.ts +8 -0
- package/dist/tools/delegate.d.ts +1 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,34 @@
|
|
|
1
1
|
# opencode-copilot-delegate
|
|
2
2
|
|
|
3
|
+
## 0.3.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 7dfb029: Eliminate head-of-line blocking and halve fork/exec cost in the orphan reaper
|
|
8
|
+
|
|
9
|
+
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:
|
|
10
|
+
|
|
11
|
+
- **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.
|
|
12
|
+
- **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.
|
|
13
|
+
|
|
14
|
+
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.
|
|
15
|
+
|
|
16
|
+
No public API changes. All callers and tests updated to use the combined `getPidIdentity` dependency.
|
|
17
|
+
|
|
18
|
+
## 0.2.0
|
|
19
|
+
|
|
20
|
+
### Minor Changes
|
|
21
|
+
|
|
22
|
+
- e2ea508: Add an orphan subprocess reaper that runs at plugin init to clean up `copilot` subprocesses left behind when the plugin reloads or the OpenCode session exits unexpectedly.
|
|
23
|
+
|
|
24
|
+
The reaper writes a per-instance PID file at `<XDG_STATE_HOME>/opencode-copilot-delegate/orphans/<plugin-pid>.pids` for every subprocess the plugin spawns and removes the entry on every terminal status transition (complete, failed, cancelled). On the next plugin init, the reaper scans the orphans directory, probes the owning plugin's liveness for each foreign file (`process.kill(<plugin-pid>, 0)`), reaps entries from files whose plugin has exited (and deletes those files), and skips entries from files whose plugin is still running.
|
|
25
|
+
|
|
26
|
+
Identity gate is strict: each kill requires the live process's `comm` (kernel-tracked executable name from `ps -o comm=`) AND `lstart` (start-time string) to match values recorded at spawn time. Combined with the spawner-liveness probe, this prevents both PID-reuse-of-an-unrelated-process and cross-instance kill of a live foreign instance's children.
|
|
27
|
+
|
|
28
|
+
Also fixes a parser cancel-race in the JSONL data handler — events buffered before the abort listener fired could previously be appended to `task.events` after `task.status` had been set to `cancelled`. The fix is a one-line `if (task.status !== 'running') break` guard at the top of the per-line loop, before `parseJsonlLine`.
|
|
29
|
+
|
|
30
|
+
The new `setStatus` helper centralizes the three terminal status mutations in `subprocess.ts` (close event, abort listener, spawn error) along with the `removePidEntry` cleanup hook. It is idempotent on terminal state — once `task.status` is terminal, subsequent `setStatus` calls with another terminal value no-op, preserving the existing `finalizeTask` `if (task.status !== 'cancelled')` invariant automatically.
|
|
31
|
+
|
|
3
32
|
## 0.1.0
|
|
4
33
|
|
|
5
34
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -83,7 +83,7 @@ Task state is in-memory inside a single OpenCode process. Calling `copilot_outpu
|
|
|
83
83
|
|
|
84
84
|
## Known Limitations (v0.1.x)
|
|
85
85
|
|
|
86
|
-
- **Orphaned subprocesses:** If OpenCode crashes mid-delegation, the `copilot` subprocess becomes orphaned. A PID-file reaper
|
|
86
|
+
- **Orphaned subprocesses (mitigated since v0.2.0):** If OpenCode crashes mid-delegation, the `copilot` subprocess becomes orphaned. A PID-file reaper now scans `<XDG_STATE_HOME>/opencode-copilot-delegate/orphans/` at every plugin init, probes the owning plugin's liveness, and reaps subprocesses whose plugin has exited. A strict identity gate (kernel-tracked `comm` + start time) prevents PID-reuse misfires.
|
|
87
87
|
- **Prompt visibility in `ps`:** The `copilot` CLI accepts the prompt as a command-line argument, which means the full prompt text appears in `ps` output for any user on the host. This is an upstream Copilot CLI behavior. Avoid delegating prompts that contain secrets or PII; pass sensitive material via files, env vars, or `--secret-env-vars` instead.
|
|
88
88
|
- **No subprocess lifetime cap:** A hung `copilot` subprocess stays in the registry as `running` indefinitely. Cancel manually via `copilot_cancel`. A configurable timeout is planned for v1.x.
|
|
89
89
|
|
package/dist/index.js
CHANGED
|
@@ -790,6 +790,10 @@ var require_merge_stream = __commonJS((exports, module) => {
|
|
|
790
790
|
};
|
|
791
791
|
});
|
|
792
792
|
|
|
793
|
+
// src/index.ts
|
|
794
|
+
import { mkdir as mkdir2 } from "fs/promises";
|
|
795
|
+
import { dirname as dirname2 } from "path";
|
|
796
|
+
|
|
793
797
|
// src/discovery/agents.ts
|
|
794
798
|
import { readdirSync } from "fs";
|
|
795
799
|
import { basename } from "path";
|
|
@@ -842,12 +846,6 @@ function buildDescription(agents) {
|
|
|
842
846
|
`);
|
|
843
847
|
}
|
|
844
848
|
|
|
845
|
-
// src/tools/cancel.ts
|
|
846
|
-
import { tool } from "@opencode-ai/plugin/tool";
|
|
847
|
-
|
|
848
|
-
// src/runtime/task-registry.ts
|
|
849
|
-
import { randomUUID } from "crypto";
|
|
850
|
-
|
|
851
849
|
// node_modules/fkill/index.js
|
|
852
850
|
import process17 from "process";
|
|
853
851
|
import path10 from "path";
|
|
@@ -9353,7 +9351,7 @@ async function fkill(inputs, options = {}) {
|
|
|
9353
9351
|
|
|
9354
9352
|
// src/lib/kill-tree.ts
|
|
9355
9353
|
async function killProcessTree(pid) {
|
|
9356
|
-
if (!Number.isFinite(pid) || pid <=
|
|
9354
|
+
if (!Number.isFinite(pid) || pid <= 1) {
|
|
9357
9355
|
return;
|
|
9358
9356
|
}
|
|
9359
9357
|
const options = {
|
|
@@ -9364,13 +9362,310 @@ async function killProcessTree(pid) {
|
|
|
9364
9362
|
await fkill(-pid, options);
|
|
9365
9363
|
}
|
|
9366
9364
|
|
|
9365
|
+
// src/runtime/orphan-reaper.ts
|
|
9366
|
+
import { spawn as spawn2 } from "child_process";
|
|
9367
|
+
import { readdir, readFile, unlink, writeFile } from "fs/promises";
|
|
9368
|
+
import { basename as basename2, extname, join } from "path";
|
|
9369
|
+
|
|
9370
|
+
// src/lib/errno.ts
|
|
9371
|
+
function isErrnoException(e) {
|
|
9372
|
+
return e instanceof Error && "code" in e;
|
|
9373
|
+
}
|
|
9374
|
+
|
|
9375
|
+
// src/runtime/orphan-reaper.ts
|
|
9376
|
+
function defaultIsPluginAlive(pid) {
|
|
9377
|
+
try {
|
|
9378
|
+
process.kill(pid, 0);
|
|
9379
|
+
return true;
|
|
9380
|
+
} catch (e) {
|
|
9381
|
+
return isErrnoException(e) && e.code === "EPERM";
|
|
9382
|
+
}
|
|
9383
|
+
}
|
|
9384
|
+
function runPs(args) {
|
|
9385
|
+
return new Promise((resolve) => {
|
|
9386
|
+
const child = spawn2("ps", args);
|
|
9387
|
+
let stdout = "";
|
|
9388
|
+
let timedOut = false;
|
|
9389
|
+
const timeout = setTimeout(() => {
|
|
9390
|
+
timedOut = true;
|
|
9391
|
+
child.kill("SIGTERM");
|
|
9392
|
+
}, 1000);
|
|
9393
|
+
child.stdout?.on("data", (chunk) => {
|
|
9394
|
+
stdout += chunk.toString("utf-8");
|
|
9395
|
+
});
|
|
9396
|
+
child.stderr?.resume();
|
|
9397
|
+
child.on("close", (code) => {
|
|
9398
|
+
clearTimeout(timeout);
|
|
9399
|
+
if (timedOut || code !== 0) {
|
|
9400
|
+
resolve(null);
|
|
9401
|
+
} else {
|
|
9402
|
+
const trimmed = stdout.trim();
|
|
9403
|
+
resolve(trimmed || null);
|
|
9404
|
+
}
|
|
9405
|
+
});
|
|
9406
|
+
child.on("error", () => {
|
|
9407
|
+
clearTimeout(timeout);
|
|
9408
|
+
resolve(null);
|
|
9409
|
+
});
|
|
9410
|
+
});
|
|
9411
|
+
}
|
|
9412
|
+
async function getPidIdentity(pid) {
|
|
9413
|
+
const raw = await runPs(["-p", String(pid), "-o", "comm=,lstart="]);
|
|
9414
|
+
if (raw === null)
|
|
9415
|
+
return null;
|
|
9416
|
+
const firstWs = raw.search(/\s/);
|
|
9417
|
+
if (firstWs === -1)
|
|
9418
|
+
return null;
|
|
9419
|
+
const comm = raw.slice(0, firstWs);
|
|
9420
|
+
const lstart = raw.slice(firstWs).trim();
|
|
9421
|
+
if (!comm || !lstart)
|
|
9422
|
+
return null;
|
|
9423
|
+
return { comm, lstart };
|
|
9424
|
+
}
|
|
9425
|
+
function parseLine(line) {
|
|
9426
|
+
const parts = line.split("\t");
|
|
9427
|
+
if (parts.length !== 3)
|
|
9428
|
+
return null;
|
|
9429
|
+
const pidStr = parts[0];
|
|
9430
|
+
if (!/^[1-9]\d*$/.test(pidStr))
|
|
9431
|
+
return null;
|
|
9432
|
+
const pid = Number(pidStr);
|
|
9433
|
+
return { pid, comm: parts[1], lstart: parts[2] };
|
|
9434
|
+
}
|
|
9435
|
+
var MAX_CONCURRENT_PROBES = 5;
|
|
9436
|
+
async function processEntry(entry, killProcessTree2, getPidIdentity2) {
|
|
9437
|
+
try {
|
|
9438
|
+
process.kill(entry.pid, 0);
|
|
9439
|
+
} catch {
|
|
9440
|
+
return { reaped: false, skipped: true };
|
|
9441
|
+
}
|
|
9442
|
+
const live = await getPidIdentity2(entry.pid);
|
|
9443
|
+
if (live === null || live.comm !== entry.comm || live.lstart !== 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
|
+
async function processEntries(entries, killProcessTree2, getPidIdentity2) {
|
|
9454
|
+
let reaped = 0;
|
|
9455
|
+
let skipped = 0;
|
|
9456
|
+
const queue = [...entries];
|
|
9457
|
+
const workerCount = Math.min(MAX_CONCURRENT_PROBES, entries.length);
|
|
9458
|
+
const workers = Array.from({ length: workerCount }, async () => {
|
|
9459
|
+
while (true) {
|
|
9460
|
+
const entry = queue.shift();
|
|
9461
|
+
if (!entry)
|
|
9462
|
+
return;
|
|
9463
|
+
const result = await processEntry(entry, killProcessTree2, getPidIdentity2);
|
|
9464
|
+
if (result.reaped)
|
|
9465
|
+
reaped++;
|
|
9466
|
+
else if (result.skipped)
|
|
9467
|
+
skipped++;
|
|
9468
|
+
}
|
|
9469
|
+
});
|
|
9470
|
+
await Promise.all(workers);
|
|
9471
|
+
return { reaped, skipped };
|
|
9472
|
+
}
|
|
9473
|
+
async function readPidFileEntries(filePath) {
|
|
9474
|
+
let content;
|
|
9475
|
+
try {
|
|
9476
|
+
content = await readFile(filePath, "utf-8");
|
|
9477
|
+
} catch {
|
|
9478
|
+
return null;
|
|
9479
|
+
}
|
|
9480
|
+
const entries = [];
|
|
9481
|
+
for (const line of content.split(`
|
|
9482
|
+
`)) {
|
|
9483
|
+
if (!line.trim())
|
|
9484
|
+
continue;
|
|
9485
|
+
const entry = parseLine(line);
|
|
9486
|
+
if (entry)
|
|
9487
|
+
entries.push(entry);
|
|
9488
|
+
}
|
|
9489
|
+
return entries;
|
|
9490
|
+
}
|
|
9491
|
+
async function cleanupAfterReap(filePath, isCurrent, currentInstancePath) {
|
|
9492
|
+
try {
|
|
9493
|
+
if (isCurrent) {
|
|
9494
|
+
await writeFile(currentInstancePath, "");
|
|
9495
|
+
return false;
|
|
9496
|
+
}
|
|
9497
|
+
await unlink(filePath);
|
|
9498
|
+
return true;
|
|
9499
|
+
} catch {
|
|
9500
|
+
return false;
|
|
9501
|
+
}
|
|
9502
|
+
}
|
|
9503
|
+
async function reapOneFile(filePath, filePid, isCurrent, currentInstancePath, isPluginAlive, killProcessTree2, getPidIdentity2) {
|
|
9504
|
+
const empty = {
|
|
9505
|
+
reaped: 0,
|
|
9506
|
+
skipped: 0,
|
|
9507
|
+
scanned: false,
|
|
9508
|
+
deleted: false
|
|
9509
|
+
};
|
|
9510
|
+
if (!isCurrent && isPluginAlive(filePid)) {
|
|
9511
|
+
return empty;
|
|
9512
|
+
}
|
|
9513
|
+
const entries = await readPidFileEntries(filePath);
|
|
9514
|
+
if (entries === null) {
|
|
9515
|
+
return empty;
|
|
9516
|
+
}
|
|
9517
|
+
const { reaped, skipped } = await processEntries(entries, killProcessTree2, getPidIdentity2);
|
|
9518
|
+
const deleted = await cleanupAfterReap(filePath, isCurrent, currentInstancePath);
|
|
9519
|
+
return { reaped, skipped, scanned: true, deleted };
|
|
9520
|
+
}
|
|
9521
|
+
async function reapOrphans(opts) {
|
|
9522
|
+
const {
|
|
9523
|
+
pidFileDir,
|
|
9524
|
+
currentInstancePath,
|
|
9525
|
+
killProcessTree: killProcessTree2,
|
|
9526
|
+
getPidIdentity: getPidIdentity2,
|
|
9527
|
+
isPluginAlive = defaultIsPluginAlive
|
|
9528
|
+
} = opts;
|
|
9529
|
+
let files;
|
|
9530
|
+
try {
|
|
9531
|
+
files = await readdir(pidFileDir);
|
|
9532
|
+
} catch {
|
|
9533
|
+
return { reaped: 0, skipped: 0, scannedFiles: 0, deletedFiles: 0 };
|
|
9534
|
+
}
|
|
9535
|
+
let reaped = 0;
|
|
9536
|
+
let skipped = 0;
|
|
9537
|
+
let scannedFiles = 0;
|
|
9538
|
+
let deletedFiles = 0;
|
|
9539
|
+
for (const file of files) {
|
|
9540
|
+
if (!file.endsWith(".pids"))
|
|
9541
|
+
continue;
|
|
9542
|
+
const filePath = join(pidFileDir, file);
|
|
9543
|
+
const stem = basename2(file, extname(file));
|
|
9544
|
+
if (!/^[1-9]\d*$/.test(stem)) {
|
|
9545
|
+
console.warn(`[orphan-reaper] Skipping non-numeric PID file: ${file}`);
|
|
9546
|
+
continue;
|
|
9547
|
+
}
|
|
9548
|
+
const filePid = Number(stem);
|
|
9549
|
+
const outcome = await reapOneFile(filePath, filePid, filePid === process.pid, currentInstancePath, isPluginAlive, killProcessTree2, getPidIdentity2);
|
|
9550
|
+
reaped += outcome.reaped;
|
|
9551
|
+
skipped += outcome.skipped;
|
|
9552
|
+
if (outcome.scanned)
|
|
9553
|
+
scannedFiles++;
|
|
9554
|
+
if (outcome.deleted)
|
|
9555
|
+
deletedFiles++;
|
|
9556
|
+
}
|
|
9557
|
+
return { reaped, skipped, scannedFiles, deletedFiles };
|
|
9558
|
+
}
|
|
9559
|
+
|
|
9560
|
+
// src/runtime/pid-file.ts
|
|
9561
|
+
import { randomBytes } from "crypto";
|
|
9562
|
+
import {
|
|
9563
|
+
chmod,
|
|
9564
|
+
constants as fsConstants,
|
|
9565
|
+
mkdir,
|
|
9566
|
+
open,
|
|
9567
|
+
readFile as readFile2,
|
|
9568
|
+
rename,
|
|
9569
|
+
unlink as unlink2
|
|
9570
|
+
} from "fs/promises";
|
|
9571
|
+
import { homedir } from "os";
|
|
9572
|
+
import { dirname, join as join2 } from "path";
|
|
9573
|
+
var writeChains = new Map;
|
|
9574
|
+
async function serializeWrite(filePath, work) {
|
|
9575
|
+
const prev = writeChains.get(filePath) ?? Promise.resolve();
|
|
9576
|
+
const next = prev.catch(() => {}).then(work);
|
|
9577
|
+
writeChains.set(filePath, next);
|
|
9578
|
+
try {
|
|
9579
|
+
await next;
|
|
9580
|
+
} finally {
|
|
9581
|
+
if (writeChains.get(filePath) === next) {
|
|
9582
|
+
writeChains.delete(filePath);
|
|
9583
|
+
}
|
|
9584
|
+
}
|
|
9585
|
+
}
|
|
9586
|
+
function resolveInstancePidFilePath() {
|
|
9587
|
+
const stateDir = process.env.XDG_STATE_HOME ?? join2(homedir(), ".local", "state");
|
|
9588
|
+
return join2(stateDir, "opencode-copilot-delegate", "orphans", `${process.pid}.pids`);
|
|
9589
|
+
}
|
|
9590
|
+
async function appendPidEntry(filePath, pid, comm, lstart) {
|
|
9591
|
+
await serializeWrite(filePath, async () => {
|
|
9592
|
+
await mkdir(dirname(filePath), { recursive: true, mode: 448 });
|
|
9593
|
+
let existing = "";
|
|
9594
|
+
try {
|
|
9595
|
+
existing = await readFile2(filePath, "utf-8");
|
|
9596
|
+
} catch (e) {
|
|
9597
|
+
if (!isErrnoException(e) || e.code !== "ENOENT")
|
|
9598
|
+
throw e;
|
|
9599
|
+
}
|
|
9600
|
+
const line = `${pid} ${comm} ${lstart}
|
|
9601
|
+
`;
|
|
9602
|
+
const content = existing + line;
|
|
9603
|
+
const tempPath = `${filePath}.tmp.${randomBytes(8).toString("hex")}`;
|
|
9604
|
+
const fd = await open(tempPath, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
|
|
9605
|
+
try {
|
|
9606
|
+
await fd.writeFile(content, { encoding: "utf-8" });
|
|
9607
|
+
} finally {
|
|
9608
|
+
await fd.close();
|
|
9609
|
+
}
|
|
9610
|
+
await rename(tempPath, filePath);
|
|
9611
|
+
await chmod(filePath, 384);
|
|
9612
|
+
});
|
|
9613
|
+
}
|
|
9614
|
+
async function removePidEntry(filePath, pid) {
|
|
9615
|
+
await serializeWrite(filePath, async () => {
|
|
9616
|
+
let existing = "";
|
|
9617
|
+
try {
|
|
9618
|
+
existing = await readFile2(filePath, "utf-8");
|
|
9619
|
+
} catch (e) {
|
|
9620
|
+
if (!isErrnoException(e) || e.code !== "ENOENT")
|
|
9621
|
+
throw e;
|
|
9622
|
+
return;
|
|
9623
|
+
}
|
|
9624
|
+
const prefix = `${pid} `;
|
|
9625
|
+
const lines = existing.split(`
|
|
9626
|
+
`);
|
|
9627
|
+
const filtered = lines.filter((line) => !line.startsWith(prefix));
|
|
9628
|
+
if (filtered.length === lines.length) {
|
|
9629
|
+
return;
|
|
9630
|
+
}
|
|
9631
|
+
const content = filtered.join(`
|
|
9632
|
+
`);
|
|
9633
|
+
const tempPath = `${filePath}.tmp.${randomBytes(8).toString("hex")}`;
|
|
9634
|
+
const fd = await open(tempPath, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
|
|
9635
|
+
try {
|
|
9636
|
+
await fd.writeFile(content, { encoding: "utf-8" });
|
|
9637
|
+
} finally {
|
|
9638
|
+
await fd.close();
|
|
9639
|
+
}
|
|
9640
|
+
await rename(tempPath, filePath);
|
|
9641
|
+
await chmod(filePath, 384);
|
|
9642
|
+
if (content.trim().length === 0) {
|
|
9643
|
+
await unlink2(filePath);
|
|
9644
|
+
}
|
|
9645
|
+
});
|
|
9646
|
+
}
|
|
9647
|
+
|
|
9648
|
+
// src/tools/cancel.ts
|
|
9649
|
+
import { tool } from "@opencode-ai/plugin/tool";
|
|
9650
|
+
|
|
9367
9651
|
// src/runtime/task-registry.ts
|
|
9652
|
+
import { randomUUID } from "crypto";
|
|
9368
9653
|
var tasks = new Map;
|
|
9369
9654
|
function createTask(input, taskId = `cpl_${randomUUID()}`) {
|
|
9655
|
+
const { pidFilePath, ...rest } = input;
|
|
9370
9656
|
const task = {
|
|
9371
|
-
...
|
|
9657
|
+
...rest,
|
|
9372
9658
|
taskId
|
|
9373
9659
|
};
|
|
9660
|
+
if (task.pid > 0 && pidFilePath) {
|
|
9661
|
+
getPidIdentity(task.pid).then((identity3) => {
|
|
9662
|
+
if (identity3) {
|
|
9663
|
+
appendPidEntry(pidFilePath, task.pid, identity3.comm, identity3.lstart).catch(() => {});
|
|
9664
|
+
} else {
|
|
9665
|
+
console.warn(`[task-registry] ps lookup returned null for pid ${task.pid}; subprocess will not be tracked for orphan reaping`);
|
|
9666
|
+
}
|
|
9667
|
+
}).catch(() => {});
|
|
9668
|
+
}
|
|
9374
9669
|
tasks.set(taskId, task);
|
|
9375
9670
|
return task;
|
|
9376
9671
|
}
|
|
@@ -9475,7 +9770,7 @@ async function notifyCompletion(client, task) {
|
|
|
9475
9770
|
}
|
|
9476
9771
|
|
|
9477
9772
|
// src/runtime/subprocess.ts
|
|
9478
|
-
import { spawn as
|
|
9773
|
+
import { spawn as spawn3 } from "child_process";
|
|
9479
9774
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
9480
9775
|
|
|
9481
9776
|
// src/lib/ansi.ts
|
|
@@ -9558,8 +9853,31 @@ function parseJsonlLine(line) {
|
|
|
9558
9853
|
return { type, data, raw };
|
|
9559
9854
|
}
|
|
9560
9855
|
|
|
9856
|
+
// src/runtime/task-status.ts
|
|
9857
|
+
var TERMINAL_STATUSES = new Set([
|
|
9858
|
+
"complete",
|
|
9859
|
+
"failed",
|
|
9860
|
+
"cancelled"
|
|
9861
|
+
]);
|
|
9862
|
+
function isTerminal(s) {
|
|
9863
|
+
return TERMINAL_STATUSES.has(s);
|
|
9864
|
+
}
|
|
9865
|
+
function setStatus(task, newStatus, options) {
|
|
9866
|
+
if (isTerminal(task.status) && isTerminal(newStatus)) {
|
|
9867
|
+
return;
|
|
9868
|
+
}
|
|
9869
|
+
task.status = newStatus;
|
|
9870
|
+
if (options?.pidFilePath && isTerminal(newStatus)) {
|
|
9871
|
+
removePidEntry(options.pidFilePath, task.pid).catch(() => {});
|
|
9872
|
+
}
|
|
9873
|
+
}
|
|
9874
|
+
|
|
9561
9875
|
// src/runtime/subprocess.ts
|
|
9562
9876
|
function flushBufferedStdout(task) {
|
|
9877
|
+
if (task.status !== "running") {
|
|
9878
|
+
task.stdoutLineBuffer = "";
|
|
9879
|
+
return;
|
|
9880
|
+
}
|
|
9563
9881
|
if (task.stdoutLineBuffer.trim().length === 0) {
|
|
9564
9882
|
task.stdoutLineBuffer = "";
|
|
9565
9883
|
return;
|
|
@@ -9574,13 +9892,11 @@ function assignFinalMessage(task) {
|
|
|
9574
9892
|
task.finalMessage = stripAnsi(content);
|
|
9575
9893
|
}
|
|
9576
9894
|
}
|
|
9577
|
-
function finalizeTask(task, exitCode, stderrText) {
|
|
9895
|
+
function finalizeTask(task, exitCode, stderrText, pidFilePath) {
|
|
9578
9896
|
flushBufferedStdout(task);
|
|
9579
9897
|
task.endedAt = Date.now();
|
|
9580
9898
|
task.exitCode = exitCode ?? undefined;
|
|
9581
|
-
|
|
9582
|
-
task.status = exitCode === 0 ? "complete" : "failed";
|
|
9583
|
-
}
|
|
9899
|
+
setStatus(task, exitCode === 0 ? "complete" : "failed", { pidFilePath });
|
|
9584
9900
|
if (stderrText.trim().length > 0) {
|
|
9585
9901
|
task.errorText = stripAnsi(stderrText.trim());
|
|
9586
9902
|
}
|
|
@@ -9601,7 +9917,7 @@ function spawnCopilot(args, opts) {
|
|
|
9601
9917
|
...process.env,
|
|
9602
9918
|
...opts.env
|
|
9603
9919
|
});
|
|
9604
|
-
const child =
|
|
9920
|
+
const child = spawn3("copilot", args, {
|
|
9605
9921
|
cwd: opts.cwd,
|
|
9606
9922
|
detached: true,
|
|
9607
9923
|
env,
|
|
@@ -9627,6 +9943,8 @@ function spawnCopilot(args, opts) {
|
|
|
9627
9943
|
const lines = task.stdoutLineBuffer.split(/\r?\n/);
|
|
9628
9944
|
task.stdoutLineBuffer = lines.pop() ?? "";
|
|
9629
9945
|
for (const line of lines) {
|
|
9946
|
+
if (task.status !== "running")
|
|
9947
|
+
break;
|
|
9630
9948
|
if (line.length === 0) {
|
|
9631
9949
|
continue;
|
|
9632
9950
|
}
|
|
@@ -9642,17 +9960,17 @@ function spawnCopilot(args, opts) {
|
|
|
9642
9960
|
if (task.status !== "running") {
|
|
9643
9961
|
return;
|
|
9644
9962
|
}
|
|
9645
|
-
task
|
|
9963
|
+
setStatus(task, "cancelled", { pidFilePath: opts.pidFilePath });
|
|
9646
9964
|
killProcessTree(task.pid).catch(() => {});
|
|
9647
9965
|
}, { once: true });
|
|
9648
9966
|
task.completionPromise = new Promise((resolve) => {
|
|
9649
9967
|
child.once("error", (error) => {
|
|
9650
|
-
task
|
|
9968
|
+
setStatus(task, "failed", { pidFilePath: opts.pidFilePath });
|
|
9651
9969
|
task.errorText = stripAnsi(error.message);
|
|
9652
9970
|
resolve();
|
|
9653
9971
|
});
|
|
9654
9972
|
child.once("close", (code) => {
|
|
9655
|
-
finalizeTask(task, code, stderrText);
|
|
9973
|
+
finalizeTask(task, code, stderrText, opts.pidFilePath);
|
|
9656
9974
|
resolve();
|
|
9657
9975
|
});
|
|
9658
9976
|
});
|
|
@@ -9709,7 +10027,10 @@ function createDelegateTool(options) {
|
|
|
9709
10027
|
let spawnResult;
|
|
9710
10028
|
let task;
|
|
9711
10029
|
try {
|
|
9712
|
-
spawnResult = spawnCopilot(cliArgs, {
|
|
10030
|
+
spawnResult = spawnCopilot(cliArgs, {
|
|
10031
|
+
cwd: options.directory,
|
|
10032
|
+
pidFilePath: options.pidFilePath
|
|
10033
|
+
});
|
|
9713
10034
|
const { taskId: spawnTaskId, ...spawnFields } = spawnResult;
|
|
9714
10035
|
task = createTask({
|
|
9715
10036
|
...spawnFields,
|
|
@@ -9718,7 +10039,8 @@ function createDelegateTool(options) {
|
|
|
9718
10039
|
args: cliArgs,
|
|
9719
10040
|
cwd: options.directory,
|
|
9720
10041
|
agentName: args.agent,
|
|
9721
|
-
modelName: args.model
|
|
10042
|
+
modelName: args.model,
|
|
10043
|
+
pidFilePath: options.pidFilePath
|
|
9722
10044
|
}, spawnTaskId);
|
|
9723
10045
|
} catch (error) {
|
|
9724
10046
|
return JSON.stringify({
|
|
@@ -9899,12 +10221,24 @@ function getAgentsDirectories(directory) {
|
|
|
9899
10221
|
var CopilotDelegate = async ({ client, directory }) => {
|
|
9900
10222
|
const agents = discoverAgents(getAgentsDirectories(directory));
|
|
9901
10223
|
const delegateDescription = buildDescription(agents);
|
|
10224
|
+
const currentInstancePath = resolveInstancePidFilePath();
|
|
10225
|
+
const pidFileDir = dirname2(currentInstancePath);
|
|
10226
|
+
try {
|
|
10227
|
+
await mkdir2(pidFileDir, { recursive: true, mode: 448 });
|
|
10228
|
+
await reapOrphans({
|
|
10229
|
+
pidFileDir,
|
|
10230
|
+
currentInstancePath,
|
|
10231
|
+
killProcessTree,
|
|
10232
|
+
getPidIdentity
|
|
10233
|
+
});
|
|
10234
|
+
} catch {}
|
|
9902
10235
|
return {
|
|
9903
10236
|
tool: {
|
|
9904
10237
|
copilot_delegate: createDelegateTool({
|
|
9905
10238
|
client,
|
|
9906
10239
|
description: delegateDescription,
|
|
9907
|
-
directory
|
|
10240
|
+
directory,
|
|
10241
|
+
pidFilePath: currentInstancePath
|
|
9908
10242
|
}),
|
|
9909
10243
|
copilot_output: createOutputTool(),
|
|
9910
10244
|
copilot_cancel: createCancelTool()
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Type predicate that narrows `unknown` to `NodeJS.ErrnoException` for safe
|
|
3
|
+
* `.code` access on errors thrown by `node:fs` and similar Node APIs.
|
|
4
|
+
*
|
|
5
|
+
* Use this in catch blocks instead of casting `e as NodeJS.ErrnoException`
|
|
6
|
+
* — the cast is unsafe when the thrown value is a string, plain object, or
|
|
7
|
+
* any non-Error type.
|
|
8
|
+
*/
|
|
9
|
+
export declare function isErrnoException(e: unknown): e is NodeJS.ErrnoException;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export interface ReapDeps {
|
|
2
|
+
killProcessTree: (pid: number) => Promise<void>;
|
|
3
|
+
getPidIdentity: (pid: number) => Promise<{
|
|
4
|
+
comm: string;
|
|
5
|
+
lstart: string;
|
|
6
|
+
} | null>;
|
|
7
|
+
isPluginAlive: (pid: number) => boolean;
|
|
8
|
+
}
|
|
9
|
+
export interface ReapResult {
|
|
10
|
+
reaped: number;
|
|
11
|
+
skipped: number;
|
|
12
|
+
scannedFiles: number;
|
|
13
|
+
deletedFiles: number;
|
|
14
|
+
}
|
|
15
|
+
export declare function defaultIsPluginAlive(pid: number): boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Read both comm (kernel-tracked executable name) and lstart (process
|
|
18
|
+
* start time) for a PID via a single ps invocation.
|
|
19
|
+
*
|
|
20
|
+
* 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`).
|
|
24
|
+
*
|
|
25
|
+
* Returns null on any failure mode (timeout, spawn error, non-zero exit,
|
|
26
|
+
* empty output, malformed output). Callers must treat null as "identity
|
|
27
|
+
* unverifiable; do not trust this PID."
|
|
28
|
+
*/
|
|
29
|
+
export declare function getPidIdentity(pid: number): Promise<{
|
|
30
|
+
comm: string;
|
|
31
|
+
lstart: string;
|
|
32
|
+
} | null>;
|
|
33
|
+
export declare function reapOrphans(opts: {
|
|
34
|
+
pidFileDir: string;
|
|
35
|
+
currentInstancePath: string;
|
|
36
|
+
killProcessTree: ReapDeps['killProcessTree'];
|
|
37
|
+
getPidIdentity: ReapDeps['getPidIdentity'];
|
|
38
|
+
isPluginAlive?: ReapDeps['isPluginAlive'];
|
|
39
|
+
}): Promise<ReapResult>;
|
|
@@ -14,6 +14,7 @@ export type CreateTaskInput = Omit<SpawnCopilotResult, 'taskId'> & {
|
|
|
14
14
|
cwd: string;
|
|
15
15
|
agentName?: string;
|
|
16
16
|
modelName?: string;
|
|
17
|
+
pidFilePath?: string;
|
|
17
18
|
};
|
|
18
19
|
export declare function createTask(input: CreateTaskInput, taskId?: string): TaskState;
|
|
19
20
|
export declare function getTask(taskId: string): TaskState | undefined;
|
package/dist/tools/delegate.d.ts
CHANGED