opencode-copilot-delegate 0.1.0 → 0.2.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 +14 -0
- package/README.md +1 -1
- package/dist/index.js +345 -20
- package/dist/lib/errno.d.ts +9 -0
- package/dist/runtime/orphan-reaper.d.ts +23 -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,19 @@
|
|
|
1
1
|
# opencode-copilot-delegate
|
|
2
2
|
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 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.
|
|
8
|
+
|
|
9
|
+
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.
|
|
10
|
+
|
|
11
|
+
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.
|
|
12
|
+
|
|
13
|
+
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`.
|
|
14
|
+
|
|
15
|
+
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.
|
|
16
|
+
|
|
3
17
|
## 0.1.0
|
|
4
18
|
|
|
5
19
|
### 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,300 @@ 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 psField(pid, field) {
|
|
9385
|
+
return new Promise((resolve) => {
|
|
9386
|
+
const child = spawn2("ps", ["-p", String(pid), "-o", `${field}=`]);
|
|
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 getPidComm(pid) {
|
|
9413
|
+
return psField(pid, "comm");
|
|
9414
|
+
}
|
|
9415
|
+
async function getPidStartTime(pid) {
|
|
9416
|
+
return psField(pid, "lstart");
|
|
9417
|
+
}
|
|
9418
|
+
function parseLine(line) {
|
|
9419
|
+
const parts = line.split("\t");
|
|
9420
|
+
if (parts.length !== 3)
|
|
9421
|
+
return null;
|
|
9422
|
+
const pidStr = parts[0];
|
|
9423
|
+
if (!/^[1-9]\d*$/.test(pidStr))
|
|
9424
|
+
return null;
|
|
9425
|
+
const pid = Number(pidStr);
|
|
9426
|
+
return { pid, comm: parts[1], lstart: parts[2] };
|
|
9427
|
+
}
|
|
9428
|
+
async function processEntries(entries, killProcessTree2, getPidComm2, getPidStartTime2) {
|
|
9429
|
+
let reaped = 0;
|
|
9430
|
+
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)
|
|
9455
|
+
reaped++;
|
|
9456
|
+
else if (r.skipped)
|
|
9457
|
+
skipped++;
|
|
9458
|
+
}
|
|
9459
|
+
}
|
|
9460
|
+
return { reaped, skipped };
|
|
9461
|
+
}
|
|
9462
|
+
async function readPidFileEntries(filePath) {
|
|
9463
|
+
let content;
|
|
9464
|
+
try {
|
|
9465
|
+
content = await readFile(filePath, "utf-8");
|
|
9466
|
+
} catch {
|
|
9467
|
+
return null;
|
|
9468
|
+
}
|
|
9469
|
+
const entries = [];
|
|
9470
|
+
for (const line of content.split(`
|
|
9471
|
+
`)) {
|
|
9472
|
+
if (!line.trim())
|
|
9473
|
+
continue;
|
|
9474
|
+
const entry = parseLine(line);
|
|
9475
|
+
if (entry)
|
|
9476
|
+
entries.push(entry);
|
|
9477
|
+
}
|
|
9478
|
+
return entries;
|
|
9479
|
+
}
|
|
9480
|
+
async function cleanupAfterReap(filePath, isCurrent, currentInstancePath) {
|
|
9481
|
+
try {
|
|
9482
|
+
if (isCurrent) {
|
|
9483
|
+
await writeFile(currentInstancePath, "");
|
|
9484
|
+
return false;
|
|
9485
|
+
}
|
|
9486
|
+
await unlink(filePath);
|
|
9487
|
+
return true;
|
|
9488
|
+
} catch {
|
|
9489
|
+
return false;
|
|
9490
|
+
}
|
|
9491
|
+
}
|
|
9492
|
+
async function reapOneFile(filePath, filePid, isCurrent, currentInstancePath, isPluginAlive, killProcessTree2, getPidComm2, getPidStartTime2) {
|
|
9493
|
+
const empty = {
|
|
9494
|
+
reaped: 0,
|
|
9495
|
+
skipped: 0,
|
|
9496
|
+
scanned: false,
|
|
9497
|
+
deleted: false
|
|
9498
|
+
};
|
|
9499
|
+
if (!isCurrent && isPluginAlive(filePid)) {
|
|
9500
|
+
return empty;
|
|
9501
|
+
}
|
|
9502
|
+
const entries = await readPidFileEntries(filePath);
|
|
9503
|
+
if (entries === null) {
|
|
9504
|
+
return empty;
|
|
9505
|
+
}
|
|
9506
|
+
const { reaped, skipped } = await processEntries(entries, killProcessTree2, getPidComm2, getPidStartTime2);
|
|
9507
|
+
const deleted = await cleanupAfterReap(filePath, isCurrent, currentInstancePath);
|
|
9508
|
+
return { reaped, skipped, scanned: true, deleted };
|
|
9509
|
+
}
|
|
9510
|
+
async function reapOrphans(opts) {
|
|
9511
|
+
const {
|
|
9512
|
+
pidFileDir,
|
|
9513
|
+
currentInstancePath,
|
|
9514
|
+
killProcessTree: killProcessTree2,
|
|
9515
|
+
getPidComm: getPidComm2,
|
|
9516
|
+
getPidStartTime: getPidStartTime2,
|
|
9517
|
+
isPluginAlive = defaultIsPluginAlive
|
|
9518
|
+
} = opts;
|
|
9519
|
+
let files;
|
|
9520
|
+
try {
|
|
9521
|
+
files = await readdir(pidFileDir);
|
|
9522
|
+
} catch {
|
|
9523
|
+
return { reaped: 0, skipped: 0, scannedFiles: 0, deletedFiles: 0 };
|
|
9524
|
+
}
|
|
9525
|
+
let reaped = 0;
|
|
9526
|
+
let skipped = 0;
|
|
9527
|
+
let scannedFiles = 0;
|
|
9528
|
+
let deletedFiles = 0;
|
|
9529
|
+
for (const file of files) {
|
|
9530
|
+
if (!file.endsWith(".pids"))
|
|
9531
|
+
continue;
|
|
9532
|
+
const filePath = join(pidFileDir, file);
|
|
9533
|
+
const stem = basename2(file, extname(file));
|
|
9534
|
+
if (!/^[1-9]\d*$/.test(stem)) {
|
|
9535
|
+
console.warn(`[orphan-reaper] Skipping non-numeric PID file: ${file}`);
|
|
9536
|
+
continue;
|
|
9537
|
+
}
|
|
9538
|
+
const filePid = Number(stem);
|
|
9539
|
+
const outcome = await reapOneFile(filePath, filePid, filePid === process.pid, currentInstancePath, isPluginAlive, killProcessTree2, getPidComm2, getPidStartTime2);
|
|
9540
|
+
reaped += outcome.reaped;
|
|
9541
|
+
skipped += outcome.skipped;
|
|
9542
|
+
if (outcome.scanned)
|
|
9543
|
+
scannedFiles++;
|
|
9544
|
+
if (outcome.deleted)
|
|
9545
|
+
deletedFiles++;
|
|
9546
|
+
}
|
|
9547
|
+
return { reaped, skipped, scannedFiles, deletedFiles };
|
|
9548
|
+
}
|
|
9549
|
+
|
|
9550
|
+
// src/runtime/pid-file.ts
|
|
9551
|
+
import { randomBytes } from "crypto";
|
|
9552
|
+
import {
|
|
9553
|
+
chmod,
|
|
9554
|
+
constants as fsConstants,
|
|
9555
|
+
mkdir,
|
|
9556
|
+
open,
|
|
9557
|
+
readFile as readFile2,
|
|
9558
|
+
rename,
|
|
9559
|
+
unlink as unlink2
|
|
9560
|
+
} from "fs/promises";
|
|
9561
|
+
import { homedir } from "os";
|
|
9562
|
+
import { dirname, join as join2 } from "path";
|
|
9563
|
+
var writeChains = new Map;
|
|
9564
|
+
async function serializeWrite(filePath, work) {
|
|
9565
|
+
const prev = writeChains.get(filePath) ?? Promise.resolve();
|
|
9566
|
+
const next = prev.catch(() => {}).then(work);
|
|
9567
|
+
writeChains.set(filePath, next);
|
|
9568
|
+
try {
|
|
9569
|
+
await next;
|
|
9570
|
+
} finally {
|
|
9571
|
+
if (writeChains.get(filePath) === next) {
|
|
9572
|
+
writeChains.delete(filePath);
|
|
9573
|
+
}
|
|
9574
|
+
}
|
|
9575
|
+
}
|
|
9576
|
+
function resolveInstancePidFilePath() {
|
|
9577
|
+
const stateDir = process.env.XDG_STATE_HOME ?? join2(homedir(), ".local", "state");
|
|
9578
|
+
return join2(stateDir, "opencode-copilot-delegate", "orphans", `${process.pid}.pids`);
|
|
9579
|
+
}
|
|
9580
|
+
async function appendPidEntry(filePath, pid, comm, lstart) {
|
|
9581
|
+
await serializeWrite(filePath, async () => {
|
|
9582
|
+
await mkdir(dirname(filePath), { recursive: true, mode: 448 });
|
|
9583
|
+
let existing = "";
|
|
9584
|
+
try {
|
|
9585
|
+
existing = await readFile2(filePath, "utf-8");
|
|
9586
|
+
} catch (e) {
|
|
9587
|
+
if (!isErrnoException(e) || e.code !== "ENOENT")
|
|
9588
|
+
throw e;
|
|
9589
|
+
}
|
|
9590
|
+
const line = `${pid} ${comm} ${lstart}
|
|
9591
|
+
`;
|
|
9592
|
+
const content = existing + line;
|
|
9593
|
+
const tempPath = `${filePath}.tmp.${randomBytes(8).toString("hex")}`;
|
|
9594
|
+
const fd = await open(tempPath, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
|
|
9595
|
+
try {
|
|
9596
|
+
await fd.writeFile(content, { encoding: "utf-8" });
|
|
9597
|
+
} finally {
|
|
9598
|
+
await fd.close();
|
|
9599
|
+
}
|
|
9600
|
+
await rename(tempPath, filePath);
|
|
9601
|
+
await chmod(filePath, 384);
|
|
9602
|
+
});
|
|
9603
|
+
}
|
|
9604
|
+
async function removePidEntry(filePath, pid) {
|
|
9605
|
+
await serializeWrite(filePath, async () => {
|
|
9606
|
+
let existing = "";
|
|
9607
|
+
try {
|
|
9608
|
+
existing = await readFile2(filePath, "utf-8");
|
|
9609
|
+
} catch (e) {
|
|
9610
|
+
if (!isErrnoException(e) || e.code !== "ENOENT")
|
|
9611
|
+
throw e;
|
|
9612
|
+
return;
|
|
9613
|
+
}
|
|
9614
|
+
const prefix = `${pid} `;
|
|
9615
|
+
const lines = existing.split(`
|
|
9616
|
+
`);
|
|
9617
|
+
const filtered = lines.filter((line) => !line.startsWith(prefix));
|
|
9618
|
+
if (filtered.length === lines.length) {
|
|
9619
|
+
return;
|
|
9620
|
+
}
|
|
9621
|
+
const content = filtered.join(`
|
|
9622
|
+
`);
|
|
9623
|
+
const tempPath = `${filePath}.tmp.${randomBytes(8).toString("hex")}`;
|
|
9624
|
+
const fd = await open(tempPath, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
|
|
9625
|
+
try {
|
|
9626
|
+
await fd.writeFile(content, { encoding: "utf-8" });
|
|
9627
|
+
} finally {
|
|
9628
|
+
await fd.close();
|
|
9629
|
+
}
|
|
9630
|
+
await rename(tempPath, filePath);
|
|
9631
|
+
await chmod(filePath, 384);
|
|
9632
|
+
if (content.trim().length === 0) {
|
|
9633
|
+
await unlink2(filePath);
|
|
9634
|
+
}
|
|
9635
|
+
});
|
|
9636
|
+
}
|
|
9637
|
+
|
|
9638
|
+
// src/tools/cancel.ts
|
|
9639
|
+
import { tool } from "@opencode-ai/plugin/tool";
|
|
9640
|
+
|
|
9367
9641
|
// src/runtime/task-registry.ts
|
|
9642
|
+
import { randomUUID } from "crypto";
|
|
9368
9643
|
var tasks = new Map;
|
|
9369
9644
|
function createTask(input, taskId = `cpl_${randomUUID()}`) {
|
|
9645
|
+
const { pidFilePath, ...rest } = input;
|
|
9370
9646
|
const task = {
|
|
9371
|
-
...
|
|
9647
|
+
...rest,
|
|
9372
9648
|
taskId
|
|
9373
9649
|
};
|
|
9650
|
+
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(() => {});
|
|
9654
|
+
} else {
|
|
9655
|
+
console.warn(`[task-registry] ps lookup returned null for pid ${task.pid}; subprocess will not be tracked for orphan reaping`);
|
|
9656
|
+
}
|
|
9657
|
+
}).catch(() => {});
|
|
9658
|
+
}
|
|
9374
9659
|
tasks.set(taskId, task);
|
|
9375
9660
|
return task;
|
|
9376
9661
|
}
|
|
@@ -9475,7 +9760,7 @@ async function notifyCompletion(client, task) {
|
|
|
9475
9760
|
}
|
|
9476
9761
|
|
|
9477
9762
|
// src/runtime/subprocess.ts
|
|
9478
|
-
import { spawn as
|
|
9763
|
+
import { spawn as spawn3 } from "child_process";
|
|
9479
9764
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
9480
9765
|
|
|
9481
9766
|
// src/lib/ansi.ts
|
|
@@ -9558,8 +9843,31 @@ function parseJsonlLine(line) {
|
|
|
9558
9843
|
return { type, data, raw };
|
|
9559
9844
|
}
|
|
9560
9845
|
|
|
9846
|
+
// src/runtime/task-status.ts
|
|
9847
|
+
var TERMINAL_STATUSES = new Set([
|
|
9848
|
+
"complete",
|
|
9849
|
+
"failed",
|
|
9850
|
+
"cancelled"
|
|
9851
|
+
]);
|
|
9852
|
+
function isTerminal(s) {
|
|
9853
|
+
return TERMINAL_STATUSES.has(s);
|
|
9854
|
+
}
|
|
9855
|
+
function setStatus(task, newStatus, options) {
|
|
9856
|
+
if (isTerminal(task.status) && isTerminal(newStatus)) {
|
|
9857
|
+
return;
|
|
9858
|
+
}
|
|
9859
|
+
task.status = newStatus;
|
|
9860
|
+
if (options?.pidFilePath && isTerminal(newStatus)) {
|
|
9861
|
+
removePidEntry(options.pidFilePath, task.pid).catch(() => {});
|
|
9862
|
+
}
|
|
9863
|
+
}
|
|
9864
|
+
|
|
9561
9865
|
// src/runtime/subprocess.ts
|
|
9562
9866
|
function flushBufferedStdout(task) {
|
|
9867
|
+
if (task.status !== "running") {
|
|
9868
|
+
task.stdoutLineBuffer = "";
|
|
9869
|
+
return;
|
|
9870
|
+
}
|
|
9563
9871
|
if (task.stdoutLineBuffer.trim().length === 0) {
|
|
9564
9872
|
task.stdoutLineBuffer = "";
|
|
9565
9873
|
return;
|
|
@@ -9574,13 +9882,11 @@ function assignFinalMessage(task) {
|
|
|
9574
9882
|
task.finalMessage = stripAnsi(content);
|
|
9575
9883
|
}
|
|
9576
9884
|
}
|
|
9577
|
-
function finalizeTask(task, exitCode, stderrText) {
|
|
9885
|
+
function finalizeTask(task, exitCode, stderrText, pidFilePath) {
|
|
9578
9886
|
flushBufferedStdout(task);
|
|
9579
9887
|
task.endedAt = Date.now();
|
|
9580
9888
|
task.exitCode = exitCode ?? undefined;
|
|
9581
|
-
|
|
9582
|
-
task.status = exitCode === 0 ? "complete" : "failed";
|
|
9583
|
-
}
|
|
9889
|
+
setStatus(task, exitCode === 0 ? "complete" : "failed", { pidFilePath });
|
|
9584
9890
|
if (stderrText.trim().length > 0) {
|
|
9585
9891
|
task.errorText = stripAnsi(stderrText.trim());
|
|
9586
9892
|
}
|
|
@@ -9601,7 +9907,7 @@ function spawnCopilot(args, opts) {
|
|
|
9601
9907
|
...process.env,
|
|
9602
9908
|
...opts.env
|
|
9603
9909
|
});
|
|
9604
|
-
const child =
|
|
9910
|
+
const child = spawn3("copilot", args, {
|
|
9605
9911
|
cwd: opts.cwd,
|
|
9606
9912
|
detached: true,
|
|
9607
9913
|
env,
|
|
@@ -9627,6 +9933,8 @@ function spawnCopilot(args, opts) {
|
|
|
9627
9933
|
const lines = task.stdoutLineBuffer.split(/\r?\n/);
|
|
9628
9934
|
task.stdoutLineBuffer = lines.pop() ?? "";
|
|
9629
9935
|
for (const line of lines) {
|
|
9936
|
+
if (task.status !== "running")
|
|
9937
|
+
break;
|
|
9630
9938
|
if (line.length === 0) {
|
|
9631
9939
|
continue;
|
|
9632
9940
|
}
|
|
@@ -9642,17 +9950,17 @@ function spawnCopilot(args, opts) {
|
|
|
9642
9950
|
if (task.status !== "running") {
|
|
9643
9951
|
return;
|
|
9644
9952
|
}
|
|
9645
|
-
task
|
|
9953
|
+
setStatus(task, "cancelled", { pidFilePath: opts.pidFilePath });
|
|
9646
9954
|
killProcessTree(task.pid).catch(() => {});
|
|
9647
9955
|
}, { once: true });
|
|
9648
9956
|
task.completionPromise = new Promise((resolve) => {
|
|
9649
9957
|
child.once("error", (error) => {
|
|
9650
|
-
task
|
|
9958
|
+
setStatus(task, "failed", { pidFilePath: opts.pidFilePath });
|
|
9651
9959
|
task.errorText = stripAnsi(error.message);
|
|
9652
9960
|
resolve();
|
|
9653
9961
|
});
|
|
9654
9962
|
child.once("close", (code) => {
|
|
9655
|
-
finalizeTask(task, code, stderrText);
|
|
9963
|
+
finalizeTask(task, code, stderrText, opts.pidFilePath);
|
|
9656
9964
|
resolve();
|
|
9657
9965
|
});
|
|
9658
9966
|
});
|
|
@@ -9709,7 +10017,10 @@ function createDelegateTool(options) {
|
|
|
9709
10017
|
let spawnResult;
|
|
9710
10018
|
let task;
|
|
9711
10019
|
try {
|
|
9712
|
-
spawnResult = spawnCopilot(cliArgs, {
|
|
10020
|
+
spawnResult = spawnCopilot(cliArgs, {
|
|
10021
|
+
cwd: options.directory,
|
|
10022
|
+
pidFilePath: options.pidFilePath
|
|
10023
|
+
});
|
|
9713
10024
|
const { taskId: spawnTaskId, ...spawnFields } = spawnResult;
|
|
9714
10025
|
task = createTask({
|
|
9715
10026
|
...spawnFields,
|
|
@@ -9718,7 +10029,8 @@ function createDelegateTool(options) {
|
|
|
9718
10029
|
args: cliArgs,
|
|
9719
10030
|
cwd: options.directory,
|
|
9720
10031
|
agentName: args.agent,
|
|
9721
|
-
modelName: args.model
|
|
10032
|
+
modelName: args.model,
|
|
10033
|
+
pidFilePath: options.pidFilePath
|
|
9722
10034
|
}, spawnTaskId);
|
|
9723
10035
|
} catch (error) {
|
|
9724
10036
|
return JSON.stringify({
|
|
@@ -9899,12 +10211,25 @@ function getAgentsDirectories(directory) {
|
|
|
9899
10211
|
var CopilotDelegate = async ({ client, directory }) => {
|
|
9900
10212
|
const agents = discoverAgents(getAgentsDirectories(directory));
|
|
9901
10213
|
const delegateDescription = buildDescription(agents);
|
|
10214
|
+
const currentInstancePath = resolveInstancePidFilePath();
|
|
10215
|
+
const pidFileDir = dirname2(currentInstancePath);
|
|
10216
|
+
try {
|
|
10217
|
+
await mkdir2(pidFileDir, { recursive: true, mode: 448 });
|
|
10218
|
+
await reapOrphans({
|
|
10219
|
+
pidFileDir,
|
|
10220
|
+
currentInstancePath,
|
|
10221
|
+
killProcessTree,
|
|
10222
|
+
getPidComm,
|
|
10223
|
+
getPidStartTime
|
|
10224
|
+
});
|
|
10225
|
+
} catch {}
|
|
9902
10226
|
return {
|
|
9903
10227
|
tool: {
|
|
9904
10228
|
copilot_delegate: createDelegateTool({
|
|
9905
10229
|
client,
|
|
9906
10230
|
description: delegateDescription,
|
|
9907
|
-
directory
|
|
10231
|
+
directory,
|
|
10232
|
+
pidFilePath: currentInstancePath
|
|
9908
10233
|
}),
|
|
9909
10234
|
copilot_output: createOutputTool(),
|
|
9910
10235
|
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,23 @@
|
|
|
1
|
+
export interface ReapDeps {
|
|
2
|
+
killProcessTree: (pid: number) => Promise<void>;
|
|
3
|
+
getPidComm: (pid: number) => Promise<string | null>;
|
|
4
|
+
getPidStartTime: (pid: number) => Promise<string | null>;
|
|
5
|
+
isPluginAlive: (pid: number) => boolean;
|
|
6
|
+
}
|
|
7
|
+
export interface ReapResult {
|
|
8
|
+
reaped: number;
|
|
9
|
+
skipped: number;
|
|
10
|
+
scannedFiles: number;
|
|
11
|
+
deletedFiles: number;
|
|
12
|
+
}
|
|
13
|
+
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: {
|
|
17
|
+
pidFileDir: string;
|
|
18
|
+
currentInstancePath: string;
|
|
19
|
+
killProcessTree: ReapDeps['killProcessTree'];
|
|
20
|
+
getPidComm: ReapDeps['getPidComm'];
|
|
21
|
+
getPidStartTime: ReapDeps['getPidStartTime'];
|
|
22
|
+
isPluginAlive?: ReapDeps['isPluginAlive'];
|
|
23
|
+
}): 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