cursor-delegate-mcp 1.22.0 → 2.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/README.md CHANGED
@@ -20,7 +20,7 @@ Cursor Delegate is the MCP bridge that lets Claude Code, ChatGPT/Codex, Copilot
20
20
 
21
21
  <br clear="left">
22
22
 
23
- ![Demo](demo.gif)
23
+ ![Demo](assets/demo.gif)
24
24
 
25
25
  ## 🧠 Frontier quality, kept
26
26
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursor-delegate-mcp",
3
- "version": "1.22.0",
3
+ "version": "2.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, 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
@@ -60,8 +62,15 @@ export class AcpClient extends EventEmitter {
60
62
  while (this._stderrChunks.length > 1 && this._stderrLength - this._stderrChunks[0].length >= STDERR_CAP) {
61
63
  this._stderrLength -= this._stderrChunks.shift().length;
62
64
  }
65
+ // Whole-chunk drops leave a remainder when one pipe read is itself larger than the cap
66
+ // (observed on GitHub Windows runners). Slice that first chunk so retained memory cannot
67
+ // grow with the flood; the public tail is still exactly one cap on read.
68
+ const overflow = this._stderrLength - STDERR_CAP;
69
+ if (overflow > 0) {
70
+ this._stderrChunks[0] = this._stderrChunks[0].slice(overflow);
71
+ this._stderrLength -= overflow;
72
+ }
63
73
  }
64
- this.emit("activity");
65
74
  });
66
75
  this.child.stderr.on("error", () => {});
67
76
  // A supervisor trip writes session/cancel, which can land after the agent is already gone.
@@ -75,7 +84,10 @@ export class AcpClient extends EventEmitter {
75
84
  const stderr = this.stderrBuffer;
76
85
  const err = makeError(
77
86
  "agent-exit",
78
- `agent exited (code=${code}${signal ? ", signal=" + signal : ""})${stderr ? ": " + String(stderr).slice(-2000) : ""}`
87
+ // stderr kept whole. This is the one string that says why the agent died — the model
88
+ // that was rejected, the quota that ran out, the login that expired — and the part that
89
+ // names it can sit anywhere in it. The 64KB ring buffer above is the bound.
90
+ `agent exited (code=${code}${signal ? ", signal=" + signal : ""})${stderr ? ": " + String(stderr) : ""}`
79
91
  );
80
92
  // exit + rejectAllPending both settle the same Promise.race; second rejection is intentional.
81
93
  this.peer?.rejectAllPending(err);
@@ -136,12 +148,22 @@ export class AcpClient extends EventEmitter {
136
148
 
137
149
  getTranscript(n) { return this.peer ? this.peer.formatLog(n) : ""; }
138
150
 
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".
151
+ // Idempotent while a teardown is in flight and after a confirmed exit, so a force-cancel
152
+ // racing the delegation's own finally tears down once. A missed exit is not the same
153
+ // fact as the process being gone: that result is not memoized, and force can retry.
143
154
  stop({ timeoutMs = STOP_EXIT_TIMEOUT_MS } = {}) {
144
- if (!this._stopping) this._stopping = this._teardown(timeoutMs);
155
+ if (!this._stopping) {
156
+ this._stopping = this._teardown(timeoutMs).then((observed) => {
157
+ // A missed exit must not poison later force-kills: the documented retry is a new
158
+ // treeKill, not the same false. A confirmed exit stays memoized so concurrent and
159
+ // later callers still join one teardown.
160
+ if (!observed) this._stopping = null;
161
+ return observed;
162
+ }, (err) => {
163
+ this._stopping = null;
164
+ throw err;
165
+ });
166
+ }
145
167
  return this._stopping;
146
168
  }
147
169
 
package/src/acp-enums.js CHANGED
@@ -3,11 +3,12 @@
3
3
  // schemas in server.js, which advertise them to hosts. A drift between the two would strip a
4
4
  // value the tool documents, or document one it strips.
5
5
  //
6
- // Plan status and todo status carry the same three values today but stay separate constants:
7
- // ACP treats them as separate enums and they are free to diverge.
6
+ // Plan status follows ACP v1 PlanEntryStatus (no cancelled). Todo status follows Cursor's
7
+ // update_todos / create_plan todo arrays, which include cancelled. They stay separate
8
+ // constants so they can diverge.
8
9
 
9
10
  export const PLAN_PRIORITIES = /** @type {const} */ (["high", "medium", "low"]);
10
11
 
11
12
  export const PLAN_STATUSES = /** @type {const} */ (["pending", "in_progress", "completed"]);
12
13
 
13
- export const TODO_STATUSES = /** @type {const} */ (["pending", "in_progress", "completed"]);
14
+ export const TODO_STATUSES = /** @type {const} */ (["pending", "in_progress", "completed", "cancelled"]);
package/src/delegate.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import process from "node:process";
2
2
  import path from "node:path";
3
3
  import { pathToFileURL } from "node:url";
4
- import { statSync } from "node:fs";
4
+ import { statSync, realpathSync } from "node:fs";
5
5
  // Async: a sync read on the server's only thread stalls every other in-flight delegation and
6
6
  // its progress stream. The statSync calls below stay sync — they are argument validation and
7
7
  // run before the spawn.
@@ -13,6 +13,7 @@ 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";
18
19
  // The one advertised id the agent resolves to a different model ("Auto"), so it is the one id
@@ -44,10 +45,15 @@ function assertSpec(spec) {
44
45
  }
45
46
  }
46
47
 
47
- // Without this, the agent's first write creates the directory: a typo'd workspace spawns a
48
- // 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.
49
53
  function assertWorkspace(workspace) {
50
- 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
+ }
51
57
  let stat;
52
58
  try {
53
59
  stat = statSync(workspace);
@@ -81,14 +87,26 @@ async function buildContextBlocks(contextFiles, workspace, client, warnings) {
81
87
  // per-entry — they are individually distinct and never arrive in bulk.
82
88
  const notFound = [];
83
89
  const root = path.resolve(workspace || process.cwd());
90
+ const identKey = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
84
91
  for (const entry of contextFiles || []) {
85
92
  if (typeof entry !== "string" || !entry.trim()) continue;
86
93
  const abs = path.resolve(workspace || process.cwd(), entry);
87
- if (seen.has(abs)) continue;
88
- seen.add(abs);
94
+ let canonical;
95
+ try {
96
+ canonical = realpathSync(abs);
97
+ } catch {
98
+ const missKey = identKey(abs);
99
+ if (seen.has(missKey)) continue;
100
+ seen.add(missKey);
101
+ notFound.push(entry);
102
+ continue;
103
+ }
104
+ const key = identKey(canonical);
105
+ if (seen.has(key)) continue;
106
+ seen.add(key);
89
107
  let stat;
90
108
  try {
91
- stat = statSync(abs);
109
+ stat = statSync(canonical);
92
110
  } catch {
93
111
  notFound.push(entry);
94
112
  continue;
@@ -97,7 +115,7 @@ async function buildContextBlocks(contextFiles, workspace, client, warnings) {
97
115
  warnings.push(`contextFile ${entry} skipped: not a file`);
98
116
  continue;
99
117
  }
100
- const mimeType = IMAGE_MIME[path.extname(abs).toLowerCase()];
118
+ const mimeType = IMAGE_MIME[path.extname(canonical).toLowerCase()];
101
119
  if (mimeType) {
102
120
  if (!client?.agentCapabilities?.promptCapabilities?.image) {
103
121
  warnings.push(`contextFile ${entry} skipped: this agent does not accept image prompts`);
@@ -107,10 +125,10 @@ async function buildContextBlocks(contextFiles, workspace, client, warnings) {
107
125
  warnings.push(`contextFile ${entry} skipped: ${Math.round(stat.size / 1024)}KB exceeds the ${MAX_IMAGE_BYTES / 1024 / 1024}MB image limit`);
108
126
  continue;
109
127
  }
110
- blocks.push({ type: "image", mimeType, data: (await readFile(abs)).toString("base64") });
128
+ blocks.push({ type: "image", mimeType, data: (await readFile(canonical)).toString("base64") });
111
129
  continue;
112
130
  }
113
- blocks.push({ type: "resource_link", uri: pathToFileURL(abs).href, name: path.basename(abs) });
131
+ blocks.push({ type: "resource_link", uri: pathToFileURL(canonical).href, name: path.basename(canonical) });
114
132
  }
115
133
  if (notFound.length) {
116
134
  warnings.push(
@@ -240,6 +258,7 @@ async function applyEffort(client, sessionId, model, value, modelOptions) {
240
258
  * model?: string, fast?: boolean, effort?: string, context?: string,
241
259
  * contextFiles?: string[], clientFactory?: (opts: any) => any,
242
260
  * idleMs?: number, handshakeMs?: number, hardCapMs?: number, timeoutMs?: number,
261
+ * onClientReady?: (client: any) => void,
243
262
  * onSessionReady?: (sessionId: string, client: any) => void,
244
263
  * onProgress?: (message: string) => void,
245
264
  * progressThrottleMs?: number, heartbeatMs?: number, signal?: AbortSignal,
@@ -249,7 +268,7 @@ export async function runDelegate({
249
268
  spec, mode = "agent", resumeSessionId, workspace,
250
269
  model = DEFAULT_MODEL, fast = false, effort, context, contextFiles, clientFactory,
251
270
  idleMs, handshakeMs, hardCapMs, timeoutMs,
252
- onSessionReady, onProgress, progressThrottleMs = 2000,
271
+ onClientReady, onSessionReady, onProgress, progressThrottleMs = 2000,
253
272
  heartbeatMs = DEFAULT_HEARTBEAT_MS,
254
273
  signal,
255
274
  } = {}) {
@@ -324,12 +343,17 @@ export async function runDelegate({
324
343
  completed: count("completed"),
325
344
  inProgress: count("in_progress"),
326
345
  pending: count("pending"),
346
+ cancelled: count("cancelled"),
327
347
  },
328
348
  };
329
349
  };
330
350
 
331
351
  const make = clientFactory || ((opts) => new AcpClient(opts));
332
352
  const client = make({ mode, onCreatePlan: state.recordCreatePlan, onTodos: state.recordTodos });
353
+ // Handed over before the spawn, because from client.start() there is an agent process and the
354
+ // caller needs something that can stop it. onSessionReady is roughly 3.4s later — a host going
355
+ // away inside that window used to exit with the agent already running and nothing holding it.
356
+ onClientReady?.(client);
333
357
  const supervisor = new SessionSupervisor(client, { idleMs: turnIdleMs, handshakeMs: shakeMs, hardCapMs: capMs });
334
358
  const onAbort = () => supervisor.abort();
335
359
  signal?.addEventListener("abort", onAbort, { once: true });
@@ -354,6 +378,10 @@ export async function runDelegate({
354
378
  heartbeat.unref?.();
355
379
  };
356
380
 
381
+ // Malformed frames noticed as they arrive, where protocolWarnings does not exist yet. Merged
382
+ // into it with the rest below.
383
+ const frameWarnings = [];
384
+
357
385
  // session/load replays the previous turn as ordinary update frames, tool_call and diff blocks
358
386
  // included. state.reset() clears what they touch but cannot unsend a progress notification, so
359
387
  // the guard below is what stops a resume reporting last turn's edits as if they were happening.
@@ -361,7 +389,17 @@ export async function runDelegate({
361
389
  if (!promptInFlight) return;
362
390
  const up = u?.update || {};
363
391
  if (up.sessionUpdate === "plan") {
364
- state.planEntries = up.entries || [];
392
+ // ACP defines entries as an array. A non-array is truthy, so it was stored as-is and
393
+ // reached the sanitizer's forEach — throwing after the turn's work was done, which is the
394
+ // one thing the sanitizer exists to prevent. Drop it here and say so instead.
395
+ if (up.entries !== undefined && !Array.isArray(up.entries)) {
396
+ frameWarnings.push(
397
+ `plan entries dropped: ACP requires an array, got ${up.entries === null ? "null" : typeof up.entries}`
398
+ );
399
+ state.planEntries = [];
400
+ } else {
401
+ state.planEntries = up.entries || [];
402
+ }
365
403
  }
366
404
  // The agent titles the turn a beat after the prompt lands ("File Creator") — useful live,
367
405
  // when several delegations run, and in timeout forensics. Kept out of the result: there it
@@ -378,7 +416,10 @@ export async function runDelegate({
378
416
  state.startTool(up.toolCallId, up.status);
379
417
  const label = up.title || up.kind || "tool";
380
418
  const path = up.locations?.[0]?.path;
381
- state.lastToolLabel = String(label) + (path ? " — " + path : "");
419
+ // Collapsed onto one line the way both readers of this take it: a progress notification
420
+ // and the "last tool call" line in a stall error. A terminal tool's title is the command
421
+ // the agent sent, which it sends verbatim — a multi-line script arrives with its newlines.
422
+ state.lastToolLabel = (String(label) + (path ? " — " + path : "")).replace(/\s+/g, " ").trim();
382
423
  try { onProgress?.(("running: " + state.lastToolLabel).slice(0, 200)); } catch {}
383
424
  }
384
425
  if (up.sessionUpdate === "agent_message_chunk" && up.content?.text) {
@@ -388,7 +429,11 @@ export async function runDelegate({
388
429
  }
389
430
  if (up.sessionUpdate === "tool_call_update") {
390
431
  state.updateToolStatus(up.toolCallId, up.status);
391
- for (const c of up.content || []) {
432
+ // Array.isArray, not `|| []`: a non-array content is truthy and iterating it throws
433
+ // "object is not iterable" here, in the readline callback, where nothing awaits it. That
434
+ // is an uncaught exception — the whole server, not this one turn — and it also stops the
435
+ // reply on the next line from being read, so the turn hangs to its cap.
436
+ for (const c of Array.isArray(up.content) ? up.content : []) {
392
437
  if (c.type === "diff" && c.path) {
393
438
  state.touched.add(c.path);
394
439
  try { onProgress?.("editing " + c.path); } catch {}
@@ -517,6 +562,7 @@ export async function runDelegate({
517
562
  if (resumeError) protocolWarnings.push(`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`);
518
563
  for (const u of unsupportedOptions) protocolWarnings.push(unsupportedWarning(model, u));
519
564
  protocolWarnings.push(...contextWarnings);
565
+ protocolWarnings.push(...frameWarnings);
520
566
  if (state.planEntries.length > 0 || state.planOverview !== undefined || state.planDetail !== undefined) {
521
567
  // Sanitize even when the plan is discarded: the warnings it raises report malformed ACP
522
568
  // frames, which the caller needs whatever mode it asked for.
@@ -580,7 +626,7 @@ export async function runDelegate({
580
626
  }
581
627
  // Opt-in: the frames land in the caller's context and nothing there is actionable — the
582
628
  // forensics above already carry that. Raw frames only help someone debugging the bridge.
583
- const frames = Number(process.env.CURSOR_DELEGATE_TRANSCRIPT);
629
+ const frames = transcriptFrames();
584
630
  if (frames > 0) {
585
631
  try {
586
632
  const transcript = client.getTranscript?.(frames);
package/src/doctor.js CHANGED
@@ -8,10 +8,27 @@ 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
 
14
+ function formatArg(value) {
15
+ const s = String(value);
16
+ if (!/[\s"]/.test(s)) return s;
17
+ return `"${s.replace(/"/g, '\\"')}"`;
18
+ }
19
+
13
20
  function formatCommand({ command, args }) {
14
- return args?.length ? `${command} ${args.join(" ")}` : command;
21
+ const bits = [formatArg(command), ...(args || []).map(formatArg)];
22
+ return args?.length ? bits.join(" ") : formatArg(command);
23
+ }
24
+
25
+ function isJsLauncher(command) {
26
+ const trimmed = String(command || "").replace(/^["']|["']$/g, "");
27
+ return /\.(?:cjs|mjs|js)$/i.test(trimmed);
28
+ }
29
+
30
+ function envReport(name, fallback = null) {
31
+ return process.env[name] !== undefined ? process.env[name] : fallback;
15
32
  }
16
33
 
17
34
  // Time-boxed because a launcher that accepts --version and then never answers would hang doctor
@@ -19,9 +36,10 @@ function formatCommand({ command, args }) {
19
36
  // exactly the case it must survive. Same guard the deep handshake has.
20
37
  export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_MS) {
21
38
  const { command, options } = spawnSpec;
22
- const isJsScript = /\.js$/i.test(command);
39
+ const launcher = String(command || "").replace(/^["']|["']$/g, "");
40
+ const isJsScript = isJsLauncher(launcher);
23
41
  const execCommand = isJsScript ? process.execPath : command;
24
- const execArgs = isJsScript ? [command, "--version"] : ["--version"];
42
+ const execArgs = isJsScript ? [launcher, "--version"] : ["--version"];
25
43
  return new Promise((resolve) => {
26
44
  let settled = false;
27
45
  let stdout = "";
@@ -33,12 +51,23 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
33
51
  resolve(result);
34
52
  };
35
53
  const child = spawn(execCommand, execArgs, { ...options, detached: DETACHED, stdio: ["ignore", "pipe", "pipe"] });
36
- child.stdout?.on("data", (chunk) => { stdout += chunk.toString(); });
54
+ // Capped: a version string is a line, and a launcher that streams instead should not be
55
+ // accumulated whole while the probe waits out its timeout.
56
+ child.stdout?.on("data", (chunk) => {
57
+ if (stdout.length < PROBE_STDOUT_CAP) stdout += chunk.toString();
58
+ });
59
+ // Drained, not merely piped. An unread pipe fills, the launcher blocks writing to it and so
60
+ // never exits, and the probe can only report that as a timeout — a healthy but noisy
61
+ // launcher reads out identically to a wedged one. Nothing consumes the bytes.
62
+ child.stderr?.on("data", () => {});
63
+ child.stderr?.on("error", () => {});
37
64
  child.on("error", () => finish({ found: false, version: null }));
38
65
  child.on("close", (code) => {
66
+ const version = code === 0 ? stdout.trim() || null : null;
39
67
  finish({
40
68
  found: true,
41
- version: code === 0 ? stdout.trim() || null : null,
69
+ version,
70
+ ...(code !== 0 ? { error: `version probe exited ${code}` } : {}),
42
71
  });
43
72
  });
44
73
  timer = setTimeout(() => {
@@ -142,8 +171,13 @@ export async function runDoctor({
142
171
  transport: "stdio",
143
172
  },
144
173
  env: {
145
- ACP_LOG_SIZE: process.env.ACP_LOG_SIZE !== undefined ? process.env.ACP_LOG_SIZE : DEFAULT_LOG_SIZE,
146
- CURSOR_DELEGATE_TRANSCRIPT: process.env.CURSOR_DELEGATE_TRANSCRIPT ?? null,
174
+ ACP_LOG_SIZE: envReport("ACP_LOG_SIZE", DEFAULT_LOG_SIZE),
175
+ ACP_AGENT_COMMAND: envReport("ACP_AGENT_COMMAND"),
176
+ ACP_AGENT_ARGS: envReport("ACP_AGENT_ARGS"),
177
+ CURSOR_DELEGATE_TRANSCRIPT: envReport("CURSOR_DELEGATE_TRANSCRIPT"),
178
+ CURSOR_DELEGATE_HANDSHAKE_MS: envReport("CURSOR_DELEGATE_HANDSHAKE_MS"),
179
+ CURSOR_DELEGATE_HARD_CAP_MS: envReport("CURSOR_DELEGATE_HARD_CAP_MS"),
180
+ CURSOR_DELEGATE_IDLE_MS: envReport("CURSOR_DELEGATE_IDLE_MS"),
147
181
  },
148
182
  };
149
183
 
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
@@ -33,9 +50,13 @@ export class JsonRpcPeer {
33
50
  // The failure transcript is the only thing that reads these frames, and it is opt-in, so
34
51
  // recording by default retained up to _logSize × FRAME_CAP bytes per delegation that nothing
35
52
  // 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;
53
+ this._recording = this._logSize > 0 && transcriptFrames() > 0;
37
54
  this._log = [];
38
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", () => {});
39
60
  this.rl.on("line", (line) => this._onLine(line));
40
61
  }
41
62
 
@@ -63,11 +84,14 @@ export class JsonRpcPeer {
63
84
  }
64
85
 
65
86
  _onLine(line) {
66
- this.onActivity();
67
87
  this._record("in", line);
68
88
  if (!line.trim()) return;
69
89
  let msg;
70
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();
71
95
  const hasId = msg.id !== undefined && msg.id !== null;
72
96
  if (hasId && (msg.result !== undefined || msg.error !== undefined)) {
73
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
  }