opencode-copilot-delegate 0.3.0 → 0.5.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,31 @@
1
1
  # opencode-copilot-delegate
2
2
 
3
+ ## 0.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - e940a28: Drop `BUILTIN_AGENTS` and enrich tool schema descriptions
8
+
9
+ **`BUILTIN_AGENTS` removal.** The plugin previously advertised six "built-in" agent names — `default`, `explore`, `task`, `general-purpose`, `code-review`, `research` — inherited from VS Code Copilot Chat / OpenCode conventions. The standalone `@github/copilot` CLI v1.0.36 ships zero of these; passing any of them as `--agent <name>` causes Copilot CLI to fail at spawn time with `Error: No such agent: <name>, available:`. The constant has been removed. `discoverAgents` now returns user agents (filtered by repo override) followed by repo agents; `Agent.source` is `'user' | 'repo'`. `buildDescription` handles the empty-discovery case by emitting an actionable hint pointing at `~/.copilot/agents` and `.github/agents`.
10
+
11
+ **Tool schema enrichment.** The three exposed tools — `copilot_delegate`, `copilot_output`, `copilot_cancel` — now ship multi-paragraph tool descriptions covering what they do, when to use them, lifecycle, common pitfalls, and return-value shape. Per-parameter `.describe()` text spells out type, default, when-required, example values, and constraints. Examples follow the patterns Magic Context's `ctx_*` tools established. The new descriptions surface in OpenCode's tool registry exposure to LLMs and via `mise run opencode:doctor --only tools`.
12
+
13
+ No runtime behavior change beyond the agent discovery fix. Tool argument shapes are unchanged; existing callers continue to work without modification.
14
+
15
+ ## 0.4.0
16
+
17
+ ### Minor Changes
18
+
19
+ - f3f21c7: Configurable orphan-reaper timeouts and parser extraction
20
+
21
+ Three medium-priority improvements to the plugin-init orphan-subprocess reaper, all from the runtime hardening backlog:
22
+
23
+ - **Configurable per-probe `ps` timeout with degradation warning**: `getPidIdentity` and the underlying `runPs` helper now accept an optional `timeoutMs` parameter (default 1000). On loaded systems where legitimate `ps` responses can exceed 1s, callers can pass a longer timeout to avoid identity-gate misses that leave orphans alive. When the timeout fires, `runPs` emits a `console.warn` so operators can detect probe degradation and tune the budget up.
24
+ - **Overall `reapOrphans` timeout with cooperative cancellation**: `reapOrphans` now accepts an optional `reapTimeoutMs` parameter (default 15000). When the timeout fires, the reap aborts via `AbortSignal`: in-flight workers cooperate by skipping their next mutating step (kill, truncate, unlink) so no dangerous side effects can occur after `reapOrphans` returns. The call resolves with an empty result and emits a `console.warn`. Prevents pathological cases (NFS `readdir` hang, all probes timing out simultaneously) from blocking plugin init indefinitely, and prevents lingering reap workers from wiping current-instance pid file entries that live tasks have appended after the timeout fired.
25
+ - **Parser extraction**: the comm/lstart parsing logic is lifted out of `getPidIdentity` into a new exported `parsePsIdentity(raw)` pure function with full edge-case coverage (empty input, single-token input, leading-whitespace input, the 15/16-char `comm` boundary, and multi-whitespace separator).
26
+
27
+ All new parameters are additive optionals; existing callers continue to work without modification. Behavior at default settings is unchanged for normal-load operation, but the new overall reap timeout introduces a conditional control-flow branch (warn + empty return) that activates only under pathological conditions where a reap exceeds the 15s default budget.
28
+
3
29
  ## 0.3.0
4
30
 
5
31
  ### Minor Changes
@@ -1,10 +1,22 @@
1
1
  export interface Agent {
2
2
  name: string;
3
- source: 'builtin' | 'user' | 'repo';
3
+ source: 'user' | 'repo';
4
4
  }
5
5
  interface DiscoverOptions {
6
6
  userAgentsDir?: string;
7
7
  repoAgentsDir?: string;
8
8
  }
9
+ /**
10
+ * Discover Copilot agents from the user and repo agent directories.
11
+ *
12
+ * Copilot CLI v1.0.36 ships zero built-in agents. Every `--agent <name>`
13
+ * argument must resolve to a discoverable `<name>.md` file in one of the
14
+ * standard agent directories (`~/.copilot/agents`, `.github/agents`, or
15
+ * `~/.copilot/installed-plugins/<plugin>/agents`). The plugin discovers the
16
+ * first two; bundled-with-plugin agents are out of scope for this discovery
17
+ * helper.
18
+ *
19
+ * Repo agents override user agents with the same name; the repo entry wins.
20
+ */
9
21
  export declare function discoverAgents(opts: DiscoverOptions): Agent[];
10
22
  export {};
@@ -1,2 +1,8 @@
1
1
  import type { Agent } from './agents';
2
+ /**
3
+ * Render a human-readable list of discovered agents for inclusion in the
4
+ * `copilot_delegate` tool description. Lists user and repo agents (no
5
+ * builtins; Copilot CLI v1.0.36 ships none). Truncates at MAX_DISPLAYED
6
+ * entries with a count of the rest.
7
+ */
2
8
  export declare function buildDescription(agents: Agent[]): string;
package/dist/index.js CHANGED
@@ -797,14 +797,6 @@ import { dirname as dirname2 } from "path";
797
797
  // src/discovery/agents.ts
798
798
  import { readdirSync } from "fs";
799
799
  import { basename } from "path";
800
- var BUILTIN_AGENTS = [
801
- "default",
802
- "explore",
803
- "task",
804
- "general-purpose",
805
- "code-review",
806
- "research"
807
- ];
808
800
  function scanDir(dir, source) {
809
801
  try {
810
802
  const entries = readdirSync(dir);
@@ -817,22 +809,24 @@ function scanDir(dir, source) {
817
809
  }
818
810
  }
819
811
  function discoverAgents(opts) {
820
- const builtins = BUILTIN_AGENTS.map((name) => ({
821
- name,
822
- source: "builtin"
823
- }));
824
812
  const userAgents = opts.userAgentsDir ? scanDir(opts.userAgentsDir, "user") : [];
825
813
  const repoAgents = opts.repoAgentsDir ? scanDir(opts.repoAgentsDir, "repo") : [];
826
- const builtinNames = new Set(BUILTIN_AGENTS);
827
814
  const overriddenNames = new Set(repoAgents.map((a) => a.name));
828
- const filteredUser = userAgents.filter((a) => !builtinNames.has(a.name)).filter((a) => !overriddenNames.has(a.name));
829
- const filteredRepo = repoAgents.filter((a) => !builtinNames.has(a.name));
830
- return [...builtins, ...filteredUser, ...filteredRepo];
815
+ const filteredUser = userAgents.filter((a) => !overriddenNames.has(a.name));
816
+ return [...filteredUser, ...repoAgents];
831
817
  }
832
818
 
833
819
  // src/discovery/description.ts
834
820
  var MAX_DISPLAYED = 20;
835
821
  function buildDescription(agents) {
822
+ if (agents.length === 0) {
823
+ return [
824
+ "No Copilot agents discovered.",
825
+ "Add `.agent.md` files to `~/.copilot/agents` (user-level) or",
826
+ "`.github/agents` (repo-level) to make them available here."
827
+ ].join(`
828
+ `);
829
+ }
836
830
  const displayed = agents.slice(0, MAX_DISPLAYED);
837
831
  const remaining = agents.length - MAX_DISPLAYED;
838
832
  const lines = ["Available Copilot agents:"];
@@ -840,7 +834,7 @@ function buildDescription(agents) {
840
834
  lines.push(` - ${agent.name} (${agent.source})`);
841
835
  }
842
836
  if (remaining > 0) {
843
- lines.push(` ... and ${remaining} more (use copilot_list_agents to see all)`);
837
+ lines.push(` ... and ${remaining} more (see ~/.copilot/agents or .github/agents)`);
844
838
  }
845
839
  return lines.join(`
846
840
  `);
@@ -9381,15 +9375,17 @@ function defaultIsPluginAlive(pid) {
9381
9375
  return isErrnoException(e) && e.code === "EPERM";
9382
9376
  }
9383
9377
  }
9384
- function runPs(args) {
9378
+ var DEFAULT_PS_TIMEOUT_MS = 1000;
9379
+ function runPs(args, timeoutMs = DEFAULT_PS_TIMEOUT_MS) {
9385
9380
  return new Promise((resolve) => {
9386
9381
  const child = spawn2("ps", args);
9387
9382
  let stdout = "";
9388
9383
  let timedOut = false;
9389
9384
  const timeout = setTimeout(() => {
9390
9385
  timedOut = true;
9386
+ console.warn(`[orphan-reaper] ps invocation exceeded ${timeoutMs}ms timeout: ps ${args.join(" ")}`);
9391
9387
  child.kill("SIGTERM");
9392
- }, 1000);
9388
+ }, timeoutMs);
9393
9389
  child.stdout?.on("data", (chunk) => {
9394
9390
  stdout += chunk.toString("utf-8");
9395
9391
  });
@@ -9409,9 +9405,8 @@ function runPs(args) {
9409
9405
  });
9410
9406
  });
9411
9407
  }
9412
- async function getPidIdentity(pid) {
9413
- const raw = await runPs(["-p", String(pid), "-o", "comm=,lstart="]);
9414
- if (raw === null)
9408
+ function parsePsIdentity(raw) {
9409
+ if (!raw)
9415
9410
  return null;
9416
9411
  const firstWs = raw.search(/\s/);
9417
9412
  if (firstWs === -1)
@@ -9422,6 +9417,12 @@ async function getPidIdentity(pid) {
9422
9417
  return null;
9423
9418
  return { comm, lstart };
9424
9419
  }
9420
+ async function getPidIdentity(pid, timeoutMs = DEFAULT_PS_TIMEOUT_MS) {
9421
+ const raw = await runPs(["-p", String(pid), "-o", "comm=,lstart="], timeoutMs);
9422
+ if (raw === null)
9423
+ return null;
9424
+ return parsePsIdentity(raw);
9425
+ }
9425
9426
  function parseLine(line) {
9426
9427
  const parts = line.split("\t");
9427
9428
  if (parts.length !== 3)
@@ -9433,13 +9434,17 @@ function parseLine(line) {
9433
9434
  return { pid, comm: parts[1], lstart: parts[2] };
9434
9435
  }
9435
9436
  var MAX_CONCURRENT_PROBES = 5;
9436
- async function processEntry(entry, killProcessTree2, getPidIdentity2) {
9437
+ async function processEntry(entry, killProcessTree2, getPidIdentity2, signal, psTimeoutMs) {
9438
+ if (signal?.aborted)
9439
+ return { reaped: false, skipped: true };
9437
9440
  try {
9438
9441
  process.kill(entry.pid, 0);
9439
9442
  } catch {
9440
9443
  return { reaped: false, skipped: true };
9441
9444
  }
9442
- const live = await getPidIdentity2(entry.pid);
9445
+ const live = await getPidIdentity2(entry.pid, psTimeoutMs);
9446
+ if (signal?.aborted)
9447
+ return { reaped: false, skipped: true };
9443
9448
  if (live === null || live.comm !== entry.comm || live.lstart !== entry.lstart) {
9444
9449
  return { reaped: false, skipped: true };
9445
9450
  }
@@ -9450,17 +9455,19 @@ async function processEntry(entry, killProcessTree2, getPidIdentity2) {
9450
9455
  return { reaped: false, skipped: true };
9451
9456
  }
9452
9457
  }
9453
- async function processEntries(entries, killProcessTree2, getPidIdentity2) {
9458
+ async function processEntries(entries, killProcessTree2, getPidIdentity2, signal, psTimeoutMs) {
9454
9459
  let reaped = 0;
9455
9460
  let skipped = 0;
9456
9461
  const queue = [...entries];
9457
9462
  const workerCount = Math.min(MAX_CONCURRENT_PROBES, entries.length);
9458
9463
  const workers = Array.from({ length: workerCount }, async () => {
9459
9464
  while (true) {
9465
+ if (signal?.aborted)
9466
+ return;
9460
9467
  const entry = queue.shift();
9461
9468
  if (!entry)
9462
9469
  return;
9463
- const result = await processEntry(entry, killProcessTree2, getPidIdentity2);
9470
+ const result = await processEntry(entry, killProcessTree2, getPidIdentity2, signal, psTimeoutMs);
9464
9471
  if (result.reaped)
9465
9472
  reaped++;
9466
9473
  else if (result.skipped)
@@ -9500,7 +9507,7 @@ async function cleanupAfterReap(filePath, isCurrent, currentInstancePath) {
9500
9507
  return false;
9501
9508
  }
9502
9509
  }
9503
- async function reapOneFile(filePath, filePid, isCurrent, currentInstancePath, isPluginAlive, killProcessTree2, getPidIdentity2) {
9510
+ async function reapOneFile(filePath, filePid, isCurrent, currentInstancePath, isPluginAlive, killProcessTree2, getPidIdentity2, signal, psTimeoutMs) {
9504
9511
  const empty = {
9505
9512
  reaped: 0,
9506
9513
  skipped: 0,
@@ -9514,17 +9521,22 @@ async function reapOneFile(filePath, filePid, isCurrent, currentInstancePath, is
9514
9521
  if (entries === null) {
9515
9522
  return empty;
9516
9523
  }
9517
- const { reaped, skipped } = await processEntries(entries, killProcessTree2, getPidIdentity2);
9524
+ const { reaped, skipped } = await processEntries(entries, killProcessTree2, getPidIdentity2, signal, psTimeoutMs);
9525
+ if (signal?.aborted) {
9526
+ return { reaped, skipped, scanned: true, deleted: false };
9527
+ }
9518
9528
  const deleted = await cleanupAfterReap(filePath, isCurrent, currentInstancePath);
9519
9529
  return { reaped, skipped, scanned: true, deleted };
9520
9530
  }
9521
- async function reapOrphans(opts) {
9531
+ async function doReap(opts) {
9522
9532
  const {
9523
9533
  pidFileDir,
9524
9534
  currentInstancePath,
9525
9535
  killProcessTree: killProcessTree2,
9526
9536
  getPidIdentity: getPidIdentity2,
9527
- isPluginAlive = defaultIsPluginAlive
9537
+ isPluginAlive = defaultIsPluginAlive,
9538
+ signal,
9539
+ psTimeoutMs
9528
9540
  } = opts;
9529
9541
  let files;
9530
9542
  try {
@@ -9537,6 +9549,8 @@ async function reapOrphans(opts) {
9537
9549
  let scannedFiles = 0;
9538
9550
  let deletedFiles = 0;
9539
9551
  for (const file of files) {
9552
+ if (signal?.aborted)
9553
+ break;
9540
9554
  if (!file.endsWith(".pids"))
9541
9555
  continue;
9542
9556
  const filePath = join(pidFileDir, file);
@@ -9546,7 +9560,7 @@ async function reapOrphans(opts) {
9546
9560
  continue;
9547
9561
  }
9548
9562
  const filePid = Number(stem);
9549
- const outcome = await reapOneFile(filePath, filePid, filePid === process.pid, currentInstancePath, isPluginAlive, killProcessTree2, getPidIdentity2);
9563
+ const outcome = await reapOneFile(filePath, filePid, filePid === process.pid, currentInstancePath, isPluginAlive, killProcessTree2, getPidIdentity2, signal, psTimeoutMs);
9550
9564
  reaped += outcome.reaped;
9551
9565
  skipped += outcome.skipped;
9552
9566
  if (outcome.scanned)
@@ -9556,6 +9570,33 @@ async function reapOrphans(opts) {
9556
9570
  }
9557
9571
  return { reaped, skipped, scannedFiles, deletedFiles };
9558
9572
  }
9573
+ var DEFAULT_REAP_TIMEOUT_MS = 15000;
9574
+ async function reapOrphans(opts) {
9575
+ const reapTimeoutMs = opts.reapTimeoutMs ?? DEFAULT_REAP_TIMEOUT_MS;
9576
+ const empty = {
9577
+ reaped: 0,
9578
+ skipped: 0,
9579
+ scannedFiles: 0,
9580
+ deletedFiles: 0
9581
+ };
9582
+ const controller = new AbortController;
9583
+ let timeoutId;
9584
+ const timeoutPromise = new Promise((resolve) => {
9585
+ timeoutId = setTimeout(() => {
9586
+ console.warn(`[orphan-reaper] reapOrphans exceeded ${reapTimeoutMs}ms budget; returning empty result`);
9587
+ controller.abort();
9588
+ resolve(empty);
9589
+ }, reapTimeoutMs);
9590
+ });
9591
+ const reapPromise = doReap({ ...opts, signal: controller.signal });
9592
+ reapPromise.catch(() => {});
9593
+ try {
9594
+ return await Promise.race([reapPromise, timeoutPromise]);
9595
+ } finally {
9596
+ if (timeoutId)
9597
+ clearTimeout(timeoutId);
9598
+ }
9599
+ }
9559
9600
 
9560
9601
  // src/runtime/pid-file.ts
9561
9602
  import { randomBytes } from "crypto";
@@ -9677,11 +9718,29 @@ function getAllTasks() {
9677
9718
  }
9678
9719
 
9679
9720
  // src/tools/cancel.ts
9721
+ var TOOL_DESCRIPTION = [
9722
+ "Cancel a running Copilot delegation.",
9723
+ "",
9724
+ "Aborts the in-flight subprocess via its `AbortController`; the subprocess receives SIGTERM through",
9725
+ "its process tree and the task transitions to `cancelled`. Any pending `copilot_output` block calls",
9726
+ "unblock immediately with the cancelled envelope.",
9727
+ "",
9728
+ "Returns `{ cancelled, was_running }`:",
9729
+ "- `cancelled: true, was_running: true` \u2014 task was running and the abort signal was sent.",
9730
+ "- `cancelled: false, was_running: false` \u2014 task is unknown to this process, or already terminal",
9731
+ " (`succeeded` / `failed` / `cancelled`). Idempotent \u2014 safe to call multiple times.",
9732
+ "",
9733
+ "Use when:",
9734
+ "- The user changes direction during a long-running delegation and the task's output is no longer needed.",
9735
+ "- The agent has determined a delegation has gone wrong (e.g., wrong agent selected) and a fresh delegate is preferable to waiting.",
9736
+ "- Concurrency limit pressure \u2014 cancel a stale low-priority task to free a slot for a higher-priority delegation."
9737
+ ].join(`
9738
+ `);
9680
9739
  function createCancelTool() {
9681
9740
  return tool({
9682
- description: "Cancel a running Copilot delegation.",
9741
+ description: TOOL_DESCRIPTION,
9683
9742
  args: {
9684
- task_id: tool.schema.string().describe("Task ID returned by copilot_delegate.")
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.")
9685
9744
  },
9686
9745
  async execute(args) {
9687
9746
  const task = getTask(args.task_id);
@@ -9984,19 +10043,45 @@ function appendRepeatedFlag(args, flag, values) {
9984
10043
  args.push(flag, value);
9985
10044
  }
9986
10045
  }
10046
+ var TOOL_DESCRIPTION2 = [
10047
+ "Delegate a task to GitHub Copilot CLI as a background subprocess.",
10048
+ "",
10049
+ "Returns a `task_id` immediately so the parent agent can continue other work in parallel.",
10050
+ "When Copilot completes, a `system-reminder` is injected into this OpenCode session and the",
10051
+ "agent retrieves the structured result with `copilot_output(task_id)`.",
10052
+ "",
10053
+ "Use for:",
10054
+ "- Long-running research, implementation, or multi-step automation that would otherwise stall the parent session.",
10055
+ "- Running multiple Copilot calls in parallel (subject to a 10-call concurrency cap, enforced here).",
10056
+ "- Isolating Copilot tool permissions per-task via `allow_tool` / `deny_tool`.",
10057
+ "",
10058
+ "Do not use for:",
10059
+ "- Short single-turn prompts the parent session can answer directly.",
10060
+ "- Tasks where the prompt would contain secrets \u2014 Copilot CLI exposes prompts in `ps` output (upstream limitation).",
10061
+ "",
10062
+ "Lifecycle:",
10063
+ "1. `copilot_delegate(...)` \u2192 returns `{ task_id }`. The subprocess starts immediately.",
10064
+ "2. Continue with other work; do not poll `copilot_output` while the task is running.",
10065
+ "3. When the task ends (success, error, or cancellation) a `system-reminder` arrives in this session.",
10066
+ "4. `copilot_output(task_id)` returns the structured envelope (status, exit_code, final_message, summary, events, ...).",
10067
+ "5. `copilot_cancel(task_id)` aborts a running task at any time.",
10068
+ "",
10069
+ "Concurrency: at most 10 Copilot delegations may be running concurrently per OpenCode session. Exceeding the cap returns `{ error: ... }` and the agent should wait for an in-flight task to complete or cancel.",
10070
+ "",
10071
+ "Agent argument: `--agent <name>` must resolve to a discovered `<name>.md` file in `~/.copilot/agents` (user-level) or `.github/agents` (repo-level). An unrecognized name is rejected by Copilot CLI at spawn time.",
10072
+ ""
10073
+ ].join(`
10074
+ `);
9987
10075
  function createDelegateTool(options) {
9988
10076
  return tool2({
9989
- description: `Delegate a task to GitHub Copilot CLI as a background subprocess.
9990
- ` + `Returns a task_id immediately; parent agent continues other work.
9991
- ` + `When Copilot completes, a system-reminder is injected into this session.
9992
- ` + "Retrieve the structured result with `copilot_output(task_id)`.\n\n" + options.description,
10077
+ description: `${TOOL_DESCRIPTION2}${options.description}`,
9993
10078
  args: {
9994
- prompt: tool2.schema.string().min(1).describe("The prompt to send to Copilot CLI."),
9995
- agent: tool2.schema.string().optional().describe("Copilot agent name. Omit for default."),
9996
- model: tool2.schema.string().optional().describe("Model override. Omit for default."),
9997
- add_dir: tool2.schema.string().array().optional().describe("Additional directories to allow."),
9998
- allow_tool: tool2.schema.string().array().optional().describe("Tool patterns to allow."),
9999
- deny_tool: tool2.schema.string().array().optional().describe("Tool patterns to deny.")
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().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."),
10081
+ model: tool2.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."),
10082
+ add_dir: tool2.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"]`.'),
10083
+ allow_tool: tool2.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.'),
10084
+ deny_tool: tool2.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.')
10000
10085
  },
10001
10086
  async execute(args, ctx) {
10002
10087
  const runningCount = getAllTasks().filter((task2) => task2.status === "running").length;
@@ -10160,16 +10245,45 @@ function buildEnvelope(input) {
10160
10245
  }
10161
10246
 
10162
10247
  // src/tools/output.ts
10248
+ var DEFAULT_TIMEOUT_MS = 30000;
10249
+ var MAX_TIMEOUT_MS = 120000;
10163
10250
  function isValidTaskId(taskId) {
10164
10251
  return taskId.length > 0 && taskId.startsWith("cpl_");
10165
10252
  }
10253
+ var TOOL_DESCRIPTION3 = [
10254
+ "Retrieve the structured result envelope for a delegated Copilot task.",
10255
+ "",
10256
+ "Most calls happen after a `copilot_delegate(...)` task triggers its completion `system-reminder`",
10257
+ "in this session. The envelope contains everything the agent needs to act on the result:",
10258
+ "",
10259
+ "- `task_id`, `status` (`running` | `succeeded` | `failed` | `cancelled` | `unknown`)",
10260
+ "- `exit_code`, `duration_ms`, `started_at`, `ended_at`",
10261
+ "- `agent_name`, `model_name`, `args` (the original CLI args)",
10262
+ "- `final_message`: the assistant's last user-visible response, or null",
10263
+ "- `error_text`: stderr tail when the subprocess failed",
10264
+ "- `summary`: counts of tool calls, files changed, and tokens consumed",
10265
+ "- `events` (when present): the sequence of parsed JSONL events from Copilot",
10266
+ "",
10267
+ "When to call:",
10268
+ "- After receiving a completion `system-reminder` for a known `task_id`.",
10269
+ "- On demand if the agent needs to inspect a still-running task \u2014 pass `block: true` to wait briefly for completion.",
10270
+ "- On task IDs the parent agent saved earlier in the session.",
10271
+ "",
10272
+ "Block mode (`block: true`):",
10273
+ "- If the task is still running, wait up to `timeout_ms` (default 30000, capped at 120000) for completion.",
10274
+ "- On timeout, returns the envelope with `timed_out: true` and the agent should call again later.",
10275
+ "- For research-style delegations that may exceed 120s, prefer non-blocking polling \u2014 call this tool again after each `system-reminder` instead of holding open a single long block.",
10276
+ "",
10277
+ 'Unknown task IDs return `{ task_id, status: "unknown", error }` rather than throwing.'
10278
+ ].join(`
10279
+ `);
10166
10280
  function createOutputTool() {
10167
10281
  return tool3({
10168
- description: "Retrieve the structured result envelope for a delegated Copilot task.",
10282
+ description: TOOL_DESCRIPTION3,
10169
10283
  args: {
10170
- task_id: tool3.schema.string().describe("Task ID returned by copilot_delegate."),
10171
- block: tool3.schema.boolean().optional().describe("Wait for completion. Default false."),
10172
- timeout_ms: tool3.schema.number().int().min(0).max(120000).optional().describe("Max wait ms when block is true. Default 30000.")
10284
+ task_id: tool3.schema.string().describe("The task ID returned by `copilot_delegate(...)`. Format: `cpl_<...>`. Required."),
10285
+ block: tool3.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."),
10286
+ timeout_ms: tool3.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.")
10173
10287
  },
10174
10288
  async execute(args) {
10175
10289
  if (!isValidTaskId(args.task_id)) {
@@ -10188,7 +10302,7 @@ function createOutputTool() {
10188
10302
  });
10189
10303
  }
10190
10304
  if (args.block && task.status === "running") {
10191
- const timeoutMs = Math.max(0, Math.min(args.timeout_ms ?? 30000, 120000));
10305
+ const timeoutMs = Math.max(0, Math.min(args.timeout_ms ?? DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS));
10192
10306
  let timer;
10193
10307
  const completed = await Promise.race([
10194
10308
  task.completionPromise.then(() => {
@@ -1,6 +1,6 @@
1
1
  export interface ReapDeps {
2
2
  killProcessTree: (pid: number) => Promise<void>;
3
- getPidIdentity: (pid: number) => Promise<{
3
+ getPidIdentity: (pid: number, timeoutMs?: number) => Promise<{
4
4
  comm: string;
5
5
  lstart: string;
6
6
  } | null>;
@@ -13,27 +13,61 @@ export interface ReapResult {
13
13
  deletedFiles: number;
14
14
  }
15
15
  export declare function defaultIsPluginAlive(pid: number): boolean;
16
+ /**
17
+ * Parse `ps -p <pid> -o comm=,lstart=` output into `{ comm, lstart }`.
18
+ *
19
+ * Output format: `<comm><whitespace><lstart>` where `comm` is a single
20
+ * non-whitespace token (kernel-tracked process name field, capped at 15
21
+ * chars on Linux and 16 chars on macOS) and `lstart` is the multi-word
22
+ * date string that follows (e.g., `Tue Apr 28 23:45:30 2026`).
23
+ *
24
+ * Splitting on the first whitespace is safe because the kernel `comm`
25
+ * field never contains whitespace. If a future refactor adds different
26
+ * `-o` fields or runs on a platform that emits padded output, this parse
27
+ * fails safe: a truncated comm won't match the recorded one, so the
28
+ * identity gate skips rather than kills.
29
+ *
30
+ * Callers must trim their input first (e.g., via `runPs`'s built-in
31
+ * trim). Leading whitespace yields an empty comm and the parser returns
32
+ * null \u2014 the safe behavior, but a poor signal for the caller.
33
+ *
34
+ * Returns null on empty input, single-token input (no lstart), and any
35
+ * other malformed shape.
36
+ */
37
+ export declare function parsePsIdentity(raw: string): {
38
+ comm: string;
39
+ lstart: string;
40
+ } | null;
16
41
  /**
17
42
  * Read both comm (kernel-tracked executable name) and lstart (process
18
43
  * start time) for a PID via a single ps invocation.
19
44
  *
20
45
  * Halves the fork/exec cost of identity verification compared with two
21
- * separate `ps -o comm=` and `ps -o lstart=` calls. The combined output
22
- * format is `<comm> <lstart>` where comm is a single token and lstart is
23
- * a multi-word date string (e.g., `Tue Apr 28 23:45:30 2026`).
46
+ * separate `ps -o comm=` and `ps -o lstart=` calls.
47
+ *
48
+ * `timeoutMs` controls the underlying ps timeout (default 1s). On loaded
49
+ * systems where legitimate ps responses can exceed 1s, callers can pass
50
+ * a longer timeout; the timeout-fire path emits a `console.warn` for
51
+ * operator visibility.
24
52
  *
25
53
  * Returns null on any failure mode (timeout, spawn error, non-zero exit,
26
54
  * empty output, malformed output). Callers must treat null as "identity
27
55
  * unverifiable; do not trust this PID."
28
56
  */
29
- export declare function getPidIdentity(pid: number): Promise<{
57
+ export declare function getPidIdentity(pid: number, timeoutMs?: number): Promise<{
30
58
  comm: string;
31
59
  lstart: string;
32
60
  } | null>;
33
- export declare function reapOrphans(opts: {
61
+ interface ReapOpts {
34
62
  pidFileDir: string;
35
63
  currentInstancePath: string;
36
64
  killProcessTree: ReapDeps['killProcessTree'];
37
65
  getPidIdentity: ReapDeps['getPidIdentity'];
38
66
  isPluginAlive?: ReapDeps['isPluginAlive'];
67
+ signal?: AbortSignal;
68
+ psTimeoutMs?: number;
69
+ }
70
+ export declare function reapOrphans(opts: Omit<ReapOpts, 'signal'> & {
71
+ reapTimeoutMs?: number;
39
72
  }): Promise<ReapResult>;
73
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-copilot-delegate",
3
- "version": "0.3.0",
3
+ "version": "0.5.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",