opencode-copilot-delegate 0.6.0 → 0.8.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,42 @@
1
1
  # opencode-copilot-delegate
2
2
 
3
+ ## 0.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 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.
8
+
9
+ 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.
10
+
11
+ 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.
12
+
13
+ - 1fc343d: Tighten orphan-reaper internals and add two new exported helpers from `src/runtime/pid-file.ts`:
14
+
15
+ - `truncatePidFile(filePath)` — truncate under the per-file `serializeWrite` lock; ENOENT (file or parent missing) silently swallowed.
16
+ - `unlinkPidFile(filePath)` — unlink under the per-file `serializeWrite` lock; ENOENT silently swallowed.
17
+
18
+ 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.
19
+
20
+ No user-visible behavior change in default usage; the bump reflects the new exported surface.
21
+
22
+ - 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.
23
+
24
+ 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.
25
+
26
+ 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.
27
+
28
+ - 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.
29
+
30
+ ## 0.7.0
31
+
32
+ ### Minor Changes
33
+
34
+ - 3f8b78e: Surface per-parameter `.describe()` text to the host runtime by patching each tool arg schema with a `_zod.toJSONSchema` override.
35
+
36
+ OpenCode's tool catalog renders plugin schemas via the host's bundled zod, which lives in a different module instance from the plugin's zod and cannot see the plugin-side `.describe()` metadata registry. The override delegates serialization back to the plugin-local zod so descriptions survive intact, mirroring the pattern shipped by `@cortexkit/opencode-magic-context` and `@cortexkit/aft-opencode`.
37
+
38
+ Also pins `zod` as a direct dependency (`^4.3.0`) with a matching `overrides` entry to keep this repo's dependency tree on a single zod version, resolving a TS2883 unportable-inferred-type error from two zod trees coexisting at build time. The `overrides` field is local to this repo's installs only; npm ignores it for downstream consumers, so external plugin authors importing this package may still see a different transitive zod from their OpenCode host. Also reverts the prior schema-chain reorder since the override makes ordering irrelevant.
39
+
3
40
  ## 0.6.0
4
41
 
5
42
  ### Minor Changes
package/dist/index.js CHANGED
@@ -9356,16 +9356,152 @@ async function killProcessTree(pid) {
9356
9356
  await fkill(-pid, options);
9357
9357
  }
9358
9358
 
9359
+ // src/lib/normalize-tool-arg-schemas.ts
9360
+ import { tool } from "@opencode-ai/plugin/tool";
9361
+ function stripRootJsonSchemaFields(jsonSchema) {
9362
+ const { $schema: _schema, ...rest } = jsonSchema;
9363
+ return rest;
9364
+ }
9365
+ function attachJsonSchemaOverride(schema) {
9366
+ const internals = schema._zod;
9367
+ if (!internals || typeof internals.toJSONSchema === "function")
9368
+ return;
9369
+ internals.toJSONSchema = () => {
9370
+ const original = internals.toJSONSchema;
9371
+ delete internals.toJSONSchema;
9372
+ try {
9373
+ return stripRootJsonSchemaFields(tool.schema.toJSONSchema(schema));
9374
+ } finally {
9375
+ internals.toJSONSchema = original;
9376
+ }
9377
+ };
9378
+ }
9379
+ function normalizeToolArgSchemas(toolDefinition) {
9380
+ for (const schema of Object.values(toolDefinition.args)) {
9381
+ attachJsonSchemaOverride(schema);
9382
+ }
9383
+ return toolDefinition;
9384
+ }
9385
+
9359
9386
  // src/runtime/orphan-reaper.ts
9360
9387
  import { spawn as spawn2 } from "child_process";
9361
- import { readdir, readFile, unlink, writeFile } from "fs/promises";
9362
- import { basename as basename2, extname, join } from "path";
9388
+ import { readdir, readFile as readFile2 } from "fs/promises";
9389
+ import { basename as basename2, extname, join as join2 } from "path";
9363
9390
 
9364
9391
  // src/lib/errno.ts
9365
9392
  function isErrnoException(e) {
9366
9393
  return e instanceof Error && "code" in e;
9367
9394
  }
9368
9395
 
9396
+ // src/runtime/pid-file.ts
9397
+ import { randomBytes } from "crypto";
9398
+ import {
9399
+ chmod,
9400
+ constants as fsConstants,
9401
+ mkdir,
9402
+ open,
9403
+ readFile,
9404
+ rename,
9405
+ unlink,
9406
+ writeFile
9407
+ } from "fs/promises";
9408
+ import { homedir } from "os";
9409
+ import { dirname, join } from "path";
9410
+ var writeChains = new Map;
9411
+ async function serializeWrite(filePath, work) {
9412
+ const prev = writeChains.get(filePath) ?? Promise.resolve();
9413
+ const next = prev.catch(() => {}).then(work);
9414
+ writeChains.set(filePath, next);
9415
+ try {
9416
+ await next;
9417
+ } finally {
9418
+ if (writeChains.get(filePath) === next) {
9419
+ writeChains.delete(filePath);
9420
+ }
9421
+ }
9422
+ }
9423
+ function resolveInstancePidFilePath() {
9424
+ const stateDir = process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state");
9425
+ return join(stateDir, "opencode-copilot-delegate", "orphans", `${process.pid}.pids`);
9426
+ }
9427
+ async function appendPidEntry(filePath, pid, comm, lstart) {
9428
+ await serializeWrite(filePath, async () => {
9429
+ await mkdir(dirname(filePath), { recursive: true, mode: 448 });
9430
+ let existing = "";
9431
+ try {
9432
+ existing = await readFile(filePath, "utf-8");
9433
+ } catch (e) {
9434
+ if (!isErrnoException(e) || e.code !== "ENOENT")
9435
+ throw e;
9436
+ }
9437
+ const line = `${pid} ${comm} ${lstart}
9438
+ `;
9439
+ const content = existing + line;
9440
+ const tempPath = `${filePath}.tmp.${randomBytes(8).toString("hex")}`;
9441
+ const fd = await open(tempPath, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
9442
+ try {
9443
+ await fd.writeFile(content, { encoding: "utf-8" });
9444
+ } finally {
9445
+ await fd.close();
9446
+ }
9447
+ await rename(tempPath, filePath);
9448
+ await chmod(filePath, 384);
9449
+ });
9450
+ }
9451
+ async function removePidEntry(filePath, pid) {
9452
+ await serializeWrite(filePath, async () => {
9453
+ let existing = "";
9454
+ try {
9455
+ existing = await readFile(filePath, "utf-8");
9456
+ } catch (e) {
9457
+ if (!isErrnoException(e) || e.code !== "ENOENT")
9458
+ throw e;
9459
+ return;
9460
+ }
9461
+ const prefix = `${pid} `;
9462
+ const lines = existing.split(`
9463
+ `);
9464
+ const filtered = lines.filter((line) => !line.startsWith(prefix));
9465
+ if (filtered.length === lines.length) {
9466
+ return;
9467
+ }
9468
+ const content = filtered.join(`
9469
+ `);
9470
+ const tempPath = `${filePath}.tmp.${randomBytes(8).toString("hex")}`;
9471
+ const fd = await open(tempPath, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
9472
+ try {
9473
+ await fd.writeFile(content, { encoding: "utf-8" });
9474
+ } finally {
9475
+ await fd.close();
9476
+ }
9477
+ await rename(tempPath, filePath);
9478
+ await chmod(filePath, 384);
9479
+ if (content.trim().length === 0) {
9480
+ await unlink(filePath);
9481
+ }
9482
+ });
9483
+ }
9484
+ async function truncatePidFile(filePath) {
9485
+ await serializeWrite(filePath, async () => {
9486
+ try {
9487
+ await writeFile(filePath, "");
9488
+ } catch (e) {
9489
+ if (!isErrnoException(e) || e.code !== "ENOENT")
9490
+ throw e;
9491
+ }
9492
+ });
9493
+ }
9494
+ async function unlinkPidFile(filePath) {
9495
+ await serializeWrite(filePath, async () => {
9496
+ try {
9497
+ await unlink(filePath);
9498
+ } catch (e) {
9499
+ if (!isErrnoException(e) || e.code !== "ENOENT")
9500
+ throw e;
9501
+ }
9502
+ });
9503
+ }
9504
+
9369
9505
  // src/runtime/orphan-reaper.ts
9370
9506
  function defaultIsPluginAlive(pid) {
9371
9507
  try {
@@ -9480,7 +9616,7 @@ async function processEntries(entries, killProcessTree2, getPidIdentity2, signal
9480
9616
  async function readPidFileEntries(filePath) {
9481
9617
  let content;
9482
9618
  try {
9483
- content = await readFile(filePath, "utf-8");
9619
+ content = await readFile2(filePath, "utf-8");
9484
9620
  } catch {
9485
9621
  return null;
9486
9622
  }
@@ -9498,16 +9634,27 @@ async function readPidFileEntries(filePath) {
9498
9634
  async function cleanupAfterReap(filePath, isCurrent, currentInstancePath) {
9499
9635
  try {
9500
9636
  if (isCurrent) {
9501
- await writeFile(currentInstancePath, "");
9637
+ await truncatePidFile(currentInstancePath);
9502
9638
  return false;
9503
9639
  }
9504
- await unlink(filePath);
9640
+ await unlinkPidFile(filePath);
9505
9641
  return true;
9506
9642
  } catch {
9507
9643
  return false;
9508
9644
  }
9509
9645
  }
9510
- async function reapOneFile(filePath, filePid, isCurrent, currentInstancePath, isPluginAlive, killProcessTree2, getPidIdentity2, signal, psTimeoutMs) {
9646
+ async function reapOneFile(args) {
9647
+ const {
9648
+ filePath,
9649
+ filePid,
9650
+ isCurrent,
9651
+ currentInstancePath,
9652
+ isPluginAlive,
9653
+ killProcessTree: killProcessTree2,
9654
+ getPidIdentity: getPidIdentity2,
9655
+ signal,
9656
+ psTimeoutMs
9657
+ } = args;
9511
9658
  const empty = {
9512
9659
  reaped: 0,
9513
9660
  skipped: 0,
@@ -9542,7 +9689,13 @@ async function doReap(opts) {
9542
9689
  try {
9543
9690
  files = await readdir(pidFileDir);
9544
9691
  } catch {
9545
- return { reaped: 0, skipped: 0, scannedFiles: 0, deletedFiles: 0 };
9692
+ return {
9693
+ reaped: 0,
9694
+ skipped: 0,
9695
+ scannedFiles: 0,
9696
+ deletedFiles: 0,
9697
+ timedOut: false
9698
+ };
9546
9699
  }
9547
9700
  let reaped = 0;
9548
9701
  let skipped = 0;
@@ -9553,14 +9706,24 @@ async function doReap(opts) {
9553
9706
  break;
9554
9707
  if (!file.endsWith(".pids"))
9555
9708
  continue;
9556
- const filePath = join(pidFileDir, file);
9709
+ const filePath = join2(pidFileDir, file);
9557
9710
  const stem = basename2(file, extname(file));
9558
9711
  if (!/^[1-9]\d*$/.test(stem)) {
9559
9712
  console.warn(`[orphan-reaper] Skipping non-numeric PID file: ${file}`);
9560
9713
  continue;
9561
9714
  }
9562
9715
  const filePid = Number(stem);
9563
- const outcome = await reapOneFile(filePath, filePid, filePid === process.pid, currentInstancePath, isPluginAlive, killProcessTree2, getPidIdentity2, signal, psTimeoutMs);
9716
+ const outcome = await reapOneFile({
9717
+ filePath,
9718
+ filePid,
9719
+ isCurrent: filePid === process.pid,
9720
+ currentInstancePath,
9721
+ isPluginAlive,
9722
+ killProcessTree: killProcessTree2,
9723
+ getPidIdentity: getPidIdentity2,
9724
+ signal,
9725
+ psTimeoutMs
9726
+ });
9564
9727
  reaped += outcome.reaped;
9565
9728
  skipped += outcome.skipped;
9566
9729
  if (outcome.scanned)
@@ -9568,16 +9731,17 @@ async function doReap(opts) {
9568
9731
  if (outcome.deleted)
9569
9732
  deletedFiles++;
9570
9733
  }
9571
- return { reaped, skipped, scannedFiles, deletedFiles };
9734
+ return { reaped, skipped, scannedFiles, deletedFiles, timedOut: false };
9572
9735
  }
9573
9736
  var DEFAULT_REAP_TIMEOUT_MS = 15000;
9574
9737
  async function reapOrphans(opts) {
9575
9738
  const reapTimeoutMs = opts.reapTimeoutMs ?? DEFAULT_REAP_TIMEOUT_MS;
9576
- const empty = {
9739
+ const zeros = {
9577
9740
  reaped: 0,
9578
9741
  skipped: 0,
9579
9742
  scannedFiles: 0,
9580
- deletedFiles: 0
9743
+ deletedFiles: 0,
9744
+ timedOut: false
9581
9745
  };
9582
9746
  const controller = new AbortController;
9583
9747
  let timeoutId;
@@ -9585,7 +9749,7 @@ async function reapOrphans(opts) {
9585
9749
  timeoutId = setTimeout(() => {
9586
9750
  console.warn(`[orphan-reaper] reapOrphans exceeded ${reapTimeoutMs}ms budget; returning empty result`);
9587
9751
  controller.abort();
9588
- resolve(empty);
9752
+ resolve({ ...zeros, timedOut: true });
9589
9753
  }, reapTimeoutMs);
9590
9754
  });
9591
9755
  const reapPromise = doReap({ ...opts, signal: controller.signal });
@@ -9598,96 +9762,37 @@ async function reapOrphans(opts) {
9598
9762
  }
9599
9763
  }
9600
9764
 
9601
- // src/runtime/pid-file.ts
9602
- import { randomBytes } from "crypto";
9603
- import {
9604
- chmod,
9605
- constants as fsConstants,
9606
- mkdir,
9607
- open,
9608
- readFile as readFile2,
9609
- rename,
9610
- unlink as unlink2
9611
- } from "fs/promises";
9612
- import { homedir } from "os";
9613
- import { dirname, join as join2 } from "path";
9614
- var writeChains = new Map;
9615
- async function serializeWrite(filePath, work) {
9616
- const prev = writeChains.get(filePath) ?? Promise.resolve();
9617
- const next = prev.catch(() => {}).then(work);
9618
- writeChains.set(filePath, next);
9619
- try {
9620
- await next;
9621
- } finally {
9622
- if (writeChains.get(filePath) === next) {
9623
- writeChains.delete(filePath);
9765
+ // src/runtime/plugin-singleton.ts
9766
+ var SINGLETON_KEY = Symbol.for("opencode-copilot-delegate.singleton.v1");
9767
+ async function plugInOnce({
9768
+ doInit,
9769
+ onDuplicate,
9770
+ pid
9771
+ }) {
9772
+ const currentPid = pid ?? process.pid;
9773
+ const g = globalThis;
9774
+ const existing = g[SINGLETON_KEY];
9775
+ if (existing && existing.pid === currentPid) {
9776
+ if (!existing.warned) {
9777
+ existing.warned = true;
9778
+ try {
9779
+ onDuplicate?.(currentPid);
9780
+ } catch {}
9624
9781
  }
9782
+ return existing.hooksPromise;
9625
9783
  }
9626
- }
9627
- function resolveInstancePidFilePath() {
9628
- const stateDir = process.env.XDG_STATE_HOME ?? join2(homedir(), ".local", "state");
9629
- return join2(stateDir, "opencode-copilot-delegate", "orphans", `${process.pid}.pids`);
9630
- }
9631
- async function appendPidEntry(filePath, pid, comm, lstart) {
9632
- await serializeWrite(filePath, async () => {
9633
- await mkdir(dirname(filePath), { recursive: true, mode: 448 });
9634
- let existing = "";
9635
- try {
9636
- existing = await readFile2(filePath, "utf-8");
9637
- } catch (e) {
9638
- if (!isErrnoException(e) || e.code !== "ENOENT")
9639
- throw e;
9640
- }
9641
- const line = `${pid} ${comm} ${lstart}
9642
- `;
9643
- const content = existing + line;
9644
- const tempPath = `${filePath}.tmp.${randomBytes(8).toString("hex")}`;
9645
- const fd = await open(tempPath, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
9646
- try {
9647
- await fd.writeFile(content, { encoding: "utf-8" });
9648
- } finally {
9649
- await fd.close();
9650
- }
9651
- await rename(tempPath, filePath);
9652
- await chmod(filePath, 384);
9653
- });
9654
- }
9655
- async function removePidEntry(filePath, pid) {
9656
- await serializeWrite(filePath, async () => {
9657
- let existing = "";
9658
- try {
9659
- existing = await readFile2(filePath, "utf-8");
9660
- } catch (e) {
9661
- if (!isErrnoException(e) || e.code !== "ENOENT")
9662
- throw e;
9663
- return;
9664
- }
9665
- const prefix = `${pid} `;
9666
- const lines = existing.split(`
9667
- `);
9668
- const filtered = lines.filter((line) => !line.startsWith(prefix));
9669
- if (filtered.length === lines.length) {
9670
- return;
9671
- }
9672
- const content = filtered.join(`
9673
- `);
9674
- const tempPath = `${filePath}.tmp.${randomBytes(8).toString("hex")}`;
9675
- const fd = await open(tempPath, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
9676
- try {
9677
- await fd.writeFile(content, { encoding: "utf-8" });
9678
- } finally {
9679
- await fd.close();
9680
- }
9681
- await rename(tempPath, filePath);
9682
- await chmod(filePath, 384);
9683
- if (content.trim().length === 0) {
9684
- await unlink2(filePath);
9685
- }
9686
- });
9784
+ const hooksPromise = doInit();
9785
+ g[SINGLETON_KEY] = {
9786
+ pid: currentPid,
9787
+ loadedAt: Date.now(),
9788
+ hooksPromise,
9789
+ warned: false
9790
+ };
9791
+ return hooksPromise;
9687
9792
  }
9688
9793
 
9689
9794
  // src/tools/cancel.ts
9690
- import { tool } from "@opencode-ai/plugin/tool";
9795
+ import { tool as tool2 } from "@opencode-ai/plugin/tool";
9691
9796
 
9692
9797
  // src/runtime/task-registry.ts
9693
9798
  import { randomUUID } from "crypto";
@@ -9737,10 +9842,10 @@ var TOOL_DESCRIPTION = [
9737
9842
  ].join(`
9738
9843
  `);
9739
9844
  function createCancelTool() {
9740
- return tool({
9845
+ return tool2({
9741
9846
  description: TOOL_DESCRIPTION,
9742
9847
  args: {
9743
- task_id: tool.schema.string().describe("The task ID returned by `copilot_delegate(...)`. Format: `cpl_<...>`. Required. Idempotent \u2014 non-running task IDs return `{ cancelled: false, was_running: false }` without error.")
9848
+ task_id: tool2.schema.string().describe("The task ID returned by `copilot_delegate(...)`. Format: `cpl_<...>`. Required. Idempotent \u2014 non-running task IDs return `{ cancelled: false, was_running: false }` without error.")
9744
9849
  },
9745
9850
  async execute(args) {
9746
9851
  const task = getTask(args.task_id);
@@ -9754,7 +9859,7 @@ function createCancelTool() {
9754
9859
  }
9755
9860
 
9756
9861
  // src/tools/delegate.ts
9757
- import { tool as tool2 } from "@opencode-ai/plugin/tool";
9862
+ import { tool as tool3 } from "@opencode-ai/plugin/tool";
9758
9863
 
9759
9864
  // src/runtime/notify.ts
9760
9865
  var inFlightCounters = new Map;
@@ -9922,7 +10027,7 @@ function isTerminal(s) {
9922
10027
  return TERMINAL_STATUSES.has(s);
9923
10028
  }
9924
10029
  function setStatus(task, newStatus, options) {
9925
- if (isTerminal(task.status) && isTerminal(newStatus)) {
10030
+ if (isTerminal(task.status)) {
9926
10031
  return;
9927
10032
  }
9928
10033
  task.status = newStatus;
@@ -10073,15 +10178,15 @@ var TOOL_DESCRIPTION2 = [
10073
10178
  ].join(`
10074
10179
  `);
10075
10180
  function createDelegateTool(options) {
10076
- return tool2({
10181
+ return tool3({
10077
10182
  description: `${TOOL_DESCRIPTION2}${options.description}`,
10078
10183
  args: {
10079
- prompt: tool2.schema.string().min(1).describe("The instruction Copilot should execute. The prompt body is the entire user-visible task; Copilot owns the planning, tool selection, and execution. Required and must be non-empty. Visible in `ps` output (upstream limitation) \u2014 never include secrets, tokens, or PII."),
10080
- agent: tool2.schema.string().describe("Agent name (without .md extension) to use for this task. Must match a discovered agent file in `~/.copilot/agents` or `.github/agents`. The list of currently discovered agents appears at the bottom of this tool description; an empty list means no agents are discoverable and `agent` must be omitted. Omit to use the Copilot CLI default.").optional(),
10081
- model: tool2.schema.string().describe("Override the default model for this task. Accepts any model string Copilot CLI recognizes \u2014 for example `claude-opus-4.7`, `claude-sonnet-4.7`, or `gpt-5`. Omit to use the user's configured default.").optional(),
10082
- add_dir: tool2.schema.string().array().describe('Additional repository paths to grant Copilot access to (multi-repo workflows). Each entry becomes a `--add-dir <path>` flag. Use absolute paths. Examples: `["/Users/me/repo-a", "/Users/me/repo-b"]`.').optional(),
10083
- allow_tool: tool2.schema.string().array().describe('Copilot tool patterns to allow during this task. Each entry becomes an `--allow-tool <pattern>` flag. Examples: `"shell(*)"`, `"edit"`, `"fetch"`. See the Copilot CLI docs for the full pattern syntax. Layered with `deny_tool` when both are present.').optional(),
10084
- deny_tool: tool2.schema.string().array().describe('Copilot tool patterns to deny during this task. Each entry becomes a `--deny-tool <pattern>` flag. Examples: `"shell(rm)"`, `"shell(curl)"`. Use to harden a task by blocking dangerous operations even if `allow_tool` would permit them.').optional()
10184
+ prompt: tool3.schema.string().min(1).describe("The instruction Copilot should execute. The prompt body is the entire user-visible task; Copilot owns the planning, tool selection, and execution. Required and must be non-empty. Visible in `ps` output (upstream limitation) \u2014 never include secrets, tokens, or PII."),
10185
+ agent: tool3.schema.string().optional().describe("Agent name (without .md extension) to use for this task. Must match a discovered agent file in `~/.copilot/agents` or `.github/agents`. The list of currently discovered agents appears at the bottom of this tool description; an empty list means no agents are discoverable and `agent` must be omitted. Omit to use the Copilot CLI default."),
10186
+ model: tool3.schema.string().optional().describe("Override the default model for this task. Accepts any model string Copilot CLI recognizes \u2014 for example `claude-opus-4.7`, `claude-sonnet-4.7`, or `gpt-5`. Omit to use the user's configured default."),
10187
+ add_dir: tool3.schema.string().array().optional().describe('Additional repository paths to grant Copilot access to (multi-repo workflows). Each entry becomes a `--add-dir <path>` flag. Use absolute paths. Examples: `["/Users/me/repo-a", "/Users/me/repo-b"]`.'),
10188
+ allow_tool: tool3.schema.string().array().optional().describe('Copilot tool patterns to allow during this task. Each entry becomes an `--allow-tool <pattern>` flag. Examples: `"shell(*)"`, `"edit"`, `"fetch"`. See the Copilot CLI docs for the full pattern syntax. Layered with `deny_tool` when both are present.'),
10189
+ deny_tool: tool3.schema.string().array().optional().describe('Copilot tool patterns to deny during this task. Each entry becomes a `--deny-tool <pattern>` flag. Examples: `"shell(rm)"`, `"shell(curl)"`. Use to harden a task by blocking dangerous operations even if `allow_tool` would permit them.')
10085
10190
  },
10086
10191
  async execute(args, ctx) {
10087
10192
  const runningCount = getAllTasks().filter((task2) => task2.status === "running").length;
@@ -10160,7 +10265,7 @@ function createDelegateTool(options) {
10160
10265
  }
10161
10266
 
10162
10267
  // src/tools/output.ts
10163
- import { tool as tool3 } from "@opencode-ai/plugin/tool";
10268
+ import { tool as tool4 } from "@opencode-ai/plugin/tool";
10164
10269
 
10165
10270
  // src/runtime/envelope.ts
10166
10271
  function extractFinalMessage(events) {
@@ -10278,12 +10383,12 @@ var TOOL_DESCRIPTION3 = [
10278
10383
  ].join(`
10279
10384
  `);
10280
10385
  function createOutputTool() {
10281
- return tool3({
10386
+ return tool4({
10282
10387
  description: TOOL_DESCRIPTION3,
10283
10388
  args: {
10284
- task_id: tool3.schema.string().describe("The task ID returned by `copilot_delegate(...)`. Format: `cpl_<...>`. Required."),
10285
- block: tool3.schema.boolean().describe("If the task is still running, wait for completion up to `timeout_ms` before returning. Default `false` \u2014 returns immediately with the current state. Set to `true` only when the agent has nothing else to do but wait.").optional(),
10286
- timeout_ms: tool3.schema.number().int().min(0).max(MAX_TIMEOUT_MS).describe("Maximum wait in milliseconds when `block` is `true`. Default 30000. Range 0\u2013120000 (the upper cap protects the OpenCode session from a single hung delegation). For long research tasks, prefer multiple non-blocking calls over a long block.").optional()
10389
+ task_id: tool4.schema.string().describe("The task ID returned by `copilot_delegate(...)`. Format: `cpl_<...>`. Required."),
10390
+ block: tool4.schema.boolean().optional().describe("If the task is still running, wait for completion up to `timeout_ms` before returning. Default `false` \u2014 returns immediately with the current state. Set to `true` only when the agent has nothing else to do but wait."),
10391
+ timeout_ms: tool4.schema.number().int().min(0).max(MAX_TIMEOUT_MS).optional().describe("Maximum wait in milliseconds when `block` is `true`. Default 30000. Range 0\u2013120000 (the upper cap protects the OpenCode session from a single hung delegation). For long research tasks, prefer multiple non-blocking calls over a long block.")
10287
10392
  },
10288
10393
  async execute(args) {
10289
10394
  if (!isValidTaskId(args.task_id)) {
@@ -10332,7 +10437,7 @@ function getAgentsDirectories(directory) {
10332
10437
  repoAgentsDir: `${directory}/.github/agents`
10333
10438
  };
10334
10439
  }
10335
- var CopilotDelegate = async ({ client, directory }) => {
10440
+ async function initializePlugin({ client, directory }) {
10336
10441
  const agents = discoverAgents(getAgentsDirectories(directory));
10337
10442
  const delegateDescription = buildDescription(agents);
10338
10443
  const currentInstancePath = resolveInstancePidFilePath();
@@ -10348,17 +10453,31 @@ var CopilotDelegate = async ({ client, directory }) => {
10348
10453
  } catch {}
10349
10454
  return {
10350
10455
  tool: {
10351
- copilot_delegate: createDelegateTool({
10456
+ copilot_delegate: normalizeToolArgSchemas(createDelegateTool({
10352
10457
  client,
10353
10458
  description: delegateDescription,
10354
10459
  directory,
10355
10460
  pidFilePath: currentInstancePath
10356
- }),
10357
- copilot_output: createOutputTool(),
10358
- copilot_cancel: createCancelTool()
10461
+ })),
10462
+ copilot_output: normalizeToolArgSchemas(createOutputTool()),
10463
+ copilot_cancel: normalizeToolArgSchemas(createCancelTool())
10359
10464
  }
10360
10465
  };
10361
- };
10466
+ }
10467
+ var CopilotDelegate = async (input) => plugInOnce({
10468
+ doInit: () => initializePlugin(input),
10469
+ onDuplicate: (pid) => {
10470
+ const message = `[copilot-delegate] duplicate factory invocation in same process (pid=${pid}); reusing existing hooks. Multiple opencode.json sources may list this plugin.`;
10471
+ console.warn(message);
10472
+ input.client.app.log({
10473
+ body: {
10474
+ service: "copilot-delegate",
10475
+ level: "warn",
10476
+ message
10477
+ }
10478
+ }).catch(() => {});
10479
+ }
10480
+ });
10362
10481
  var src_default = CopilotDelegate;
10363
10482
  export {
10364
10483
  src_default as default
@@ -0,0 +1,11 @@
1
+ import type { ToolDefinition } from '@opencode-ai/plugin';
2
+ /**
3
+ * Walks a tool definition's `args` map and patches each schema with a
4
+ * JSON Schema override (see {@link attachJsonSchemaOverride}). Mutates and
5
+ * returns the same definition for fluent composition:
6
+ *
7
+ * ```ts
8
+ * const tool = normalizeToolArgSchemas(createDelegateTool({...}))
9
+ * ```
10
+ */
11
+ export declare function normalizeToolArgSchemas<TDefinition extends Pick<ToolDefinition, 'args'>>(toolDefinition: TDefinition): TDefinition;
@@ -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 ReapOpts {
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<ReapOpts, 'signal'> & {
84
+ export declare function reapOrphans(opts: Omit<ReapOptions, 'signal'> & {
71
85
  reapTimeoutMs?: number;
72
86
  }): Promise<ReapResult>;
73
- export {};
@@ -1,3 +1,16 @@
1
1
  export declare function resolveInstancePidFilePath(): string;
2
2
  export declare function appendPidEntry(filePath: string, pid: number, comm: string, lstart: string): Promise<void>;
3
3
  export declare function removePidEntry(filePath: string, pid: number): Promise<void>;
4
+ /**
5
+ * Truncate a PID file under the same per-file serialize lock used by
6
+ * appendPidEntry/removePidEntry, so a concurrent writer cannot interleave
7
+ * with the truncation. ENOENT is silently swallowed in both forms:
8
+ * file-already-gone AND parent-directory-missing. Other errno values
9
+ * propagate.
10
+ */
11
+ export declare function truncatePidFile(filePath: string): Promise<void>;
12
+ /**
13
+ * Remove a PID file under the same per-file serialize lock. ENOENT is
14
+ * silently swallowed (file already gone). Other errno values propagate.
15
+ */
16
+ 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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-copilot-delegate",
3
- "version": "0.6.0",
3
+ "version": "0.8.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",
@@ -58,6 +58,10 @@
58
58
  "publish-changesets": "bun run build && changeset publish"
59
59
  },
60
60
  "dependencies": {
61
- "fkill": "10.0.3"
61
+ "fkill": "10.0.3",
62
+ "zod": "^4.3.0"
63
+ },
64
+ "overrides": {
65
+ "zod": "^4.3.0"
62
66
  }
63
67
  }