cursor-delegate-mcp 2.9.0 → 2.10.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/src/server.js CHANGED
@@ -24,10 +24,8 @@ if (nodeMajor < 20) {
24
24
  process.exit(1);
25
25
  }
26
26
 
27
- // sessionId -> the set of delegations currently running on it. A set, not a single handle,
28
- // because a resume can race the turn it resumes: both are live, both are cancellable, and
29
- // keying one handle per id let whichever finished first deregister the other — after which
30
- // cancel reported a running session as already ended.
27
+ // sessionId -> the delegations running on it. A set because a resume can race the turn it
28
+ // resumes; with one handle per id, whichever finished first deregistered the other.
31
29
  const inFlight = new Map();
32
30
  function registerInFlight(map, sessionId, handle) {
33
31
  const handles = map.get(sessionId);
@@ -44,31 +42,24 @@ function unregisterInFlight(map, sessionId, handle) {
44
42
  handles.delete(handle);
45
43
  if (handles.size === 0) map.delete(sessionId);
46
44
  }
47
- // Delegations whose session has not opened yet. inFlight is keyed by session id, and that id
48
- // arrives about 3.4s after the agent process does — so between client.start() and session/new
49
- // there is a live, auto-approved agent that the map cannot name. Shutdown walks this too.
50
- // cancel deliberately does not: an id the caller has never been given is not one it can pass.
45
+ // Delegations whose session has not opened yet: the agent runs ~3.4s before inFlight can key it.
46
+ // Shutdown walks this; cancel cannot, since the caller has no id for these yet.
51
47
  const pendingDelegations = new Set();
52
48
 
53
- // Session ids seen this process, kept after the turn ends so cancel can tell a finished
54
- // session (resumable, only the turn is over) from an id that never existed. Bounded so a
55
- // long-lived server does not grow without limit.
49
+ // Session ids seen by this process, kept after the turn ends so cancel can tell a finished
50
+ // (still resumable) session from an id that never existed. Bounded.
56
51
  const seenSessions = new Set();
57
52
  const SEEN_SESSIONS_CAP = 500;
58
53
  function rememberSession(set, id) {
59
54
  if (id == null) return;
60
- // Set iteration order makes the delete-then-add a small LRU: a session that is still being
61
- // resumed moves back to the recent end, so it outlives an equally old id that was seen once
62
- // and never again. Without it the id a caller is actually working with ages out on insertion
63
- // order alone, and cancel then calls a live, resumable session one that never existed.
55
+ // Delete-then-add makes the Set an LRU, so a session still being resumed outlives one seen once.
64
56
  if (set.has(id)) set.delete(id);
65
57
  set.add(id);
66
58
  if (set.size > SEEN_SESSIONS_CAP) set.delete(set.values().next().value);
67
59
  }
68
60
 
69
- // Loaded at connect, before any tool schema is, so this carries only pre-call facts: what a
70
- // caller needs to decide whether to delegate at all. Call-time facts belong on the parameter
71
- // descriptions, read while the call is being written.
61
+ // Read at connect, so only what decides whether to delegate at all. Call-time facts belong on
62
+ // the parameter descriptions.
72
63
  export const SERVER_INSTRUCTIONS = `Delegate coding work to Cursor through the delegate tool. Every permission the agent requests is auto-approved, in every mode: agent/plan/ask reach any file the user account can, and mode instructs the agent rather than limiting it. Scope workspace tightly and review the git diff after every run — filesReportedByEditTools carries only what the agent's edit tools reported; the diff is authoritative.`;
73
64
 
74
65
  const planEntrySchema = z.object({
@@ -77,10 +68,9 @@ const planEntrySchema = z.object({
77
68
  status: z.enum(PLAN_STATUSES).optional(),
78
69
  }).passthrough();
79
70
 
80
- // No outputSchema: that also requires structuredContent, and a host that reads both (Codex)
81
- // puts the payload in context twice. One JSON text block; the .strict() copy is in
82
- // delegate.test.js. Field meanings: skills/delegate/reference.md. cancel status lives on
83
- // its tool description.
71
+ // No outputSchema: it requires structuredContent too, and a host that reads both (Codex) puts the
72
+ // payload in context twice. Strict copy in delegate.test.js; field meanings in
73
+ // skills/delegate/reference.md.
84
74
  export const delegateOutputShape = {
85
75
  result: z.string(),
86
76
  resultSource: z.enum(["pre-tool-fallback", "none"]).optional(),
@@ -111,9 +101,9 @@ export const delegateOutputShape = {
111
101
  }).optional(),
112
102
  };
113
103
 
114
- // Same in-repo contract as delegateOutputShape. Relayed agent fields stay unknown so a
115
- // weird protocolVersion is a diagnostic, not a failed call. doctor.test.js holds the
116
- // strict copy. Handshake is its own shape: a .strict() on agent does not look inside it.
104
+ // Same contract as delegateOutputShape; strict copy in doctor.test.js. Relayed agent fields stay
105
+ // unknown so an odd protocolVersion is a diagnostic, not a failed call. Handshake is its own
106
+ // shape because .strict() does not look inside a nested object.
117
107
  export const doctorHandshakeShape = {
118
108
  ok: z.boolean(),
119
109
  error: z.string().optional(),
@@ -122,7 +112,7 @@ export const doctorHandshakeShape = {
122
112
  models: z.array(z.unknown()).optional(),
123
113
  currentModel: z.unknown().optional(),
124
114
  modes: z.array(z.unknown()).optional(),
125
- // Built here rather than relayed, so it gets a real type where its neighbours get z.unknown().
115
+ // Built here, not relayed, so it gets a real type.
126
116
  currentModelOptions: z.array(z.object({
127
117
  id: z.string(),
128
118
  name: z.string().optional(),
@@ -140,7 +130,7 @@ export const doctorAgentShape = {
140
130
  handshake: z.object(doctorHandshakeShape).passthrough().optional(),
141
131
  };
142
132
 
143
- // agent is split out because a top-level .strict() does not look inside a nested object.
133
+ // agent is split out for the same reason as handshake.
144
134
  export const doctorOutputShape = {
145
135
  plugin: z.object({ version: z.string() }).passthrough(),
146
136
  client: z.object({
@@ -166,8 +156,7 @@ export const delegateInputSchema = z.object({
166
156
  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."),
167
157
  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."),
168
158
  fast: z.boolean().default(false).describe("Fast tier; higher cost — only when the user asks."),
169
- // Which values a model offers is only knowable after selecting it, so this stays an open
170
- // string and the bridge validates the exact token against the live option list.
159
+ // Open string: a model's values are known only once it is selected, then validated live.
171
160
  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."),
172
161
  context: z.string().trim().min(1).optional().describe("Context window size; gpt-5.x accepts 272k and 1m. Do not pass speculatively."),
173
162
  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."),
@@ -192,8 +181,8 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
192
181
  if (progressToken != null) {
193
182
  let progress = 0;
194
183
  onProgress = (message) => {
195
- // sendNotification is async: its rejection settles outside this try and would exit the
196
- // server. The try stays for a sync throw, which lands before Promise.resolve can wrap it.
184
+ // An unhandled rejection from sendNotification would exit the server; the try catches a
185
+ // sync throw.
197
186
  try {
198
187
  Promise.resolve(extra.sendNotification({
199
188
  method: "notifications/progress",
@@ -224,16 +213,12 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
224
213
  },
225
214
  onSessionReady: (sessionId, client) => {
226
215
  capturedSessionId = sessionId;
227
- // The same handle moves across, so a shutdown racing this boundary finds it on exactly
228
- // one side of it rather than on neither.
216
+ // The same handle moves across, so a racing shutdown finds it on exactly one side.
229
217
  handle ??= { client, cancelRequested: false };
230
218
  pending.delete(handle);
231
219
  registerInFlight(inFlight, sessionId, handle);
232
220
  rememberSession(seenSessions, sessionId);
233
- // Emit the id the moment the session opens, before the turn finishes, so a host that
234
- // can call tools concurrently has something to pass to cancel mid-run — otherwise the
235
- // id only arrives when delegate returns, by which point there is nothing to cancel.
236
- // (Hosts that serialize tool calls still cannot cancel in flight; that is a host limit.)
221
+ // Sent now so a host that can call tools concurrently has an id to cancel mid-run.
237
222
  onProgress(`session ready: ${sessionId}`);
238
223
  },
239
224
  });
@@ -241,15 +226,13 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
241
226
  return { content: [{ type: "text", text: JSON.stringify(out) }] };
242
227
  } catch (err) {
243
228
  return {
244
- // The reason is already decided upstream; naming it here saves the caller parsing
245
- // prose to tell a timeout from a rejected argument.
229
+ // The reason up front, so the caller need not parse prose to tell a timeout from a bad argument.
246
230
  content: [{ type: "text", text: `delegate failed${err?.reason ? ` [${err.reason}]` : ""}: ` + (err?.message || String(err)) }],
247
231
  isError: true,
248
232
  };
249
233
  } finally {
250
- // Drops only this delegation's own handle; the id stays registered while another turn
251
- // is still running on it. A delegation that failed before its session opened is only ever
252
- // in pending, and one that opened is only ever in the map — the delete covers both.
234
+ // Drops only this delegation's handle, from whichever of pending or the map holds it; the id
235
+ // stays registered while another turn runs on it.
253
236
  if (handle) pending.delete(handle);
254
237
  if (capturedSessionId) unregisterInFlight(inFlight, capturedSessionId, handle);
255
238
  }
@@ -260,9 +243,10 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
260
243
  * runDelegate?: (opts: any) => Promise<any>,
261
244
  * runDoctor?: (opts: any) => Promise<any>,
262
245
  * forceGraceMs?: number,
246
+ * pending?: Set<any>,
263
247
  * }} [opts]
264
248
  */
265
- export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000 } = {}) {
249
+ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000, pending = pendingDelegations } = {}) {
266
250
  const runDelegate = runDelegateInjected || runDelegateDefault;
267
251
  const runDoctor = runDoctorInjected || runDoctorDefault;
268
252
  const server = new McpServer(
@@ -284,7 +268,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
284
268
  openWorldHint: true,
285
269
  },
286
270
  },
287
- async (args, extra) => runDelegateTool({ args, extra, runDelegate, inFlight, pending: pendingDelegations, seenSessions })
271
+ async (args, extra) => runDelegateTool({ args, extra, runDelegate, inFlight, pending, seenSessions })
288
272
  );
289
273
 
290
274
  server.registerTool(
@@ -293,7 +277,8 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
293
277
  description:
294
278
  "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).",
295
279
  inputSchema: {
296
- sessionId: z.string(),
280
+ // Blank is a malformed call, not a stale id.
281
+ sessionId: z.string().trim().min(1, "sessionId must not be blank"),
297
282
  force: z.boolean().default(false).describe("Kill the agent process if the turn is still running after a short grace period."),
298
283
  },
299
284
  annotations: {
@@ -307,39 +292,32 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
307
292
  async ({ sessionId, force }) => {
308
293
  const handles = inFlight.get(sessionId);
309
294
  if (!handles || handles.size === 0) {
310
- // A finished session and a garbage id are both "not in flight". Reporting them alike
311
- // would read as "bad id" for a session that ran and is still resumable.
295
+ // A finished session is still resumable; only an unknown id is not-found.
312
296
  const known = seenSessions.has(sessionId);
313
297
  return cancelResult(known ? "not-running" : "not-found", sessionId);
314
298
  }
315
- // Cancel every turn running on the id: the caller named a session, not one of the
316
- // turns that happen to share it.
317
- for (const handle of handles) handle.cancelRequested = true;
318
- await Promise.all([...handles].map((handle) => handle.client.cancel(sessionId).catch(() => {})));
299
+ // Every turn on the id (the caller named a session), taken now: a resume that registers during
300
+ // the grace or the kill is not swept in.
301
+ const targeted = [...handles];
302
+ for (const handle of targeted) handle.cancelRequested = true;
303
+ await Promise.all(targeted.map((handle) => handle.client.cancel(sessionId).catch(() => {})));
319
304
  if (!force) {
320
- // The handles stay registered: session/cancel is best-effort, so the turn may still
321
- // be running. Dropping them here made the natural escalation — cancel, wait, cancel
322
- // with force — report not-found while the agent was alive. Each delegation's own
323
- // finally removes its handle when the turn actually settles.
305
+ // Handles stay registered: session/cancel is advisory, and a later force must still find
306
+ // the turn. Each delegation's finally removes its handle when the turn settles.
324
307
  return cancelResult("cancelled", sessionId);
325
308
  }
326
- // Watched rather than slept through: cursor-agent can stop a cancelled turn well inside the
327
- // grace, and the delegation's finally drops its handle the moment the turn settles.
309
+ // Polled, not slept through: the turn often settles well inside the grace.
310
+ const running = () => targeted.filter((handle) => inFlight.get(sessionId)?.has(handle));
328
311
  const graceEnds = Date.now() + forceGraceMs;
329
- while (Date.now() < graceEnds && inFlight.get(sessionId)?.size) {
312
+ while (Date.now() < graceEnds && running().length) {
330
313
  await new Promise((r) => setTimeout(r, Math.min(50, Math.max(1, graceEnds - Date.now()))));
331
314
  }
332
- const stillRunning = inFlight.get(sessionId);
333
- if (!stillRunning || stillRunning.size === 0) return cancelResult("cancelled", sessionId);
334
- // Snapshot before awaiting stop. A resume that registers during teardown must not be
335
- // swept out of the map — it was never killed, and inFlight.delete(sessionId) would
336
- // hide it from cancel and shutdown.
337
- const toKill = [...stillRunning];
315
+ const toKill = running();
316
+ if (toKill.length === 0) return cancelResult("cancelled", sessionId);
338
317
  const observed = await Promise.all(
339
318
  toKill.map((handle) => Promise.resolve(handle.client.stop()).catch(() => false))
340
319
  );
341
- // "killed" claims the process is gone, so it needs the exit, not just a dispatched signal.
342
- // When one does not follow, the handles stay registered and force can be tried again.
320
+ // "killed" needs an observed exit; without one the handles stay and force can be retried.
343
321
  if (!observed.every(Boolean)) return cancelResult("cancelled", sessionId);
344
322
  for (const handle of toKill) unregisterInFlight(inFlight, sessionId, handle);
345
323
  return cancelResult("killed", sessionId);
@@ -365,15 +343,23 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
365
343
  openWorldHint: false,
366
344
  },
367
345
  },
368
- async ({ deep }) => {
369
- const out = await runDoctor({
370
- deep,
371
- getClientInfo: () => ({
372
- capabilities: server.server.getClientCapabilities(),
373
- version: server.server.getClientVersion(),
374
- }),
375
- });
376
- return { content: [{ type: "text", text: JSON.stringify(out) }] };
346
+ async ({ deep }, extra) => {
347
+ // doctor's processes sit in pending while it runs, where shutdown already looks.
348
+ const handles = [];
349
+ try {
350
+ const out = await runDoctor({
351
+ deep,
352
+ signal: extra?.signal,
353
+ onClientReady: (client) => { const handle = { client }; handles.push(handle); pending.add(handle); },
354
+ getClientInfo: () => ({
355
+ capabilities: server.server.getClientCapabilities(),
356
+ version: server.server.getClientVersion(),
357
+ }),
358
+ });
359
+ return { content: [{ type: "text", text: JSON.stringify(out) }] };
360
+ } finally {
361
+ for (const handle of handles) pending.delete(handle);
362
+ }
377
363
  }
378
364
  );
379
365
 
@@ -399,51 +385,40 @@ export function installSignalCleanup(map, {
399
385
  stdin = process.stdin,
400
386
  } = {}) {
401
387
  let shuttingDown = false;
402
- const shutdown = (code) => {
403
- // A second trigger skips the wait below: the kills are already dispatched, and a caller
404
- // that has asked twice wants out now.
405
- if (shuttingDown) return exit(code);
388
+ const shutdown = (code, fromSignal = false) => {
389
+ // A second signal exits without the wait, the kills already sent. A stdin EOF does not: a
390
+ // hangup closes stdin right after its SIGHUP.
391
+ if (shuttingDown) return fromSignal ? exit(code) : undefined;
406
392
  shuttingDown = true;
407
- // Set in the handler, not left to the exit below: a loop that runs dry on its own still
408
- // has to die with the code the signal asked for, and the scheduled exit may never get a
409
- // turn to run.
393
+ // Set now: the loop may run dry before the scheduled exit gets a turn.
410
394
  setExitCode(code);
411
395
  const stops = [];
412
396
  const dispatch = (handle) => {
413
397
  try { stops.push(Promise.resolve(handle.client.stop()).catch(() => {})); } catch {}
414
398
  };
415
399
  for (const handles of map.values()) for (const handle of handles) dispatch(handle);
416
- // Delegations still inside their handshake. The agent is already running for these, and this
417
- // is the only place it is reachable from — they have no session id to be keyed under yet.
400
+ // Delegations still in their handshake: their agent runs, and only pending reaches it.
418
401
  for (const handle of pending) dispatch(handle);
419
- // On Windows the kill is a separate taskkill process: exiting before it walks the tree
420
- // orphans everything below the shell wrapper — the ps1 launcher and the versioned agent
421
- // were measured surviving the server's exit. stop() bounds itself (observed exit or its
422
- // own deadline), so this wait is short and finite on every platform.
423
- // Scheduled rather than called from the kill's own continuation, so the exit runs on a
424
- // clean loop turn instead of on the settlement stack.
402
+ // Waits for the kills: on Windows taskkill is a separate process, and exiting first orphans the
403
+ // launcher and agent below the shell (measured). stop() bounds itself, so the wait is finite.
404
+ // The exit is scheduled onto a clean loop turn rather than run on the settlement stack.
425
405
  const leave = () => schedule(() => exit(code));
426
406
  Promise.all(stops).then(leave, leave);
427
407
  };
428
- // Each agent runs in its own process group on POSIX, so a signal aimed at this process no
429
- // longer reaches it. Installing a handler replaces Node's default; swallowing Ctrl-C would
430
- // leak the agent. shutdown() already walks pending, so this covers spawn through session/new.
408
+ // On POSIX each agent has its own process group, which a signal to this process misses, so the
409
+ // handler kills them first. SIGHUP too: a closed terminal, whose default leaves them running.
431
410
  if (DETACHED) {
432
- const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143]]);
433
- for (const [signal, code] of signals) process.on(signal, () => shutdown(code));
411
+ const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]]);
412
+ for (const [signal, code] of signals) process.on(signal, () => shutdown(code, true));
434
413
  }
435
- // Closing the server's stdin is how a stdio host shuts the transport down, and it is what a
436
- // host reaches for before it resorts to a signal. The SDK transport does not listen for it —
437
- // it subscribes to `data` and `error` only — so EOF leaves this process up with a delegation
438
- // still running and nobody left to hand it to.
414
+ // A stdio host closes stdin before it resorts to a signal, and the SDK transport ignores EOF
415
+ // (it listens for `data` and `error` only).
439
416
  stdin.on("end", () => shutdown(0));
440
417
  }
441
418
 
442
419
  if (isMain) {
443
- // Without this the flag falls through to the transport, which owns stdout and waits on stdin —
444
- // so confirming an install meant wiring the server into a host first. Reads the package.json
445
- // beside this file, so it reports the code that is actually running rather than what a
446
- // manifest pinned. stdout is free here because the transport never starts.
420
+ // Answered before the transport starts, so an install can be checked without a host. Reads the
421
+ // package.json beside this file: the code actually running, not what a manifest pinned.
447
422
  const argv = process.argv.slice(2);
448
423
  if (argv.includes("--version") || argv.includes("-v")) {
449
424
  console.log(readPackageVersion());
@@ -11,9 +11,8 @@ export class SessionSupervisor {
11
11
  this.client = client;
12
12
  this.handshakeMs = handshakeMs;
13
13
  this.hardCapMs = hardCapMs;
14
- // Mid-turn idle detection is opt-in and off by default. cursor-agent emits no ACP
15
- // frames while a shell command runs, so silence during a prompt turn says nothing
16
- // about liveness: a probe measured 26.9s of dead wire for a healthy 20s command.
14
+ // Idle detection is opt-in: cursor-agent sends no frames while a shell command runs (26.9s of
15
+ // silence measured for a healthy 20s command).
17
16
  this.idleMs = idleMs > 0 ? idleMs : 0;
18
17
  this.sessionId = null;
19
18
  this.lastActivityAt = Date.now();
@@ -58,9 +57,8 @@ export class SessionSupervisor {
58
57
  }, this.handshakeMs);
59
58
  }
60
59
 
61
- // The handshake is strict request/response, so silence there is real evidence of a
62
- // wedged agent. Once the prompt is in flight that stops being true, and the deadline
63
- // must come off.
60
+ // Silence in the request/response handshake means a wedged agent; once the prompt is in flight
61
+ // it does not, so the deadline comes off.
64
62
  promptStarted() {
65
63
  if (this._promptStarted) return;
66
64
  this._promptStarted = true;
package/src/spawn.js CHANGED
@@ -1,32 +1,39 @@
1
1
  import process from "node:process";
2
- import { existsSync, statSync } from "node:fs";
2
+ import { lstatSync, readFileSync, statSync } from "node:fs";
3
3
  import path from "node:path";
4
4
 
5
+ // Splits on whitespace outside quotes. A closed quote at an argument's start or after "=" groups
6
+ // and is removed (--log-file="C:\a b\x.log"); elsewhere it is a character (O'Brien). \ is literal.
5
7
  export function splitArgs(raw) {
8
+ const s = String(raw || "");
6
9
  const args = [];
7
- const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
8
- for (const m of String(raw || "").matchAll(re)) {
9
- args.push(m[1] ?? m[2] ?? m[3]);
10
+ let i = 0;
11
+ for (;;) {
12
+ while (i < s.length && /\s/.test(s[i])) i++;
13
+ if (i >= s.length) return args;
14
+ let arg = "";
15
+ while (i < s.length && !/\s/.test(s[i])) {
16
+ const end = (s[i] === '"' || s[i] === "'") && (arg === "" || arg.endsWith("=")) ? s.indexOf(s[i], i + 1) : -1;
17
+ if (end === -1) { arg += s[i++]; continue; }
18
+ arg += s.slice(i + 1, end);
19
+ i = end + 1;
20
+ }
21
+ args.push(arg);
10
22
  }
11
- return args;
12
23
  }
13
24
 
14
- // On Windows cursor-agent writes every hook command as PowerShell, but runs it in Git Bash when
15
- // it finds MSYSTEM, or a SHELL naming Git Bash, in its environment. A host running in Git Bash
16
- // (Claude Code on Windows) passes both down, bash rejects the PowerShell line, and the agent
17
- // reports every hooked tool call as blocked. Dropped, the agent falls back to PowerShell, the
18
- // shell it uses when started outside Git Bash.
25
+ // On Windows cursor-agent writes hook commands as PowerShell but runs them in Git Bash when it sees
26
+ // MSYSTEM or a Git Bash SHELL, which a host in Git Bash (Claude Code) passes down; bash then blocks
27
+ // every hooked tool call. Without the two vars the agent uses PowerShell.
19
28
  const WIN32_DROPPED_ENV = new Set(["MSYSTEM", "SHELL"]);
20
29
 
21
30
  function agentEnv(env = process.env) {
22
31
  return Object.fromEntries(Object.entries(env).filter(([key]) => !WIN32_DROPPED_ENV.has(key.toUpperCase())));
23
32
  }
24
33
 
25
- // shell:true on win32 is what lets a .cmd/.ps1 launcher resolve at all, and it means the
26
- // command and args are parsed by cmd.exe. Safe only because both come from the environment,
27
- // which is already as trusted as this process: anything that can set them can run code here
28
- // anyway. Routing host- or caller-supplied values into either variable would turn this into a
29
- // command-injection path, so don't.
34
+ // shell:true on win32 lets a .cmd launcher resolve, and means cmd.exe parses the command line.
35
+ // Safe only because both values come from the environment, already as trusted as this process.
36
+ // Never route host- or caller-supplied values into them: that is command injection.
30
37
  export function resolveAcpSpawn() {
31
38
  const command = process.env.ACP_AGENT_COMMAND || "cursor-agent";
32
39
  const args = process.env.ACP_AGENT_ARGS
@@ -36,21 +43,100 @@ export function resolveAcpSpawn() {
36
43
  return { command, args, options: { shell: win32, ...(win32 ? { env: agentEnv() } : {}) } };
37
44
  }
38
45
 
39
- // Through a shell the spawn itself always succeeds: cmd.exe starts, fails to find the launcher and
40
- // exits 1 with a localized "is not recognized" line, so Node's spawn 'error' event never fires and
41
- // a missing cursor-agent reads as an agent crash. Resolving the launcher first is what lets that
42
- // case be reported as not installed. Mirrors cmd's lookup: a path is checked as given, a bare name
43
- // against each PATH entry, both with and without each PATHEXT extension. Pass the env the child
44
- // will get: on win32 that is agentEnv(), not process.env.
46
+ // Under shell:true Node hands cmd.exe one unquoted line, so a value with a space or metacharacter
47
+ // splits there. Quoted at the spawn sites, so the spec keeps plain args. A value already holding a
48
+ // quote passes as given: cmd cannot nest them, and pre-quoted paths worked before. cmd still
49
+ // expands %VAR% inside quotes.
50
+ function cmdQuote(value) {
51
+ const s = String(value);
52
+ if (s.includes('"') || (s !== "" && !/[\s&|<>^(),;=]/.test(s))) return s;
53
+ // Doubled so the child's argv parser does not read a trailing backslash as escaping the quote.
54
+ return `"${s.replace(/(\\+)$/, "$1$1")}"`;
55
+ }
56
+
57
+ /**
58
+ * What to hand spawn() for a spec, at each spawn site so doctor reads the spec as configured.
59
+ * @param {string} command @param {string[]} args
60
+ * @param {{ shell?: boolean | string, env?: NodeJS.ProcessEnv } | undefined} options
61
+ */
62
+ export function spawnArgv(command, args, options) {
63
+ if (!(options?.shell && process.platform === "win32")) return { command, args, options };
64
+ const env = options.env || process.env;
65
+ // cmd.exe opens a .ps1 with its file association, so a .ps1, or the one a forwarding .cmd runs,
66
+ // goes to powershell.exe -File as cursor-agent.cmd does. Only x.ps1 itself: x.ps1.cmd stays cmd's.
67
+ const name = String(command).replace(/^["']|["']$/g, "");
68
+ const script = /\.ps1$/i.test(name) ? findCommand(name, env, true) : forwardedScript(findCommand(name, env), env);
69
+ if (script) {
70
+ const rootKey = Object.keys(env).find((k) => k.toUpperCase() === "SYSTEMROOT");
71
+ const powershell = rootKey && env[rootKey]
72
+ ? path.win32.join(env[rootKey], "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
73
+ : "powershell.exe";
74
+ return {
75
+ command: powershell,
76
+ args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script, ...args],
77
+ options: { ...options, shell: false },
78
+ };
79
+ }
80
+ // One line and no args array: Node 24 warns (DEP0190) on args under shell:true.
81
+ return { command: [command, ...args].map(cmdQuote).join(" "), args: [], options };
82
+ }
83
+
84
+ // The .ps1 a .cmd passes its args to (powershell ... -File "%~dp0x.ps1" %*, or a variable set from
85
+ // %~dp0), else null. cursor-agent.cmd and its copy agent.cmd do this; cmd.exe and their delayed
86
+ // expansion rewrite !, %VAR%, ^ and quotes in the args, and the .ps1 repeats their update step.
87
+ function forwardedScript(file, env) {
88
+ if (!file || !/\.(cmd|bat)$/i.test(file)) return null;
89
+ let text;
90
+ try {
91
+ if (statSync(file).size > 64 * 1024) return null;
92
+ text = readFileSync(file, "latin1");
93
+ } catch {
94
+ return null;
95
+ }
96
+ const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
97
+ const dirVars = [...text.matchAll(/^\s*set\s+"?(\w+)=%~dp0"?\s*$/gim)].map((m) => `%${m[1]}%`);
98
+ const ownDir = ["%~dp0", ...dirVars].map(escape).join("|");
99
+ const forwards = new RegExp(`powershell(?:\\.exe)?"?[^\\r\\n]*\\s-File\\s+"(?:${ownDir})\\\\?([^"\\\\/:\\r\\n]+\\.ps1)"\\s+%\\*`, "i");
100
+ const target = text.match(forwards)?.[1];
101
+ return target ? findCommand(path.join(path.dirname(file), target), env, true) : null;
102
+ }
103
+
104
+ // Through a shell the spawn always succeeds (cmd.exe exits 1, "is not recognized"), so a missing
105
+ // launcher is looked up first to report it as not installed. Mirrors cmd: a path as given, a bare
106
+ // name on each PATH entry, each with and without each PATHEXT extension. Pass the env the child
107
+ // gets: on win32, agentEnv().
45
108
  export function commandExists(command, env = process.env) {
109
+ return findCommand(command, env) !== null;
110
+ }
111
+
112
+ /** The file that lookup lands on, or null. exact skips the PATHEXT extensions. */
113
+ function findCommand(command, env, exact = false) {
46
114
  const name = String(command || "").replace(/^["']|["']$/g, "");
47
- if (!name) return false;
115
+ if (!name) return null;
48
116
  const pathKey = Object.keys(env).find((k) => k.toUpperCase() === "PATH");
49
117
  const extKey = Object.keys(env).find((k) => k.toUpperCase() === "PATHEXT");
50
- const exts = ["", ...String((extKey && env[extKey]) || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)];
51
- const isFile = (p) => { try { return existsSync(p) && statSync(p).isFile(); } catch { return false; } };
52
- const hit = (base) => exts.some((ext) => isFile(base + ext) || isFile(base + ext.toLowerCase()));
118
+ const exts = exact ? [""] : ["", ...String((extKey && env[extKey]) || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)];
119
+ const isFile = (p) => {
120
+ try {
121
+ return statSync(p).isFile();
122
+ } catch (e) {
123
+ // A Store app's alias (WindowsApps\pwsh.exe) is a link into a folder this user cannot stat,
124
+ // so stat fails with EACCES, yet cmd runs it. A link to a missing file fails with ENOENT.
125
+ if (process.platform !== "win32" || (e.code !== "EACCES" && e.code !== "EPERM")) return false;
126
+ try { return lstatSync(p).isSymbolicLink(); } catch { return false; }
127
+ }
128
+ };
129
+ const hit = (base) => {
130
+ for (const ext of exts) {
131
+ for (const p of [base + ext, base + ext.toLowerCase()]) if (isFile(p)) return p;
132
+ }
133
+ return null;
134
+ };
53
135
  if (/[\\/]/.test(name)) return hit(name);
54
136
  const dirs = String((pathKey && env[pathKey]) || "").split(path.delimiter).filter(Boolean);
55
- return dirs.some((dir) => hit(path.join(dir.replace(/^"|"$/g, ""), name)));
137
+ for (const dir of dirs) {
138
+ const found = hit(path.join(dir.replace(/^"|"$/g, ""), name));
139
+ if (found) return found;
140
+ }
141
+ return null;
56
142
  }
package/src/turn-state.js CHANGED
@@ -1,8 +1,6 @@
1
- // Everything describing the turn in progress, in one object because it has to be wiped as one:
2
- // session/load replays the previous turn as ordinary update frames, so anything left behind
3
- // leaks into the next result. Fields are declared in exactly one place, freshFields(), which is
4
- // also what reset() applies — a field added there is reset for free, and one that is missed is a
5
- // silent stale-data bug on resume.
1
+ // The turn in progress, in one object so it can be wiped as one: session/load replays the
2
+ // previous turn as ordinary updates. Declare every field in freshFields(), which reset() applies;
3
+ // a field kept elsewhere leaks stale data into a resumed turn.
6
4
 
7
5
  const isTerminalToolStatus = (status) =>
8
6
  status === "completed" || status === "failed" || status === "cancelled";
@@ -42,31 +40,27 @@ function progressStream(prefix, onProgress, throttleMs) {
42
40
  };
43
41
  }
44
42
 
45
- // The single declaration of what a turn accumulates.
46
43
  function freshFields() {
47
44
  return {
48
45
  resultChunks: [],
49
- // Text superseded by a later tool call is normally a preamble ("Inspecting the
50
- // implementation."), but the rule cannot tell a preamble from the whole answer: an agent
51
- // that replies and then runs one more command has its entire reply discarded, leaving the
52
- // caller "" with stopReason end_turn and no error. Kept so it can be handed back when
53
- // nothing survived — labelled, never blended with a real final message.
46
+ // Text a later tool call superseded: usually a preamble, but the whole answer when the agent
47
+ // replied and then ran one more command. Handed back, labelled, only when nothing followed.
54
48
  discardedResult: "",
55
49
  sawToolCall: false,
56
50
  collectingPostToolResult: false,
57
51
  activeToolCalls: new Set(),
58
- // Ids observed terminal, so a stale non-terminal re-send for one is recognized and dropped
59
- // instead of restarting collection — which would demote an already-collected final message
60
- // to discardedResult and mislabel it pre-tool-fallback.
52
+ // Ids seen terminal, so a stale non-terminal re-send is dropped instead of restarting
53
+ // collection and demoting the collected final message.
61
54
  finishedToolCalls: new Set(),
62
55
  planEntries: [],
63
56
  planOverview: undefined,
64
57
  planDetail: undefined,
65
- // merge:false replaces the list, merge:true upserts by id. Entries always arrive complete,
66
- // so a keyed set is enough — no field-level merging.
58
+ // merge:false replaces the list, merge:true upserts by id; entries arrive complete.
67
59
  todos: new Map(),
68
60
  sawTodoFrame: false,
69
61
  touched: new Set(),
62
+ // The newest tool call's id, title and path; its updates refine the title and path.
63
+ lastTool: null,
70
64
  lastToolLabel: null,
71
65
  sessionTitle: undefined,
72
66
  };
@@ -96,8 +90,7 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
96
90
  state.resultChunks.length = 0;
97
91
  },
98
92
 
99
- // The stream is the model's own message, bounded by its output limit; a byte cap
100
- // here would hand back a partial answer as if it were the whole one.
93
+ // Uncapped: the model's output limit bounds it, and a cap would pass off a partial answer.
101
94
  appendResult(text) {
102
95
  state.resultChunks.push(text);
103
96
  },
@@ -128,8 +121,8 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
128
121
  state.finishedToolCalls.add(toolCallId);
129
122
  }
130
123
  if (state.activeToolCalls.size === 0 && !state.collectingPostToolResult) {
131
- // Discard any message text emitted while tools were still running.
132
- // A duplicate or late terminal update must not wipe an already-collected final message.
124
+ // Drops text emitted while tools ran. Guarded so a duplicate or late terminal update
125
+ // cannot wipe a collected final message.
133
126
  state.resetResult();
134
127
  state.collectingPostToolResult = true;
135
128
  }
@@ -140,8 +133,7 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
140
133
  }
141
134
  },
142
135
 
143
- // True while a message chunk still belongs in the result: before any tool ran, or after
144
- // the last one finished.
136
+ // A chunk belongs in the result before any tool ran or after the last one finished.
145
137
  collectingResult() {
146
138
  return !state.sawToolCall || (state.collectingPostToolResult && state.activeToolCalls.size === 0);
147
139
  },