opencode-copilot-delegate 0.7.0 → 0.9.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 +43 -0
- package/dist/index.js +290 -109
- package/dist/runtime/notify.d.ts +8 -1
- package/dist/runtime/orphan-reaper.d.ts +18 -5
- package/dist/runtime/pid-file.d.ts +16 -0
- package/dist/runtime/plugin-singleton.d.ts +58 -0
- package/dist/runtime/task-status.d.ts +9 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,48 @@
|
|
|
1
1
|
# opencode-copilot-delegate
|
|
2
2
|
|
|
3
|
+
## 0.9.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 80b549e: Improve runtime observability and fix a silent failure in completion notifications.
|
|
8
|
+
|
|
9
|
+
- `killProcessTree` now classifies fkill failures by probing the process group with `process.kill(-pid, 0)`. ESRCH is reported as an already-gone group and the failure is suppressed; alive or unknown states preserve the original throw with a more accurate warning. The probe targets `-pid` (the process group) rather than the leader so children leaking after a leader exit are no longer misclassified as benign.
|
|
10
|
+
- `notifyCompletion`'s fallback `client.app.log` call now uses the structured SDK shape (`{ body: { service, level, message } }`) and is wrapped in `try/catch` so synchronous SDK throws can no longer escape the documented "never throws" contract.
|
|
11
|
+
- All runtime warnings now share the `[copilot-delegate]` prefix across `kill-tree`, `orphan-reaper`, `pid-file`, `task-registry`, and `task-status`, making operator log filtering predictable.
|
|
12
|
+
- Internal contract documentation: `setStatus` and `writeChains` carry JSDoc covering terminal-state transitions and the per-file serialize chain.
|
|
13
|
+
|
|
14
|
+
- 4f2e8b5: Harden PID file and orphan-reaper state path handling against same-user symlink attacks.
|
|
15
|
+
|
|
16
|
+
- Use no-follow PID file opens for read and truncate paths so symlinked `.pids` files are rejected instead of read or truncated.
|
|
17
|
+
- Reject symlinked PID file parent directories before orphan reaping, cleanup, and plugin init state-directory creation so `orphans/` scans and cleanup do not follow attacker-controlled links.
|
|
18
|
+
|
|
19
|
+
## 0.8.0
|
|
20
|
+
|
|
21
|
+
### Minor Changes
|
|
22
|
+
|
|
23
|
+
- 0c21f43: Make the plugin factory idempotent across multiple OpenCode config sources within the same process. When `~/.config/opencode/opencode.json` AND a project-level `opencode.json` (or any other combination of config sources) both list `opencode-copilot-delegate`, OpenCode previously invoked the factory once per source — each invocation evaluating the plugin module fresh, running orphan reaping, and registering its own copy of the three tools. The result was duplicated tools in the catalog, duplicated init side effects (PID-file `mkdir`, `reapOrphans`), and per-invocation closure state that could diverge across registrations.
|
|
24
|
+
|
|
25
|
+
The factory now resolves at most once per process via a `globalThis` symbol singleton (`Symbol.for('opencode-copilot-delegate.singleton.v1')`). Subsequent invocations within the same PID return the cached hooks promise, skip the heavy init, and emit a single one-shot warning (via `console.warn` AND `client.app.log` under `service=copilot-delegate`) so duplicate-config situations remain observable in logs. Across distinct OpenCode processes the singleton is fresh — each process initializes normally.
|
|
26
|
+
|
|
27
|
+
No configuration change is required for users with a single config source. Users with duplicate registrations will see one warning per process and a single set of tools in the catalog.
|
|
28
|
+
|
|
29
|
+
- 1fc343d: Tighten orphan-reaper internals and add two new exported helpers from `src/runtime/pid-file.ts`:
|
|
30
|
+
|
|
31
|
+
- `truncatePidFile(filePath)` — truncate under the per-file `serializeWrite` lock; ENOENT (file or parent missing) silently swallowed.
|
|
32
|
+
- `unlinkPidFile(filePath)` — unlink under the per-file `serializeWrite` lock; ENOENT silently swallowed.
|
|
33
|
+
|
|
34
|
+
Also export `ReapOptions` from `src/runtime/orphan-reaper.ts` (consolidates `ReapDeps` + reap-specific opts via interface extension), and consolidate `reapOneFile` to a single opts-bag parameter. `cleanupAfterReap` now routes its truncate-on-current and unlink-on-foreign paths through the new helpers so any future change that runs reap concurrent with task spawns is automatically race-safe.
|
|
35
|
+
|
|
36
|
+
No user-visible behavior change in default usage; the bump reflects the new exported surface.
|
|
37
|
+
|
|
38
|
+
- 42c5239: Add `timedOut: boolean` to `ReapResult` so consumers can distinguish a successful no-op reap (nothing to do) from a timeout-aborted reap (gave up; orphans may remain). The flag is `false` on every success path and `true` only when the overall `reapOrphans` timeout fires.
|
|
39
|
+
|
|
40
|
+
When `timedOut` is `true`, the count fields are zero placeholders, not partial-progress accounting — in-flight workers may have already invoked `killProcessTree` or scanned files before the abort signal landed, but those side effects are not reflected in the returned counts. Treat a timed-out result as "no reliable count signal" and warn or retry.
|
|
41
|
+
|
|
42
|
+
Note for TypeScript consumers: `ReapResult` is exported from the package's runtime types and gains a required field. Any caller constructing a `ReapResult` literal will need to add `timedOut` explicitly. Internal callers in this repo are already updated.
|
|
43
|
+
|
|
44
|
+
- 3491e63: Tighten the `setStatus` lifecycle helper to forbid terminal → non-terminal transitions. Once a task reaches `complete`, `failed`, or `cancelled`, every subsequent `setStatus` call is a no-op. Previously the helper short-circuited only when both old and new status were terminal, leaving an unintended resurrection path that no caller exercises but the contract permitted. This narrows the public API contract; no caller behavior changes.
|
|
45
|
+
|
|
3
46
|
## 0.7.0
|
|
4
47
|
|
|
5
48
|
### Minor Changes
|
package/dist/index.js
CHANGED
|
@@ -9343,7 +9343,35 @@ async function fkill(inputs, options = {}) {
|
|
|
9343
9343
|
}
|
|
9344
9344
|
}
|
|
9345
9345
|
|
|
9346
|
+
// src/lib/errno.ts
|
|
9347
|
+
function isErrnoException(e) {
|
|
9348
|
+
return e instanceof Error && "code" in e;
|
|
9349
|
+
}
|
|
9350
|
+
|
|
9346
9351
|
// src/lib/kill-tree.ts
|
|
9352
|
+
function formatError(error) {
|
|
9353
|
+
if (error instanceof AggregateError && error.errors.length > 0) {
|
|
9354
|
+
return error.errors.map((entry) => String(entry)).join("; ");
|
|
9355
|
+
}
|
|
9356
|
+
if (error instanceof Error) {
|
|
9357
|
+
return error.message;
|
|
9358
|
+
}
|
|
9359
|
+
return String(error);
|
|
9360
|
+
}
|
|
9361
|
+
function probeRootPid(pid) {
|
|
9362
|
+
try {
|
|
9363
|
+
process.kill(-pid, 0);
|
|
9364
|
+
return { state: "alive" };
|
|
9365
|
+
} catch (error) {
|
|
9366
|
+
if (isErrnoException(error) && error.code === "ESRCH") {
|
|
9367
|
+
return { state: "gone" };
|
|
9368
|
+
}
|
|
9369
|
+
return {
|
|
9370
|
+
state: "unknown",
|
|
9371
|
+
code: isErrnoException(error) ? error.code : undefined
|
|
9372
|
+
};
|
|
9373
|
+
}
|
|
9374
|
+
}
|
|
9347
9375
|
async function killProcessTree(pid) {
|
|
9348
9376
|
if (!Number.isFinite(pid) || pid <= 1) {
|
|
9349
9377
|
return;
|
|
@@ -9353,7 +9381,22 @@ async function killProcessTree(pid) {
|
|
|
9353
9381
|
forceAfterTimeout: 2000,
|
|
9354
9382
|
waitForExit: 5000
|
|
9355
9383
|
};
|
|
9356
|
-
|
|
9384
|
+
try {
|
|
9385
|
+
await fkill(-pid, options);
|
|
9386
|
+
} catch (error) {
|
|
9387
|
+
const probe = probeRootPid(pid);
|
|
9388
|
+
const failure = formatError(error);
|
|
9389
|
+
if (probe.state === "gone") {
|
|
9390
|
+
console.warn(`[copilot-delegate] fkill failed for pid ${pid}, but root pid ${pid} is already gone; skipping follow-up kill handling (${failure})`);
|
|
9391
|
+
return;
|
|
9392
|
+
}
|
|
9393
|
+
if (probe.state === "alive") {
|
|
9394
|
+
console.warn(`[copilot-delegate] fkill failed for pid ${pid}, and root pid ${pid} is still alive; processes may remain running (${failure})`);
|
|
9395
|
+
throw error;
|
|
9396
|
+
}
|
|
9397
|
+
console.warn(`[copilot-delegate] fkill failed for pid ${pid}, and root pid probe failed with ${probe.code ?? "unknown error"}; process state is uncertain (${failure})`);
|
|
9398
|
+
throw error;
|
|
9399
|
+
}
|
|
9357
9400
|
}
|
|
9358
9401
|
|
|
9359
9402
|
// src/lib/normalize-tool-arg-schemas.ts
|
|
@@ -9385,12 +9428,154 @@ function normalizeToolArgSchemas(toolDefinition) {
|
|
|
9385
9428
|
|
|
9386
9429
|
// src/runtime/orphan-reaper.ts
|
|
9387
9430
|
import { spawn as spawn2 } from "child_process";
|
|
9388
|
-
import { readdir
|
|
9389
|
-
import { basename as basename2, extname, join } from "path";
|
|
9431
|
+
import { readdir } from "fs/promises";
|
|
9432
|
+
import { basename as basename2, extname, join as join2 } from "path";
|
|
9390
9433
|
|
|
9391
|
-
// src/
|
|
9392
|
-
|
|
9393
|
-
|
|
9434
|
+
// src/runtime/pid-file.ts
|
|
9435
|
+
import { randomBytes } from "crypto";
|
|
9436
|
+
import {
|
|
9437
|
+
chmod,
|
|
9438
|
+
constants as fsConstants,
|
|
9439
|
+
lstat,
|
|
9440
|
+
mkdir,
|
|
9441
|
+
open,
|
|
9442
|
+
rename,
|
|
9443
|
+
unlink
|
|
9444
|
+
} from "fs/promises";
|
|
9445
|
+
import { homedir } from "os";
|
|
9446
|
+
import { dirname, join } from "path";
|
|
9447
|
+
var writeChains = new Map;
|
|
9448
|
+
var oNoFollow = fsConstants.O_NOFOLLOW ?? 0;
|
|
9449
|
+
function symlinkPathError(path11) {
|
|
9450
|
+
return new Error(`[copilot-delegate] refusing symlink path: ${path11}`);
|
|
9451
|
+
}
|
|
9452
|
+
async function assertNotSymlink(path11) {
|
|
9453
|
+
const stats = await lstat(path11);
|
|
9454
|
+
if (stats.isSymbolicLink()) {
|
|
9455
|
+
throw symlinkPathError(path11);
|
|
9456
|
+
}
|
|
9457
|
+
}
|
|
9458
|
+
async function assertPluginStateDirNotSymlink(filePath) {
|
|
9459
|
+
try {
|
|
9460
|
+
await assertNotSymlink(dirname(dirname(filePath)));
|
|
9461
|
+
} catch (e) {
|
|
9462
|
+
if (!isErrnoException(e) || e.code !== "ENOENT")
|
|
9463
|
+
throw e;
|
|
9464
|
+
}
|
|
9465
|
+
}
|
|
9466
|
+
async function assertOrphansDirNotSymlink(filePath) {
|
|
9467
|
+
await assertNotSymlink(dirname(filePath));
|
|
9468
|
+
}
|
|
9469
|
+
async function readPidFileNoFollow(filePath) {
|
|
9470
|
+
const fd = await open(filePath, oNoFollow | fsConstants.O_RDONLY);
|
|
9471
|
+
try {
|
|
9472
|
+
return await fd.readFile({ encoding: "utf-8" });
|
|
9473
|
+
} finally {
|
|
9474
|
+
await fd.close();
|
|
9475
|
+
}
|
|
9476
|
+
}
|
|
9477
|
+
async function serializeWrite(filePath, work) {
|
|
9478
|
+
const prev = writeChains.get(filePath) ?? Promise.resolve();
|
|
9479
|
+
const next = prev.catch(() => {}).then(work);
|
|
9480
|
+
writeChains.set(filePath, next);
|
|
9481
|
+
try {
|
|
9482
|
+
await next;
|
|
9483
|
+
} finally {
|
|
9484
|
+
if (writeChains.get(filePath) === next) {
|
|
9485
|
+
writeChains.delete(filePath);
|
|
9486
|
+
}
|
|
9487
|
+
}
|
|
9488
|
+
}
|
|
9489
|
+
function resolveInstancePidFilePath() {
|
|
9490
|
+
const stateDir = process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state");
|
|
9491
|
+
return join(stateDir, "opencode-copilot-delegate", "orphans", `${process.pid}.pids`);
|
|
9492
|
+
}
|
|
9493
|
+
async function appendPidEntry(filePath, pid, comm, lstart) {
|
|
9494
|
+
await serializeWrite(filePath, async () => {
|
|
9495
|
+
await assertPluginStateDirNotSymlink(filePath);
|
|
9496
|
+
await mkdir(dirname(filePath), { recursive: true, mode: 448 });
|
|
9497
|
+
await assertOrphansDirNotSymlink(filePath);
|
|
9498
|
+
let existing = "";
|
|
9499
|
+
try {
|
|
9500
|
+
existing = await readPidFileNoFollow(filePath);
|
|
9501
|
+
} catch (e) {
|
|
9502
|
+
if (!isErrnoException(e) || e.code !== "ENOENT")
|
|
9503
|
+
throw e;
|
|
9504
|
+
}
|
|
9505
|
+
const line = `${pid} ${comm} ${lstart}
|
|
9506
|
+
`;
|
|
9507
|
+
const content = existing + line;
|
|
9508
|
+
const tempPath = `${filePath}.tmp.${randomBytes(8).toString("hex")}`;
|
|
9509
|
+
const fd = await open(tempPath, fsConstants.O_EXCL | fsConstants.O_CREAT | oNoFollow | fsConstants.O_WRONLY, 384);
|
|
9510
|
+
try {
|
|
9511
|
+
await fd.writeFile(content, { encoding: "utf-8" });
|
|
9512
|
+
} finally {
|
|
9513
|
+
await fd.close();
|
|
9514
|
+
}
|
|
9515
|
+
await rename(tempPath, filePath);
|
|
9516
|
+
await chmod(filePath, 384);
|
|
9517
|
+
});
|
|
9518
|
+
}
|
|
9519
|
+
async function removePidEntry(filePath, pid) {
|
|
9520
|
+
await serializeWrite(filePath, async () => {
|
|
9521
|
+
let existing = "";
|
|
9522
|
+
try {
|
|
9523
|
+
await assertOrphansDirNotSymlink(filePath);
|
|
9524
|
+
existing = await readPidFileNoFollow(filePath);
|
|
9525
|
+
} catch (e) {
|
|
9526
|
+
if (!isErrnoException(e) || e.code !== "ENOENT")
|
|
9527
|
+
throw e;
|
|
9528
|
+
return;
|
|
9529
|
+
}
|
|
9530
|
+
const prefix = `${pid} `;
|
|
9531
|
+
const lines = existing.split(`
|
|
9532
|
+
`);
|
|
9533
|
+
const filtered = lines.filter((line) => !line.startsWith(prefix));
|
|
9534
|
+
if (filtered.length === lines.length) {
|
|
9535
|
+
return;
|
|
9536
|
+
}
|
|
9537
|
+
const content = filtered.join(`
|
|
9538
|
+
`);
|
|
9539
|
+
const tempPath = `${filePath}.tmp.${randomBytes(8).toString("hex")}`;
|
|
9540
|
+
const fd = await open(tempPath, fsConstants.O_EXCL | fsConstants.O_CREAT | oNoFollow | fsConstants.O_WRONLY, 384);
|
|
9541
|
+
try {
|
|
9542
|
+
await fd.writeFile(content, { encoding: "utf-8" });
|
|
9543
|
+
} finally {
|
|
9544
|
+
await fd.close();
|
|
9545
|
+
}
|
|
9546
|
+
await rename(tempPath, filePath);
|
|
9547
|
+
await chmod(filePath, 384);
|
|
9548
|
+
if (content.trim().length === 0) {
|
|
9549
|
+
await unlink(filePath);
|
|
9550
|
+
}
|
|
9551
|
+
});
|
|
9552
|
+
}
|
|
9553
|
+
async function truncatePidFile(filePath) {
|
|
9554
|
+
await serializeWrite(filePath, async () => {
|
|
9555
|
+
try {
|
|
9556
|
+
await assertOrphansDirNotSymlink(filePath);
|
|
9557
|
+
const fd = await open(filePath, oNoFollow | fsConstants.O_WRONLY);
|
|
9558
|
+
try {
|
|
9559
|
+
await fd.truncate(0);
|
|
9560
|
+
} finally {
|
|
9561
|
+
await fd.close();
|
|
9562
|
+
}
|
|
9563
|
+
} catch (e) {
|
|
9564
|
+
if (!isErrnoException(e) || e.code !== "ENOENT")
|
|
9565
|
+
throw e;
|
|
9566
|
+
}
|
|
9567
|
+
});
|
|
9568
|
+
}
|
|
9569
|
+
async function unlinkPidFile(filePath) {
|
|
9570
|
+
await serializeWrite(filePath, async () => {
|
|
9571
|
+
try {
|
|
9572
|
+
await assertOrphansDirNotSymlink(filePath);
|
|
9573
|
+
await unlink(filePath);
|
|
9574
|
+
} catch (e) {
|
|
9575
|
+
if (!isErrnoException(e) || e.code !== "ENOENT")
|
|
9576
|
+
throw e;
|
|
9577
|
+
}
|
|
9578
|
+
});
|
|
9394
9579
|
}
|
|
9395
9580
|
|
|
9396
9581
|
// src/runtime/orphan-reaper.ts
|
|
@@ -9410,7 +9595,7 @@ function runPs(args, timeoutMs = DEFAULT_PS_TIMEOUT_MS) {
|
|
|
9410
9595
|
let timedOut = false;
|
|
9411
9596
|
const timeout = setTimeout(() => {
|
|
9412
9597
|
timedOut = true;
|
|
9413
|
-
console.warn(`[
|
|
9598
|
+
console.warn(`[copilot-delegate] ps invocation exceeded ${timeoutMs}ms timeout: ps ${args.join(" ")}`);
|
|
9414
9599
|
child.kill("SIGTERM");
|
|
9415
9600
|
}, timeoutMs);
|
|
9416
9601
|
child.stdout?.on("data", (chunk) => {
|
|
@@ -9507,7 +9692,8 @@ async function processEntries(entries, killProcessTree2, getPidIdentity2, signal
|
|
|
9507
9692
|
async function readPidFileEntries(filePath) {
|
|
9508
9693
|
let content;
|
|
9509
9694
|
try {
|
|
9510
|
-
|
|
9695
|
+
await assertOrphansDirNotSymlink(filePath);
|
|
9696
|
+
content = await readPidFileNoFollow(filePath);
|
|
9511
9697
|
} catch {
|
|
9512
9698
|
return null;
|
|
9513
9699
|
}
|
|
@@ -9524,17 +9710,29 @@ async function readPidFileEntries(filePath) {
|
|
|
9524
9710
|
}
|
|
9525
9711
|
async function cleanupAfterReap(filePath, isCurrent, currentInstancePath) {
|
|
9526
9712
|
try {
|
|
9713
|
+
await assertOrphansDirNotSymlink(isCurrent ? currentInstancePath : filePath);
|
|
9527
9714
|
if (isCurrent) {
|
|
9528
|
-
await
|
|
9715
|
+
await truncatePidFile(currentInstancePath);
|
|
9529
9716
|
return false;
|
|
9530
9717
|
}
|
|
9531
|
-
await
|
|
9718
|
+
await unlinkPidFile(filePath);
|
|
9532
9719
|
return true;
|
|
9533
9720
|
} catch {
|
|
9534
9721
|
return false;
|
|
9535
9722
|
}
|
|
9536
9723
|
}
|
|
9537
|
-
async function reapOneFile(
|
|
9724
|
+
async function reapOneFile(args) {
|
|
9725
|
+
const {
|
|
9726
|
+
filePath,
|
|
9727
|
+
filePid,
|
|
9728
|
+
isCurrent,
|
|
9729
|
+
currentInstancePath,
|
|
9730
|
+
isPluginAlive,
|
|
9731
|
+
killProcessTree: killProcessTree2,
|
|
9732
|
+
getPidIdentity: getPidIdentity2,
|
|
9733
|
+
signal,
|
|
9734
|
+
psTimeoutMs
|
|
9735
|
+
} = args;
|
|
9538
9736
|
const empty = {
|
|
9539
9737
|
reaped: 0,
|
|
9540
9738
|
skipped: 0,
|
|
@@ -9567,9 +9765,16 @@ async function doReap(opts) {
|
|
|
9567
9765
|
} = opts;
|
|
9568
9766
|
let files;
|
|
9569
9767
|
try {
|
|
9768
|
+
await assertOrphansDirNotSymlink(currentInstancePath);
|
|
9570
9769
|
files = await readdir(pidFileDir);
|
|
9571
9770
|
} catch {
|
|
9572
|
-
return {
|
|
9771
|
+
return {
|
|
9772
|
+
reaped: 0,
|
|
9773
|
+
skipped: 0,
|
|
9774
|
+
scannedFiles: 0,
|
|
9775
|
+
deletedFiles: 0,
|
|
9776
|
+
timedOut: false
|
|
9777
|
+
};
|
|
9573
9778
|
}
|
|
9574
9779
|
let reaped = 0;
|
|
9575
9780
|
let skipped = 0;
|
|
@@ -9580,14 +9785,24 @@ async function doReap(opts) {
|
|
|
9580
9785
|
break;
|
|
9581
9786
|
if (!file.endsWith(".pids"))
|
|
9582
9787
|
continue;
|
|
9583
|
-
const filePath =
|
|
9788
|
+
const filePath = join2(pidFileDir, file);
|
|
9584
9789
|
const stem = basename2(file, extname(file));
|
|
9585
9790
|
if (!/^[1-9]\d*$/.test(stem)) {
|
|
9586
|
-
console.warn(`[
|
|
9791
|
+
console.warn(`[copilot-delegate] Skipping non-numeric PID file: ${file}`);
|
|
9587
9792
|
continue;
|
|
9588
9793
|
}
|
|
9589
9794
|
const filePid = Number(stem);
|
|
9590
|
-
const outcome = await reapOneFile(
|
|
9795
|
+
const outcome = await reapOneFile({
|
|
9796
|
+
filePath,
|
|
9797
|
+
filePid,
|
|
9798
|
+
isCurrent: filePid === process.pid,
|
|
9799
|
+
currentInstancePath,
|
|
9800
|
+
isPluginAlive,
|
|
9801
|
+
killProcessTree: killProcessTree2,
|
|
9802
|
+
getPidIdentity: getPidIdentity2,
|
|
9803
|
+
signal,
|
|
9804
|
+
psTimeoutMs
|
|
9805
|
+
});
|
|
9591
9806
|
reaped += outcome.reaped;
|
|
9592
9807
|
skipped += outcome.skipped;
|
|
9593
9808
|
if (outcome.scanned)
|
|
@@ -9595,24 +9810,25 @@ async function doReap(opts) {
|
|
|
9595
9810
|
if (outcome.deleted)
|
|
9596
9811
|
deletedFiles++;
|
|
9597
9812
|
}
|
|
9598
|
-
return { reaped, skipped, scannedFiles, deletedFiles };
|
|
9813
|
+
return { reaped, skipped, scannedFiles, deletedFiles, timedOut: false };
|
|
9599
9814
|
}
|
|
9600
9815
|
var DEFAULT_REAP_TIMEOUT_MS = 15000;
|
|
9601
9816
|
async function reapOrphans(opts) {
|
|
9602
9817
|
const reapTimeoutMs = opts.reapTimeoutMs ?? DEFAULT_REAP_TIMEOUT_MS;
|
|
9603
|
-
const
|
|
9818
|
+
const zeros = {
|
|
9604
9819
|
reaped: 0,
|
|
9605
9820
|
skipped: 0,
|
|
9606
9821
|
scannedFiles: 0,
|
|
9607
|
-
deletedFiles: 0
|
|
9822
|
+
deletedFiles: 0,
|
|
9823
|
+
timedOut: false
|
|
9608
9824
|
};
|
|
9609
9825
|
const controller = new AbortController;
|
|
9610
9826
|
let timeoutId;
|
|
9611
9827
|
const timeoutPromise = new Promise((resolve) => {
|
|
9612
9828
|
timeoutId = setTimeout(() => {
|
|
9613
|
-
console.warn(`[
|
|
9829
|
+
console.warn(`[copilot-delegate] reapOrphans exceeded ${reapTimeoutMs}ms budget; returning empty result`);
|
|
9614
9830
|
controller.abort();
|
|
9615
|
-
resolve(
|
|
9831
|
+
resolve({ ...zeros, timedOut: true });
|
|
9616
9832
|
}, reapTimeoutMs);
|
|
9617
9833
|
});
|
|
9618
9834
|
const reapPromise = doReap({ ...opts, signal: controller.signal });
|
|
@@ -9625,92 +9841,33 @@ async function reapOrphans(opts) {
|
|
|
9625
9841
|
}
|
|
9626
9842
|
}
|
|
9627
9843
|
|
|
9628
|
-
// src/runtime/
|
|
9629
|
-
|
|
9630
|
-
|
|
9631
|
-
|
|
9632
|
-
|
|
9633
|
-
|
|
9634
|
-
|
|
9635
|
-
|
|
9636
|
-
|
|
9637
|
-
|
|
9638
|
-
|
|
9639
|
-
|
|
9640
|
-
|
|
9641
|
-
|
|
9642
|
-
|
|
9643
|
-
|
|
9644
|
-
const next = prev.catch(() => {}).then(work);
|
|
9645
|
-
writeChains.set(filePath, next);
|
|
9646
|
-
try {
|
|
9647
|
-
await next;
|
|
9648
|
-
} finally {
|
|
9649
|
-
if (writeChains.get(filePath) === next) {
|
|
9650
|
-
writeChains.delete(filePath);
|
|
9844
|
+
// src/runtime/plugin-singleton.ts
|
|
9845
|
+
var SINGLETON_KEY = Symbol.for("opencode-copilot-delegate.singleton.v1");
|
|
9846
|
+
async function plugInOnce({
|
|
9847
|
+
doInit,
|
|
9848
|
+
onDuplicate,
|
|
9849
|
+
pid
|
|
9850
|
+
}) {
|
|
9851
|
+
const currentPid = pid ?? process.pid;
|
|
9852
|
+
const g = globalThis;
|
|
9853
|
+
const existing = g[SINGLETON_KEY];
|
|
9854
|
+
if (existing && existing.pid === currentPid) {
|
|
9855
|
+
if (!existing.warned) {
|
|
9856
|
+
existing.warned = true;
|
|
9857
|
+
try {
|
|
9858
|
+
onDuplicate?.(currentPid);
|
|
9859
|
+
} catch {}
|
|
9651
9860
|
}
|
|
9861
|
+
return existing.hooksPromise;
|
|
9652
9862
|
}
|
|
9653
|
-
|
|
9654
|
-
|
|
9655
|
-
|
|
9656
|
-
|
|
9657
|
-
|
|
9658
|
-
|
|
9659
|
-
|
|
9660
|
-
|
|
9661
|
-
let existing = "";
|
|
9662
|
-
try {
|
|
9663
|
-
existing = await readFile2(filePath, "utf-8");
|
|
9664
|
-
} catch (e) {
|
|
9665
|
-
if (!isErrnoException(e) || e.code !== "ENOENT")
|
|
9666
|
-
throw e;
|
|
9667
|
-
}
|
|
9668
|
-
const line = `${pid} ${comm} ${lstart}
|
|
9669
|
-
`;
|
|
9670
|
-
const content = existing + line;
|
|
9671
|
-
const tempPath = `${filePath}.tmp.${randomBytes(8).toString("hex")}`;
|
|
9672
|
-
const fd = await open(tempPath, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
|
|
9673
|
-
try {
|
|
9674
|
-
await fd.writeFile(content, { encoding: "utf-8" });
|
|
9675
|
-
} finally {
|
|
9676
|
-
await fd.close();
|
|
9677
|
-
}
|
|
9678
|
-
await rename(tempPath, filePath);
|
|
9679
|
-
await chmod(filePath, 384);
|
|
9680
|
-
});
|
|
9681
|
-
}
|
|
9682
|
-
async function removePidEntry(filePath, pid) {
|
|
9683
|
-
await serializeWrite(filePath, async () => {
|
|
9684
|
-
let existing = "";
|
|
9685
|
-
try {
|
|
9686
|
-
existing = await readFile2(filePath, "utf-8");
|
|
9687
|
-
} catch (e) {
|
|
9688
|
-
if (!isErrnoException(e) || e.code !== "ENOENT")
|
|
9689
|
-
throw e;
|
|
9690
|
-
return;
|
|
9691
|
-
}
|
|
9692
|
-
const prefix = `${pid} `;
|
|
9693
|
-
const lines = existing.split(`
|
|
9694
|
-
`);
|
|
9695
|
-
const filtered = lines.filter((line) => !line.startsWith(prefix));
|
|
9696
|
-
if (filtered.length === lines.length) {
|
|
9697
|
-
return;
|
|
9698
|
-
}
|
|
9699
|
-
const content = filtered.join(`
|
|
9700
|
-
`);
|
|
9701
|
-
const tempPath = `${filePath}.tmp.${randomBytes(8).toString("hex")}`;
|
|
9702
|
-
const fd = await open(tempPath, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
|
|
9703
|
-
try {
|
|
9704
|
-
await fd.writeFile(content, { encoding: "utf-8" });
|
|
9705
|
-
} finally {
|
|
9706
|
-
await fd.close();
|
|
9707
|
-
}
|
|
9708
|
-
await rename(tempPath, filePath);
|
|
9709
|
-
await chmod(filePath, 384);
|
|
9710
|
-
if (content.trim().length === 0) {
|
|
9711
|
-
await unlink2(filePath);
|
|
9712
|
-
}
|
|
9713
|
-
});
|
|
9863
|
+
const hooksPromise = doInit();
|
|
9864
|
+
g[SINGLETON_KEY] = {
|
|
9865
|
+
pid: currentPid,
|
|
9866
|
+
loadedAt: Date.now(),
|
|
9867
|
+
hooksPromise,
|
|
9868
|
+
warned: false
|
|
9869
|
+
};
|
|
9870
|
+
return hooksPromise;
|
|
9714
9871
|
}
|
|
9715
9872
|
|
|
9716
9873
|
// src/tools/cancel.ts
|
|
@@ -9730,7 +9887,7 @@ function createTask(input, taskId = `cpl_${randomUUID()}`) {
|
|
|
9730
9887
|
if (identity3) {
|
|
9731
9888
|
appendPidEntry(pidFilePath, task.pid, identity3.comm, identity3.lstart).catch(() => {});
|
|
9732
9889
|
} else {
|
|
9733
|
-
console.warn(`[
|
|
9890
|
+
console.warn(`[copilot-delegate] ps lookup returned null for pid ${task.pid}; subprocess will not be tracked for orphan reaping`);
|
|
9734
9891
|
}
|
|
9735
9892
|
}).catch(() => {});
|
|
9736
9893
|
}
|
|
@@ -9844,7 +10001,15 @@ async function notifyCompletion(client, task) {
|
|
|
9844
10001
|
}
|
|
9845
10002
|
});
|
|
9846
10003
|
} catch (error) {
|
|
9847
|
-
|
|
10004
|
+
try {
|
|
10005
|
+
client.app.log({
|
|
10006
|
+
body: {
|
|
10007
|
+
service: "copilot-delegate",
|
|
10008
|
+
level: "warn",
|
|
10009
|
+
message: `Failed to inject notification for ${task.taskId}: ${error}`
|
|
10010
|
+
}
|
|
10011
|
+
}).catch(() => {});
|
|
10012
|
+
} catch {}
|
|
9848
10013
|
}
|
|
9849
10014
|
try {
|
|
9850
10015
|
const variant = task.status === "complete" ? "success" : "error";
|
|
@@ -9949,7 +10114,7 @@ function isTerminal(s) {
|
|
|
9949
10114
|
return TERMINAL_STATUSES.has(s);
|
|
9950
10115
|
}
|
|
9951
10116
|
function setStatus(task, newStatus, options) {
|
|
9952
|
-
if (isTerminal(task.status)
|
|
10117
|
+
if (isTerminal(task.status)) {
|
|
9953
10118
|
return;
|
|
9954
10119
|
}
|
|
9955
10120
|
task.status = newStatus;
|
|
@@ -10359,13 +10524,15 @@ function getAgentsDirectories(directory) {
|
|
|
10359
10524
|
repoAgentsDir: `${directory}/.github/agents`
|
|
10360
10525
|
};
|
|
10361
10526
|
}
|
|
10362
|
-
|
|
10527
|
+
async function initializePlugin({ client, directory }) {
|
|
10363
10528
|
const agents = discoverAgents(getAgentsDirectories(directory));
|
|
10364
10529
|
const delegateDescription = buildDescription(agents);
|
|
10365
10530
|
const currentInstancePath = resolveInstancePidFilePath();
|
|
10366
10531
|
const pidFileDir = dirname2(currentInstancePath);
|
|
10367
10532
|
try {
|
|
10533
|
+
await assertPluginStateDirNotSymlink(currentInstancePath);
|
|
10368
10534
|
await mkdir2(pidFileDir, { recursive: true, mode: 448 });
|
|
10535
|
+
await assertOrphansDirNotSymlink(currentInstancePath);
|
|
10369
10536
|
await reapOrphans({
|
|
10370
10537
|
pidFileDir,
|
|
10371
10538
|
currentInstancePath,
|
|
@@ -10385,7 +10552,21 @@ var CopilotDelegate = async ({ client, directory }) => {
|
|
|
10385
10552
|
copilot_cancel: normalizeToolArgSchemas(createCancelTool())
|
|
10386
10553
|
}
|
|
10387
10554
|
};
|
|
10388
|
-
}
|
|
10555
|
+
}
|
|
10556
|
+
var CopilotDelegate = async (input) => plugInOnce({
|
|
10557
|
+
doInit: () => initializePlugin(input),
|
|
10558
|
+
onDuplicate: (pid) => {
|
|
10559
|
+
const message = `[copilot-delegate] duplicate factory invocation in same process (pid=${pid}); reusing existing hooks. Multiple opencode.json sources may list this plugin.`;
|
|
10560
|
+
console.warn(message);
|
|
10561
|
+
input.client.app.log({
|
|
10562
|
+
body: {
|
|
10563
|
+
service: "copilot-delegate",
|
|
10564
|
+
level: "warn",
|
|
10565
|
+
message
|
|
10566
|
+
}
|
|
10567
|
+
}).catch(() => {});
|
|
10568
|
+
}
|
|
10569
|
+
});
|
|
10389
10570
|
var src_default = CopilotDelegate;
|
|
10390
10571
|
export {
|
|
10391
10572
|
src_default as default
|
package/dist/runtime/notify.d.ts
CHANGED
|
@@ -36,7 +36,14 @@ export type NotifyClient = {
|
|
|
36
36
|
}) => unknown;
|
|
37
37
|
};
|
|
38
38
|
app: {
|
|
39
|
-
log: (
|
|
39
|
+
log: (opts: {
|
|
40
|
+
body: {
|
|
41
|
+
service: string;
|
|
42
|
+
level: string;
|
|
43
|
+
message: string;
|
|
44
|
+
extra?: unknown;
|
|
45
|
+
};
|
|
46
|
+
}) => Promise<unknown>;
|
|
40
47
|
};
|
|
41
48
|
};
|
|
42
49
|
/** Task information needed for building the notification. */
|
|
@@ -6,11 +6,27 @@ export interface ReapDeps {
|
|
|
6
6
|
} | null>;
|
|
7
7
|
isPluginAlive: (pid: number) => boolean;
|
|
8
8
|
}
|
|
9
|
+
/**
|
|
10
|
+
* Aggregated outcome of a single `reapOrphans` invocation.
|
|
11
|
+
*
|
|
12
|
+
* `timedOut` is `true` when `reapOrphans` aborted due to its overall
|
|
13
|
+
* timeout budget. The flag distinguishes a successful no-op (no `.pids`
|
|
14
|
+
* files to scan, all counts naturally zero) from a timeout-aborted reap
|
|
15
|
+
* that stopped mid-flight (orphans may remain).
|
|
16
|
+
*
|
|
17
|
+
* IMPORTANT: when `timedOut` is `true`, the count fields are zero
|
|
18
|
+
* placeholders, NOT partial-progress accounting. In-flight workers may
|
|
19
|
+
* have already incremented internal counters or even invoked
|
|
20
|
+
* `killProcessTree` before the timeout fired, but those side effects are
|
|
21
|
+
* not reflected in the returned counts. Treat a timed-out result as "no
|
|
22
|
+
* reliable count signal" and consider warning or retrying.
|
|
23
|
+
*/
|
|
9
24
|
export interface ReapResult {
|
|
10
25
|
reaped: number;
|
|
11
26
|
skipped: number;
|
|
12
27
|
scannedFiles: number;
|
|
13
28
|
deletedFiles: number;
|
|
29
|
+
timedOut: boolean;
|
|
14
30
|
}
|
|
15
31
|
export declare function defaultIsPluginAlive(pid: number): boolean;
|
|
16
32
|
/**
|
|
@@ -58,16 +74,13 @@ export declare function getPidIdentity(pid: number, timeoutMs?: number): Promise
|
|
|
58
74
|
comm: string;
|
|
59
75
|
lstart: string;
|
|
60
76
|
} | null>;
|
|
61
|
-
interface
|
|
77
|
+
export interface ReapOptions extends Omit<ReapDeps, 'isPluginAlive'> {
|
|
62
78
|
pidFileDir: string;
|
|
63
79
|
currentInstancePath: string;
|
|
64
|
-
killProcessTree: ReapDeps['killProcessTree'];
|
|
65
|
-
getPidIdentity: ReapDeps['getPidIdentity'];
|
|
66
80
|
isPluginAlive?: ReapDeps['isPluginAlive'];
|
|
67
81
|
signal?: AbortSignal;
|
|
68
82
|
psTimeoutMs?: number;
|
|
69
83
|
}
|
|
70
|
-
export declare function reapOrphans(opts: Omit<
|
|
84
|
+
export declare function reapOrphans(opts: Omit<ReapOptions, 'signal'> & {
|
|
71
85
|
reapTimeoutMs?: number;
|
|
72
86
|
}): Promise<ReapResult>;
|
|
73
|
-
export {};
|
|
@@ -1,3 +1,19 @@
|
|
|
1
|
+
export declare function assertPluginStateDirNotSymlink(filePath: string): Promise<void>;
|
|
2
|
+
export declare function assertOrphansDirNotSymlink(filePath: string): Promise<void>;
|
|
3
|
+
export declare function readPidFileNoFollow(filePath: string): Promise<string>;
|
|
1
4
|
export declare function resolveInstancePidFilePath(): string;
|
|
2
5
|
export declare function appendPidEntry(filePath: string, pid: number, comm: string, lstart: string): Promise<void>;
|
|
3
6
|
export declare function removePidEntry(filePath: string, pid: number): Promise<void>;
|
|
7
|
+
/**
|
|
8
|
+
* Truncate a PID file under the same per-file serialize lock used by
|
|
9
|
+
* appendPidEntry/removePidEntry, so a concurrent writer cannot interleave
|
|
10
|
+
* with the truncation. ENOENT is silently swallowed in both forms:
|
|
11
|
+
* file-already-gone AND parent-directory-missing. Other errno values
|
|
12
|
+
* propagate.
|
|
13
|
+
*/
|
|
14
|
+
export declare function truncatePidFile(filePath: string): Promise<void>;
|
|
15
|
+
/**
|
|
16
|
+
* Remove a PID file under the same per-file serialize lock. ENOENT is
|
|
17
|
+
* silently swallowed (file already gone). Other errno values propagate.
|
|
18
|
+
*/
|
|
19
|
+
export declare function unlinkPidFile(filePath: string): Promise<void>;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-process singleton guard for the plugin factory.
|
|
3
|
+
*
|
|
4
|
+
* OpenCode invokes the plugin factory more than once per process when the
|
|
5
|
+
* same plugin is referenced by multiple config sources (for example a
|
|
6
|
+
* user-level `~/.config/opencode/opencode.json` AND a project-level
|
|
7
|
+
* `opencode.json`). Each invocation evaluates the plugin module fresh —
|
|
8
|
+
* module-local variables reset between calls — so the singleton state
|
|
9
|
+
* must live on `globalThis` to persist across module instances within
|
|
10
|
+
* the same process.
|
|
11
|
+
*
|
|
12
|
+
* On the first invocation the init runs normally and the resulting hooks
|
|
13
|
+
* promise is cached on `globalThis`. On subsequent invocations within
|
|
14
|
+
* the same PID the cached promise is returned and `onDuplicate` is
|
|
15
|
+
* invoked exactly once (subsequent duplicates are silent so logs do not
|
|
16
|
+
* spam). Across PIDs the singleton is treated as absent and init runs
|
|
17
|
+
* fresh — `globalThis` is per-process, but the explicit PID guard adds
|
|
18
|
+
* defensive belt-and-suspenders against any state-leakage edge case.
|
|
19
|
+
*
|
|
20
|
+
* The cached value is the init Promise rather than the resolved value so
|
|
21
|
+
* a second invocation that arrives while the first is still awaiting
|
|
22
|
+
* `mkdir` / `reapOrphans` converges on the same init result instead of
|
|
23
|
+
* starting a parallel init.
|
|
24
|
+
*
|
|
25
|
+
* **Known limitation — rejected init is cached.** If `doInit()` rejects,
|
|
26
|
+
* the rejected promise is stored on `globalThis` and every subsequent
|
|
27
|
+
* invocation in the same PID returns the same rejection without
|
|
28
|
+
* retrying init. This is intentional: re-running heavy init on every
|
|
29
|
+
* call would defeat the singleton's purpose. Recovery requires a
|
|
30
|
+
* process restart. OpenCode currently surfaces a failed plugin factory
|
|
31
|
+
* as a startup error rather than retrying within the process, so this
|
|
32
|
+
* matches the upstream contract.
|
|
33
|
+
*/
|
|
34
|
+
export interface PlugInOnceOptions<T> {
|
|
35
|
+
/** Heavy init work that should run at most once per process. */
|
|
36
|
+
doInit: () => Promise<T>;
|
|
37
|
+
/**
|
|
38
|
+
* Called exactly once on the first duplicate invocation in the same
|
|
39
|
+
* process. Subsequent duplicates are silent. Receives the same `pid`
|
|
40
|
+
* value the guard used for its identity check (so test overrides flow
|
|
41
|
+
* through faithfully). Implementations must not throw; fire-and-forget
|
|
42
|
+
* side effects (logging, metrics) are expected. Synchronous exceptions
|
|
43
|
+
* are swallowed defensively.
|
|
44
|
+
*/
|
|
45
|
+
onDuplicate?: (pid: number) => void;
|
|
46
|
+
/** Test override; defaults to `process.pid`. */
|
|
47
|
+
pid?: number;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Run `doInit` at most once per process, returning the cached hooks
|
|
51
|
+
* promise on subsequent invocations within the same PID.
|
|
52
|
+
*/
|
|
53
|
+
export declare function plugInOnce<T>({ doInit, onDuplicate, pid, }: PlugInOnceOptions<T>): Promise<T>;
|
|
54
|
+
/**
|
|
55
|
+
* Test-only: clear the singleton state so the next invocation re-runs
|
|
56
|
+
* init. Must not be called in production code paths.
|
|
57
|
+
*/
|
|
58
|
+
export declare function _resetPluginSingleton(): void;
|
|
@@ -2,6 +2,15 @@ import type { TaskStatus } from './envelope';
|
|
|
2
2
|
export interface SetStatusOptions {
|
|
3
3
|
pidFilePath?: string;
|
|
4
4
|
}
|
|
5
|
+
/**
|
|
6
|
+
* Transition `task` to `newStatus`, enforcing the forward-only lifecycle.
|
|
7
|
+
*
|
|
8
|
+
* Idempotent on any terminal state (complete, failed, cancelled): once a task
|
|
9
|
+
* reaches a terminal status every subsequent call is a no-op. This prevents
|
|
10
|
+
* both terminal→terminal re-classification and terminal→non-terminal
|
|
11
|
+
* resurrection. When transitioning to a terminal state and `pidFilePath` is
|
|
12
|
+
* provided, the task's PID entry is removed from the orphan-reaper file.
|
|
13
|
+
*/
|
|
5
14
|
export declare function setStatus(task: {
|
|
6
15
|
status: TaskStatus;
|
|
7
16
|
pid: number;
|