cursor-delegate-mcp 1.20.0 → 1.22.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursor-delegate-mcp",
3
- "version": "1.20.0",
3
+ "version": "1.22.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, or Copilot to Cursor's CLI agent — structured results, plan mode, and changed files.",
package/src/acp-client.js CHANGED
@@ -4,11 +4,14 @@ import { StringDecoder } from "node:string_decoder";
4
4
  import { JsonRpcPeer } from "./jsonrpc.js";
5
5
  import { createRequestRouter } from "./request-router.js";
6
6
  import { resolveAcpSpawn } from "./spawn.js";
7
- import { isChildAlive, treeKill } from "./proc.js";
7
+ import { DETACHED, isChildAlive, treeKill } from "./proc.js";
8
8
  import { VERSION } from "./version.js";
9
9
  import { makeError } from "./errors.js";
10
10
 
11
11
  const STDERR_CAP = 64 * 1024;
12
+ // How long stop() waits for the child to actually exit after the kill is dispatched. SIGKILL and
13
+ // taskkill /F land in milliseconds, so this only ever elapses when the kill did not work.
14
+ const STOP_EXIT_TIMEOUT_MS = 2000;
12
15
 
13
16
  export class AcpClient extends EventEmitter {
14
17
  /**
@@ -27,6 +30,8 @@ export class AcpClient extends EventEmitter {
27
30
  this.onTodos = onTodos;
28
31
  this._stderrChunks = [];
29
32
  this._stderrLength = 0;
33
+ /** @type {Promise<boolean> | null} */
34
+ this._stopping = null;
30
35
  }
31
36
 
32
37
  // The tail of stderr, which is what an exit error quotes. Kept as chunks and joined on read:
@@ -44,7 +49,7 @@ export class AcpClient extends EventEmitter {
44
49
  this._stderrLength = 0;
45
50
  const stderrDecoder = new StringDecoder("utf8");
46
51
  this._exitEmitted = false;
47
- this.child = spawn(command, args, { ...options, stdio: ["pipe", "pipe", "pipe"] });
52
+ this.child = spawn(command, args, { ...options, detached: DETACHED, stdio: ["pipe", "pipe", "pipe"] });
48
53
  this.child.stderr.on("data", (chunk) => {
49
54
  const text = stderrDecoder.write(chunk);
50
55
  if (text) {
@@ -131,12 +136,40 @@ export class AcpClient extends EventEmitter {
131
136
 
132
137
  getTranscript(n) { return this.peer ? this.peer.formatLog(n) : ""; }
133
138
 
134
- stop() {
135
- try { this.peer?.close(); } catch {}
136
- if (isChildAlive(this.child) && this.child.pid) {
137
- treeKill(this.child.pid).catch(() => {});
138
- } else {
139
- try { this.child?.kill(); } catch {}
139
+ // Idempotent, so a force-cancel racing the delegation's own finally tears down once and both
140
+ // see the same answer. Resolves true when the child was observed to exit, false when the bound
141
+ // elapsed first: dispatching a signal is not the same fact as the process being gone, and
142
+ // cancel reports the difference rather than calling both "killed".
143
+ stop({ timeoutMs = STOP_EXIT_TIMEOUT_MS } = {}) {
144
+ if (!this._stopping) this._stopping = this._teardown(timeoutMs);
145
+ return this._stopping;
146
+ }
147
+
148
+ async _teardown(timeoutMs) {
149
+ const child = this.child;
150
+ if (!child?.pid) {
151
+ try { this.peer?.close(); } catch {}
152
+ return true;
140
153
  }
154
+ const alive = isChildAlive(child);
155
+ // Subscribed before the kill is dispatched. A child that dies immediately would otherwise
156
+ // exit in the gap and leave this waiting on an event that has already fired.
157
+ const exited = alive
158
+ ? /** @type {Promise<boolean>} */ (new Promise((resolve) => child.once("exit", () => resolve(true))))
159
+ : Promise.resolve(true);
160
+ // Runs for an exited child too: the agent can be gone while the commands it spawned are still
161
+ // running, and on POSIX they stay in its process group, which is the only handle left on them.
162
+ treeKill(child.pid, { childAlive: alive }).catch(() => {});
163
+ /** @type {NodeJS.Timeout | undefined} */
164
+ let timer;
165
+ const bounded = /** @type {Promise<boolean>} */ (new Promise((resolve) => {
166
+ timer = setTimeout(() => resolve(false), timeoutMs);
167
+ }));
168
+ const observed = await Promise.race([exited, bounded]);
169
+ clearTimeout(timer);
170
+ // Pending RPCs are left to the exit handler, which rejects them with agent-exit. Rejecting
171
+ // them here too would settle the same promises twice for no new information.
172
+ try { this.peer?.close(); } catch {}
173
+ return observed;
141
174
  }
142
175
  }
package/src/delegate.js CHANGED
@@ -12,9 +12,12 @@ import { normalizeAgentReportedFiles } from "./agent-reported-files.js";
12
12
  import { makeTurnState } from "./turn-state.js";
13
13
  import { makeError } from "./errors.js";
14
14
  import { PLAN_PRIORITIES, PLAN_STATUSES, TODO_STATUSES } from "./acp-enums.js";
15
- import { optionsFrom, resolveEffortId, unsupportedWarning } from "./model-options.js";
15
+ import { optionsFrom, resolveEffort, unsupportedWarning } from "./model-options.js";
16
16
 
17
17
  export const DEFAULT_MODEL = "composer-2.5";
18
+ // The one advertised id the agent resolves to a different model ("Auto"), so it is the one id
19
+ // whose served model has to be read back off a config reply for effectiveModel.
20
+ const ROUTED_MODEL = "default";
18
21
  export const DEFAULT_HANDSHAKE_MS = 60000;
19
22
  export const DEFAULT_HEARTBEAT_MS = 30000;
20
23
 
@@ -33,37 +36,12 @@ function fmtDuration(ms) {
33
36
  return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s`;
34
37
  }
35
38
 
36
- // Two separate questions. "Could this be a path?" is loose — worth a stat. "Was a path clearly
37
- // intended?" must be strict, since ordinary prose names files ("fix the bug in src/api.js") and
38
- // must never be rejected for it. Whitespace discriminates: a path argument has none.
39
- function looksLikeSpecPath(spec) {
40
- return !spec.includes("\n")
41
- && (spec.includes("/") || spec.includes("\\") || spec.endsWith(".md") || spec.endsWith(".txt"));
42
- }
43
- const isBareSpecPath = (spec) => !/\s/.test(spec.trim());
44
-
45
- async function resolveSpec(spec) {
46
- if (typeof spec !== "string") return spec;
47
- // A blank spec spins up a live session that only replies "No prompt content provided" —
48
- // a billed turn for nothing. Reject it here, before the spawn, like the other bad specs.
49
- if (spec.trim() === "") {
50
- throw makeError("invalid-spec", "spec is empty. Provide a task brief inline, or a path to one.");
51
- }
52
- if (!looksLikeSpecPath(spec)) return spec;
53
- let stat;
54
- try {
55
- stat = statSync(spec);
56
- } catch {
57
- // Only a bare path was unambiguously meant as one. Anything else is prose that happens
58
- // to name a file, and prose is the common case.
59
- if (!isBareSpecPath(spec)) return spec;
60
- throw makeError("invalid-spec", `spec looks like a file path but nothing exists at ${spec}. Pass the brief inline, or fix the path.`);
39
+ // A blank spec spins up a live session that only replies "No prompt content provided" —
40
+ // a billed turn for nothing. Reject it before the spawn, like a bad workspace.
41
+ function assertSpec(spec) {
42
+ if (typeof spec === "string" && spec.trim() === "") {
43
+ throw makeError("invalid-spec", "spec is empty. Provide a task brief.");
61
44
  }
62
- if (stat.isFile()) return readFile(spec, "utf8");
63
- if (isBareSpecPath(spec)) {
64
- throw makeError("invalid-spec", `spec looks like a file path but ${spec} is not a file. Pass the brief inline, or point at a file.`);
65
- }
66
- return spec;
67
45
  }
68
46
 
69
47
  // Without this, the agent's first write creates the directory: a typo'd workspace spawns a
@@ -204,6 +182,13 @@ async function applyConfig(client, sessionId, configId, value) {
204
182
 
205
183
  // The resolved model appears only in a set_config_option reply's configOptions (set_model
206
184
  // returns nothing). Absent for models that reject every option sent — the field then stays off.
185
+ // session/new and session/load both report the values the session opens with, which is what makes
186
+ // a config round-trip skippable: the bridge can see it would set what is already set.
187
+ function configOptionValue(configOptions, id) {
188
+ const opt = (Array.isArray(configOptions) ? configOptions : []).find((o) => o?.id === id);
189
+ return typeof opt?.currentValue === "string" ? opt.currentValue : undefined;
190
+ }
191
+
207
192
  function servedModelFrom(res) {
208
193
  const opts = optionsFrom(res);
209
194
  if (opts === undefined) return undefined;
@@ -211,13 +196,42 @@ function servedModelFrom(res) {
211
196
  return typeof m?.currentValue === "string" ? m.currentValue : undefined;
212
197
  }
213
198
 
214
- // Sent under whichever id the model declares. A model that refuses fast leaves no option list;
215
- // only then are the candidate ids tried in turn.
216
- async function applyEffort(client, sessionId, value, modelOptions) {
217
- const id = resolveEffortId(modelOptions, value);
218
- if (id === undefined) return { applied: false };
219
- const r = await applyConfig(client, sessionId, id, value);
220
- return r.unsupported ? { applied: false } : { applied: true, res: r.res };
199
+ // Sent only when the exact value appears under a thought-level option the selected model
200
+ // advertised. Local validation keeps a bad token out of ACP and, more importantly, out of a
201
+ // billed prompt. Missing capability data is not mislabeled as a caller mistake.
202
+ async function applyEffort(client, sessionId, model, value, modelOptions) {
203
+ const resolved = resolveEffort(modelOptions, value);
204
+ if (resolved.status === "unavailable") {
205
+ throw makeError(
206
+ "effort-options-unavailable",
207
+ `Cannot validate effort ${JSON.stringify(value)} for ${JSON.stringify(model)}:`
208
+ + " the selected model did not report a usable effort option list."
209
+ );
210
+ }
211
+ if (resolved.status === "unsupported") {
212
+ throw makeError(
213
+ "invalid-effort",
214
+ `Model ${JSON.stringify(model)} does not advertise configurable effort.`
215
+ + ` Accepted: none. Omit effort; do not send ${JSON.stringify("none")}.`
216
+ );
217
+ }
218
+ if (resolved.status === "invalid") {
219
+ throw makeError(
220
+ "invalid-effort",
221
+ `Invalid effort ${JSON.stringify(value)} for ${JSON.stringify(model)}.`
222
+ + ` Accepted: ${JSON.stringify(resolved.accepted)}.`
223
+ );
224
+ }
225
+
226
+ const r = await applyConfig(client, sessionId, resolved.id, resolved.value);
227
+ if (r.unsupported) {
228
+ throw makeError(
229
+ "effort-options-unavailable",
230
+ `Cannot apply effort ${JSON.stringify(value)} for ${JSON.stringify(model)}:`
231
+ + ` the selected model advertised option ${JSON.stringify(resolved.id)} but rejected it.`
232
+ );
233
+ }
234
+ return r.res;
221
235
  }
222
236
 
223
237
  /**
@@ -239,18 +253,17 @@ export async function runDelegate({
239
253
  heartbeatMs = DEFAULT_HEARTBEAT_MS,
240
254
  signal,
241
255
  } = {}) {
256
+ // Nothing between here and the abort listener below may await: addEventListener does not
257
+ // replay an abort that already fired, so an abort landing in that window would be lost. A
258
+ // spec read used to await here, and did lose one. Throwing, not supervisor.abort(): tripping
259
+ // before supervise() installs its reject settles the supervisor with nothing listening.
242
260
  if (signal?.aborted) {
243
261
  throw makeError("aborted", "delegation aborted by MCP host");
244
262
  }
245
263
  // Before the spawn: validating later costs a process, a handshake and a billed turn.
246
264
  assertWorkspace(workspace);
247
- const promptText = await resolveSpec(spec);
248
- // addEventListener does not replay an abort that already fired, and the listener is registered
249
- // below, so an abort during the await above is otherwise lost. Throwing, not supervisor.abort():
250
- // tripping before supervise() installs its reject settles the supervisor with nothing listening.
251
- if (signal?.aborted) {
252
- throw makeError("aborted", "delegation aborted by MCP host");
253
- }
265
+ assertSpec(spec);
266
+ const promptText = spec;
254
267
  const capMs = hardCapMs ?? timeoutMs ?? envMs("CURSOR_DELEGATE_HARD_CAP_MS", 3600000);
255
268
  const shakeMs = handshakeMs ?? envMs("CURSOR_DELEGATE_HANDSHAKE_MS", DEFAULT_HANDSHAKE_MS);
256
269
  const turnIdleMs = idleMs ?? envMs("CURSOR_DELEGATE_IDLE_MS", 0);
@@ -399,15 +412,28 @@ export async function runDelegate({
399
412
  supervisor.setSessionId(sessionId);
400
413
  onSessionReady?.(sessionId, client);
401
414
  assertKnownModel(client, model);
402
- await client.setModel(sessionId, model);
403
- // fast is always sent — a resumed session may already have it on, so false is a real
404
- // instruction. Its reply carries this model's configOptions, which is where the effort id
405
- // comes from. effort and context go only when the caller named one. Each reply reports the
406
- // now-current model; the last one seen wins.
407
- const fastResult = await applyConfig(client, sessionId, "fast", fast);
408
- if (fastResult.unsupported && fast) unsupportedOptions.push({ arg: "fast" });
409
- else servedModel = servedModelFrom(fastResult.res) ?? servedModel;
410
- let modelOptions = optionsFrom(fastResult.res);
415
+ // session/new and session/load both report the model the session opened on, and an id that
416
+ // already matches is served without an explicit set — measured, so this round-trip has
417
+ // nothing to change. Cursor carries the selection across sessions, so the common shape
418
+ // (same model twice running) hits this.
419
+ const openedOnModel = client.sessionModels?.currentModelId === model;
420
+ if (!openedOnModel) await client.setModel(sessionId, model);
421
+ // fast is an instruction, not a probe. Cursor persists the tier, and persists it per model —
422
+ // both measured: one fast:true turn leaves the next fresh session reporting fast=true, and a
423
+ // set_model to another model reports that model's own tier. So the opening snapshot only
424
+ // describes the tier in force when the session also opened on this model; after a switch it
425
+ // describes the model we left. Skip only when both hold, which is the steady-state path this
426
+ // is for, and send whenever the reply itself is read: effort needs its option list, and a
427
+ // routable id needs the served model. An absent value reads as a mismatch and sends. effort
428
+ // and context go only when the caller named one; the last reply seen wins.
429
+ const openedFast = configOptionValue(client.configOptions, "fast");
430
+ let modelOptions;
431
+ if (!openedOnModel || openedFast !== String(fast) || effort !== undefined || model === ROUTED_MODEL) {
432
+ const fastResult = await applyConfig(client, sessionId, "fast", fast);
433
+ if (fastResult.unsupported && fast) unsupportedOptions.push({ arg: "fast" });
434
+ else servedModel = servedModelFrom(fastResult.res) ?? servedModel;
435
+ modelOptions = optionsFrom(fastResult.res);
436
+ }
411
437
  // A model that refuses fast leaves no list. Re-asserting the model just set is inert, and
412
438
  // its reply carries the full list — measured on claude-haiku-4-5, which refuses fast.
413
439
  if (modelOptions === undefined && effort !== undefined) {
@@ -416,9 +442,8 @@ export async function runDelegate({
416
442
  servedModel = servedModelFrom(reasserted.res) ?? servedModel;
417
443
  }
418
444
  if (effort !== undefined) {
419
- const applied = await applyEffort(client, sessionId, effort, modelOptions);
420
- if (!applied.applied) unsupportedOptions.push({ arg: "effort", modelOptions });
421
- else servedModel = servedModelFrom(applied.res) ?? servedModel;
445
+ const r = await applyEffort(client, sessionId, model, effort, modelOptions);
446
+ servedModel = servedModelFrom(r) ?? servedModel;
422
447
  }
423
448
  if (context !== undefined) {
424
449
  const r = await applyConfig(client, sessionId, "context", context);
@@ -567,6 +592,8 @@ export async function runDelegate({
567
592
  clearInterval(heartbeat);
568
593
  signal?.removeEventListener("abort", onAbort);
569
594
  try { supervisor.finish(); } catch {}
570
- client.stop();
595
+ // Deliberately not awaited: stop() waits for the child to exit, and every turn — success as
596
+ // much as failure — would pay that before returning. Nothing here reads whether it landed.
597
+ Promise.resolve(client.stop()).catch(() => {});
571
598
  }
572
599
  }
package/src/doctor.js CHANGED
@@ -2,7 +2,7 @@ import process from "node:process";
2
2
  import { spawn } from "node:child_process";
3
3
  import { AcpClient } from "./acp-client.js";
4
4
  import { resolveAcpSpawn } from "./spawn.js";
5
- import { treeKill } from "./proc.js";
5
+ import { DETACHED, treeKill } from "./proc.js";
6
6
  import { readPackageVersion } from "./version.js";
7
7
  import { allowedValues } from "./model-options.js";
8
8
 
@@ -32,7 +32,7 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
32
32
  clearTimeout(timer);
33
33
  resolve(result);
34
34
  };
35
- const child = spawn(execCommand, execArgs, { ...options, stdio: ["ignore", "pipe", "pipe"] });
35
+ const child = spawn(execCommand, execArgs, { ...options, detached: DETACHED, stdio: ["ignore", "pipe", "pipe"] });
36
36
  child.stdout?.on("data", (chunk) => { stdout += chunk.toString(); });
37
37
  child.on("error", () => finish({ found: false, version: null }));
38
38
  child.on("close", (code) => {
@@ -77,7 +77,9 @@ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs
77
77
  })();
78
78
  const timeout = new Promise((_, reject) => {
79
79
  timer = setTimeout(() => {
80
- try { client.stop(); } catch {}
80
+ // Not awaited, so the timeout still rejects at its stated deadline rather than at the
81
+ // deadline plus teardown. The finally below awaits the same idempotent promise.
82
+ try { Promise.resolve(client.stop()).catch(() => {}); } catch {}
81
83
  reject(new Error(`Handshake timed out after ${timeoutMs}ms`));
82
84
  }, timeoutMs);
83
85
  });
@@ -87,7 +89,9 @@ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs
87
89
  return { ok: false, error: err?.message || String(err) };
88
90
  } finally {
89
91
  clearTimeout(timer);
90
- try { client.stop(); } catch {}
92
+ // Awaited so doctor does not return while the agent it spawned is still being torn down.
93
+ // A killed child exits in milliseconds; only one that ignores the kill costs the full bound.
94
+ try { await Promise.resolve(client.stop()); } catch {}
91
95
  }
92
96
  }
93
97
 
package/src/jsonrpc.js CHANGED
@@ -30,6 +30,10 @@ export class JsonRpcPeer {
30
30
  // 0 disables recording and is documented; anything unparseable is a typo, and silently
31
31
  // disabling the transcript on a typo is the opposite of what the setter wanted.
32
32
  this._logSize = readLogSize(process.env.ACP_LOG_SIZE);
33
+ // The failure transcript is the only thing that reads these frames, and it is opt-in, so
34
+ // recording by default retained up to _logSize × FRAME_CAP bytes per delegation that nothing
35
+ // would ever ask for. ACP_LOG_SIZE still bounds retention and still disables at 0.
36
+ this._recording = this._logSize > 0 && Number(process.env.CURSOR_DELEGATE_TRANSCRIPT) > 0;
33
37
  this._log = [];
34
38
  this.rl = readline.createInterface({ input });
35
39
  this.rl.on("line", (line) => this._onLine(line));
@@ -39,7 +43,7 @@ export class JsonRpcPeer {
39
43
  // chatty turn cost more than parsing the frames. Let the array overshoot by a quarter and trim
40
44
  // in one batch; readers below take the last _logSize, so what the log reports is unchanged.
41
45
  _record(dir, line) {
42
- if (this._logSize <= 0) return;
46
+ if (!this._recording) return;
43
47
  const truncated = line.length > FRAME_CAP ? line.slice(0, FRAME_CAP) : line;
44
48
  this._log.push({ t: Date.now(), dir, line: truncated });
45
49
  if (this._log.length > this._logSize + (this._logSize >> 2)) {
@@ -21,32 +21,27 @@ export function allowedValues(opt) {
21
21
  .filter((v) => typeof v === "string");
22
22
  }
23
23
 
24
- function isBoolean(opt) {
25
- const v = allowedValues(opt).slice().sort();
26
- return v.length === 2 && v[0] === "false" && v[1] === "true";
27
- }
24
+ // Resolve only values the selected model advertised. This keeps future vocabularies working
25
+ // without aliases or a ranking table: xhigh, extra-high, max and ultra are just exact tokens.
26
+ // A reported config list with no thought-level option is authoritative (unsupported); no list,
27
+ // an empty list, or a thought-level option with no usable id/values is not.
28
+ export function resolveEffort(options, value) {
29
+ if (!Array.isArray(options) || options.length === 0) return { status: "unavailable" };
30
+
31
+ const candidates = options.filter(isThoughtLevel);
32
+ if (candidates.length === 0) return { status: "unsupported", accepted: [] };
33
+
34
+ const usable = candidates.filter((o) => typeof o?.id === "string");
35
+ const accepted = [...new Set(usable.flatMap(allowedValues))];
36
+ if (usable.length === 0 || accepted.length === 0) return { status: "unavailable" };
28
37
 
29
- // Claude declares thinking (true|false) and effort (low|medium|high) together, so the value picks
30
- // the id. With no match, a non-boolean candidate still goes: the agent's own "Invalid value for X"
31
- // names the allowed set. A boolean-only model (claude-haiku-4-5 declares just thinking) gets
32
- // nothing — sending a level there is a guaranteed invalid value, which would fail the run.
33
- export function resolveEffortId(options, value) {
34
- const candidates = (Array.isArray(options) ? options : []).filter(isThoughtLevel);
35
- if (candidates.length === 0) return undefined;
36
- const pick = candidates.find((o) => allowedValues(o).includes(value))
37
- ?? candidates.find((o) => !isBoolean(o));
38
- return typeof pick?.id === "string" ? pick.id : undefined;
38
+ const pick = usable.find((o) => allowedValues(o).includes(value));
39
+ if (pick === undefined) return { status: "invalid", accepted };
40
+ return { status: "matched", id: pick.id, value };
39
41
  }
40
42
 
41
- // effort's id varies per model, so name the ids the model declares. fast and context are sent
42
- // under their own names.
43
- export function unsupportedWarning(model, { arg, modelOptions }) {
44
- if (arg !== "effort") return `model ${model} has no ${arg} option; the requested value was ignored`;
45
- // No reply carried a list, so claiming the model declares nothing would assert a capability
46
- // never observed.
47
- if (modelOptions === undefined) return `effort ignored: ${model} did not report its option list`;
48
- const ids = modelOptions.filter(isThoughtLevel).map((o) => o?.id).filter(Boolean);
49
- return ids.length
50
- ? `effort ignored: ${model} declares ${ids.join(", ")}, which did not take the requested value`
51
- : `effort ignored: ${model} declares no thinking or reasoning option`;
43
+ // Effort failures are fatal before the prompt. Only fast and context reach this soft-diagnostic
44
+ // path, and both are sent under their own names.
45
+ export function unsupportedWarning(model, { arg }) {
46
+ return `model ${model} has no ${arg} option; the requested value was ignored`;
52
47
  }
package/src/proc.js CHANGED
@@ -5,14 +5,26 @@ export function isChildAlive(child) {
5
5
  return child && child.exitCode === null && child.signalCode === null;
6
6
  }
7
7
 
8
+ // POSIX only: detached makes the child a process group leader (setsid), which is what lets
9
+ // treeKill reach the agent's own children. On win32 it would mean a separate console instead,
10
+ // and taskkill /T already walks the tree. Every spawn site applies it, not resolveAcpSpawn —
11
+ // an injected spawnSpec has to become a group leader too or the group kill finds nothing.
12
+ export const DETACHED = process.platform !== "win32";
13
+
8
14
  // On win32 a plain child.kill() only reaches the shell wrapper (spawn uses shell: true);
9
15
  // taskkill /T takes the whole tree so the agent itself dies too.
10
- export async function treeKill(pid) {
16
+ export async function treeKill(pid, { childAlive = true } = {}) {
11
17
  if (process.platform === "win32") {
12
18
  await /** @type {Promise<void>} */ (new Promise((resolve) => {
13
19
  execFile("taskkill", ["/PID", String(pid), "/T", "/F"], () => resolve());
14
20
  }));
15
21
  return;
16
22
  }
17
- try { process.kill(pid, "SIGKILL"); } catch {}
23
+ // Negative pid signals the whole group, so the agent's descendants go with it. A group outlives
24
+ // its leader while any member is left, which is why this runs even for an exited child: that is
25
+ // the case where descendants are the only thing still running.
26
+ try { process.kill(-pid, "SIGKILL"); } catch {}
27
+ // Reaches a child that is not a group leader, where the group kill raised ESRCH. Skipped once
28
+ // the child is gone, since a reaped pid can already belong to something else.
29
+ if (childAlive) { try { process.kill(pid, "SIGKILL"); } catch {} }
18
30
  }
package/src/server.js CHANGED
@@ -7,7 +7,8 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
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
- import { VERSION } from "./version.js";
10
+ import { VERSION, readPackageVersion } from "./version.js";
11
+ import { DETACHED } from "./proc.js";
11
12
  import { PLAN_PRIORITIES, PLAN_STATUSES, TODO_STATUSES } from "./acp-enums.js";
12
13
 
13
14
  const nodeMajor = Number(process.versions.node.split(".")[0]);
@@ -103,20 +104,26 @@ export const delegateOutputShape = {
103
104
  // doctor.test.js parses every result against a strict copy of this shape.
104
105
  //
105
106
  // Types only; what the fields mean is documented once, in TECHNICAL.md.
107
+ // Split out so the drift guard can make it strict on its own: a .strict() on agent does not look
108
+ // inside handshake, which is the level this schema has drifted at twice.
109
+ export const doctorHandshakeShape = {
110
+ ok: z.boolean(),
111
+ error: z.string().optional(),
112
+ protocolVersion: z.unknown().optional(),
113
+ agentCapabilities: z.unknown().optional(),
114
+ models: z.array(z.unknown()).optional(),
115
+ currentModel: z.unknown().optional(),
116
+ modes: z.array(z.unknown()).optional(),
117
+ // Built here rather than relayed, so it gets a real type where its neighbours get z.unknown().
118
+ currentModelOptions: z.array(z.object({ id: z.string(), values: z.array(z.string()) })).optional(),
119
+ };
120
+
106
121
  export const doctorAgentShape = {
107
122
  found: z.boolean(),
108
123
  command: z.string(),
109
124
  version: z.string().nullable(),
110
125
  error: z.string().optional(),
111
- handshake: z.object({
112
- ok: z.boolean(),
113
- error: z.string().optional(),
114
- protocolVersion: z.unknown().optional(),
115
- agentCapabilities: z.unknown().optional(),
116
- models: z.array(z.unknown()).optional(),
117
- currentModel: z.unknown().optional(),
118
- modes: z.array(z.unknown()).optional(),
119
- }).passthrough().optional(),
126
+ handshake: z.object(doctorHandshakeShape).passthrough().optional(),
120
127
  };
121
128
 
122
129
  // Exported as a shape for the same reason as delegateOutputShape, and with agent split out
@@ -141,15 +148,15 @@ export const doctorOutputShape = {
141
148
  };
142
149
 
143
150
  export const delegateInputSchema = z.object({
144
- spec: z.string().trim().min(1, "spec must not be blank").describe("Task brief: goal, scope, fixed decisions quoted exactly, acceptance criteria. Point at files to read rather than pasting code. A lone file path is read as the brief."),
151
+ 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."),
145
152
  mode: z.enum(["agent", "plan", "ask"]).default("agent").describe("agent implements; plan and ask are instructions to the agent, not limits."),
146
153
  resumeSessionId: z.string().optional().describe("Continue an existing ACP session."),
147
154
  workspace: z.string().optional().describe("The agent's working directory, not a limit. Defaults to the server process cwd, which under npx is often not your project root — pass it explicitly. Must already exist; never create one for the call."),
148
155
  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."),
149
156
  fast: z.boolean().default(false).describe("Fast tier; higher cost — only when the user asks."),
150
- // Which options a model offers, and their valid values, are only knowable by asking the
151
- // agent, so these stay open strings and the agent rejects what it does not accept.
152
- effort: z.string().trim().min(1).optional().describe("Thinking effort; ids and values differ per model, and some offer none. gpt-5.x: none, low, medium, high, extra-high. doctor deep:true lists the current model's."),
157
+ // Which values a model offers is only knowable after selecting it, so this stays an open
158
+ // string and the bridge validates the exact token against the live option list.
159
+ 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."),
153
160
  context: z.string().trim().min(1).optional().describe("Context window size; gpt-5.x accepts 272k and 1m. Do not pass speculatively."),
154
161
  contextFiles: z.array(z.string()).optional().describe("Paths to attach instead of pasting contents into spec. Text becomes references the agent may open; images (png/jpg/gif/webp, <5MB) are sent inline. Relative paths resolve against workspace but are not limited to it. Skips are reported in protocolWarnings, never fatal."),
155
162
  });
@@ -245,7 +252,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
245
252
  "delegate",
246
253
  {
247
254
  description:
248
- `Delegate a coding task to cursor-agent over ACP. Never shell out to cursor-agent — use this tool only. Auto-approves every permission the agent requests, in any mode and anywhere on disk. Clarifying questions arrive as prose in result — resume with resumeSessionId to answer. Keep model (${DEFAULT_MODEL}), fast and effort at their defaults unless the user asks. See the delegate skill.`,
255
+ `Delegate a coding task to cursor-agent over ACP. Never shell out to cursor-agent — use this tool only. Auto-approves every permission the agent requests, in any mode and anywhere on disk. Clarifying questions arrive as prose in result — resume with resumeSessionId to answer. Keep model (${DEFAULT_MODEL}), fast and effort at their defaults unless the user explicitly asks. See the delegate skill.`,
249
256
  inputSchema: delegateInputSchema,
250
257
  annotations: {
251
258
  title: "Delegate coding task to Cursor",
@@ -262,7 +269,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
262
269
  "cancel",
263
270
  {
264
271
  description:
265
- "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, not-running (turn already ended, still resumable), not-found (id never seen this process).",
272
+ "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).",
266
273
  inputSchema: {
267
274
  sessionId: z.string(),
268
275
  force: z.boolean().default(false).describe("Kill the agent process if the turn is still running after a short grace period."),
@@ -297,7 +304,12 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
297
304
  await new Promise((r) => setTimeout(r, forceGraceMs));
298
305
  const stillRunning = inFlight.get(sessionId);
299
306
  if (!stillRunning || stillRunning.size === 0) return cancelResult("cancelled", sessionId);
300
- for (const handle of stillRunning) handle.client.stop();
307
+ const observed = await Promise.all(
308
+ [...stillRunning].map((handle) => Promise.resolve(handle.client.stop()).catch(() => false))
309
+ );
310
+ // "killed" claims the process is gone, so it needs the exit, not just a dispatched signal.
311
+ // When one does not follow, the handles stay registered and force can be tried again.
312
+ if (!observed.every(Boolean)) return cancelResult("cancelled", sessionId);
301
313
  inFlight.delete(sessionId);
302
314
  return cancelResult("killed", sessionId);
303
315
  }
@@ -347,7 +359,34 @@ if (process.argv[1]) {
347
359
  }
348
360
  }
349
361
 
362
+ // Each agent runs in its own process group on POSIX, so a SIGINT or SIGTERM aimed at this process
363
+ // no longer reaches it the way it did when the two shared a group. Kill what is registered, then
364
+ // exit explicitly: installing a handler replaces Node's default, and a server that swallows Ctrl-C
365
+ // would be a worse bug than the agent it leaks. Delegations still in their handshake are not in
366
+ // the map yet, so this covers the turn, not the first few seconds of it.
367
+ export function installSignalCleanup(map, { exit = (code) => process.exit(code) } = {}) {
368
+ if (!DETACHED) return;
369
+ const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143]]);
370
+ for (const [signal, code] of signals) {
371
+ process.on(signal, () => {
372
+ for (const handles of map.values()) {
373
+ for (const handle of handles) { try { handle.client.stop(); } catch {} }
374
+ }
375
+ exit(code);
376
+ });
377
+ }
378
+ }
379
+
350
380
  if (isMain) {
351
- const server = buildServer();
352
- await server.connect(new StdioServerTransport());
381
+ // Without this the flag falls through to the transport, which owns stdout and waits on stdin —
382
+ // so confirming an install meant wiring the server into a host first. Reads the package.json
383
+ // beside this file, so it reports the code that is actually running rather than what a
384
+ // manifest pinned. stdout is free here because the transport never starts.
385
+ if (process.argv.slice(2).includes("--version")) {
386
+ console.log(readPackageVersion());
387
+ } else {
388
+ const server = buildServer();
389
+ installSignalCleanup(inFlight);
390
+ await server.connect(new StdioServerTransport());
391
+ }
353
392
  }