cursor-delegate-mcp 1.21.0 → 2.0.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.21.0",
3
+ "version": "2.0.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.",
@@ -44,7 +44,8 @@
44
44
  "PRIVACY.md",
45
45
  "SECURITY.md",
46
46
  "TERMS.md",
47
- "LICENSE"
47
+ "LICENSE",
48
+ "CHANGELOG.md"
48
49
  ],
49
50
  "scripts": {
50
51
  "test": "node scripts/run-tests.mjs",
package/src/acp-client.js CHANGED
@@ -34,6 +34,8 @@ export class AcpClient extends EventEmitter {
34
34
  this._stopping = null;
35
35
  }
36
36
 
37
+ // stderr is captured but does not count as activity: the supervisor measures ACP frames, and
38
+ // an agent writing diagnostics is not the same fact as a turn making progress.
37
39
  // The tail of stderr, which is what an exit error quotes. Kept as chunks and joined on read:
38
40
  // rebuilding a 64KB string per chunk was the whole cost of a noisy agent. A StringDecoder
39
41
  // holds partial UTF-8 across chunk boundaries, so a multi-byte character split by the pipe
@@ -61,7 +63,6 @@ export class AcpClient extends EventEmitter {
61
63
  this._stderrLength -= this._stderrChunks.shift().length;
62
64
  }
63
65
  }
64
- this.emit("activity");
65
66
  });
66
67
  this.child.stderr.on("error", () => {});
67
68
  // A supervisor trip writes session/cancel, which can land after the agent is already gone.
@@ -75,7 +76,10 @@ export class AcpClient extends EventEmitter {
75
76
  const stderr = this.stderrBuffer;
76
77
  const err = makeError(
77
78
  "agent-exit",
78
- `agent exited (code=${code}${signal ? ", signal=" + signal : ""})${stderr ? ": " + String(stderr).slice(-2000) : ""}`
79
+ // stderr kept whole. This is the one string that says why the agent died — the model
80
+ // that was rejected, the quota that ran out, the login that expired — and the part that
81
+ // names it can sit anywhere in it. The 64KB ring buffer above is the bound.
82
+ `agent exited (code=${code}${signal ? ", signal=" + signal : ""})${stderr ? ": " + String(stderr) : ""}`
79
83
  );
80
84
  // exit + rejectAllPending both settle the same Promise.race; second rejection is intentional.
81
85
  this.peer?.rejectAllPending(err);
package/src/delegate.js CHANGED
@@ -13,8 +13,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
15
  import { optionsFrom, resolveEffort, unsupportedWarning } from "./model-options.js";
16
+ import { transcriptFrames } from "./jsonrpc.js";
16
17
 
17
18
  export const DEFAULT_MODEL = "composer-2.5";
19
+ // The one advertised id the agent resolves to a different model ("Auto"), so it is the one id
20
+ // whose served model has to be read back off a config reply for effectiveModel.
21
+ const ROUTED_MODEL = "default";
18
22
  export const DEFAULT_HANDSHAKE_MS = 60000;
19
23
  export const DEFAULT_HEARTBEAT_MS = 30000;
20
24
 
@@ -33,43 +37,23 @@ function fmtDuration(ms) {
33
37
  return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s`;
34
38
  }
35
39
 
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.`);
40
+ // A blank spec spins up a live session that only replies "No prompt content provided" —
41
+ // a billed turn for nothing. Reject it before the spawn, like a bad workspace.
42
+ function assertSpec(spec) {
43
+ if (typeof spec === "string" && spec.trim() === "") {
44
+ throw makeError("invalid-spec", "spec is empty. Provide a task brief.");
61
45
  }
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
46
  }
68
47
 
69
- // Without this, the agent's first write creates the directory: a typo'd workspace spawns a
70
- // parallel empty tree and every layer reports success. Same check contextFiles applies.
48
+ // Named, never defaulted: under npx or a plugin launch the server's own cwd is a cache directory
49
+ // or the user's home, so a defaulted workspace put an auto-approved agent to work on a tree
50
+ // nobody asked about while every layer reported success. And without the existence check the
51
+ // agent's first write creates the directory, so a typo spawns a parallel empty tree. Same check
52
+ // contextFiles applies.
71
53
  function assertWorkspace(workspace) {
72
- if (workspace === undefined || workspace === null) return;
54
+ if (typeof workspace !== "string" || workspace.trim() === "") {
55
+ throw makeError("invalid-workspace", "workspace is required. Name the directory the agent should work in.");
56
+ }
73
57
  let stat;
74
58
  try {
75
59
  stat = statSync(workspace);
@@ -204,6 +188,13 @@ async function applyConfig(client, sessionId, configId, value) {
204
188
 
205
189
  // The resolved model appears only in a set_config_option reply's configOptions (set_model
206
190
  // returns nothing). Absent for models that reject every option sent — the field then stays off.
191
+ // session/new and session/load both report the values the session opens with, which is what makes
192
+ // a config round-trip skippable: the bridge can see it would set what is already set.
193
+ function configOptionValue(configOptions, id) {
194
+ const opt = (Array.isArray(configOptions) ? configOptions : []).find((o) => o?.id === id);
195
+ return typeof opt?.currentValue === "string" ? opt.currentValue : undefined;
196
+ }
197
+
207
198
  function servedModelFrom(res) {
208
199
  const opts = optionsFrom(res);
209
200
  if (opts === undefined) return undefined;
@@ -255,6 +246,7 @@ async function applyEffort(client, sessionId, model, value, modelOptions) {
255
246
  * model?: string, fast?: boolean, effort?: string, context?: string,
256
247
  * contextFiles?: string[], clientFactory?: (opts: any) => any,
257
248
  * idleMs?: number, handshakeMs?: number, hardCapMs?: number, timeoutMs?: number,
249
+ * onClientReady?: (client: any) => void,
258
250
  * onSessionReady?: (sessionId: string, client: any) => void,
259
251
  * onProgress?: (message: string) => void,
260
252
  * progressThrottleMs?: number, heartbeatMs?: number, signal?: AbortSignal,
@@ -264,22 +256,21 @@ export async function runDelegate({
264
256
  spec, mode = "agent", resumeSessionId, workspace,
265
257
  model = DEFAULT_MODEL, fast = false, effort, context, contextFiles, clientFactory,
266
258
  idleMs, handshakeMs, hardCapMs, timeoutMs,
267
- onSessionReady, onProgress, progressThrottleMs = 2000,
259
+ onClientReady, onSessionReady, onProgress, progressThrottleMs = 2000,
268
260
  heartbeatMs = DEFAULT_HEARTBEAT_MS,
269
261
  signal,
270
262
  } = {}) {
263
+ // Nothing between here and the abort listener below may await: addEventListener does not
264
+ // replay an abort that already fired, so an abort landing in that window would be lost. A
265
+ // spec read used to await here, and did lose one. Throwing, not supervisor.abort(): tripping
266
+ // before supervise() installs its reject settles the supervisor with nothing listening.
271
267
  if (signal?.aborted) {
272
268
  throw makeError("aborted", "delegation aborted by MCP host");
273
269
  }
274
270
  // Before the spawn: validating later costs a process, a handshake and a billed turn.
275
271
  assertWorkspace(workspace);
276
- const promptText = await resolveSpec(spec);
277
- // addEventListener does not replay an abort that already fired, and the listener is registered
278
- // below, so an abort during the await above is otherwise lost. Throwing, not supervisor.abort():
279
- // tripping before supervise() installs its reject settles the supervisor with nothing listening.
280
- if (signal?.aborted) {
281
- throw makeError("aborted", "delegation aborted by MCP host");
282
- }
272
+ assertSpec(spec);
273
+ const promptText = spec;
283
274
  const capMs = hardCapMs ?? timeoutMs ?? envMs("CURSOR_DELEGATE_HARD_CAP_MS", 3600000);
284
275
  const shakeMs = handshakeMs ?? envMs("CURSOR_DELEGATE_HANDSHAKE_MS", DEFAULT_HANDSHAKE_MS);
285
276
  const turnIdleMs = idleMs ?? envMs("CURSOR_DELEGATE_IDLE_MS", 0);
@@ -346,6 +337,10 @@ export async function runDelegate({
346
337
 
347
338
  const make = clientFactory || ((opts) => new AcpClient(opts));
348
339
  const client = make({ mode, onCreatePlan: state.recordCreatePlan, onTodos: state.recordTodos });
340
+ // Handed over before the spawn, because from client.start() there is an agent process and the
341
+ // caller needs something that can stop it. onSessionReady is roughly 3.4s later — a host going
342
+ // away inside that window used to exit with the agent already running and nothing holding it.
343
+ onClientReady?.(client);
349
344
  const supervisor = new SessionSupervisor(client, { idleMs: turnIdleMs, handshakeMs: shakeMs, hardCapMs: capMs });
350
345
  const onAbort = () => supervisor.abort();
351
346
  signal?.addEventListener("abort", onAbort, { once: true });
@@ -370,6 +365,10 @@ export async function runDelegate({
370
365
  heartbeat.unref?.();
371
366
  };
372
367
 
368
+ // Malformed frames noticed as they arrive, where protocolWarnings does not exist yet. Merged
369
+ // into it with the rest below.
370
+ const frameWarnings = [];
371
+
373
372
  // session/load replays the previous turn as ordinary update frames, tool_call and diff blocks
374
373
  // included. state.reset() clears what they touch but cannot unsend a progress notification, so
375
374
  // the guard below is what stops a resume reporting last turn's edits as if they were happening.
@@ -377,7 +376,17 @@ export async function runDelegate({
377
376
  if (!promptInFlight) return;
378
377
  const up = u?.update || {};
379
378
  if (up.sessionUpdate === "plan") {
380
- state.planEntries = up.entries || [];
379
+ // ACP defines entries as an array. A non-array is truthy, so it was stored as-is and
380
+ // reached the sanitizer's forEach — throwing after the turn's work was done, which is the
381
+ // one thing the sanitizer exists to prevent. Drop it here and say so instead.
382
+ if (up.entries !== undefined && !Array.isArray(up.entries)) {
383
+ frameWarnings.push(
384
+ `plan entries dropped: ACP requires an array, got ${up.entries === null ? "null" : typeof up.entries}`
385
+ );
386
+ state.planEntries = [];
387
+ } else {
388
+ state.planEntries = up.entries || [];
389
+ }
381
390
  }
382
391
  // The agent titles the turn a beat after the prompt lands ("File Creator") — useful live,
383
392
  // when several delegations run, and in timeout forensics. Kept out of the result: there it
@@ -394,7 +403,10 @@ export async function runDelegate({
394
403
  state.startTool(up.toolCallId, up.status);
395
404
  const label = up.title || up.kind || "tool";
396
405
  const path = up.locations?.[0]?.path;
397
- state.lastToolLabel = String(label) + (path ? " — " + path : "");
406
+ // Collapsed onto one line the way both readers of this take it: a progress notification
407
+ // and the "last tool call" line in a stall error. A terminal tool's title is the command
408
+ // the agent sent, which it sends verbatim — a multi-line script arrives with its newlines.
409
+ state.lastToolLabel = (String(label) + (path ? " — " + path : "")).replace(/\s+/g, " ").trim();
398
410
  try { onProgress?.(("running: " + state.lastToolLabel).slice(0, 200)); } catch {}
399
411
  }
400
412
  if (up.sessionUpdate === "agent_message_chunk" && up.content?.text) {
@@ -404,7 +416,11 @@ export async function runDelegate({
404
416
  }
405
417
  if (up.sessionUpdate === "tool_call_update") {
406
418
  state.updateToolStatus(up.toolCallId, up.status);
407
- for (const c of up.content || []) {
419
+ // Array.isArray, not `|| []`: a non-array content is truthy and iterating it throws
420
+ // "object is not iterable" here, in the readline callback, where nothing awaits it. That
421
+ // is an uncaught exception — the whole server, not this one turn — and it also stops the
422
+ // reply on the next line from being read, so the turn hangs to its cap.
423
+ for (const c of Array.isArray(up.content) ? up.content : []) {
408
424
  if (c.type === "diff" && c.path) {
409
425
  state.touched.add(c.path);
410
426
  try { onProgress?.("editing " + c.path); } catch {}
@@ -428,15 +444,28 @@ export async function runDelegate({
428
444
  supervisor.setSessionId(sessionId);
429
445
  onSessionReady?.(sessionId, client);
430
446
  assertKnownModel(client, model);
431
- await client.setModel(sessionId, model);
432
- // fast is always sent — a resumed session may already have it on, so false is a real
433
- // instruction. Its reply carries this model's configOptions, which is where the effort id
434
- // comes from. effort and context go only when the caller named one. Each reply reports the
435
- // now-current model; the last one seen wins.
436
- const fastResult = await applyConfig(client, sessionId, "fast", fast);
437
- if (fastResult.unsupported && fast) unsupportedOptions.push({ arg: "fast" });
438
- else servedModel = servedModelFrom(fastResult.res) ?? servedModel;
439
- let modelOptions = optionsFrom(fastResult.res);
447
+ // session/new and session/load both report the model the session opened on, and an id that
448
+ // already matches is served without an explicit set — measured, so this round-trip has
449
+ // nothing to change. Cursor carries the selection across sessions, so the common shape
450
+ // (same model twice running) hits this.
451
+ const openedOnModel = client.sessionModels?.currentModelId === model;
452
+ if (!openedOnModel) await client.setModel(sessionId, model);
453
+ // fast is an instruction, not a probe. Cursor persists the tier, and persists it per model —
454
+ // both measured: one fast:true turn leaves the next fresh session reporting fast=true, and a
455
+ // set_model to another model reports that model's own tier. So the opening snapshot only
456
+ // describes the tier in force when the session also opened on this model; after a switch it
457
+ // describes the model we left. Skip only when both hold, which is the steady-state path this
458
+ // is for, and send whenever the reply itself is read: effort needs its option list, and a
459
+ // routable id needs the served model. An absent value reads as a mismatch and sends. effort
460
+ // and context go only when the caller named one; the last reply seen wins.
461
+ const openedFast = configOptionValue(client.configOptions, "fast");
462
+ let modelOptions;
463
+ if (!openedOnModel || openedFast !== String(fast) || effort !== undefined || model === ROUTED_MODEL) {
464
+ const fastResult = await applyConfig(client, sessionId, "fast", fast);
465
+ if (fastResult.unsupported && fast) unsupportedOptions.push({ arg: "fast" });
466
+ else servedModel = servedModelFrom(fastResult.res) ?? servedModel;
467
+ modelOptions = optionsFrom(fastResult.res);
468
+ }
440
469
  // A model that refuses fast leaves no list. Re-asserting the model just set is inert, and
441
470
  // its reply carries the full list — measured on claude-haiku-4-5, which refuses fast.
442
471
  if (modelOptions === undefined && effort !== undefined) {
@@ -520,6 +549,7 @@ export async function runDelegate({
520
549
  if (resumeError) protocolWarnings.push(`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`);
521
550
  for (const u of unsupportedOptions) protocolWarnings.push(unsupportedWarning(model, u));
522
551
  protocolWarnings.push(...contextWarnings);
552
+ protocolWarnings.push(...frameWarnings);
523
553
  if (state.planEntries.length > 0 || state.planOverview !== undefined || state.planDetail !== undefined) {
524
554
  // Sanitize even when the plan is discarded: the warnings it raises report malformed ACP
525
555
  // frames, which the caller needs whatever mode it asked for.
@@ -583,7 +613,7 @@ export async function runDelegate({
583
613
  }
584
614
  // Opt-in: the frames land in the caller's context and nothing there is actionable — the
585
615
  // forensics above already carry that. Raw frames only help someone debugging the bridge.
586
- const frames = Number(process.env.CURSOR_DELEGATE_TRANSCRIPT);
616
+ const frames = transcriptFrames();
587
617
  if (frames > 0) {
588
618
  try {
589
619
  const transcript = client.getTranscript?.(frames);
package/src/doctor.js CHANGED
@@ -8,6 +8,7 @@ import { allowedValues } from "./model-options.js";
8
8
 
9
9
  const HANDSHAKE_TIMEOUT_MS = 15_000;
10
10
  const VERSION_PROBE_TIMEOUT_MS = 10_000;
11
+ const PROBE_STDOUT_CAP = 64 * 1024;
11
12
  const DEFAULT_LOG_SIZE = "2000";
12
13
 
13
14
  function formatCommand({ command, args }) {
@@ -33,7 +34,16 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
33
34
  resolve(result);
34
35
  };
35
36
  const child = spawn(execCommand, execArgs, { ...options, detached: DETACHED, stdio: ["ignore", "pipe", "pipe"] });
36
- child.stdout?.on("data", (chunk) => { stdout += chunk.toString(); });
37
+ // Capped: a version string is a line, and a launcher that streams instead should not be
38
+ // accumulated whole while the probe waits out its timeout.
39
+ child.stdout?.on("data", (chunk) => {
40
+ if (stdout.length < PROBE_STDOUT_CAP) stdout += chunk.toString();
41
+ });
42
+ // Drained, not merely piped. An unread pipe fills, the launcher blocks writing to it and so
43
+ // never exits, and the probe can only report that as a timeout — a healthy but noisy
44
+ // launcher reads out identically to a wedged one. Nothing consumes the bytes.
45
+ child.stderr?.on("data", () => {});
46
+ child.stderr?.on("error", () => {});
37
47
  child.on("error", () => finish({ found: false, version: null }));
38
48
  child.on("close", (code) => {
39
49
  finish({
package/src/jsonrpc.js CHANGED
@@ -10,6 +10,23 @@ function readLogSize(raw) {
10
10
  return Math.floor(n);
11
11
  }
12
12
 
13
+ // Depth an unparseable CURSOR_DELEGATE_TRANSCRIPT reads as. Deliberately not DEFAULT_LOG_SIZE:
14
+ // that one bounds what the log retains in memory, this one is how much lands in the caller's
15
+ // context. 1.10.0 removed a 40-frame always-on dump from failure text; opt-in is what buys this
16
+ // budget, so keep it in that neighbourhood.
17
+ const TRANSCRIPT_DEFAULT_FRAMES = 50;
18
+
19
+ // Frames of transcript CURSOR_DELEGATE_TRANSCRIPT asks for. Unset or blank means none and a
20
+ // number is the count (0 = none); anything unparseable reads as on at the default depth —
21
+ // "true" and "yes" are natural things to set, and silently disabling the transcript on them is
22
+ // the opposite of what the setter wanted.
23
+ export function transcriptFrames(raw = process.env.CURSOR_DELEGATE_TRANSCRIPT) {
24
+ if (raw === undefined || raw.trim() === "") return 0;
25
+ const n = Number(raw);
26
+ if (!Number.isFinite(n)) return TRANSCRIPT_DEFAULT_FRAMES;
27
+ return Math.max(0, Math.floor(n));
28
+ }
29
+
13
30
  export class JsonRpcPeer {
14
31
  /**
15
32
  * @param {import("node:stream").Readable} input
@@ -30,8 +47,16 @@ export class JsonRpcPeer {
30
47
  // 0 disables recording and is documented; anything unparseable is a typo, and silently
31
48
  // disabling the transcript on a typo is the opposite of what the setter wanted.
32
49
  this._logSize = readLogSize(process.env.ACP_LOG_SIZE);
50
+ // The failure transcript is the only thing that reads these frames, and it is opt-in, so
51
+ // recording by default retained up to _logSize × FRAME_CAP bytes per delegation that nothing
52
+ // would ever ask for. ACP_LOG_SIZE still bounds retention and still disables at 0.
53
+ this._recording = this._logSize > 0 && transcriptFrames() > 0;
33
54
  this._log = [];
34
55
  this.rl = readline.createInterface({ input });
56
+ // The interface re-emits the input stream's error as its own, so the handler acp-client.js
57
+ // puts on the child's stdout does not cover this one: an unhandled 'error' here is an
58
+ // uncaught exception, which takes down the server and every concurrent delegation with it.
59
+ this.rl.on("error", () => {});
35
60
  this.rl.on("line", (line) => this._onLine(line));
36
61
  }
37
62
 
@@ -39,7 +64,7 @@ export class JsonRpcPeer {
39
64
  // chatty turn cost more than parsing the frames. Let the array overshoot by a quarter and trim
40
65
  // in one batch; readers below take the last _logSize, so what the log reports is unchanged.
41
66
  _record(dir, line) {
42
- if (this._logSize <= 0) return;
67
+ if (!this._recording) return;
43
68
  const truncated = line.length > FRAME_CAP ? line.slice(0, FRAME_CAP) : line;
44
69
  this._log.push({ t: Date.now(), dir, line: truncated });
45
70
  if (this._log.length > this._logSize + (this._logSize >> 2)) {
@@ -59,11 +84,14 @@ export class JsonRpcPeer {
59
84
  }
60
85
 
61
86
  _onLine(line) {
62
- this.onActivity();
63
87
  this._record("in", line);
64
88
  if (!line.trim()) return;
65
89
  let msg;
66
90
  try { msg = JSON.parse(line); } catch { return; }
91
+ // Only a parsed frame counts. A blank line, a launcher banner or anything else the agent
92
+ // prints is not the protocol advancing, and treating it as such is what let a chatty
93
+ // launcher hold the idle guard open and made "Last ACP frame Ns ago" report a stderr byte.
94
+ this.onActivity();
67
95
  const hasId = msg.id !== undefined && msg.id !== null;
68
96
  if (hasId && (msg.result !== undefined || msg.error !== undefined)) {
69
97
  // Keyed by string: a peer that echoes "1" for the id 1 is still answering that request,
package/src/proc.js CHANGED
@@ -14,9 +14,15 @@ export const DETACHED = process.platform !== "win32";
14
14
  // On win32 a plain child.kill() only reaches the shell wrapper (spawn uses shell: true);
15
15
  // taskkill /T takes the whole tree so the agent itself dies too.
16
16
  export async function treeKill(pid, { childAlive = true } = {}) {
17
+ if (!pid) return;
17
18
  if (process.platform === "win32") {
19
+ // taskkill /T walks parent links, which an exited leader no longer has: what it started is
20
+ // either gone with it or detached and out of reach. So a post-exit kill has nothing left to
21
+ // reach, and a reaped pid can already belong to somebody else — which makes the gate the
22
+ // whole of it here, where POSIX still has the group to aim at.
23
+ if (!childAlive) return;
18
24
  await /** @type {Promise<void>} */ (new Promise((resolve) => {
19
- execFile("taskkill", ["/PID", String(pid), "/T", "/F"], () => resolve());
25
+ execFile("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true }, () => resolve());
20
26
  }));
21
27
  return;
22
28
  }
@@ -15,13 +15,16 @@ export function createRequestRouter({ respond, respondError, onCreatePlan, onTod
15
15
  try {
16
16
  if (method === "session/request_permission") {
17
17
  const opts = params?.options || [];
18
+ // The two allow kinds only. Taking opts[0] when neither is offered returned a reject
19
+ // id under a `selected` outcome, which the agent reads as an approval of the denial —
20
+ // a silent skip from a bridge that advertises auto-approval.
18
21
  const pick =
19
22
  opts.find((o) => o.kind === "allow_always") ||
20
- opts.find((o) => o.kind === "allow_once") ||
21
- opts[0];
23
+ opts.find((o) => o.kind === "allow_once");
22
24
  // Selecting nothing is not a selection: an options-less request answered with
23
- // optionId undefined is a malformed ACP response. Say cancelled and let the agent
24
- // decide what to do about it.
25
+ // optionId undefined is a malformed ACP response, and a request offering no allow
26
+ // option is one this bridge can approve nothing in. Say cancelled to both and let the
27
+ // agent decide what to do about it.
25
28
  if (!pick?.optionId) return respond(id, { outcome: { outcome: "cancelled" } });
26
29
  return respond(id, { outcome: { outcome: "selected", optionId: pick.optionId } });
27
30
  }
@@ -48,7 +51,9 @@ export function createRequestRouter({ respond, respondError, onCreatePlan, onTod
48
51
  }
49
52
  return respondError(id, -32601, `Unhandled method: ${method}`);
50
53
  } catch (err) {
51
- return respondError(id, -32000, `Router error: ${err?.message || err}`);
54
+ // -32603, not -32000: ACP assigns -32000 to auth_required, and a bug on this side
55
+ // reported as "authenticate" sends the agent down a recovery path that cannot work.
56
+ return respondError(id, -32603, `Router error: ${err?.message || err}`);
52
57
  }
53
58
  };
54
59
  }
package/src/server.js CHANGED
@@ -7,7 +7,7 @@ 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
11
  import { DETACHED } from "./proc.js";
12
12
  import { PLAN_PRIORITIES, PLAN_STATUSES, TODO_STATUSES } from "./acp-enums.js";
13
13
 
@@ -37,13 +37,24 @@ function unregisterInFlight(map, sessionId, handle) {
37
37
  handles.delete(handle);
38
38
  if (handles.size === 0) map.delete(sessionId);
39
39
  }
40
+ // Delegations whose session has not opened yet. inFlight is keyed by session id, and that id
41
+ // arrives about 3.4s after the agent process does — so between client.start() and session/new
42
+ // there is a live, auto-approved agent that the map cannot name. Shutdown walks this too.
43
+ // cancel deliberately does not: an id the caller has never been given is not one it can pass.
44
+ const pendingDelegations = new Set();
45
+
40
46
  // Session ids seen this process, kept after the turn ends so cancel can tell a finished
41
47
  // session (resumable, only the turn is over) from an id that never existed. Bounded so a
42
48
  // long-lived server does not grow without limit.
43
49
  const seenSessions = new Set();
44
50
  const SEEN_SESSIONS_CAP = 500;
45
51
  function rememberSession(set, id) {
46
- if (id == null || set.has(id)) return;
52
+ if (id == null) return;
53
+ // Set iteration order makes the delete-then-add a small LRU: a session that is still being
54
+ // resumed moves back to the recent end, so it outlives an equally old id that was seen once
55
+ // and never again. Without it the id a caller is actually working with ages out on insertion
56
+ // order alone, and cancel then calls a live, resumable session one that never existed.
57
+ if (set.has(id)) set.delete(id);
47
58
  set.add(id);
48
59
  if (set.size > SEEN_SESSIONS_CAP) set.delete(set.values().next().value);
49
60
  }
@@ -148,10 +159,10 @@ export const doctorOutputShape = {
148
159
  };
149
160
 
150
161
  export const delegateInputSchema = z.object({
151
- 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."),
162
+ 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."),
152
163
  mode: z.enum(["agent", "plan", "ask"]).default("agent").describe("agent implements; plan and ask are instructions to the agent, not limits."),
153
164
  resumeSessionId: z.string().optional().describe("Continue an existing ACP session."),
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."),
165
+ workspace: z.string().trim().min(1, "workspace must not be blank").describe("The agent's working directory, not a limit. Smallest directory holding the task's files; with no such directory the project root is the floor. Must already exist; never create one for the call."),
155
166
  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."),
156
167
  fast: z.boolean().default(false).describe("Fast tier; higher cost — only when the user asks."),
157
168
  // Which values a model offers is only knowable after selecting it, so this stays an open
@@ -166,11 +177,12 @@ export const delegateInputSchema = z.object({
166
177
  * args: any, extra?: any,
167
178
  * runDelegate: (opts: any) => Promise<any>,
168
179
  * inFlight: Map<string, Set<any>>,
180
+ * pending?: Set<any>,
169
181
  * seenSessions?: Set<string>,
170
182
  * }} deps
171
183
  * @returns {Promise<import("@modelcontextprotocol/sdk/types.js").CallToolResult>}
172
184
  */
173
- export async function runDelegateTool({ args, extra, runDelegate, inFlight, seenSessions = new Set() }) {
185
+ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pending = new Set(), seenSessions = new Set() }) {
174
186
  const { spec, mode, resumeSessionId, workspace, model, fast, effort, context, contextFiles } = args;
175
187
 
176
188
  const progressToken = extra?._meta?.progressToken;
@@ -197,7 +209,7 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, seen
197
209
  spec,
198
210
  mode,
199
211
  resumeSessionId,
200
- workspace: workspace || process.cwd(),
212
+ workspace,
201
213
  model,
202
214
  fast,
203
215
  effort,
@@ -205,9 +217,16 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, seen
205
217
  contextFiles,
206
218
  onProgress,
207
219
  signal: extra?.signal,
220
+ onClientReady: (client) => {
221
+ handle = { client, cancelRequested: false };
222
+ pending.add(handle);
223
+ },
208
224
  onSessionReady: (sessionId, client) => {
209
225
  capturedSessionId = sessionId;
210
- handle = { client, cancelRequested: false };
226
+ // The same handle moves across, so a shutdown racing this boundary finds it on exactly
227
+ // one side of it rather than on neither.
228
+ handle ??= { client, cancelRequested: false };
229
+ pending.delete(handle);
211
230
  registerInFlight(inFlight, sessionId, handle);
212
231
  rememberSession(seenSessions, sessionId);
213
232
  // Emit the id the moment the session opens, before the turn finishes, so a host that
@@ -228,7 +247,9 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, seen
228
247
  };
229
248
  } finally {
230
249
  // Drops only this delegation's own handle; the id stays registered while another turn
231
- // is still running on it.
250
+ // is still running on it. A delegation that failed before its session opened is only ever
251
+ // in pending, and one that opened is only ever in the map — the delete covers both.
252
+ if (handle) pending.delete(handle);
232
253
  if (capturedSessionId) unregisterInFlight(inFlight, capturedSessionId, handle);
233
254
  }
234
255
  }
@@ -262,7 +283,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
262
283
  openWorldHint: true,
263
284
  },
264
285
  },
265
- async (args, extra) => runDelegateTool({ args, extra, runDelegate, inFlight, seenSessions })
286
+ async (args, extra) => runDelegateTool({ args, extra, runDelegate, inFlight, pending: pendingDelegations, seenSessions })
266
287
  );
267
288
 
268
289
  server.registerTool(
@@ -359,26 +380,68 @@ if (process.argv[1]) {
359
380
  }
360
381
  }
361
382
 
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
- });
383
+ // Kill what is still running, then exit, on any way the host has of going away.
384
+ export function installSignalCleanup(map, {
385
+ pending = new Set(),
386
+ exit = (code) => process.exit(code),
387
+ setExitCode = (code) => { process.exitCode = code; },
388
+ schedule = (fn) => setImmediate(fn),
389
+ stdin = process.stdin,
390
+ } = {}) {
391
+ let shuttingDown = false;
392
+ const shutdown = (code) => {
393
+ // A second trigger skips the wait below: the kills are already dispatched, and a caller
394
+ // that has asked twice wants out now.
395
+ if (shuttingDown) return exit(code);
396
+ shuttingDown = true;
397
+ // Set in the handler, not left to the exit below: a loop that runs dry on its own still
398
+ // has to die with the code the signal asked for, and the scheduled exit may never get a
399
+ // turn to run.
400
+ setExitCode(code);
401
+ const stops = [];
402
+ const dispatch = (handle) => {
403
+ try { stops.push(Promise.resolve(handle.client.stop()).catch(() => {})); } catch {}
404
+ };
405
+ for (const handles of map.values()) for (const handle of handles) dispatch(handle);
406
+ // Delegations still inside their handshake. The agent is already running for these, and this
407
+ // is the only place it is reachable from — they have no session id to be keyed under yet.
408
+ for (const handle of pending) dispatch(handle);
409
+ // On Windows the kill is a separate taskkill process: exiting before it walks the tree
410
+ // orphans everything below the shell wrapper — the ps1 launcher and the versioned agent
411
+ // were measured surviving the server's exit. stop() bounds itself (observed exit or its
412
+ // own deadline), so this wait is short and finite on every platform.
413
+ // Scheduled rather than called from the kill's own continuation, so the exit runs on a
414
+ // clean loop turn instead of on the settlement stack.
415
+ const leave = () => schedule(() => exit(code));
416
+ Promise.all(stops).then(leave, leave);
417
+ };
418
+ // Each agent runs in its own process group on POSIX, so a signal aimed at this process no
419
+ // longer reaches it the way it did when the two shared a group. Installing a handler replaces
420
+ // Node's default, and a server that swallows Ctrl-C would be a worse bug than the agent it
421
+ // leaks. Delegations still inside their handshake are reached through `pending`, so this
422
+ // covers the agent from the moment it is spawned, not from the moment its session opens.
423
+ if (DETACHED) {
424
+ const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143]]);
425
+ for (const [signal, code] of signals) process.on(signal, () => shutdown(code));
377
426
  }
427
+ // Closing the server's stdin is how a stdio host shuts the transport down, and it is what a
428
+ // host reaches for before it resorts to a signal. The SDK transport does not listen for it —
429
+ // it subscribes to `data` and `error` only — so EOF leaves this process up with a delegation
430
+ // still running and nobody left to hand it to.
431
+ stdin.on("end", () => shutdown(0));
378
432
  }
379
433
 
380
434
  if (isMain) {
381
- const server = buildServer();
382
- installSignalCleanup(inFlight);
383
- await server.connect(new StdioServerTransport());
435
+ // Without this the flag falls through to the transport, which owns stdout and waits on stdin —
436
+ // so confirming an install meant wiring the server into a host first. Reads the package.json
437
+ // beside this file, so it reports the code that is actually running rather than what a
438
+ // manifest pinned. stdout is free here because the transport never starts.
439
+ const argv = process.argv.slice(2);
440
+ if (argv.includes("--version") || argv.includes("-v")) {
441
+ console.log(readPackageVersion());
442
+ } else {
443
+ const server = buildServer();
444
+ installSignalCleanup(inFlight, { pending: pendingDelegations });
445
+ await server.connect(new StdioServerTransport());
446
+ }
384
447
  }