cursor-delegate-mcp 3.0.1 → 3.1.1

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,59 @@ All notable changes to this project are documented here. The format follows
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [3.1.1] - 2026-11-24
10
+
11
+ ### Changed
12
+
13
+ - A finished task is kept for its hour however many finish, where only the last 100 were kept.
14
+ - `cancel` tells every session the server has seen from an unknown id, where only the last 500
15
+ sessions were kept.
16
+
17
+ ### Fixed
18
+
19
+ - The server shuts down, stopping its agents, when its stdio transport closes. When the server's
20
+ stdout broke, as it does when the host dies, the transport paused stdin, no stdin EOF arrived,
21
+ and the server and the agent kept running.
22
+ - A completed task's result carries `resultType: "complete"`, as the `tools/call` result it stands
23
+ for, which the tasks extension's client schema requires.
24
+ - A task id resumes its session for as long as the server runs, not only for the hour its task is
25
+ kept.
26
+ - A finished task's status message is its error, or none, instead of its last progress line.
27
+ - `tasks/update` refuses a request with no `inputResponses`.
28
+
29
+ ## [3.1.0] - 2026-11-24
30
+
31
+ ### Changed
32
+
33
+ - A stopped task's status message stays `cancelled; resume with resumeSessionId <id>` after the
34
+ run ends, where it became the run's `delegate failed [aborted]` error. It gains a note when the
35
+ run had started a fresh session after a failed resume, or when the stop did not see cursor-agent
36
+ exit.
37
+ - A process the server would start after shutdown began fails with `spawn-failed` instead of
38
+ starting.
39
+ - A stop counts as done once cursor-agent's exit was seen and its tree kill finished. On Windows it
40
+ waits for `taskkill` to finish with the tree.
41
+ - A shutdown signal that arrives after stdin closed sets the exit code and waits for the agents to
42
+ be stopped, where it exited at once. Only a second signal skips that wait.
43
+ - An aborted `doctor` version probe returns once its stop saw the probe exit: up to 4 s, where it
44
+ was 2 s.
45
+
46
+ ### Fixed
47
+
48
+ - A shutdown signal during `doctor` with `deep: true` stops the agent doctor starts for its
49
+ handshake, rather than exiting with it running.
50
+ - A delegation that fails, times out or is aborted during setup sends cursor-agent nothing more: a
51
+ reply that arrives afterwards no longer goes on to change the session's model, effort or mode, or
52
+ to send the prompt. In task mode a handshake timeout fails the call, rather than answering it
53
+ with a task id.
54
+ - A cancel before the prompt ends the delegation at once with `stopReason: "cancelled"`, rather
55
+ than waiting on the setup request in flight.
56
+ - A delegation aborted or timed out during setup sends no progress notifications after its call
57
+ returned.
58
+ - Text cursor-agent sends while `contextFiles` are read stays out of `result`.
59
+ - The note that cursor-agent may still be running and the resume hint reach the caller whatever
60
+ cursor-agent's side threw, a frozen error or a value that is not an Error included.
61
+
9
62
  ## [3.0.1] - 2026-11-23
10
63
 
11
64
  ### Fixed
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursor-delegate-mcp",
3
- "version": "3.0.1",
3
+ "version": "3.1.1",
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
@@ -1,17 +1,34 @@
1
- import { spawn } from "node:child_process";
2
1
  import { EventEmitter } from "node:events";
3
2
  import { StringDecoder } from "node:string_decoder";
4
3
  import { JsonRpcPeer } from "./jsonrpc.js";
5
4
  import { createRequestRouter } from "./request-router.js";
6
- import { commandExists, resolveAcpSpawn, spawnArgv } from "./spawn.js";
7
- import { DETACHED, isChildAlive, treeKill } from "./proc.js";
5
+ import { commandExists, resolveAcpSpawn } from "./spawn.js";
6
+ import { children, isChildAlive, spawnChild } from "./proc.js";
8
7
  import { VERSION } from "./version.js";
9
8
  import { makeError } from "./errors.js";
10
9
 
11
10
  const STDERR_CAP = 64 * 1024;
12
- // How long stop() waits for the exit after the kill. SIGKILL and taskkill /F land in milliseconds,
13
- // so this elapses only when the kill failed.
14
- const STOP_EXIT_TIMEOUT_MS = 2000;
11
+
12
+ // Each phase lists the transitions it allows; any other is refused.
13
+ /** @typedef {"setup" | "running" | "cancelled-in-setup" | "cancelled" | "ended" | "exited"} WirePhase */
14
+ /** @typedef {"prompt" | "cancel" | "end" | "exit"} WireTransition */
15
+ /** @type {Record<WirePhase, Partial<Record<WireTransition, WirePhase>>>} */
16
+ const PHASES = {
17
+ setup: { prompt: "running", cancel: "cancelled-in-setup", end: "ended", exit: "exited" },
18
+ running: { cancel: "cancelled", end: "ended", exit: "exited" },
19
+ "cancelled-in-setup": { exit: "exited" },
20
+ cancelled: { exit: "exited" },
21
+ ended: { exit: "exited" },
22
+ exited: {},
23
+ };
24
+
25
+ // What a request the phase refuses throws; after a cancel before the prompt, with the cancel's reason.
26
+ /** @param {WirePhase} phase */
27
+ function wireClosed(phase) {
28
+ return phase === "cancelled-in-setup"
29
+ ? makeError("cancelled-in-setup", "cancelled before the prompt was sent")
30
+ : makeError("wire-closed", `no prompt can go out: the wire is ${phase}`);
31
+ }
15
32
 
16
33
  export class AcpClient extends EventEmitter {
17
34
  /**
@@ -20,11 +37,15 @@ export class AcpClient extends EventEmitter {
20
37
  * mode?: string,
21
38
  * onCreatePlan?: (body: any) => void,
22
39
  * onTodos?: (body: any) => void,
40
+ * registry?: import("./proc.js").ChildRegistry,
23
41
  * }} [opts]
24
42
  */
25
- constructor({ spawnSpec, mode, onCreatePlan, onTodos } = {}) {
43
+ constructor({ spawnSpec, mode, onCreatePlan, onTodos, registry = children } = {}) {
26
44
  super();
27
45
  this.spawnSpec = spawnSpec || resolveAcpSpawn();
46
+ this.registry = registry;
47
+ /** @type {import("./proc.js").TrackedChild | null} */
48
+ this._tracked = null;
28
49
  this.mode = mode;
29
50
  this.onCreatePlan = onCreatePlan;
30
51
  this.onTodos = onTodos;
@@ -32,8 +53,12 @@ export class AcpClient extends EventEmitter {
32
53
  this._stderrLength = 0;
33
54
  /** @type {Promise<boolean> | null} */
34
55
  this._stopping = null;
56
+ /** @type {WirePhase} */
57
+ this._phase = "setup";
35
58
  }
36
59
 
60
+ get child() { return this._tracked?.child; }
61
+
37
62
  // The stderr tail an exit error quotes. Kept as chunks and joined on read, so a noisy agent costs
38
63
  // a push per chunk; a StringDecoder keeps a multi-byte character split across reads intact.
39
64
  // stderr is not ACP activity, so it does not feed the supervisor.
@@ -42,18 +67,16 @@ export class AcpClient extends EventEmitter {
42
67
  return joined.length > STDERR_CAP ? joined.slice(-STDERR_CAP) : joined;
43
68
  }
44
69
 
45
- start() {
70
+ async start() {
46
71
  const { command, args, options } = this.spawnSpec;
47
72
  const opts = /** @type {{ shell?: boolean, env?: NodeJS.ProcessEnv }} */ (options);
48
73
  if (opts?.shell && !commandExists(command, opts.env)) {
49
- return Promise.reject(makeError("spawn-failed", `Failed to spawn agent (${command}): not found on PATH. Install Cursor CLI and run 'cursor-agent login'.`));
74
+ throw makeError("spawn-failed", `Failed to spawn agent (${command}): not found on PATH. Install Cursor CLI and run 'cursor-agent login'.`);
50
75
  }
76
+ this._tracked = spawnChild(command, args, opts, { stdio: ["pipe", "pipe", "pipe"] }, this.registry);
51
77
  this._stderrChunks = [];
52
78
  this._stderrLength = 0;
53
79
  const stderrDecoder = new StringDecoder("utf8");
54
- this._exitEmitted = false;
55
- const argv = spawnArgv(command, args, opts);
56
- this.child = spawn(argv.command, argv.args, { ...argv.options, detached: DETACHED, stdio: ["pipe", "pipe", "pipe"] });
57
80
  this.child.stderr.on("data", (chunk) => {
58
81
  const text = stderrDecoder.write(chunk);
59
82
  if (text) {
@@ -78,9 +101,9 @@ export class AcpClient extends EventEmitter {
78
101
  // take down the server. readline adds no handler on stdout either.
79
102
  this.child.stdin.on("error", () => {});
80
103
  this.child.stdout.on("error", () => {});
104
+ // Both 'exit' and 'close' land here; the transition the first one takes refuses the second.
81
105
  const emitExit = (code, signal) => {
82
- if (this._exitEmitted) return;
83
- this._exitEmitted = true;
106
+ if (!this._advance("exit")) return;
84
107
  const stderr = this.stderrBuffer;
85
108
  const err = makeError(
86
109
  "agent-exit",
@@ -128,7 +151,7 @@ export class AcpClient extends EventEmitter {
128
151
 
129
152
  // Stashed for the unknown-model check and doctor deep, so neither needs a second handshake.
130
153
  async initialize() {
131
- const res = await this.peer.request("initialize", { protocolVersion: 1, clientInfo: { name: "cursor-delegate-mcp", version: VERSION }, clientCapabilities: { _meta: { parameterizedModelPicker: true } } });
154
+ const res = await this._setup("initialize", { protocolVersion: 1, clientInfo: { name: "cursor-delegate-mcp", version: VERSION }, clientCapabilities: { _meta: { parameterizedModelPicker: true } } });
132
155
  this.protocolVersion = res?.protocolVersion;
133
156
  this.agentCapabilities = res?.agentCapabilities;
134
157
  return res;
@@ -139,15 +162,38 @@ export class AcpClient extends EventEmitter {
139
162
  this.configOptions = res?.configOptions;
140
163
  return res;
141
164
  }
142
- async newSession(cwd) { return this._captureSession(await this.peer.request("session/new", { cwd, mcpServers: [] })); }
143
- async loadSession(sessionId, cwd) { return this._captureSession(await this.peer.request("session/load", { sessionId, cwd, mcpServers: [] })); }
144
- setModel(sessionId, modelId) { return this.peer.request("session/set_model", { sessionId, modelId }); }
145
- setConfigOption(sessionId, configId, value) { return this.peer.request("session/set_config_option", { sessionId, configId, value: String(value) }); } // configId, not optionId; ACP wants a string value
146
- setMode(sessionId, modeId) { return this.peer.request("session/set_mode", { sessionId, modeId }); }
147
- prompt(sessionId, blocks) { return this.peer.request("session/prompt", { sessionId, prompt: blocks }); }
165
+ async newSession(cwd) { return this._captureSession(await this._setup("session/new", { cwd, mcpServers: [] })); }
166
+ async loadSession(sessionId, cwd) { return this._captureSession(await this._setup("session/load", { sessionId, cwd, mcpServers: [] })); }
167
+ setModel(sessionId, modelId) { return this._setup("session/set_model", { sessionId, modelId }); }
168
+ setConfigOption(sessionId, configId, value) { return this._setup("session/set_config_option", { sessionId, configId, value: String(value) }); } // configId, not optionId; ACP wants a string value
169
+ setMode(sessionId, modeId) { return this._setup("session/set_mode", { sessionId, modeId }); }
170
+ // Every request before the task prompt. A reply that lands once setup ended, at a cancel or a
171
+ // failed delegation, is refused too, so no setup step runs on from it.
172
+ async _setup(method, params) {
173
+ if (this._phase !== "setup") throw wireClosed(this._phase);
174
+ const reply = await this.peer.request(method, params);
175
+ if (this._phase !== "setup") throw wireClosed(this._phase);
176
+ return reply;
177
+ }
178
+
179
+ /** @param {WireTransition} transition @returns {WirePhase | undefined} */
180
+ _advance(transition) {
181
+ const next = PHASES[this._phase][transition];
182
+ if (next) this._phase = next;
183
+ return next;
184
+ }
185
+
186
+ // The task prompt, and the only way into the running phase.
187
+ prompt(sessionId, blocks) {
188
+ if (!this._advance("prompt")) throw wireClosed(this._phase);
189
+ return this.peer.request("session/prompt", { sessionId, prompt: blocks });
190
+ }
191
+ // The delegation is decided: nothing sent from here on would reach a caller.
192
+ endTurn() { this._advance("end"); }
193
+ // Before the prompt nothing runs that the agent could finish, so the supervisor ends the
194
+ // delegation at once, whatever setup is awaiting.
148
195
  cancel(sessionId) {
149
- // Recorded so runDelegate can hold back a prompt not yet sent.
150
- this.cancelRequested = true;
196
+ if (this._advance("cancel") === "cancelled-in-setup") this.emit("cancelled-in-setup");
151
197
  this.peer.notify("session/cancel", { sessionId });
152
198
  return Promise.resolve();
153
199
  }
@@ -155,8 +201,9 @@ export class AcpClient extends EventEmitter {
155
201
  getTranscript(n) { return this.peer ? this.peer.formatLog(n) : ""; }
156
202
 
157
203
  // Idempotent while teardown is in flight and after a confirmed exit. A missed exit is not
158
- // memoized — force retries with a new treeKill. A confirmed exit stays so later callers join.
159
- stop({ timeoutMs = STOP_EXIT_TIMEOUT_MS } = {}) {
204
+ // memoized, so a later stop kills again. A confirmed exit stays so later callers join.
205
+ /** @param {{ timeoutMs?: number }} [opts] */
206
+ stop({ timeoutMs } = {}) {
160
207
  if (!this._stopping) {
161
208
  this._stopping = this._teardown(timeoutMs).then((observed) => {
162
209
  if (!observed) this._stopping = null;
@@ -170,29 +217,16 @@ export class AcpClient extends EventEmitter {
170
217
  }
171
218
 
172
219
  async _teardown(timeoutMs) {
173
- const child = this.child;
174
- if (!child?.pid) {
220
+ const tracked = this._tracked;
221
+ if (!tracked) {
175
222
  try { this.peer?.close(); } catch {}
176
223
  return true;
177
224
  }
178
- const alive = isChildAlive(child);
179
- // Subscribed before the kill, so an instant exit is not missed.
180
- const exited = alive
181
- ? /** @type {Promise<boolean>} */ (new Promise((resolve) => child.once("exit", () => resolve(true))))
182
- : Promise.resolve(true);
183
- // Runs for an exited child too: the agent can be gone while the commands it spawned are still
184
- // running, and on POSIX they stay in its process group, which is the only handle left on them.
185
- treeKill(child.pid, { childAlive: alive }).catch(() => {});
186
- /** @type {NodeJS.Timeout | undefined} */
187
- let timer;
188
- const bounded = /** @type {Promise<boolean>} */ (new Promise((resolve) => {
189
- timer = setTimeout(() => resolve(false), timeoutMs);
190
- }));
191
- const observed = await Promise.race([exited, bounded]);
192
- clearTimeout(timer);
225
+ const { child } = tracked;
226
+ const observed = await tracked.stop({ timeoutMs });
193
227
  // On an observed exit, emitExit rejects in-flight RPCs with stderr, and racing it here would
194
228
  // drop that. Only a child still alive after the stop has its RPCs settled here.
195
- if (!observed && !this._exitEmitted && isChildAlive(child)) {
229
+ if (!observed && this._phase !== "exited" && isChildAlive(child)) {
196
230
  try {
197
231
  this.peer?.rejectAllPending(makeError("agent-exit", "agent process did not exit after stop"));
198
232
  } catch {}
package/src/delegate.js CHANGED
@@ -249,9 +249,9 @@ async function applyEffort(client, sessionId, model, value, modelOptions) {
249
249
  * model?: string, fast?: boolean, effort?: string, context?: string,
250
250
  * contextFiles?: string[], clientFactory?: (opts: any) => any,
251
251
  * idleMs?: number, handshakeMs?: number, hardCapMs?: number, timeoutMs?: number,
252
- * onClientReady?: (client: any) => void,
253
252
  * onSessionReady?: (sessionId: string, client: any) => void,
254
- * onPromptSent?: (sessionId: string) => void,
253
+ * onPromptSent?: (sessionId: string, resumeNote?: string) => void,
254
+ * onUnseenExit?: (note: string) => void,
255
255
  * onTurnEnd?: () => void,
256
256
  * onProgress?: (message: string) => void,
257
257
  * progressThrottleMs?: number, heartbeatMs?: number, signal?: AbortSignal,
@@ -261,7 +261,7 @@ export async function runDelegate({
261
261
  spec, mode = "agent", resumeSessionId, workspace,
262
262
  model = DEFAULT_MODEL, fast = false, effort, context, contextFiles, clientFactory,
263
263
  idleMs, handshakeMs, hardCapMs, timeoutMs,
264
- onClientReady, onSessionReady, onPromptSent, onTurnEnd, onProgress, progressThrottleMs = 2000,
264
+ onSessionReady, onPromptSent, onUnseenExit, onTurnEnd, onProgress, progressThrottleMs = 2000,
265
265
  heartbeatMs = DEFAULT_HEARTBEAT_MS,
266
266
  signal,
267
267
  } = {}) {
@@ -342,9 +342,6 @@ export async function runDelegate({
342
342
 
343
343
  const make = clientFactory || ((opts) => new AcpClient(opts));
344
344
  const client = make({ mode, onCreatePlan: state.recordCreatePlan, onTodos: state.recordTodos });
345
- // Before the spawn, so the caller can stop the agent from its first moment; onSessionReady comes
346
- // ~3.4s later, and a host exiting in between would leave the agent running.
347
- onClientReady?.(client);
348
345
  const supervisor = new SessionSupervisor(client, { idleMs: turnIdleMs, handshakeMs: shakeMs, hardCapMs: capMs });
349
346
  const onAbort = () => supervisor.abort();
350
347
  signal?.addEventListener("abort", onAbort, { once: true });
@@ -354,7 +351,8 @@ export async function runDelegate({
354
351
  let promptInFlight = false;
355
352
  let heartbeat = null;
356
353
  const startHeartbeat = () => {
357
- if (!(heartbeatMs > 0)) return;
354
+ // Setup orphaned by a trip must not arm a timer the teardown has already cleared.
355
+ if (!(heartbeatMs > 0) || supervisor.settled) return;
358
356
  const startedAt = Date.now();
359
357
  heartbeat = setInterval(() => {
360
358
  const parts = [
@@ -447,6 +445,10 @@ export async function runDelegate({
447
445
 
448
446
  let sessionId;
449
447
  let resumeError;
448
+ // Otherwise a resume hint reads as continuing work this session never had.
449
+ const resumeNote = () => (resumeError
450
+ ? `resuming ${resumeSessionId} had already failed (${resumeError}), so this ran as a fresh session and none of that earlier work was in context.`
451
+ : undefined);
450
452
  const unsupportedOptions = [];
451
453
  let servedModel;
452
454
  let effectiveEffort;
@@ -454,8 +456,8 @@ export async function runDelegate({
454
456
  // Set before the teardown in finally, which notes an unseen exit on whichever is going out.
455
457
  /** @type {any} */
456
458
  let out;
457
- /** @type {any} */
458
- let failed;
459
+ /** @type {{ cause: any, reason?: string, notes: string[] } | undefined} */
460
+ let failure;
459
461
  try {
460
462
  const res = await supervisor.supervise(async () => {
461
463
  await client.start();
@@ -515,14 +517,13 @@ export async function runDelegate({
515
517
  state.reset();
516
518
  supervisor.promptStarted();
517
519
  startHeartbeat();
518
- promptInFlight = true;
519
520
  try {
520
521
  const blocks = await buildContextBlocks(contextFiles, workspace, client, contextWarnings);
521
- // The caller has the id from session/new on, so a cancel can come before there is a turn.
522
- if (client.cancelRequested) return { stopReason: "cancelled", cancelledBeforePrompt: true };
522
+ // Raised with the prompt, so a frame sent while attachments were read is not folded in.
523
+ promptInFlight = true;
523
524
  const turn = client.prompt(sessionId, [{ type: "text", text: promptText }, ...blocks]);
524
525
  // Every argument has been accepted by now, so a caller may stop waiting on the result.
525
- try { onPromptSent?.(sessionId); } catch {}
526
+ try { onPromptSent?.(sessionId, resumeNote()); } catch {}
526
527
  return await turn;
527
528
  } finally {
528
529
  // The result is assembled across later awaits; a frame trailing the turn must not join it.
@@ -546,7 +547,7 @@ export async function runDelegate({
546
547
  "the agent ran a tool after its last message and never spoke again, so no final message closed the turn."
547
548
  + " result carries the last message before that tool call — it may be a preamble rather than the answer."
548
549
  );
549
- } else if (!finalMessageAvailable && !res?.cancelledBeforePrompt) {
550
+ } else if (!finalMessageAvailable) {
550
551
  protocolWarnings.push("the agent ended the turn without emitting any message; result is empty.");
551
552
  }
552
553
  let stopReason;
@@ -597,42 +598,47 @@ export async function runDelegate({
597
598
  if (protocolWarnings.length) out.protocolWarnings = protocolWarnings;
598
599
  return out;
599
600
  } catch (err) {
601
+ // A cancel before the prompt is the outcome the caller asked for: there was no turn to fail.
602
+ if (err?.reason === "cancelled-in-setup" && sessionId) {
603
+ out = { result: "", sessionId, resultSource: "none", stopReason: "cancelled" };
604
+ if (resumeSessionId && sessionId === resumeSessionId) out.resumed = true;
605
+ if (resumeError) out.protocolWarnings = [`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`];
606
+ return out;
607
+ }
600
608
  // A JSON-RPC code means the agent rejected something rather than the bridge breaking — the
601
609
  // distinction a caller needs to tell "fix your arguments" from "retry".
602
- if (!err?.reason && typeof err?.code === "number") err.reason = "agent-error";
610
+ const reason = err?.reason || (typeof err?.code === "number" ? "agent-error" : undefined);
611
+ failure = { cause: err, reason, notes: [] };
612
+ const { notes } = failure;
603
613
  // A bare duration cannot distinguish a wedged agent from a slow command, so name what was
604
614
  // outstanding — it also lets a retry resume the work already done.
605
- const isTimeout = err?.reason === "hard-cap" || err?.reason === "idle-timeout";
615
+ const isTimeout = reason === "hard-cap" || reason === "idle-timeout";
606
616
  // A handshake timeout gets the forensics but not the long-command advice: no prompt was sent,
607
617
  // so no shell command explains the silence.
608
- const isStall = isTimeout || err?.reason === "handshake-timeout";
609
- // Not on an abort: the SDK sends no response to a request its host cancelled.
610
- if (isStall || err?.reason === "agent-exit") {
618
+ const isStall = isTimeout || reason === "handshake-timeout";
619
+ // Not on an abort: a cancelled request gets no response, and a cancelled task keeps its own
620
+ // status message.
621
+ if (isStall || reason === "agent-exit") {
611
622
  const age = fmtDuration(supervisor.msSinceActivity());
612
- err.message += `\n\nLast ACP frame ${age} ago${state.lastToolLabel ? `; last tool call: ${state.lastToolLabel}` : ""}.`;
613
- if (state.sessionTitle) err.message += ` The agent titled this turn ${JSON.stringify(state.sessionTitle)}.`;
623
+ notes.push(`\n\nLast ACP frame ${age} ago${state.lastToolLabel ? `; last tool call: ${state.lastToolLabel}` : ""}.`);
624
+ if (state.sessionTitle) notes.push(` The agent titled this turn ${JSON.stringify(state.sessionTitle)}.`);
614
625
  if (state.sawTodoFrame) {
615
626
  const { todoProgress } = sanitizeTodos([]);
616
627
  const current = state.todoLabel();
617
- err.message += ` ${todoProgress.completed} of ${todoProgress.total} todos completed`
618
- + `${current ? `; ${current}` : ""}.`;
628
+ notes.push(` ${todoProgress.completed} of ${todoProgress.total} todos completed${current ? `; ${current}` : ""}.`);
619
629
  }
620
630
  const files = normalizeAgentReportedFiles([...state.touched], workspace);
621
- if (files.length) err.message += ` Files reported edited: ${files.join(", ")}.`;
622
- }
623
- if (resumeError) {
624
- // Otherwise the resume hint reads as continuing work this session never had.
625
- err.message += ` Note: resuming ${resumeSessionId} had already failed (${resumeError}),`
626
- + ` so this ran as a fresh session and none of that earlier work was in context.`;
631
+ if (files.length) notes.push(` Files reported edited: ${files.join(", ")}.`);
627
632
  }
633
+ if (resumeError) notes.push(` Note: ${resumeNote()}`);
628
634
  // Any failure after session/new leaves a resumable session, unknown-model and a rejected
629
635
  // config value included, not just the stalls.
630
- if (sessionId) err.message += ` Resume with resumeSessionId ${sessionId}.`;
636
+ if (sessionId) notes.push(` Resume with resumeSessionId ${sessionId}.`);
631
637
  if (isTimeout) {
632
638
  // Name the knob that fired: the hard cap does nothing for an idle-timeout.
633
- const knob = err.reason === "idle-timeout" ? "CURSOR_DELEGATE_IDLE_MS" : "CURSOR_DELEGATE_HARD_CAP_MS";
634
- err.message += " cursor-agent does not stream shell output over ACP, so a long-running command emits"
635
- + ` nothing until it exits. Split the command, run it in the background and poll, or raise ${knob}.`;
639
+ const knob = reason === "idle-timeout" ? "CURSOR_DELEGATE_IDLE_MS" : "CURSOR_DELEGATE_HARD_CAP_MS";
640
+ 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}.`);
636
642
  }
637
643
  // Opt-in: raw frames add nothing actionable to the caller's context beyond the forensics
638
644
  // above; they help only someone debugging the bridge.
@@ -640,11 +646,9 @@ export async function runDelegate({
640
646
  if (frames > 0) {
641
647
  try {
642
648
  const transcript = client.getTranscript?.(frames);
643
- if (transcript) err.message += `\n\n--- recent ACP transcript (last ${frames} frames) ---\n` + transcript;
649
+ if (transcript) notes.push(`\n\n--- recent ACP transcript (last ${frames} frames) ---\n` + transcript);
644
650
  } catch {}
645
651
  }
646
- failed = err;
647
- throw err;
648
652
  } finally {
649
653
  // The turn is decided: from here a cancel finds nothing running.
650
654
  try { onTurnEnd?.(); } catch {}
@@ -652,17 +656,19 @@ export async function runDelegate({
652
656
  signal?.removeEventListener("abort", onAbort);
653
657
  try { supervisor.finish(); } catch {}
654
658
  // Awaited: a host may close stdin on the result, and on Windows the server's exit does not take
655
- // a running agent with it (server.smoke.test.js). An exit not seen is noted instead.
656
- // A rejected stop counts as unseen; an unseen exit is not memoized, so a retry kills afresh.
657
- const stopOnce = () => Promise.resolve(client.stop()).catch(() => false);
658
- let exited = await stopOnce();
659
- if (exited === false) exited = await stopOnce();
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 {}
660
663
  if (exited === false) {
661
664
  const pid = client.child?.pid;
662
665
  const note = `the bridge stopped cursor-agent${pid ? ` (pid ${pid})` : ""} but did not see it exit; it may still be running.`;
663
- // A failure whose message cannot be written keeps its own error rather than a TypeError.
664
- if (failed) { try { failed.message += ` Note: ${note}`; } catch {} }
666
+ if (failure) failure.notes.push(` Note: ${note}`);
665
667
  else if (out) (out.protocolWarnings ??= []).push(note);
668
+ try { onUnseenExit?.(note); } catch {}
666
669
  }
667
670
  }
671
+ // After teardown, so the exit note it adds is in the message.
672
+ const { cause, reason, notes } = /** @type {NonNullable<typeof failure>} */ (failure);
673
+ throw makeError(reason, (cause?.message || String(cause)) + notes.join(""), { code: cause?.code, cause });
668
674
  }
package/src/doctor.js CHANGED
@@ -1,17 +1,14 @@
1
1
  import process from "node:process";
2
- import { spawn } from "node:child_process";
3
2
  import { existsSync } from "node:fs";
4
3
  import { AcpClient } from "./acp-client.js";
5
- import { commandExists, resolveAcpSpawn, spawnArgv } from "./spawn.js";
6
- import { DETACHED, isChildAlive, treeKill } from "./proc.js";
4
+ import { commandExists, resolveAcpSpawn } from "./spawn.js";
5
+ import { children, spawnChild } from "./proc.js";
7
6
  import { readPackageVersion } from "./version.js";
8
7
  import { describeOptions } from "./model-options.js";
9
8
 
10
9
  const HANDSHAKE_TIMEOUT_MS = 15_000;
11
10
  const VERSION_PROBE_TIMEOUT_MS = 10_000;
12
11
  const PROBE_STDOUT_CAP = 64 * 1024;
13
- // How long an aborted probe waits for its kill and close, as stop() bounds an agent's.
14
- const PROBE_KILL_WAIT_MS = 2000;
15
12
  const DEFAULT_LOG_SIZE = "2000";
16
13
 
17
14
  function formatArg(value) {
@@ -39,9 +36,9 @@ function envReport(name, fallback = null) {
39
36
  /**
40
37
  * @param {{ command: string, args: string[], options?: any }} spawnSpec
41
38
  * @param {number} [timeoutMs]
42
- * @param {{ signal?: AbortSignal, onSpawn?: (probe: { pid: number | undefined, stop: () => Promise<void> }) => void }} [opts]
39
+ * @param {{ signal?: AbortSignal, registry?: import("./proc.js").ChildRegistry }} [opts]
43
40
  */
44
- export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_MS, { signal, onSpawn } = {}) {
41
+ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_MS, { signal, registry = children } = {}) {
45
42
  const { command, args, options } = spawnSpec;
46
43
  const launcher = String(command || "").replace(/^["']|["']$/g, "");
47
44
  const isJsScript = isJsLauncher(launcher);
@@ -54,10 +51,16 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
54
51
  // Through a shell, a missing launcher still spawns (the shell does) and would read as found.
55
52
  if (options?.shell && !isJsScript && !commandExists(launcher, options.env)) return Promise.resolve({ found: false, version: null });
56
53
  const aborted = { version: null, error: "version probe aborted by MCP host" };
57
- // Interrupted already: nothing is spawned, and found comes from the lookup alone.
58
- if (signal?.aborted) {
59
- return Promise.resolve({ found: isJsScript ? existsSync(launcher) : commandExists(launcher, options?.env), ...aborted });
54
+ // Interrupted already, or shutting down: nothing is spawned, and found comes from the lookup alone.
55
+ const notRun = (error) => Promise.resolve({ found: isJsScript ? existsSync(launcher) : commandExists(launcher, options?.env), version: null, error });
56
+ if (signal?.aborted) return notRun(aborted.error);
57
+ let probe;
58
+ try {
59
+ probe = spawnChild(execCommand, execArgs, options, { stdio: ["ignore", "pipe", "pipe"] }, registry);
60
+ } catch (err) {
61
+ return notRun(err.message);
60
62
  }
63
+ const { child } = probe;
61
64
  return new Promise((resolve) => {
62
65
  let settled = false;
63
66
  let aborting = false;
@@ -70,19 +73,12 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
70
73
  signal?.removeEventListener("abort", onAbort);
71
74
  resolve(result);
72
75
  };
73
- const argv = spawnArgv(execCommand, execArgs, options);
74
- const child = spawn(argv.command, argv.args, { ...argv.options, detached: DETACHED, stdio: ["ignore", "pipe", "pipe"] });
75
- // treeKill: on win32 a plain kill reaches only the wrapper, not the launcher.
76
- const stop = () => (child.pid ? treeKill(child.pid, { childAlive: isChildAlive(child) }).catch(() => {}) : Promise.resolve());
77
- onSpawn?.({ pid: child.pid, stop });
78
- const closed = new Promise((r) => child.once("close", r));
79
- // Settles once the probe has closed, so doctor does not return with it running.
76
+ // Settles once the stop saw the probe exit, so doctor does not return with it running.
80
77
  const onAbort = () => {
81
78
  // Else it fires during the kill and reports a timeout.
82
79
  clearTimeout(timer);
83
80
  aborting = true;
84
- const bound = new Promise((r) => { setTimeout(r, PROBE_KILL_WAIT_MS).unref?.(); });
85
- Promise.race([Promise.all([stop(), closed]), bound]).then(() => finish({ found: true, ...aborted }));
81
+ probe.stop().then(() => finish({ found: true, ...aborted }));
86
82
  };
87
83
  signal?.addEventListener("abort", onAbort, { once: true });
88
84
  // Capped: a version is one line, and a launcher that streams is not kept whole.
@@ -94,6 +90,8 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
94
90
  child.stderr?.on("error", () => {});
95
91
  child.on("error", () => finish({ found: false, version: null }));
96
92
  child.on("close", (code) => {
93
+ // Closed: its pid may be reused, so no later stop may kill it.
94
+ probe.release();
97
95
  // An aborted probe reports the abort, not the exit its kill caused.
98
96
  if (aborting) return;
99
97
  const version = code === 0 ? stdout.trim() || null : null;
@@ -104,7 +102,8 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
104
102
  });
105
103
  });
106
104
  timer = setTimeout(() => {
107
- stop();
105
+ // Not awaited, so the timeout returns on time; the probe stays tracked until its stop settles.
106
+ probe.stop();
108
107
  // It spawned, so it is found; it just never answered.
109
108
  finish({ found: true, version: null, error: `version probe timed out after ${timeoutMs}ms` });
110
109
  }, timeoutMs);
@@ -112,11 +111,9 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
112
111
  });
113
112
  }
114
113
 
115
- async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs, signal, onClientReady }) {
114
+ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs, signal }) {
116
115
  if (signal?.aborted) return { ok: false, error: "Handshake aborted by MCP host" };
117
116
  const client = clientFactory({ spawnSpec });
118
- // Handed out before the spawn, so a server shutdown can stop it.
119
- onClientReady?.(client);
120
117
  const workspaceDir = workspace || process.cwd();
121
118
  let timer;
122
119
  let onAbort;
@@ -163,7 +160,6 @@ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs
163
160
  }
164
161
 
165
162
  /**
166
- * onClientReady gets each process doctor starts, probe then agent, so a shutdown can stop it.
167
163
  * @param {{
168
164
  * getClientInfo?: () => { capabilities?: any, version?: any, protocolVersion?: string },
169
165
  * deep?: boolean,
@@ -174,7 +170,6 @@ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs
174
170
  * versionTimeoutMs?: number,
175
171
  * readVersion?: () => string,
176
172
  * signal?: AbortSignal,
177
- * onClientReady?: (client: { stop: () => any }) => void,
178
173
  * }} [opts]
179
174
  */
180
175
  export async function runDoctor({
@@ -187,10 +182,9 @@ export async function runDoctor({
187
182
  versionTimeoutMs = VERSION_PROBE_TIMEOUT_MS,
188
183
  readVersion = readPackageVersion,
189
184
  signal,
190
- onClientReady,
191
185
  } = {}) {
192
186
  const { capabilities, version, protocolVersion } = getClientInfo();
193
- const agentProbe = await probeAgentVersion(spawnSpec, versionTimeoutMs, { signal, onSpawn: onClientReady });
187
+ const agentProbe = await probeAgentVersion(spawnSpec, versionTimeoutMs, { signal });
194
188
 
195
189
  /** @type {{ plugin: any, client: any, agent: any & { handshake?: any }, runtime: any, env: any }} */
196
190
  const out = {
@@ -233,7 +227,6 @@ export async function runDoctor({
233
227
  workspace,
234
228
  timeoutMs: handshakeTimeoutMs,
235
229
  signal,
236
- onClientReady,
237
230
  });
238
231
  }
239
232
 
package/src/errors.js CHANGED
@@ -1,18 +1,21 @@
1
1
  /**
2
2
  * Every failure carries a `reason`, so a caller can tell "fix your arguments" from "retry"
3
- * without parsing prose. Errors off the wire also carry the agent's JSON-RPC `code`.
3
+ * without parsing prose. Errors off the wire also carry the agent's JSON-RPC `code`. A note goes on
4
+ * a new error with the old one as its `cause`: a caught error may be frozen or a primitive.
4
5
  *
5
6
  * @typedef {Error & { reason?: string, code?: number }} DelegateError
6
7
  */
7
8
 
8
9
  /**
9
- * @param {string} reason
10
+ * @param {string | undefined} reason
10
11
  * @param {string} message
11
- * @returns {DelegateError}
12
+ * @param {{ code?: number, cause?: unknown }} [extra]
13
+ * @returns {Readonly<DelegateError>}
12
14
  */
13
- export function makeError(reason, message) {
15
+ export function makeError(reason, message, { code, cause } = {}) {
14
16
  /** @type {DelegateError} */
15
- const err = new Error(message);
16
- err.reason = reason;
17
+ const err = new Error(message, cause === undefined ? undefined : { cause });
18
+ if (reason !== undefined) err.reason = reason;
19
+ if (code !== undefined) err.code = code;
17
20
  return err;
18
21
  }
package/src/jsonrpc.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import readline from "node:readline";
2
+ import { makeError } from "./errors.js";
2
3
 
3
4
  const FRAME_CAP = 2048;
4
5
  const DEFAULT_LOG_SIZE = 2000;
@@ -92,10 +93,7 @@ export class JsonRpcPeer {
92
93
  this.pending.delete(key);
93
94
  // cursor-agent puts the reason in error.data.message; error.message is a bare "Invalid params".
94
95
  if (msg.error) {
95
- /** @type {import("./errors.js").DelegateError} */
96
- const err = new Error([msg.error.message || "rpc error", msg.error.data?.message].filter(Boolean).join(": "));
97
- err.code = msg.error.code;
98
- p.reject(err);
96
+ p.reject(makeError(undefined, [msg.error.message || "rpc error", msg.error.data?.message].filter(Boolean).join(": "), { code: msg.error.code }));
99
97
  }
100
98
  else p.resolve(msg.result);
101
99
  }
package/src/proc.js CHANGED
@@ -1,13 +1,15 @@
1
1
  import process from "node:process";
2
- import { execFile } from "node:child_process";
2
+ import { execFile, spawn } from "node:child_process";
3
+ import { spawnArgv } from "./spawn.js";
4
+ import { makeError } from "./errors.js";
3
5
 
4
6
  export function isChildAlive(child) {
5
7
  return child && child.exitCode === null && child.signalCode === null;
6
8
  }
7
9
 
8
10
  // POSIX only: a process group leader (setsid) lets treeKill reach the agent's children. On win32
9
- // it would mean a new console, and taskkill /T walks the tree anyway. Applied at each spawn site,
10
- // not in resolveAcpSpawn, so an injected spec gets it too.
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.
11
13
  export const DETACHED = process.platform !== "win32";
12
14
 
13
15
  // On win32 child.kill() reaches only the wrapper; taskkill /T takes the whole tree.
@@ -29,3 +31,101 @@ export async function treeKill(pid, { childAlive = true } = {}) {
29
31
  // the child is gone, since a reaped pid can already belong to something else.
30
32
  if (childAlive) { try { process.kill(pid, "SIGKILL"); } catch {} }
31
33
  }
34
+
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;
38
+
39
+ async function killAndSeeExit(child, timeoutMs) {
40
+ if (!child.pid) return true;
41
+ 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;
58
+ }
59
+
60
+ /**
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
68
+ */
69
+
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.
72
+ export function createChildRegistry() {
73
+ /** @type {Set<TrackedChild>} */
74
+ const live = new Set();
75
+ let closed = false;
76
+ return {
77
+ /**
78
+ * @param {() => ChildKill} start
79
+ * @returns {TrackedChild}
80
+ */
81
+ track(start) {
82
+ 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;
107
+ },
108
+ // Each stop sends its kill as it starts, so on POSIX every kill is out before this returns.
109
+ stopAll() {
110
+ closed = true;
111
+ return Promise.all([...live].map((entry) => entry.stop())).then(() => undefined);
112
+ },
113
+ };
114
+ }
115
+
116
+ export const children = createChildRegistry();
117
+
118
+ /**
119
+ * The one place a process starts, so shutdown reaches every one. Throws spawn-failed once shutdown
120
+ * began, before spawning.
121
+ * @param {string} command @param {string[]} args @param {any} options
122
+ * @param {{ stdio: any }} where
123
+ * @param {ChildRegistry} [registry]
124
+ */
125
+ export function spawnChild(command, args, options, { stdio }, registry = children) {
126
+ return registry.track(() => {
127
+ 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) };
130
+ });
131
+ }
package/src/server.js CHANGED
@@ -3,12 +3,12 @@ import process from "node:process";
3
3
  import { realpathSync } from "node:fs";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { McpServer, CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, PROTOCOL_VERSION_META_KEY } from "@modelcontextprotocol/server";
6
- import { serveStdio } from "@modelcontextprotocol/server/stdio";
6
+ import { serveStdio, StdioServerTransport } from "@modelcontextprotocol/server/stdio";
7
7
  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 } from "./proc.js";
11
+ import { DETACHED, children } from "./proc.js";
12
12
  import { PLAN_PRIORITIES, PLAN_STATUSES, TODO_STATUSES } from "./acp-enums.js";
13
13
  import { TASKS_EXTENSION, createTaskStore, listsTasks, registerTaskHandlers, runAsTask } from "./tasks.js";
14
14
 
@@ -43,21 +43,9 @@ function unregisterInFlight(map, sessionId, handle) {
43
43
  handles.delete(handle);
44
44
  if (handles.size === 0) map.delete(sessionId);
45
45
  }
46
- // Delegations whose session has not opened yet: the agent runs ~3.4s before inFlight can key it.
47
- // Shutdown walks this; cancel cannot, since the caller has no id for these yet.
48
- const pendingDelegations = new Set();
49
-
50
46
  // Session ids seen by this process, kept after the turn ends so cancel can tell a finished
51
- // (still resumable) session from an id that never existed. Bounded.
47
+ // (still resumable) session from an id that never existed.
52
48
  const seenSessions = new Set();
53
- const SEEN_SESSIONS_CAP = 500;
54
- function rememberSession(set, id) {
55
- if (id == null) return;
56
- // Delete-then-add makes the Set an LRU, so a session still being resumed outlives one seen once.
57
- if (set.has(id)) set.delete(id);
58
- set.add(id);
59
- if (set.size > SEEN_SESSIONS_CAP) set.delete(set.values().next().value);
60
- }
61
49
 
62
50
  // Delegations answered as MCP tasks. Module-level, as inFlight: a task outlives the request that
63
51
  // started it, and serveStdio may build more than one server instance.
@@ -189,18 +177,18 @@ export function progressNotifier(ctx) {
189
177
  * args: any, ctx?: any,
190
178
  * runDelegate: (opts: any) => Promise<any>,
191
179
  * inFlight: Map<string, Set<any>>,
192
- * pending?: Set<any>,
193
180
  * seenSessions?: Set<string>,
194
181
  * signal?: AbortSignal,
195
182
  * onProgress?: (message: string) => void,
196
- * onPromptSent?: (sessionId: string, handle: any) => void,
183
+ * onPromptSent?: (sessionId: string, handle: any, resumeNote?: string) => void,
184
+ * onUnseenExit?: (note: string) => void,
197
185
  * onTurnEnd?: () => void,
198
186
  * }} deps
199
187
  * @returns {Promise<import("@modelcontextprotocol/server").CallToolResult>}
200
188
  */
201
189
  export async function runDelegateTool({
202
- args, ctx, runDelegate, inFlight, pending = new Set(), seenSessions = new Set(),
203
- signal = ctx?.mcpReq?.signal, onProgress = progressNotifier(ctx), onPromptSent, onTurnEnd,
190
+ args, ctx, runDelegate, inFlight, seenSessions = new Set(),
191
+ signal = ctx?.mcpReq?.signal, onProgress = progressNotifier(ctx), onPromptSent, onUnseenExit, onTurnEnd,
204
192
  }) {
205
193
  const { spec, mode, resumeSessionId, workspace, model, fast, effort, context, contextFiles } = args;
206
194
 
@@ -219,18 +207,13 @@ export async function runDelegateTool({
219
207
  contextFiles,
220
208
  onProgress,
221
209
  signal,
222
- onPromptSent: onPromptSent && ((sessionId) => onPromptSent(sessionId, handle)),
223
- onClientReady: (client) => {
224
- handle = { client, cancelRequested: false };
225
- pending.add(handle);
226
- },
210
+ onPromptSent: onPromptSent && ((sessionId, resumeNote) => onPromptSent(sessionId, handle, resumeNote)),
211
+ onUnseenExit,
227
212
  onSessionReady: (sessionId, client) => {
228
213
  capturedSessionId = sessionId;
229
- // The same handle moves across, so a racing shutdown finds it on exactly one side.
230
- handle ??= { client, cancelRequested: false };
231
- pending.delete(handle);
214
+ handle = { client, cancelRequested: false };
232
215
  registerInFlight(inFlight, sessionId, handle);
233
- rememberSession(seenSessions, sessionId);
216
+ seenSessions.add(sessionId);
234
217
  // Sent now so a host that can call tools concurrently has an id to cancel mid-run.
235
218
  onProgress(`session ready: ${sessionId}`);
236
219
  },
@@ -248,9 +231,7 @@ export async function runDelegateTool({
248
231
  isError: true,
249
232
  };
250
233
  } finally {
251
- // Drops only this delegation's handle, from whichever of pending or the map holds it; the id
252
- // stays registered while another turn runs on it.
253
- if (handle) pending.delete(handle);
234
+ // Drops only this delegation's handle; the id stays registered while another turn runs on it.
254
235
  if (capturedSessionId) unregisterInFlight(inFlight, capturedSessionId, handle);
255
236
  }
256
237
  }
@@ -260,14 +241,13 @@ export async function runDelegateTool({
260
241
  * runDelegate?: (opts: any) => Promise<any>,
261
242
  * runDoctor?: (opts: any) => Promise<any>,
262
243
  * forceGraceMs?: number,
263
- * pending?: Set<any>,
264
244
  * inFlight?: Map<string, Set<any>>,
265
245
  * era?: "legacy" | "modern",
266
246
  * tasks?: ReturnType<typeof createTaskStore>,
267
247
  * }} [opts]
268
248
  */
269
249
  export function buildServer({
270
- runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000, pending = pendingDelegations,
250
+ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000,
271
251
  inFlight: flights = inFlight, era, tasks = taskStore,
272
252
  } = {}) {
273
253
  const runDelegate = runDelegateInjected || runDelegateDefault;
@@ -308,9 +288,9 @@ export function buildServer({
308
288
  },
309
289
  async (args, ctx) => {
310
290
  // Claude Code tells the model a task's id and never its session id, even after a stop.
311
- const resumeSessionId = tasks.get(args.resumeSessionId)?.sessionId ?? args.resumeSessionId;
291
+ const resumeSessionId = tasks.sessionOf(args.resumeSessionId) ?? args.resumeSessionId;
312
292
  /** @param {Record<string, any>} [over] */
313
- const run = (over) => runDelegateTool({ args: { ...args, resumeSessionId }, ctx, runDelegate, inFlight: flights, pending, seenSessions, ...over });
293
+ const run = (over) => runDelegateTool({ args: { ...args, resumeSessionId }, ctx, runDelegate, inFlight: flights, seenSessions, ...over });
314
294
  if (!servesTasks || !listsTasks(ctx)) return run();
315
295
  return /** @type {any} */ (runAsTask({ run, signal: ctx?.mcpReq?.signal, notify: progressNotifier(ctx), store: tasks }));
316
296
  }
@@ -320,7 +300,7 @@ export function buildServer({
320
300
  "cancel",
321
301
  {
322
302
  description:
323
- "Best-effort cancel of an in-flight delegation by sessionId. session/cancel is advisory — the agent may finish the turn anyway, and the delegate result then carries cancelRequested. Status: cancelled, killed (agent process observed to exit), not-running (turn already ended, still resumable), not-found (id not in this process's recent session history).",
303
+ "Best-effort cancel of an in-flight delegation by sessionId. session/cancel is advisory — the agent may finish the turn anyway, and the delegate result then carries cancelRequested. Status: cancelled, killed (agent process observed to exit), not-running (turn already ended, still resumable), not-found (id not in this process's session history).",
324
304
  inputSchema: z.object({
325
305
  // Blank is a malformed call, not a stale id.
326
306
  sessionId: z.string().trim().min(1, "sessionId must not be blank").describe("When delegate runs as an MCP task, its server-side task id works too."),
@@ -391,19 +371,8 @@ export function buildServer({
391
371
  },
392
372
  },
393
373
  async ({ deep }, ctx) => {
394
- // doctor's processes sit in pending while it runs, where shutdown already looks.
395
- const handles = [];
396
- try {
397
- const out = await runDoctor({
398
- deep,
399
- signal: ctx?.mcpReq?.signal,
400
- onClientReady: (client) => { const handle = { client }; handles.push(handle); pending.add(handle); },
401
- getClientInfo: () => clientInfoOf(server, ctx),
402
- });
403
- return { content: [{ type: "text", text: JSON.stringify(out) }] };
404
- } finally {
405
- for (const handle of handles) pending.delete(handle);
406
- }
374
+ const out = await runDoctor({ deep, signal: ctx?.mcpReq?.signal, getClientInfo: () => clientInfoOf(server, ctx) });
375
+ return { content: [{ type: "text", text: JSON.stringify(out) }] };
407
376
  }
408
377
  );
409
378
 
@@ -431,36 +400,36 @@ if (process.argv[1]) {
431
400
  }
432
401
  }
433
402
 
434
- // Kill what is still running, then exit, on any way the host has of going away.
435
- export function installSignalCleanup(map, {
436
- pending = new Set(),
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, {
437
407
  exit = (code) => process.exit(code),
438
408
  setExitCode = (code) => { process.exitCode = code; },
439
409
  schedule = (fn) => setImmediate(fn),
440
410
  stdin = process.stdin,
441
411
  } = {}) {
442
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;
443
416
  const shutdown = (code, fromSignal = false) => {
444
- // A second signal exits without the wait, the kills already sent. A stdin EOF does not: a
445
- // hangup closes stdin right after its SIGHUP.
446
- if (shuttingDown) return fromSignal ? exit(code) : undefined;
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
+ }
447
424
  shuttingDown = true;
425
+ exitCode = code;
448
426
  // Set now: the loop may run dry before the scheduled exit gets a turn.
449
427
  setExitCode(code);
450
- const stops = [];
451
- // An unseen exit is not memoized, so a second stop dispatches a fresh kill before the exit.
452
- const stopOnce = (handle) => Promise.resolve(handle.client.stop()).catch(() => false);
453
- const dispatch = (handle) => {
454
- try { stops.push(stopOnce(handle).then((exited) => (exited === false ? stopOnce(handle) : exited))); } catch {}
455
- };
456
- for (const handles of map.values()) for (const handle of handles) dispatch(handle);
457
- // Delegations still in their handshake: their agent runs, and only pending reaches it.
458
- for (const handle of pending) dispatch(handle);
459
428
  // Waits for the kills: on Windows taskkill is a separate process, and exiting first orphans the
460
- // launcher and agent below the shell (measured). stop() bounds itself, so the wait is finite.
429
+ // launcher and agent below the shell (measured). Each stop bounds itself, so the wait is finite.
461
430
  // The exit is scheduled onto a clean loop turn rather than run on the settlement stack.
462
- const leave = () => schedule(() => exit(code));
463
- Promise.all(stops).then(leave, leave);
431
+ const leave = () => schedule(() => exit(exitCode));
432
+ registry.stopAll().then(leave, leave);
464
433
  };
465
434
  // On POSIX each agent has its own process group, which a signal to this process misses, so the
466
435
  // handler kills them first. SIGHUP too: a closed terminal, whose default leaves them running.
@@ -471,6 +440,7 @@ export function installSignalCleanup(map, {
471
440
  // A stdio host closes stdin before it resorts to a signal. The SDK aborts in-flight requests on
472
441
  // EOF; this also stops their agents directly, waits for the kills, and exits.
473
442
  stdin.on("end", () => shutdown(0));
443
+ return () => shutdown(0);
474
444
  }
475
445
 
476
446
  if (isMain) {
@@ -480,9 +450,16 @@ if (isMain) {
480
450
  if (argv.includes("--version") || argv.includes("-v")) {
481
451
  console.log(readPackageVersion());
482
452
  } else {
483
- installSignalCleanup(inFlight, { pending: pendingDelegations });
453
+ const hostGone = installSignalCleanup();
454
+ const transport = new StdioServerTransport();
484
455
  // One factory serves both protocol eras: a 2025-era initialize pins a legacy instance, and only
485
456
  // a modern one answers with tasks.
486
- serveStdio(({ era }) => buildServer({ era }));
457
+ serveStdio(({ era }) => buildServer({ era }), { transport });
458
+ // The transport also closes on a broken stdout, and then pauses stdin, so no 'end' arrives.
459
+ const closeServers = transport.onclose;
460
+ transport.onclose = () => {
461
+ closeServers?.();
462
+ hostGone();
463
+ };
487
464
  }
488
465
  }
@@ -27,6 +27,7 @@ export class SessionSupervisor {
27
27
  this.lastActivityAt = Date.now();
28
28
  this._resetIdle();
29
29
  };
30
+ this._onSetupCancel = () => this._trip("cancelled-in-setup", "cancelled before the prompt was sent");
30
31
  this._onExit = (info) => {
31
32
  this._trip(
32
33
  "agent-exit",
@@ -40,6 +41,10 @@ export class SessionSupervisor {
40
41
  this.sessionId = sessionId;
41
42
  }
42
43
 
44
+ get settled() {
45
+ return this._settled;
46
+ }
47
+
43
48
  msSinceActivity() {
44
49
  return Date.now() - this.lastActivityAt;
45
50
  }
@@ -49,6 +54,7 @@ export class SessionSupervisor {
49
54
  this._armed = true;
50
55
  this.client.on("activity", this._onActivity);
51
56
  this.client.on("exit", this._onExit);
57
+ this.client.on("cancelled-in-setup", this._onSetupCancel);
52
58
  this._hardCapTimer = setTimeout(() => {
53
59
  this._trip("hard-cap", `Session hard-cap exceeded after ${this.hardCapMs}ms`);
54
60
  }, this.hardCapMs);
@@ -72,6 +78,7 @@ export class SessionSupervisor {
72
78
  this._armed = false;
73
79
  this.client.off("activity", this._onActivity);
74
80
  this.client.off("exit", this._onExit);
81
+ this.client.off("cancelled-in-setup", this._onSetupCancel);
75
82
  clearTimeout(this._idleTimer);
76
83
  clearTimeout(this._handshakeTimer);
77
84
  clearTimeout(this._hardCapTimer);
@@ -101,6 +108,8 @@ export class SessionSupervisor {
101
108
  if (reason === "idle-timeout" || reason === "handshake-timeout" || reason === "hard-cap" || reason === "aborted") {
102
109
  if (this.sessionId) { try { this.client.cancel(this.sessionId); } catch {} }
103
110
  }
111
+ // Ended whether or not a session opened, so setup orphaned by this trip sends nothing more.
112
+ try { this.client.endTurn?.(); } catch {}
104
113
  this._guardReject?.(err);
105
114
  }
106
115
 
package/src/tasks.js CHANGED
@@ -6,7 +6,6 @@ import { CLIENT_CAPABILITIES_META_KEY, MissingRequiredClientCapabilityError, Pro
6
6
  export const TASKS_EXTENSION = "io.modelcontextprotocol/tasks";
7
7
 
8
8
  const RETAIN_MS = 60 * 60 * 1000;
9
- const MAX_FINISHED = 100;
10
9
  const FAST_POLL_MS = 3000;
11
10
  const SLOW_POLL_MS = 10000;
12
11
  const FAST_POLL_FOR_MS = 60 * 1000;
@@ -20,26 +19,38 @@ export function listsTasks(ctx) {
20
19
  * @typedef {{
21
20
  * taskId: string, status: "working" | "completed" | "failed" | "cancelled",
22
21
  * createdAt: number, lastUpdatedAt: number, endedAt?: number, statusMessage?: string,
23
- * sessionId?: string, handle?: any, turnEnded: boolean, ac: AbortController,
22
+ * sessionId?: string, handle?: any, resumeNote?: string, turnEnded: boolean, ac: AbortController,
24
23
  * result?: any, error?: { code: number, message: string },
25
24
  * }} Task
26
25
  */
27
26
 
28
- /** @param {{ now?: () => number, retainMs?: number, maxFinished?: number }} [opts] */
29
- export function createTaskStore({ now = Date.now, retainMs = RETAIN_MS, maxFinished = MAX_FINISHED } = {}) {
27
+ /** @param {{ now?: () => number, retainMs?: number }} [opts] */
28
+ export function createTaskStore({ now = Date.now, retainMs = RETAIN_MS } = {}) {
30
29
  /** @type {Map<string, Task>} */
31
30
  const tasks = new Map();
31
+ // A dropped task's session, so its id still resumes it: the host shows the model only the task id.
32
+ /** @type {Map<string, string>} */
33
+ const sessions = new Map();
32
34
  // A running task is never dropped: its id is the host's only handle on the run.
33
35
  const prune = () => {
34
36
  const t = now();
35
- const finished = [...tasks.values()].filter((task) => task.endedAt !== undefined);
36
- for (const task of finished) if (t - /** @type {number} */ (task.endedAt) > retainMs) tasks.delete(task.taskId);
37
- const kept = finished.filter((task) => tasks.has(task.taskId))
38
- .sort((a, b) => /** @type {number} */ (a.endedAt) - /** @type {number} */ (b.endedAt));
39
- for (const task of kept.slice(0, Math.max(0, kept.length - maxFinished))) tasks.delete(task.taskId);
37
+ for (const task of tasks.values()) {
38
+ if (task.endedAt === undefined || t - task.endedAt <= retainMs) continue;
39
+ tasks.delete(task.taskId);
40
+ if (task.sessionId) sessions.set(task.taskId, task.sessionId);
41
+ }
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();
40
50
  };
41
51
  return {
42
52
  now,
53
+ note,
43
54
  /** @returns {Task} */
44
55
  create() {
45
56
  const t = now();
@@ -49,22 +60,30 @@ export function createTaskStore({ now = Date.now, retainMs = RETAIN_MS, maxFinis
49
60
  add(task) { prune(); tasks.set(task.taskId, task); },
50
61
  /** @param {string} taskId */
51
62
  get(taskId) { prune(); return tasks.get(taskId); },
63
+ /** @param {string | undefined} taskId */
64
+ sessionOf(taskId) {
65
+ if (taskId === undefined) return undefined;
66
+ prune();
67
+ return tasks.get(taskId)?.sessionId ?? sessions.get(taskId);
68
+ },
69
+ // A cancelled task keeps its own status message: the run's error names the abort, a reason no
70
+ // blocking call returns.
52
71
  /** @param {Task} task @param {{ result?: any, error?: any }} outcome */
53
72
  finish(task, outcome) {
54
73
  if (task.status === "working") {
55
- task.endedAt = now();
74
+ task.endedAt = task.lastUpdatedAt = now();
75
+ // The last progress line is stale once the run is over; a failure says why instead.
56
76
  if ("error" in outcome) {
57
77
  task.status = "failed";
58
78
  task.error = { code: ProtocolErrorCode.InternalError, message: String(outcome.error?.message ?? outcome.error) };
79
+ task.statusMessage = task.error.message;
59
80
  } else {
60
81
  task.status = "completed";
61
- task.result = outcome.result;
82
+ // The tools/call result a 2026-07-28 host would have read, marked as one.
83
+ task.result = { ...outcome.result, resultType: "complete" };
84
+ task.statusMessage = undefined;
62
85
  }
63
- } else if (outcome.result?.isError) {
64
- // A cancelled run's own error names its resume id and an agent the stop did not see exit.
65
- task.statusMessage = outcome.result.content?.[0]?.text ?? task.statusMessage;
66
86
  }
67
- task.lastUpdatedAt = now();
68
87
  prune();
69
88
  },
70
89
  // A turn that has ended has its result decided, so a cancel leaves it, as the cancel tool does.
@@ -73,6 +92,7 @@ export function createTaskStore({ now = Date.now, retainMs = RETAIN_MS, maxFinis
73
92
  if (task.status !== "working" || task.turnEnded) return;
74
93
  task.status = "cancelled";
75
94
  task.statusMessage = task.sessionId ? `cancelled; resume with resumeSessionId ${task.sessionId}` : "cancelled";
95
+ if (task.resumeNote) note(task, task.resumeNote);
76
96
  task.endedAt = task.lastUpdatedAt = now();
77
97
  task.ac.abort();
78
98
  },
@@ -100,7 +120,7 @@ export function createTaskStore({ now = Date.now, retainMs = RETAIN_MS, maxFinis
100
120
  * Runs a delegation that answers its request with a task once the prompt is sent. A run that
101
121
  * settles before then, setup failures included, answers with its result as a blocking call does.
102
122
  * @param {{
103
- * run: (over: { signal: AbortSignal, onProgress: (m: string) => void, onPromptSent: (id: string, handle?: any) => void, onTurnEnd: () => void }) => Promise<any>,
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>,
104
124
  * signal?: AbortSignal, notify?: (message: string) => void, store: ReturnType<typeof createTaskStore>,
105
125
  * }} opts
106
126
  */
@@ -124,13 +144,13 @@ export async function runAsTask({ run, signal, notify = () => {}, store }) {
124
144
  // Once the task is the answer, progress belongs to the task, not the request.
125
145
  if (!answered) notify(message);
126
146
  },
127
- onPromptSent: (sessionId, handle) => { task.sessionId = sessionId; task.handle = handle; markSent(); },
147
+ onPromptSent: (sessionId, handle, resumeNote) => { task.sessionId = sessionId; task.handle = handle; task.resumeNote = resumeNote; markSent(); },
148
+ onUnseenExit: (note) => store.note(task, note),
128
149
  onTurnEnd: () => { task.turnEnded = true; },
129
150
  }).then((result) => ({ result }), (error) => ({ error }));
130
151
  const first = await Promise.race([sent, outcome]);
131
152
  signal?.removeEventListener("abort", forward);
132
- // An abort before the agent has a session sends no session/cancel, so setup can still reach the
133
- // prompt; the request is gone by then and nobody would receive the task id.
153
+ // A request cancelled as its prompt goes out is gone, so nobody would receive the task id.
134
154
  const settled = first ?? (task.ac.signal.aborted ? await outcome : undefined);
135
155
  if (settled) {
136
156
  if ("error" in settled) throw settled.error;
@@ -160,8 +180,15 @@ export function registerTaskHandlers(server, store) {
160
180
  server.server.setRequestHandler("tasks/get", { params: TaskParams, result: AnyResult },
161
181
  async (/** @type {any} */ { taskId }, /** @type {any} */ ctx) => store.view(find(taskId, ctx)));
162
182
  // A delegation never enters input_required: its questions come back in the result.
183
+ // The SDK lifts inputResponses into ctx before validation, and reads a non-object as an empty map.
163
184
  server.server.setRequestHandler("tasks/update", { params: TaskParams, result: AnyResult },
164
- async (/** @type {any} */ { taskId }, /** @type {any} */ ctx) => { find(taskId, ctx); return {}; });
185
+ async (/** @type {any} */ { taskId }, /** @type {any} */ ctx) => {
186
+ find(taskId, ctx);
187
+ if (ctx?.mcpReq?.inputResponses === undefined) {
188
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, "tasks/update needs inputResponses");
189
+ }
190
+ return {};
191
+ });
165
192
  server.server.setRequestHandler("tasks/cancel", { params: TaskParams, result: AnyResult },
166
193
  async (/** @type {any} */ { taskId }, /** @type {any} */ ctx) => { store.cancel(find(taskId, ctx)); return {}; });
167
194
  }