cursor-delegate-mcp 3.1.1 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,55 @@ All notable changes to this project are documented here. The format follows
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [3.2.0] - 2026-11-24
10
+
11
+ ### Changed
12
+
13
+ - A stop kills cursor-agent's process tree once and waits up to 5 s for cursor-agent to exit; on
14
+ Windows `taskkill` first gets up to 5 s of its own. A stop that cannot confirm the exit is final,
15
+ and the result warns `the bridge stopped cursor-agent (pid <pid>) but could not confirm that
16
+ cursor-agent and its processes exited; they may still be running.`, where it said the bridge did
17
+ not see cursor-agent exit and a later stop tried again.
18
+ - A force cancel whose kill cannot confirm the exit reports `cancelled`, and the session is no
19
+ longer kept for another force.
20
+ - Shutdown stops every agent, waits for the stops, and exits with the code of whatever triggered it
21
+ first. SIGINT, SIGTERM and SIGHUP trigger it on Windows too. A later signal waits for the same
22
+ stop, where a second signal killed each agent's process group and exited at once.
23
+ - A stopped task's status message carries a note only when the run started a fresh session after a
24
+ failed resume. A stop that cannot confirm cursor-agent exited is reported in the delegate result's
25
+ `protocolWarnings`.
26
+ - An `agent-error` message ends with the request and JSON-RPC code cursor-agent answered with, as in
27
+ `(session/new JSON-RPC -32603)`, and so does the note of a resume that failed for a session that
28
+ still exists. The skill reference describes `agent-error` as an error answer named with its code,
29
+ where it called every such code a rejected argument.
30
+ - The `model` field and the skill reference name only the default model and point to
31
+ `doctor deep:true` for the ids an account offers.
32
+
33
+ ### Removed
34
+
35
+ - `CURSOR_DELEGATE_IDLE_MS`, the opt-in mid-turn idle guard (off by default), and its `idle-timeout`
36
+ reason. doctor no longer reports it.
37
+ - `ACP_LOG_SIZE`. The flight recorder keeps exactly the frames `CURSOR_DELEGATE_TRANSCRIPT` shows,
38
+ and records only while it is set. doctor no longer reports it.
39
+ - The protocol warning for each malformed plan or todo value. A plan entry or todo without string
40
+ content is still dropped, and a priority or status outside the ACP values still removed.
41
+
42
+ ### Fixed
43
+
44
+ - On Windows a `taskkill` that fails or runs past 5 s is followed by a kill of the launcher by its
45
+ handle, and the result warns that cursor-agent and its processes may still be running. A failed
46
+ `taskkill` went unreported.
47
+ - `resumeSessionId` is trimmed, and a blank one starts a new session, as in agy-delegate-mcp. Both
48
+ were sent to cursor-agent as given.
49
+
50
+ ### Internal
51
+
52
+ - `src/proc.js` and `src/shutdown.js` are the same in agy-delegate-mcp, cursor-delegate-mcp and
53
+ codex-delegate-mcp.
54
+ - `npm test` runs the test files named on the command line, without a deadline.
55
+ - The result and doctor shapes the tests check are in `test/output-shapes.js`.
56
+ - Tests of limits, options and source layout the code no longer has are removed.
57
+
9
58
  ## [3.1.1] - 2026-11-24
10
59
 
11
60
  ### Changed
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursor-delegate-mcp",
3
- "version": "3.1.1",
3
+ "version": "3.2.0",
4
4
  "mcpName": "io.github.andreilungeanu/cursor-delegate-mcp",
5
5
  "type": "module",
6
6
  "description": "Delegate multi-file coding work from Claude Code, Codex, Copilot, or any MCP client to Cursor's CLI agent — structured results, plan mode, and changed files.",
package/src/acp-client.js CHANGED
@@ -3,7 +3,7 @@ import { StringDecoder } from "node:string_decoder";
3
3
  import { JsonRpcPeer } from "./jsonrpc.js";
4
4
  import { createRequestRouter } from "./request-router.js";
5
5
  import { commandExists, resolveAcpSpawn } from "./spawn.js";
6
- import { children, isChildAlive, spawnChild } from "./proc.js";
6
+ import { children, isChildAlive, spawnChild, stopChild } from "./proc.js";
7
7
  import { VERSION } from "./version.js";
8
8
  import { makeError } from "./errors.js";
9
9
 
@@ -44,28 +44,20 @@ export class AcpClient extends EventEmitter {
44
44
  super();
45
45
  this.spawnSpec = spawnSpec || resolveAcpSpawn();
46
46
  this.registry = registry;
47
- /** @type {import("./proc.js").TrackedChild | null} */
48
- this._tracked = null;
47
+ /** @type {any} */
48
+ this._child = null;
49
49
  this.mode = mode;
50
50
  this.onCreatePlan = onCreatePlan;
51
51
  this.onTodos = onTodos;
52
- this._stderrChunks = [];
53
- this._stderrLength = 0;
52
+ // The stderr tail an exit error quotes; not counted as activity.
53
+ this.stderrBuffer = "";
54
54
  /** @type {Promise<boolean> | null} */
55
55
  this._stopping = null;
56
56
  /** @type {WirePhase} */
57
57
  this._phase = "setup";
58
58
  }
59
59
 
60
- get child() { return this._tracked?.child; }
61
-
62
- // The stderr tail an exit error quotes. Kept as chunks and joined on read, so a noisy agent costs
63
- // a push per chunk; a StringDecoder keeps a multi-byte character split across reads intact.
64
- // stderr is not ACP activity, so it does not feed the supervisor.
65
- get stderrBuffer() {
66
- const joined = this._stderrChunks.join("");
67
- return joined.length > STDERR_CAP ? joined.slice(-STDERR_CAP) : joined;
68
- }
60
+ get child() { return this._child; }
69
61
 
70
62
  async start() {
71
63
  const { command, args, options } = this.spawnSpec;
@@ -73,28 +65,12 @@ export class AcpClient extends EventEmitter {
73
65
  if (opts?.shell && !commandExists(command, opts.env)) {
74
66
  throw makeError("spawn-failed", `Failed to spawn agent (${command}): not found on PATH. Install Cursor CLI and run 'cursor-agent login'.`);
75
67
  }
76
- this._tracked = spawnChild(command, args, opts, { stdio: ["pipe", "pipe", "pipe"] }, this.registry);
77
- this._stderrChunks = [];
78
- this._stderrLength = 0;
68
+ this._child = spawnChild(command, args, opts, { stdio: ["pipe", "pipe", "pipe"] }, this.registry);
69
+ this.stderrBuffer = "";
70
+ // Keeps a UTF-8 character split across reads whole.
79
71
  const stderrDecoder = new StringDecoder("utf8");
80
72
  this.child.stderr.on("data", (chunk) => {
81
- const text = stderrDecoder.write(chunk);
82
- if (text) {
83
- this._stderrChunks.push(text);
84
- this._stderrLength += text.length;
85
- // Drop whole chunks from the front only once well past the cap, so the common case
86
- // costs one push. The joined tail is trimmed exactly on read.
87
- while (this._stderrChunks.length > 1 && this._stderrLength - this._stderrChunks[0].length >= STDERR_CAP) {
88
- this._stderrLength -= this._stderrChunks.shift().length;
89
- }
90
- // A single read larger than the cap (seen on GitHub Windows runners) is sliced too, so
91
- // retained memory stays bounded.
92
- const overflow = this._stderrLength - STDERR_CAP;
93
- if (overflow > 0) {
94
- this._stderrChunks[0] = this._stderrChunks[0].slice(overflow);
95
- this._stderrLength -= overflow;
96
- }
97
- }
73
+ this.stderrBuffer = (this.stderrBuffer + stderrDecoder.write(chunk)).slice(-STDERR_CAP);
98
74
  });
99
75
  this.child.stderr.on("error", () => {});
100
76
  // session/cancel can be written after the agent is gone, and an unhandled pipe 'error' would
@@ -200,36 +176,22 @@ export class AcpClient extends EventEmitter {
200
176
 
201
177
  getTranscript(n) { return this.peer ? this.peer.formatLog(n) : ""; }
202
178
 
203
- // Idempotent while teardown is in flight and after a confirmed exit. A missed exit is not
204
- // memoized, so a later stop kills again. A confirmed exit stays so later callers join.
205
- /** @param {{ timeoutMs?: number }} [opts] */
206
- stop({ timeoutMs } = {}) {
207
- if (!this._stopping) {
208
- this._stopping = this._teardown(timeoutMs).then((observed) => {
209
- if (!observed) this._stopping = null;
210
- return observed;
211
- }, (err) => {
212
- this._stopping = null;
213
- throw err;
214
- });
215
- }
179
+ // One stop per client, which every caller joins.
180
+ stop() {
181
+ this._stopping ??= this._teardown();
216
182
  return this._stopping;
217
183
  }
218
184
 
219
- async _teardown(timeoutMs) {
220
- const tracked = this._tracked;
221
- if (!tracked) {
185
+ async _teardown() {
186
+ const child = this._child;
187
+ if (!child) {
222
188
  try { this.peer?.close(); } catch {}
223
189
  return true;
224
190
  }
225
- const { child } = tracked;
226
- const observed = await tracked.stop({ timeoutMs });
227
- // On an observed exit, emitExit rejects in-flight RPCs with stderr, and racing it here would
228
- // drop that. Only a child still alive after the stop has its RPCs settled here.
229
- if (!observed && this._phase !== "exited" && isChildAlive(child)) {
230
- try {
231
- this.peer?.rejectAllPending(makeError("agent-exit", "agent process did not exit after stop"));
232
- } catch {}
191
+ const observed = await stopChild(child);
192
+ // On an exit, emitExit rejects in-flight RPCs with stderr; rejecting here first would lose it.
193
+ if (isChildAlive(child)) {
194
+ try { this.peer?.rejectAllPending(makeError("agent-exit", "agent process did not exit after stop")); } catch {}
233
195
  }
234
196
  try { this.peer?.close(); } catch {}
235
197
  return observed;
package/src/delegate.js CHANGED
@@ -19,10 +19,10 @@ export const DEFAULT_MODEL = "composer-2.5";
19
19
  // whose served model has to be read back off a config reply for effectiveModel.
20
20
  const ROUTED_MODEL = "default";
21
21
  export const DEFAULT_HANDSHAKE_MS = 60000;
22
- export const DEFAULT_HEARTBEAT_MS = 30000;
22
+ const DEFAULT_HEARTBEAT_MS = 30000;
23
23
 
24
24
  // A malformed or non-positive value falls back to the default, so a blank var (Number("") is 0)
25
- // cannot arm a zero-length deadline. The idle guard is off because its own fallback is 0.
25
+ // cannot arm a zero-length deadline.
26
26
  function envMs(name, fallback) {
27
27
  const raw = process.env[name];
28
28
  if (raw === undefined) return fallback;
@@ -145,6 +145,12 @@ function isMissingSession(err) {
145
145
  && /\bnot found\b|\bdoes not exist\b|\bunknown session\b|\bno such session\b/i.test(message);
146
146
  }
147
147
 
148
+ // The request and code of an error the agent answered with, as " (session/new JSON-RPC -32603)"; else "".
149
+ function rpcNote(err) {
150
+ if (err?.reason || typeof err?.code !== "number") return "";
151
+ return ` (${err.method ? `${err.method} ` : ""}JSON-RPC ${err.code})`;
152
+ }
153
+
148
154
  async function openSession(client, resumeSessionId, workspace) {
149
155
  if (!resumeSessionId) return client.newSession(workspace);
150
156
  try {
@@ -154,7 +160,7 @@ async function openSession(client, resumeSessionId, workspace) {
154
160
  if (!isMissingSession(err)) {
155
161
  throw makeError(
156
162
  "resume-failed",
157
- `session ${resumeSessionId} could not be loaded: ${err?.message || String(err)}.`
163
+ `session ${resumeSessionId} could not be loaded: ${err?.message || String(err)}${rpcNote(err)}.`
158
164
  + ` The session was not resumed and no fresh session was started — retry, or omit`
159
165
  + ` resumeSessionId to start fresh deliberately.`
160
166
  );
@@ -248,10 +254,9 @@ async function applyEffort(client, sessionId, model, value, modelOptions) {
248
254
  * spec?: string, mode?: string, resumeSessionId?: string, workspace?: string,
249
255
  * model?: string, fast?: boolean, effort?: string, context?: string,
250
256
  * contextFiles?: string[], clientFactory?: (opts: any) => any,
251
- * idleMs?: number, handshakeMs?: number, hardCapMs?: number, timeoutMs?: number,
257
+ * handshakeMs?: number, hardCapMs?: number, timeoutMs?: number,
252
258
  * onSessionReady?: (sessionId: string, client: any) => void,
253
259
  * onPromptSent?: (sessionId: string, resumeNote?: string) => void,
254
- * onUnseenExit?: (note: string) => void,
255
260
  * onTurnEnd?: () => void,
256
261
  * onProgress?: (message: string) => void,
257
262
  * progressThrottleMs?: number, heartbeatMs?: number, signal?: AbortSignal,
@@ -260,8 +265,8 @@ async function applyEffort(client, sessionId, model, value, modelOptions) {
260
265
  export async function runDelegate({
261
266
  spec, mode = "agent", resumeSessionId, workspace,
262
267
  model = DEFAULT_MODEL, fast = false, effort, context, contextFiles, clientFactory,
263
- idleMs, handshakeMs, hardCapMs, timeoutMs,
264
- onSessionReady, onPromptSent, onUnseenExit, onTurnEnd, onProgress, progressThrottleMs = 2000,
268
+ handshakeMs, hardCapMs, timeoutMs,
269
+ onSessionReady, onPromptSent, onTurnEnd, onProgress, progressThrottleMs = 2000,
265
270
  heartbeatMs = DEFAULT_HEARTBEAT_MS,
266
271
  signal,
267
272
  } = {}) {
@@ -277,56 +282,27 @@ export async function runDelegate({
277
282
  const promptText = spec;
278
283
  const capMs = hardCapMs ?? timeoutMs ?? envMs("CURSOR_DELEGATE_HARD_CAP_MS", DEFAULT_HARD_CAP_MS);
279
284
  const shakeMs = handshakeMs ?? envMs("CURSOR_DELEGATE_HANDSHAKE_MS", DEFAULT_HANDSHAKE_MS);
280
- const turnIdleMs = idleMs ?? envMs("CURSOR_DELEGATE_IDLE_MS", 0);
281
285
  const state = makeTurnState({ onProgress, progressThrottleMs });
282
286
 
283
- // ACP requires string plan content and bounds priority/status. A frame that violates that must
284
- // not fail the MCP call after the work is done — drop the bad data, report it as a diagnostic.
285
- const sanitizePlan = (warnings) => {
286
- const entries = [];
287
- state.planEntries.forEach((raw, i) => {
288
- if (typeof raw?.content !== "string") {
289
- warnings.push(`plan entry ${i} dropped: ACP requires string content, got ${raw === null ? "null" : typeof raw?.content}`);
290
- return;
291
- }
287
+ // ACP requires string plan content and bounds priority and status. An entry without text is
288
+ // dropped and a value outside the bounds removed, so the result keeps its shape.
289
+ const sanitizePlan = () => {
290
+ const entries = state.planEntries.filter((raw) => typeof raw?.content === "string").map((raw) => {
292
291
  const entry = { ...raw };
293
- if (entry.priority !== undefined && !PLAN_PRIORITIES.includes(entry.priority)) {
294
- warnings.push(`plan entry ${i}: non-ACP priority ${JSON.stringify(entry.priority)} removed`);
295
- delete entry.priority;
296
- }
297
- if (entry.status !== undefined && !PLAN_STATUSES.includes(entry.status)) {
298
- warnings.push(`plan entry ${i}: non-ACP status ${JSON.stringify(entry.status)} removed`);
299
- delete entry.status;
300
- }
301
- entries.push(entry);
292
+ if (!PLAN_PRIORITIES.includes(entry.priority)) delete entry.priority;
293
+ if (!PLAN_STATUSES.includes(entry.status)) delete entry.status;
294
+ return entry;
302
295
  });
303
296
  const plan = { entries };
304
- if (state.planOverview !== undefined) {
305
- if (typeof state.planOverview === "string") plan.overview = state.planOverview;
306
- else warnings.push("plan overview dropped: expected string");
307
- }
308
- if (state.planDetail !== undefined) {
309
- if (typeof state.planDetail === "string") plan.detail = state.planDetail;
310
- else warnings.push("plan detail dropped: expected string");
311
- }
297
+ if (typeof state.planOverview === "string") plan.overview = state.planOverview;
298
+ if (typeof state.planDetail === "string") plan.detail = state.planDetail;
312
299
  return plan;
313
300
  };
314
301
 
315
- const sanitizeTodos = (warnings) => {
316
- const entries = [];
317
- let i = -1;
318
- for (const raw of state.todos.values()) {
319
- i++;
320
- if (typeof raw?.content !== "string") {
321
- warnings.push(`todo ${i} dropped: expected string content, got ${raw === null ? "null" : typeof raw?.content}`);
322
- continue;
323
- }
324
- const status = TODO_STATUSES.includes(raw.status) ? raw.status : undefined;
325
- if (raw.status !== undefined && status === undefined) {
326
- warnings.push(`todo ${i}: unknown status ${JSON.stringify(raw.status)} removed`);
327
- }
328
- entries.push({ id: String(raw.id), content: raw.content, ...(status ? { status } : {}) });
329
- }
302
+ const sanitizeTodos = () => {
303
+ const entries = [...state.todos.values()]
304
+ .filter((raw) => typeof raw?.content === "string")
305
+ .map((raw) => ({ id: String(raw.id), content: raw.content, ...(TODO_STATUSES.includes(raw.status) ? { status: raw.status } : {}) }));
330
306
  const count = (s) => entries.filter((e) => e.status === s).length;
331
307
  return {
332
308
  todos: entries,
@@ -342,7 +318,7 @@ export async function runDelegate({
342
318
 
343
319
  const make = clientFactory || ((opts) => new AcpClient(opts));
344
320
  const client = make({ mode, onCreatePlan: state.recordCreatePlan, onTodos: state.recordTodos });
345
- const supervisor = new SessionSupervisor(client, { idleMs: turnIdleMs, handshakeMs: shakeMs, hardCapMs: capMs });
321
+ const supervisor = new SessionSupervisor(client, { handshakeMs: shakeMs, hardCapMs: capMs });
346
322
  const onAbort = () => supervisor.abort();
347
323
  signal?.addEventListener("abort", onAbort, { once: true });
348
324
 
@@ -453,7 +429,7 @@ export async function runDelegate({
453
429
  let servedModel;
454
430
  let effectiveEffort;
455
431
  const contextWarnings = [];
456
- // Set before the teardown in finally, which notes an unseen exit on whichever is going out.
432
+ // Set before the teardown in finally, which notes an unconfirmed stop on whichever is going out.
457
433
  /** @type {any} */
458
434
  let out;
459
435
  /** @type {{ cause: any, reason?: string, notes: string[] } | undefined} */
@@ -581,17 +557,15 @@ export async function runDelegate({
581
557
  protocolWarnings.push(...contextWarnings);
582
558
  protocolWarnings.push(...frameWarnings);
583
559
  if (state.planEntries.length > 0 || state.planOverview !== undefined || state.planDetail !== undefined) {
584
- // Sanitized even when dropped: its warnings report malformed frames in any mode.
585
- const plan = sanitizePlan(protocolWarnings);
586
560
  // In plan/ask the result is the plan in prose; entries would put the same steps in context
587
561
  // twice, and the implementing resume reads the session, not this field. In agent mode the
588
562
  // result is the implementation report, so the plan stays.
589
- if (!dropPlan) out.plan = plan;
563
+ if (!dropPlan) out.plan = sanitizePlan();
590
564
  }
591
565
  // Only when the agent tracked todos: an empty list would read as "nothing done". The list
592
566
  // itself only while items remain; once all are done it restates the counts.
593
567
  if (state.sawTodoFrame) {
594
- const { todos: todoList, todoProgress } = sanitizeTodos(protocolWarnings);
568
+ const { todos: todoList, todoProgress } = sanitizeTodos();
595
569
  out.todoProgress = todoProgress;
596
570
  if (todoProgress.completed < todoProgress.total) out.todos = todoList;
597
571
  }
@@ -605,14 +579,16 @@ export async function runDelegate({
605
579
  if (resumeError) out.protocolWarnings = [`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`];
606
580
  return out;
607
581
  }
608
- // A JSON-RPC code means the agent rejected something rather than the bridge breaking — the
609
- // distinction a caller needs to tell "fix your arguments" from "retry".
610
- const reason = err?.reason || (typeof err?.code === "number" ? "agent-error" : undefined);
582
+ // A JSON-RPC code means the agent answered with an error, not that the bridge broke: a rejected
583
+ // argument (-32602) or a failure of its own (-32603).
584
+ const fromAgent = !err?.reason && typeof err?.code === "number";
585
+ const reason = err?.reason || (fromAgent ? "agent-error" : undefined);
611
586
  failure = { cause: err, reason, notes: [] };
612
587
  const { notes } = failure;
588
+ if (fromAgent) notes.push(rpcNote(err));
613
589
  // A bare duration cannot distinguish a wedged agent from a slow command, so name what was
614
590
  // outstanding — it also lets a retry resume the work already done.
615
- const isTimeout = reason === "hard-cap" || reason === "idle-timeout";
591
+ const isTimeout = reason === "hard-cap";
616
592
  // A handshake timeout gets the forensics but not the long-command advice: no prompt was sent,
617
593
  // so no shell command explains the silence.
618
594
  const isStall = isTimeout || reason === "handshake-timeout";
@@ -623,7 +599,7 @@ export async function runDelegate({
623
599
  notes.push(`\n\nLast ACP frame ${age} ago${state.lastToolLabel ? `; last tool call: ${state.lastToolLabel}` : ""}.`);
624
600
  if (state.sessionTitle) notes.push(` The agent titled this turn ${JSON.stringify(state.sessionTitle)}.`);
625
601
  if (state.sawTodoFrame) {
626
- const { todoProgress } = sanitizeTodos([]);
602
+ const { todoProgress } = sanitizeTodos();
627
603
  const current = state.todoLabel();
628
604
  notes.push(` ${todoProgress.completed} of ${todoProgress.total} todos completed${current ? `; ${current}` : ""}.`);
629
605
  }
@@ -635,10 +611,8 @@ export async function runDelegate({
635
611
  // config value included, not just the stalls.
636
612
  if (sessionId) notes.push(` Resume with resumeSessionId ${sessionId}.`);
637
613
  if (isTimeout) {
638
- // Name the knob that fired: the hard cap does nothing for an idle-timeout.
639
- const knob = reason === "idle-timeout" ? "CURSOR_DELEGATE_IDLE_MS" : "CURSOR_DELEGATE_HARD_CAP_MS";
640
614
  notes.push(" cursor-agent does not stream shell output over ACP, so a long-running command emits"
641
- + ` nothing until it exits. Split the command, run it in the background and poll, or raise ${knob}.`);
615
+ + " nothing until it exits. Split the command, run it in the background and poll, or raise CURSOR_DELEGATE_HARD_CAP_MS.");
642
616
  }
643
617
  // Opt-in: raw frames add nothing actionable to the caller's context beyond the forensics
644
618
  // above; they help only someone debugging the bridge.
@@ -656,16 +630,13 @@ export async function runDelegate({
656
630
  signal?.removeEventListener("abort", onAbort);
657
631
  try { supervisor.finish(); } catch {}
658
632
  // Awaited: a host may close stdin on the result, and on Windows the server's exit does not take
659
- // a running agent with it (server.smoke.test.js). An exit not seen is noted instead, as is a
660
- // stop that rejects.
661
- let exited = false;
662
- try { exited = await client.stop(); } catch {}
633
+ // a running agent with it (server.smoke.test.js). A stop that cannot confirm the exit is noted.
634
+ const exited = await client.stop();
663
635
  if (exited === false) {
664
636
  const pid = client.child?.pid;
665
- const note = `the bridge stopped cursor-agent${pid ? ` (pid ${pid})` : ""} but did not see it exit; it may still be running.`;
637
+ const note = `the bridge stopped cursor-agent${pid ? ` (pid ${pid})` : ""} but could not confirm that cursor-agent and its processes exited; they may still be running.`;
666
638
  if (failure) failure.notes.push(` Note: ${note}`);
667
639
  else if (out) (out.protocolWarnings ??= []).push(note);
668
- try { onUnseenExit?.(note); } catch {}
669
640
  }
670
641
  }
671
642
  // After teardown, so the exit note it adds is in the message.
package/src/doctor.js CHANGED
@@ -2,14 +2,12 @@ import process from "node:process";
2
2
  import { existsSync } from "node:fs";
3
3
  import { AcpClient } from "./acp-client.js";
4
4
  import { commandExists, resolveAcpSpawn } from "./spawn.js";
5
- import { children, spawnChild } from "./proc.js";
5
+ import { children, spawnChild, stopChild } from "./proc.js";
6
6
  import { readPackageVersion } from "./version.js";
7
7
  import { describeOptions } from "./model-options.js";
8
8
 
9
9
  const HANDSHAKE_TIMEOUT_MS = 15_000;
10
10
  const VERSION_PROBE_TIMEOUT_MS = 10_000;
11
- const PROBE_STDOUT_CAP = 64 * 1024;
12
- const DEFAULT_LOG_SIZE = "2000";
13
11
 
14
12
  function formatArg(value) {
15
13
  const s = String(value);
@@ -54,60 +52,35 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
54
52
  // Interrupted already, or shutting down: nothing is spawned, and found comes from the lookup alone.
55
53
  const notRun = (error) => Promise.resolve({ found: isJsScript ? existsSync(launcher) : commandExists(launcher, options?.env), version: null, error });
56
54
  if (signal?.aborted) return notRun(aborted.error);
57
- let probe;
55
+ let child;
58
56
  try {
59
- probe = spawnChild(execCommand, execArgs, options, { stdio: ["ignore", "pipe", "pipe"] }, registry);
57
+ child = spawnChild(execCommand, execArgs, options, { stdio: ["ignore", "pipe", "pipe"] }, registry);
60
58
  } catch (err) {
61
59
  return notRun(err.message);
62
60
  }
63
- const { child } = probe;
64
61
  return new Promise((resolve) => {
65
- let settled = false;
66
- let aborting = false;
67
62
  let stdout = "";
68
- let timer;
69
63
  const finish = (result) => {
70
- if (settled) return;
71
- settled = true;
72
64
  clearTimeout(timer);
73
65
  signal?.removeEventListener("abort", onAbort);
74
66
  resolve(result);
75
67
  };
76
- // Settles once the stop saw the probe exit, so doctor does not return with it running.
77
- const onAbort = () => {
78
- // Else it fires during the kill and reports a timeout.
79
- clearTimeout(timer);
80
- aborting = true;
81
- probe.stop().then(() => finish({ found: true, ...aborted }));
82
- };
83
- signal?.addEventListener("abort", onAbort, { once: true });
84
- // Capped: a version is one line, and a launcher that streams is not kept whole.
85
- child.stdout?.on("data", (chunk) => {
86
- if (stdout.length < PROBE_STDOUT_CAP) stdout += chunk.toString();
87
- });
88
- // Drained: a full stderr pipe blocks the launcher, and a noisy one would read as wedged.
89
- child.stderr?.on("data", () => {});
90
- child.stderr?.on("error", () => {});
68
+ child.stdout.on("data", (chunk) => { stdout += chunk; });
69
+ // Drained: a full pipe blocks a noisy launcher, which would then read as a timeout.
70
+ child.stderr.on("data", () => {});
71
+ child.stderr.on("error", () => {});
91
72
  child.on("error", () => finish({ found: false, version: null }));
92
- child.on("close", (code) => {
93
- // Closed: its pid may be reused, so no later stop may kill it.
94
- probe.release();
95
- // An aborted probe reports the abort, not the exit its kill caused.
96
- if (aborting) return;
97
- const version = code === 0 ? stdout.trim() || null : null;
98
- finish({
99
- found: true,
100
- version,
101
- ...(code !== 0 ? { error: `version probe exited ${code}` } : {}),
102
- });
103
- });
104
- timer = setTimeout(() => {
105
- // Not awaited, so the timeout returns on time; the probe stays tracked until its stop settles.
106
- probe.stop();
107
- // It spawned, so it is found; it just never answered.
73
+ child.on("close", (code) => finish(code === 0 ? { found: true, version: stdout.trim() || null } : { found: true, version: null, error: `version probe exited ${code}` }));
74
+ // It spawned, so it is installed; it did not answer.
75
+ const timer = setTimeout(() => {
76
+ stopChild(child);
108
77
  finish({ found: true, version: null, error: `version probe timed out after ${timeoutMs}ms` });
109
78
  }, timeoutMs);
110
- timer.unref?.();
79
+ const onAbort = () => {
80
+ stopChild(child);
81
+ finish({ found: true, ...aborted });
82
+ };
83
+ signal?.addEventListener("abort", onAbort, { once: true });
111
84
  });
112
85
  }
113
86
 
@@ -210,13 +183,11 @@ export async function runDoctor({
210
183
  transport: "stdio",
211
184
  },
212
185
  env: {
213
- ACP_LOG_SIZE: envReport("ACP_LOG_SIZE", DEFAULT_LOG_SIZE),
214
186
  ACP_AGENT_COMMAND: envReport("ACP_AGENT_COMMAND"),
215
187
  ACP_AGENT_ARGS: envReport("ACP_AGENT_ARGS"),
216
188
  CURSOR_DELEGATE_TRANSCRIPT: envReport("CURSOR_DELEGATE_TRANSCRIPT"),
217
189
  CURSOR_DELEGATE_HANDSHAKE_MS: envReport("CURSOR_DELEGATE_HANDSHAKE_MS"),
218
190
  CURSOR_DELEGATE_HARD_CAP_MS: envReport("CURSOR_DELEGATE_HARD_CAP_MS"),
219
- CURSOR_DELEGATE_IDLE_MS: envReport("CURSOR_DELEGATE_IDLE_MS"),
220
191
  },
221
192
  };
222
193
 
package/src/errors.js CHANGED
@@ -3,19 +3,20 @@
3
3
  * without parsing prose. Errors off the wire also carry the agent's JSON-RPC `code`. A note goes on
4
4
  * a new error with the old one as its `cause`: a caught error may be frozen or a primitive.
5
5
  *
6
- * @typedef {Error & { reason?: string, code?: number }} DelegateError
6
+ * @typedef {Error & { reason?: string, code?: number, method?: string }} DelegateError
7
7
  */
8
8
 
9
9
  /**
10
10
  * @param {string | undefined} reason
11
11
  * @param {string} message
12
- * @param {{ code?: number, cause?: unknown }} [extra]
12
+ * @param {{ code?: number, method?: string, cause?: unknown }} [extra]
13
13
  * @returns {Readonly<DelegateError>}
14
14
  */
15
- export function makeError(reason, message, { code, cause } = {}) {
15
+ export function makeError(reason, message, { code, method, cause } = {}) {
16
16
  /** @type {DelegateError} */
17
17
  const err = new Error(message, cause === undefined ? undefined : { cause });
18
18
  if (reason !== undefined) err.reason = reason;
19
19
  if (code !== undefined) err.code = code;
20
+ if (method !== undefined) err.method = method;
20
21
  return err;
21
22
  }
package/src/jsonrpc.js CHANGED
@@ -2,17 +2,8 @@ import readline from "node:readline";
2
2
  import { makeError } from "./errors.js";
3
3
 
4
4
  const FRAME_CAP = 2048;
5
- const DEFAULT_LOG_SIZE = 2000;
6
5
 
7
- function readLogSize(raw) {
8
- if (raw === undefined) return DEFAULT_LOG_SIZE;
9
- const n = Number(raw);
10
- if (!Number.isFinite(n) || n < 0) return DEFAULT_LOG_SIZE;
11
- return Math.floor(n);
12
- }
13
-
14
- // Depth for an unparseable CURSOR_DELEGATE_TRANSCRIPT. Not DEFAULT_LOG_SIZE: that bounds memory,
15
- // this bounds what lands in the caller's context, so keep it near the old 40-frame dump.
6
+ // Depth for an unparseable CURSOR_DELEGATE_TRANSCRIPT; it bounds what lands in the caller's context.
16
7
  const TRANSCRIPT_DEFAULT_FRAMES = 50;
17
8
 
18
9
  // Frames CURSOR_DELEGATE_TRANSCRIPT asks for: unset or blank is none, a number is the count
@@ -41,10 +32,8 @@ export class JsonRpcPeer {
41
32
  this.onActivity = onActivity || (() => {});
42
33
  this.nextId = 1;
43
34
  this.pending = new Map();
44
- // 0 disables recording; an unparseable value is a typo and keeps the default.
45
- this._logSize = readLogSize(process.env.ACP_LOG_SIZE);
46
- // Only the opt-in failure transcript reads these frames, so record only when it is on.
47
- this._recording = this._logSize > 0 && transcriptFrames() > 0;
35
+ // Only the opt-in failure transcript reads these frames, so only as many as it shows are kept.
36
+ this._logSize = transcriptFrames();
48
37
  this._log = [];
49
38
  this.rl = readline.createInterface({ input });
50
39
  // readline re-emits the stream's error as its own, which acp-client's stdout handler does not
@@ -53,25 +42,16 @@ export class JsonRpcPeer {
53
42
  this.rl.on("line", (line) => this._onLine(line));
54
43
  }
55
44
 
56
- // Overshoots by a quarter and trims in one batch, rather than shifting the array per frame;
57
- // readers take the last _logSize.
58
45
  _record(dir, line) {
59
- if (!this._recording) return;
60
- const truncated = line.length > FRAME_CAP ? line.slice(0, FRAME_CAP) : line;
61
- this._log.push({ t: Date.now(), dir, line: truncated });
62
- if (this._log.length > this._logSize + (this._logSize >> 2)) {
63
- this._log = this._log.slice(-this._logSize);
64
- }
65
- }
66
-
67
- _entries() {
68
- return this._log.length > this._logSize ? this._log.slice(-this._logSize) : this._log;
46
+ if (!this._logSize) return;
47
+ this._log.push({ t: Date.now(), dir, line: line.length > FRAME_CAP ? line.slice(0, FRAME_CAP) : line });
48
+ if (this._log.length > this._logSize) this._log.shift();
69
49
  }
70
50
 
71
- getLog() { return [...this._entries()]; }
51
+ getLog() { return [...this._log]; }
72
52
 
73
53
  formatLog(n) {
74
- const entries = n !== undefined ? this._entries().slice(-n) : this._entries();
54
+ const entries = n !== undefined ? this._log.slice(-n) : this._log;
75
55
  return entries.map((e) => `${new Date(e.t).toISOString()} ${e.dir} ${e.line}`).join("\n");
76
56
  }
77
57
 
@@ -81,8 +61,7 @@ export class JsonRpcPeer {
81
61
  let msg;
82
62
  try { msg = JSON.parse(line); } catch { return; }
83
63
  if (msg === null || typeof msg !== "object" || Array.isArray(msg)) return;
84
- // Only a parsed frame is activity; a blank line or launcher banner must not hold the idle
85
- // guard open.
64
+ // Only a parsed frame is activity; a blank line or launcher banner is not.
86
65
  this.onActivity();
87
66
  const hasId = msg.id !== undefined && msg.id !== null;
88
67
  if (hasId && (msg.result !== undefined || msg.error !== undefined)) {
@@ -93,7 +72,7 @@ export class JsonRpcPeer {
93
72
  this.pending.delete(key);
94
73
  // cursor-agent puts the reason in error.data.message; error.message is a bare "Invalid params".
95
74
  if (msg.error) {
96
- p.reject(makeError(undefined, [msg.error.message || "rpc error", msg.error.data?.message].filter(Boolean).join(": "), { code: msg.error.code }));
75
+ p.reject(makeError(undefined, [msg.error.message || "rpc error", msg.error.data?.message].filter(Boolean).join(": "), { code: msg.error.code, method: p.method }));
97
76
  }
98
77
  else p.resolve(msg.result);
99
78
  }
@@ -113,7 +92,7 @@ export class JsonRpcPeer {
113
92
  request(method, params) {
114
93
  const id = this.nextId++;
115
94
  return new Promise((resolve, reject) => {
116
- this.pending.set(String(id), { resolve, reject });
95
+ this.pending.set(String(id), { resolve, reject, method });
117
96
  this._write({ jsonrpc: "2.0", id, method, params });
118
97
  });
119
98
  }
package/src/proc.js CHANGED
@@ -7,108 +7,124 @@ export function isChildAlive(child) {
7
7
  return child && child.exitCode === null && child.signalCode === null;
8
8
  }
9
9
 
10
- // POSIX only: a process group leader (setsid) lets treeKill reach the agent's children. On win32
11
- // it would mean a new console, and taskkill /T walks the tree anyway. Applied in spawnChild, not
12
- // in resolveAcpSpawn, so an injected spec gets it too.
10
+ // POSIX only: detached makes the child a process group leader, so treeKill reaches its children.
11
+ // On win32 it would open a separate console, and taskkill /T walks the tree.
13
12
  export const DETACHED = process.platform !== "win32";
14
13
 
15
- // On win32 child.kill() reaches only the wrapper; taskkill /T takes the whole tree.
14
+ // How long taskkill may run, and then how long a stop waits for the exit.
15
+ export const KILL_WAIT_MS = 5000;
16
+
17
+ // Every process below pid, from one ps snapshot. Empty when ps fails: the group kill still runs.
18
+ function descendantPids(pid) {
19
+ return /** @type {Promise<number[]>} */ (new Promise((resolve) => {
20
+ execFile("ps", ["-A", "-o", "pid=,ppid="], { timeout: 3000 }, (err, stdout) => {
21
+ if (err) return resolve([]);
22
+ /** @type {Map<number, number[]>} */
23
+ const byParent = new Map();
24
+ for (const line of String(stdout).split("\n")) {
25
+ const [p, pp] = line.trim().split(/\s+/).map(Number);
26
+ if (!p || !Number.isFinite(pp)) continue;
27
+ if (!byParent.has(pp)) byParent.set(pp, []);
28
+ byParent.get(pp)?.push(p);
29
+ }
30
+ const out = [];
31
+ const queue = [pid];
32
+ while (queue.length) {
33
+ for (const c of byParent.get(queue.shift()) ?? []) {
34
+ if (!out.includes(c)) { out.push(c); queue.push(c); }
35
+ }
36
+ }
37
+ resolve(out);
38
+ });
39
+ }));
40
+ }
41
+
42
+ // On win32 a plain kill reaches only the launcher; taskkill /T takes the tree. False when taskkill
43
+ // failed or stalled. Its 128 is a process that ended before taskkill reached it: the launcher, or a
44
+ // short-lived command during the walk (measured).
16
45
  export async function treeKill(pid, { childAlive = true } = {}) {
17
- if (!pid) return;
46
+ if (!pid) return true;
18
47
  if (process.platform === "win32") {
19
- // taskkill /T follows parent links, which an exited leader no longer has, and a reaped pid can
20
- // already belong to another process: after the exit there is nothing safe to kill.
21
- if (!childAlive) return;
22
- await /** @type {Promise<void>} */ (new Promise((resolve) => {
23
- execFile("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true }, () => resolve());
48
+ // An exited leader has no tree left for taskkill to walk, and its pid may be reused.
49
+ if (!childAlive) return true;
50
+ return /** @type {Promise<boolean>} */ (new Promise((resolve) => {
51
+ execFile("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true, timeout: KILL_WAIT_MS, killSignal: "SIGKILL" }, (err) => resolve(!err || err.code === 128));
24
52
  }));
25
- return;
26
53
  }
27
- // The negative pid signals the whole group, which outlives its leader, so this runs even after
28
- // the child exited: its descendants may still be running.
54
+ // Commands in a session of their own are outside the group: walked while the child is alive to
55
+ // hold their parent links.
56
+ const descendants = childAlive ? await descendantPids(pid) : [];
57
+ // The group, even after the leader exited: members can outlive it.
29
58
  try { process.kill(-pid, "SIGKILL"); } catch {}
30
- // Reaches a child that is not a group leader, where the group kill raised ESRCH. Skipped once
31
- // the child is gone, since a reaped pid can already belong to something else.
59
+ for (const d of descendants) {
60
+ try { process.kill(-d, "SIGKILL"); } catch {}
61
+ try { process.kill(d, "SIGKILL"); } catch {}
62
+ }
63
+ // A child that is not a group leader; skipped once reaped, as its pid may be reused.
32
64
  if (childAlive) { try { process.kill(pid, "SIGKILL"); } catch {} }
65
+ return true;
33
66
  }
34
67
 
35
- // How long one kill attempt waits for the exit and the tree kill. SIGKILL and taskkill /F land in
36
- // milliseconds, so this elapses only when the kill failed.
37
- export const KILL_WAIT_MS = 2000;
68
+ /** @type {WeakMap<object, Promise<boolean>>} */
69
+ const stops = new WeakMap();
38
70
 
39
- async function killAndSeeExit(child, timeoutMs) {
71
+ /**
72
+ * Kills child's tree, its own handle too when the tree kill fails, and waits for the exit within
73
+ * KILL_WAIT_MS. True when the exit was seen and the tree kill succeeded. Once per child: every later
74
+ * call gets the same promise.
75
+ * @param {any} child
76
+ * @returns {Promise<boolean>}
77
+ */
78
+ export function stopChild(child) {
79
+ let stop = stops.get(child);
80
+ if (!stop) {
81
+ stop = killAndWait(child);
82
+ stops.set(child, stop);
83
+ }
84
+ return stop;
85
+ }
86
+
87
+ async function killAndWait(child) {
40
88
  if (!child.pid) return true;
41
89
  const alive = isChildAlive(child);
42
- // Subscribed before the kill, so an instant exit is not missed.
43
- const exited = alive
44
- ? /** @type {Promise<boolean>} */ (new Promise((resolve) => child.once("exit", () => resolve(true))))
45
- : Promise.resolve(true);
46
- // Runs for an exited child too: on POSIX the commands it spawned stay in its process group.
47
- const killed = treeKill(child.pid, { childAlive: alive }).catch(() => {});
48
- /** @type {NodeJS.Timeout | undefined} */
49
- let timer;
50
- const bounded = /** @type {Promise<boolean>} */ (new Promise((resolve) => {
51
- timer = setTimeout(() => resolve(false), timeoutMs);
52
- }));
53
- const observed = await Promise.race([exited, bounded]);
54
- // On win32 taskkill can still be at work on the tree once the launcher's exit is seen.
55
- const treeKilled = await Promise.race([killed.then(() => true), bounded]);
56
- clearTimeout(timer);
57
- return observed && treeKilled;
90
+ // Subscribed before the kill, so an immediate exit is not missed.
91
+ const exited = alive ? new Promise((resolve) => child.once("exit", () => resolve(true))) : Promise.resolve(true);
92
+ const tidy = await treeKill(child.pid, { childAlive: alive }).catch(() => false);
93
+ if (!tidy && isChildAlive(child)) { try { child.kill("SIGKILL"); } catch {} }
94
+ return (await withDeadline(exited, KILL_WAIT_MS, false)) && tidy;
58
95
  }
59
96
 
60
97
  /**
61
- * @typedef {{
62
- * child: any,
63
- * stop: (opts?: { timeoutMs?: number }) => Promise<boolean>,
64
- * release: () => void,
65
- * }} TrackedChild
66
- * @typedef {{ child?: any, kill: (timeoutMs: number) => Promise<boolean> }} ChildKill
67
- * @typedef {ReturnType<typeof createChildRegistry>} ChildRegistry
98
+ * promise's value, or fallback once ms have passed.
99
+ * @template T @param {Promise<T>} promise @param {number} ms @param {T} fallback @returns {Promise<T>}
68
100
  */
101
+ export function withDeadline(promise, ms, fallback) {
102
+ /** @type {NodeJS.Timeout | undefined} */
103
+ let timer;
104
+ const deadline = new Promise((resolve) => { timer = setTimeout(() => resolve(fallback), ms); });
105
+ return Promise.race([promise, deadline]).finally(() => clearTimeout(timer));
106
+ }
107
+
108
+ /** @typedef {ReturnType<typeof createChildRegistry>} ChildRegistry */
69
109
 
70
- // The processes still to stop. An entry leaves once a stop saw its exit and its tree kill ended, or
71
- // its owner releases it; after that its pid may be reused.
110
+ // The processes shutdown stops. A child leaves when it exits, as its pid may then be reused.
72
111
  export function createChildRegistry() {
73
- /** @type {Set<TrackedChild>} */
112
+ /** @type {Set<any>} */
74
113
  const live = new Set();
75
114
  let closed = false;
76
115
  return {
77
- /**
78
- * @param {() => ChildKill} start
79
- * @returns {TrackedChild}
80
- */
116
+ /** @param {() => any} start a spawned child, or null */
81
117
  track(start) {
82
118
  if (closed) throw makeError("spawn-failed", "the server is shutting down, so no process was started");
83
- const kill = start();
84
- /** @type {Promise<boolean> | null} */
85
- let stopping = null;
86
- const attempt = (timeoutMs) => {
87
- try { return Promise.resolve(kill.kill(timeoutMs)).catch(() => false); } catch { return Promise.resolve(false); }
88
- };
89
- /** @type {TrackedChild} */
90
- const entry = {
91
- child: kill.child,
92
- // An attempt that missed the exit is retried once; a later stop kills again.
93
- stop: ({ timeoutMs = KILL_WAIT_MS } = {}) => {
94
- if (!live.has(entry)) return Promise.resolve(true);
95
- stopping ??= attempt(timeoutMs).then((seen) => seen || attempt(timeoutMs)).then((seen) => {
96
- stopping = null;
97
- if (seen) live.delete(entry);
98
- return seen;
99
- });
100
- return stopping;
101
- },
102
- // For a child that closed by itself.
103
- release: () => { if (!stopping) live.delete(entry); },
104
- };
105
- live.add(entry);
106
- return entry;
119
+ const child = start();
120
+ if (!child) return null;
121
+ live.add(child);
122
+ child.once("exit", () => live.delete(child));
123
+ return child;
107
124
  },
108
- // Each stop sends its kill as it starts, so on POSIX every kill is out before this returns.
109
125
  stopAll() {
110
126
  closed = true;
111
- return Promise.all([...live].map((entry) => entry.stop())).then(() => undefined);
127
+ return Promise.all([...live].map(stopChild)).then(() => undefined);
112
128
  },
113
129
  };
114
130
  }
@@ -125,7 +141,6 @@ export const children = createChildRegistry();
125
141
  export function spawnChild(command, args, options, { stdio }, registry = children) {
126
142
  return registry.track(() => {
127
143
  const argv = spawnArgv(command, args, options);
128
- const child = spawn(argv.command, argv.args, { ...argv.options, detached: DETACHED, stdio });
129
- return { child, kill: (timeoutMs) => killAndSeeExit(child, timeoutMs) };
144
+ return spawn(argv.command, argv.args, { ...argv.options, detached: DETACHED, stdio });
130
145
  });
131
146
  }
package/src/server.js CHANGED
@@ -8,8 +8,8 @@ import { z } from "zod";
8
8
  import { DEFAULT_MODEL, runDelegate as runDelegateDefault } from "./delegate.js";
9
9
  import { runDoctor as runDoctorDefault } from "./doctor.js";
10
10
  import { VERSION, readPackageVersion } from "./version.js";
11
- import { DETACHED, children } from "./proc.js";
12
- import { PLAN_PRIORITIES, PLAN_STATUSES, TODO_STATUSES } from "./acp-enums.js";
11
+ import { children } from "./proc.js";
12
+ import { installSignalCleanup } from "./shutdown.js";
13
13
  import { TASKS_EXTENSION, createTaskStore, listsTasks, registerTaskHandlers, runAsTask } from "./tasks.js";
14
14
 
15
15
  const ICON_BASE = `https://raw.githubusercontent.com/andreilungeanu/cursor-delegate-mcp/v${VERSION}/assets`;
@@ -55,100 +55,12 @@ const taskStore = createTaskStore();
55
55
  // the parameter descriptions.
56
56
  export const SERVER_INSTRUCTIONS = `Delegate coding work to Cursor through the delegate tool. Every permission the agent requests is auto-approved, in every mode: agent/plan/ask reach any file the user account can, and mode instructs the agent rather than limiting it. Scope workspace tightly and review the git diff after every run — filesReportedByEditTools carries only what the agent's edit tools reported; the diff is authoritative.`;
57
57
 
58
- const planEntrySchema = z.object({
59
- content: z.string(),
60
- priority: z.enum(PLAN_PRIORITIES).optional(),
61
- status: z.enum(PLAN_STATUSES).optional(),
62
- }).passthrough();
63
-
64
- // No outputSchema: it requires structuredContent too, and a host that reads both (Codex) puts the
65
- // payload in context twice. Strict copy in delegate.test.js; field meanings in
66
- // skills/delegate/reference.md.
67
- export const delegateOutputShape = {
68
- result: z.string(),
69
- resultSource: z.enum(["pre-tool-fallback", "none"]).optional(),
70
- effectiveModel: z.string().optional(),
71
- effectiveEffort: z.record(z.string(), z.string()).optional(),
72
- stopReason: z.string().optional(),
73
- sessionId: z.string(),
74
- filesReportedByEditTools: z.array(z.string()).optional(),
75
- resumed: z.boolean().optional(),
76
- cancelRequested: z.boolean().optional(),
77
- protocolWarnings: z.array(z.string()).optional(),
78
- plan: z.object({
79
- entries: z.array(planEntrySchema),
80
- overview: z.string().optional(),
81
- detail: z.string().optional(),
82
- }).optional(),
83
- todos: z.array(z.object({
84
- id: z.string(),
85
- content: z.string(),
86
- status: z.enum(TODO_STATUSES).optional(),
87
- })).optional(),
88
- todoProgress: z.object({
89
- total: z.number(),
90
- completed: z.number(),
91
- inProgress: z.number(),
92
- pending: z.number(),
93
- cancelled: z.number(),
94
- }).optional(),
95
- };
96
-
97
- // Same contract as delegateOutputShape; strict copy in doctor.test.js. Relayed agent fields stay
98
- // unknown so an odd protocolVersion is a diagnostic, not a failed call. Handshake is its own
99
- // shape because .strict() does not look inside a nested object.
100
- export const doctorHandshakeShape = {
101
- ok: z.boolean(),
102
- error: z.string().optional(),
103
- protocolVersion: z.unknown().optional(),
104
- agentCapabilities: z.unknown().optional(),
105
- models: z.array(z.unknown()).optional(),
106
- currentModel: z.unknown().optional(),
107
- modes: z.array(z.unknown()).optional(),
108
- // Built here, not relayed, so it gets a real type.
109
- currentModelOptions: z.array(z.object({
110
- id: z.string(),
111
- name: z.string().optional(),
112
- category: z.string().optional(),
113
- values: z.array(z.string()),
114
- currentValue: z.string().optional(),
115
- })).optional(),
116
- };
117
-
118
- export const doctorAgentShape = {
119
- found: z.boolean(),
120
- command: z.string(),
121
- version: z.string().nullable(),
122
- error: z.string().optional(),
123
- handshake: z.object(doctorHandshakeShape).passthrough().optional(),
124
- };
125
-
126
- // agent is split out for the same reason as handshake.
127
- export const doctorOutputShape = {
128
- plugin: z.object({ version: z.string() }).passthrough(),
129
- client: z.object({
130
- name: z.string().nullable(),
131
- version: z.string().nullable(),
132
- capabilities: z.record(z.string(), z.unknown()),
133
- protocolVersion: z.string().optional(),
134
- }).passthrough(),
135
- agent: z.object(doctorAgentShape).passthrough(),
136
- runtime: z.object({
137
- node: z.string(),
138
- platform: z.string(),
139
- arch: z.string(),
140
- cwd: z.string(),
141
- transport: z.literal("stdio"),
142
- }),
143
- env: z.record(z.string(), z.unknown()),
144
- };
145
-
146
58
  export const delegateInputSchema = z.object({
147
59
  spec: z.string().trim().min(1, "spec must not be blank").describe("Task brief: goal, scope, fixed decisions quoted exactly, acceptance criteria. Sent as written. Point at files to read rather than pasting code, or attach them with contextFiles."),
148
60
  mode: z.enum(["agent", "plan", "ask"]).default("agent").describe("agent implements; plan and ask are instructions to the agent, not limits."),
149
- resumeSessionId: z.string().optional().describe("Continue an existing ACP session. When delegate ran as an MCP task, its server-side task id works too."),
61
+ resumeSessionId: z.string().trim().optional().describe("Continue an existing ACP session. When delegate ran as an MCP task, its server-side task id works too."),
150
62
  workspace: z.string().trim().min(1, "workspace must not be blank").describe("The agent's working directory, not a limit. Smallest directory holding the task's files; with no such directory the project root is the floor. Must already exist; never create one for the call."),
151
- model: z.string().trim().min(1, "model must be a non-empty string").default(DEFAULT_MODEL).describe("Bare ACP family id, version included: composer-2.5, grok-4.5, claude-opus-5, gpt-5.6-sol. doctor deep:true lists every id."),
63
+ model: z.string().trim().min(1, "model must be a non-empty string").default(DEFAULT_MODEL).describe(`Bare ACP family id, version included, such as ${DEFAULT_MODEL}. The ids on offer depend on the account; doctor deep:true lists them.`),
152
64
  fast: z.boolean().default(false).describe("Fast tier; higher cost — only when the user asks."),
153
65
  // Open string: a model's values are known only once it is selected, then validated live.
154
66
  effort: z.string().trim().min(1).optional().describe("Exact Cursor thinking-effort value for the selected model. Values differ per model and some expose no effort option; invalid values fail before the prompt and name the accepted set. Pass only when the user asks for Cursor effort — the host's own reasoning setting is unrelated."),
@@ -181,14 +93,13 @@ export function progressNotifier(ctx) {
181
93
  * signal?: AbortSignal,
182
94
  * onProgress?: (message: string) => void,
183
95
  * onPromptSent?: (sessionId: string, handle: any, resumeNote?: string) => void,
184
- * onUnseenExit?: (note: string) => void,
185
96
  * onTurnEnd?: () => void,
186
97
  * }} deps
187
98
  * @returns {Promise<import("@modelcontextprotocol/server").CallToolResult>}
188
99
  */
189
100
  export async function runDelegateTool({
190
101
  args, ctx, runDelegate, inFlight, seenSessions = new Set(),
191
- signal = ctx?.mcpReq?.signal, onProgress = progressNotifier(ctx), onPromptSent, onUnseenExit, onTurnEnd,
102
+ signal = ctx?.mcpReq?.signal, onProgress = progressNotifier(ctx), onPromptSent, onTurnEnd,
192
103
  }) {
193
104
  const { spec, mode, resumeSessionId, workspace, model, fast, effort, context, contextFiles } = args;
194
105
 
@@ -198,7 +109,8 @@ export async function runDelegateTool({
198
109
  const out = await runDelegate({
199
110
  spec,
200
111
  mode,
201
- resumeSessionId,
112
+ // Blank is no resume: hosts fill optional fields with "".
113
+ resumeSessionId: resumeSessionId || undefined,
202
114
  workspace,
203
115
  model,
204
116
  fast,
@@ -208,7 +120,6 @@ export async function runDelegateTool({
208
120
  onProgress,
209
121
  signal,
210
122
  onPromptSent: onPromptSent && ((sessionId, resumeNote) => onPromptSent(sessionId, handle, resumeNote)),
211
- onUnseenExit,
212
123
  onSessionReady: (sessionId, client) => {
213
124
  capturedSessionId = sessionId;
214
125
  handle = { client, cancelRequested: false };
@@ -344,7 +255,7 @@ export function buildServer({
344
255
  const observed = await Promise.all(
345
256
  toKill.map((handle) => Promise.resolve(handle.client.stop()).catch(() => false))
346
257
  );
347
- // "killed" needs an observed exit; without one the handles stay and force can be retried.
258
+ // "killed" needs an observed exit.
348
259
  if (!observed.every(Boolean)) return cancelResult("cancelled", sessionId);
349
260
  for (const handle of toKill) unregisterInFlight(flights, sessionId, handle);
350
261
  return cancelResult("killed", sessionId);
@@ -400,49 +311,6 @@ if (process.argv[1]) {
400
311
  }
401
312
  }
402
313
 
403
- // Kill what is still running, then exit, on any way the host has of going away. Returns the
404
- // shutdown stdin EOF triggers, for a host that goes some other way.
405
- /** @param {import("./proc.js").ChildRegistry} [registry] @returns {() => void} */
406
- export function installSignalCleanup(registry = children, {
407
- exit = (code) => process.exit(code),
408
- setExitCode = (code) => { process.exitCode = code; },
409
- schedule = (fn) => setImmediate(fn),
410
- stdin = process.stdin,
411
- } = {}) {
412
- let shuttingDown = false;
413
- let signalsSeen = 0;
414
- // The code shutdown exits with: a signal's, even when it follows the stdin EOF.
415
- let exitCode = 0;
416
- const shutdown = (code, fromSignal = false) => {
417
- // Only a second signal skips the wait for the kills, which the first pass already sent: a
418
- // hangup closes stdin and sends SIGHUP, in either order.
419
- if (fromSignal) signalsSeen++;
420
- if (shuttingDown) {
421
- if (fromSignal && signalsSeen === 1) { exitCode = code; setExitCode(code); }
422
- return signalsSeen < 2 ? undefined : exit(code);
423
- }
424
- shuttingDown = true;
425
- exitCode = code;
426
- // Set now: the loop may run dry before the scheduled exit gets a turn.
427
- setExitCode(code);
428
- // Waits for the kills: on Windows taskkill is a separate process, and exiting first orphans the
429
- // launcher and agent below the shell (measured). Each stop bounds itself, so the wait is finite.
430
- // The exit is scheduled onto a clean loop turn rather than run on the settlement stack.
431
- const leave = () => schedule(() => exit(exitCode));
432
- registry.stopAll().then(leave, leave);
433
- };
434
- // On POSIX each agent has its own process group, which a signal to this process misses, so the
435
- // handler kills them first. SIGHUP too: a closed terminal, whose default leaves them running.
436
- if (DETACHED) {
437
- const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]]);
438
- for (const [signal, code] of signals) process.on(signal, () => shutdown(code, true));
439
- }
440
- // A stdio host closes stdin before it resorts to a signal. The SDK aborts in-flight requests on
441
- // EOF; this also stops their agents directly, waits for the kills, and exits.
442
- stdin.on("end", () => shutdown(0));
443
- return () => shutdown(0);
444
- }
445
-
446
314
  if (isMain) {
447
315
  // Answered before the transport starts, so an install can be checked without a host. Reads the
448
316
  // package.json beside this file: the code actually running, not what a manifest pinned.
@@ -450,7 +318,7 @@ if (isMain) {
450
318
  if (argv.includes("--version") || argv.includes("-v")) {
451
319
  console.log(readPackageVersion());
452
320
  } else {
453
- const hostGone = installSignalCleanup();
321
+ const hostGone = installSignalCleanup(() => children.stopAll());
454
322
  const transport = new StdioServerTransport();
455
323
  // One factory serves both protocol eras: a 2025-era initialize pins a legacy instance, and only
456
324
  // a modern one answers with tasks.
@@ -6,32 +6,24 @@ export class SessionSupervisor {
6
6
  constructor(client, {
7
7
  handshakeMs = 60000,
8
8
  hardCapMs = DEFAULT_HARD_CAP_MS,
9
- idleMs = 0,
10
9
  } = {}) {
11
10
  this.client = client;
12
11
  this.handshakeMs = handshakeMs;
13
12
  this.hardCapMs = hardCapMs;
14
- // Idle detection is opt-in: cursor-agent sends no frames while a shell command runs (26.9s of
15
- // silence measured for a healthy 20s command).
16
- this.idleMs = idleMs > 0 ? idleMs : 0;
17
13
  this.sessionId = null;
18
14
  this.lastActivityAt = Date.now();
19
- this._idleTimer = null;
20
15
  this._handshakeTimer = null;
21
16
  this._hardCapTimer = null;
22
17
  this._armed = false;
23
18
  this._settled = false;
24
19
  this._promptStarted = false;
25
20
  this._guardReject = null;
26
- this._onActivity = () => {
27
- this.lastActivityAt = Date.now();
28
- this._resetIdle();
29
- };
21
+ this._onActivity = () => { this.lastActivityAt = Date.now(); };
30
22
  this._onSetupCancel = () => this._trip("cancelled-in-setup", "cancelled before the prompt was sent");
31
23
  this._onExit = (info) => {
32
24
  this._trip(
33
25
  "agent-exit",
34
- // Kept whole, for the reason acp-client.js states where it builds the same message.
26
+ // stderr kept whole, as in acp-client.js.
35
27
  `agent exited (code=${info.code}${info.signal ? ", signal=" + info.signal : ""})${info.stderr ? ": " + String(info.stderr) : ""}`
36
28
  );
37
29
  };
@@ -41,6 +33,7 @@ export class SessionSupervisor {
41
33
  this.sessionId = sessionId;
42
34
  }
43
35
 
36
+ // True once decided (a trip or the work's end); work still running after a trip reads it to stop.
44
37
  get settled() {
45
38
  return this._settled;
46
39
  }
@@ -63,14 +56,12 @@ export class SessionSupervisor {
63
56
  }, this.handshakeMs);
64
57
  }
65
58
 
66
- // Silence in the request/response handshake means a wedged agent; once the prompt is in flight
67
- // it does not, so the deadline comes off.
59
+ // Silence in the request/response handshake means a wedged agent; during the prompt it does not.
68
60
  promptStarted() {
69
61
  if (this._promptStarted) return;
70
62
  this._promptStarted = true;
71
63
  clearTimeout(this._handshakeTimer);
72
64
  this._handshakeTimer = null;
73
- this._resetIdle();
74
65
  }
75
66
 
76
67
  disarm() {
@@ -79,23 +70,12 @@ export class SessionSupervisor {
79
70
  this.client.off("activity", this._onActivity);
80
71
  this.client.off("exit", this._onExit);
81
72
  this.client.off("cancelled-in-setup", this._onSetupCancel);
82
- clearTimeout(this._idleTimer);
83
73
  clearTimeout(this._handshakeTimer);
84
74
  clearTimeout(this._hardCapTimer);
85
- this._idleTimer = null;
86
75
  this._handshakeTimer = null;
87
76
  this._hardCapTimer = null;
88
77
  }
89
78
 
90
- _resetIdle() {
91
- clearTimeout(this._idleTimer);
92
- this._idleTimer = null;
93
- if (!this.idleMs || !this._promptStarted || !this._armed || this._settled) return;
94
- this._idleTimer = setTimeout(() => {
95
- this._trip("idle-timeout", `Session idle timeout after ${this.idleMs}ms`);
96
- }, this.idleMs);
97
- }
98
-
99
79
  abort() {
100
80
  this._trip("aborted", "delegation aborted by MCP host.");
101
81
  }
@@ -105,10 +85,10 @@ export class SessionSupervisor {
105
85
  this._settled = true;
106
86
  this.disarm();
107
87
  const err = makeError(reason, message);
108
- if (reason === "idle-timeout" || reason === "handshake-timeout" || reason === "hard-cap" || reason === "aborted") {
88
+ if (reason === "handshake-timeout" || reason === "hard-cap" || reason === "aborted") {
109
89
  if (this.sessionId) { try { this.client.cancel(this.sessionId); } catch {} }
110
90
  }
111
- // Ended whether or not a session opened, so setup orphaned by this trip sends nothing more.
91
+ // Closed whether or not a session opened, so setup orphaned by this trip cannot still prompt.
112
92
  try { this.client.endTurn?.(); } catch {}
113
93
  this._guardReject?.(err);
114
94
  }
@@ -0,0 +1,27 @@
1
+ import process from "node:process";
2
+
3
+ /**
4
+ * Runs stopAll once, then exits, on any way the host has of going away: SIGINT, SIGTERM, SIGHUP,
5
+ * stdin EOF, or the returned function. A later trigger waits for the same stop, so a host that
6
+ * follows SIGINT with SIGTERM does not cut the kills short. Every stop is bounded.
7
+ * @param {() => Promise<unknown>} stopAll
8
+ * @param {{ exit?: (code: number) => void, stdin?: NodeJS.EventEmitter }} [opts]
9
+ * @returns {() => void}
10
+ */
11
+ export function installSignalCleanup(stopAll, { exit = (code) => process.exit(code), stdin = process.stdin } = {}) {
12
+ let stopping = false;
13
+ /** @param {number} code */
14
+ const shutdown = (code) => {
15
+ if (stopping) return;
16
+ stopping = true;
17
+ // Waits for the kills: on Windows taskkill is a separate process, and exiting first leaves the
18
+ // agent running (measured).
19
+ Promise.resolve().then(stopAll).catch(() => {}).finally(() => exit(code));
20
+ };
21
+ // Replaces Node's default exit on a signal, which on POSIX never reaches agents in groups of their own.
22
+ for (const [signal, code] of /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]])) {
23
+ process.on(signal, () => shutdown(code));
24
+ }
25
+ stdin.on("end", () => shutdown(0));
26
+ return () => shutdown(0);
27
+ }
package/src/tasks.js CHANGED
@@ -40,17 +40,8 @@ export function createTaskStore({ now = Date.now, retainMs = RETAIN_MS } = {}) {
40
40
  if (task.sessionId) sessions.set(task.taskId, task.sessionId);
41
41
  }
42
42
  };
43
- // A fact that changes what to do after a cancel, such as an agent the stop did not see exit.
44
- /** @param {Task} task @param {string} text */
45
- const note = (task, text) => {
46
- if (task.status !== "cancelled") return;
47
- const base = task.statusMessage ?? "cancelled";
48
- task.statusMessage = `${base}${base.endsWith(".") ? "" : "."} Note: ${text}`;
49
- task.lastUpdatedAt = now();
50
- };
51
43
  return {
52
44
  now,
53
- note,
54
45
  /** @returns {Task} */
55
46
  create() {
56
47
  const t = now();
@@ -91,8 +82,9 @@ export function createTaskStore({ now = Date.now, retainMs = RETAIN_MS } = {}) {
91
82
  cancel(task) {
92
83
  if (task.status !== "working" || task.turnEnded) return;
93
84
  task.status = "cancelled";
94
- task.statusMessage = task.sessionId ? `cancelled; resume with resumeSessionId ${task.sessionId}` : "cancelled";
95
- if (task.resumeNote) note(task, task.resumeNote);
85
+ const resume = task.sessionId ? `cancelled; resume with resumeSessionId ${task.sessionId}` : "cancelled";
86
+ // A resume that fell back changes what to do next, so it stays on the cancelled task.
87
+ task.statusMessage = task.resumeNote ? `${resume}. Note: ${task.resumeNote}` : resume;
96
88
  task.endedAt = task.lastUpdatedAt = now();
97
89
  task.ac.abort();
98
90
  },
@@ -120,7 +112,7 @@ export function createTaskStore({ now = Date.now, retainMs = RETAIN_MS } = {}) {
120
112
  * Runs a delegation that answers its request with a task once the prompt is sent. A run that
121
113
  * settles before then, setup failures included, answers with its result as a blocking call does.
122
114
  * @param {{
123
- * run: (over: { signal: AbortSignal, onProgress: (m: string) => void, onPromptSent: (id: string, handle?: any, resumeNote?: string) => void, onUnseenExit: (note: string) => void, onTurnEnd: () => void }) => Promise<any>,
115
+ * run: (over: { signal: AbortSignal, onProgress: (m: string) => void, onPromptSent: (id: string, handle?: any, resumeNote?: string) => void, onTurnEnd: () => void }) => Promise<any>,
124
116
  * signal?: AbortSignal, notify?: (message: string) => void, store: ReturnType<typeof createTaskStore>,
125
117
  * }} opts
126
118
  */
@@ -145,7 +137,6 @@ export async function runAsTask({ run, signal, notify = () => {}, store }) {
145
137
  if (!answered) notify(message);
146
138
  },
147
139
  onPromptSent: (sessionId, handle, resumeNote) => { task.sessionId = sessionId; task.handle = handle; task.resumeNote = resumeNote; markSent(); },
148
- onUnseenExit: (note) => store.note(task, note),
149
140
  onTurnEnd: () => { task.turnEnded = true; },
150
141
  }).then((result) => ({ result }), (error) => ({ error }));
151
142
  const first = await Promise.race([sent, outcome]);