cursor-delegate-mcp 2.9.0 → 2.11.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/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,112 @@ 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
+ // Windows PowerShell 5.1 pastes each argument into the command line unescaped, drops an empty one,
58
+ // and quotes one only if it has whitespace outside an even count of ". Escaped for node's parser;
59
+ // with whitespace a quote goes as "", which keeps that count even and reads as " inside the quotes.
60
+ function escapeForPs51(arg) {
61
+ if (arg === "") return '""';
62
+ const spaced = /\s/.test(arg);
63
+ const s = arg.replace(/(\\*)"/g, (_, bs) => `${bs}${bs}${spaced ? '""' : '\\"'}`);
64
+ return spaced ? s.replace(/(\\+)$/, "$1$1") : s;
65
+ }
66
+
67
+ /**
68
+ * What to hand spawn() for a spec, at each spawn site so doctor reads the spec as configured.
69
+ * @param {string} command @param {string[]} args
70
+ * @param {{ shell?: boolean | string, env?: NodeJS.ProcessEnv } | undefined} options
71
+ */
72
+ export function spawnArgv(command, args, options) {
73
+ if (!(options?.shell && process.platform === "win32")) return { command, args, options };
74
+ const env = options.env || process.env;
75
+ // cmd.exe opens a .ps1 with its file association, so a .ps1, or the one a forwarding .cmd runs,
76
+ // goes to powershell.exe -File as cursor-agent.cmd does. Only x.ps1 itself: x.ps1.cmd stays cmd's.
77
+ const name = String(command).replace(/^["']|["']$/g, "");
78
+ const direct = /\.ps1$/i.test(name);
79
+ const script = direct ? findCommand(name, env, true) : forwardedScript(findCommand(name, env), env);
80
+ if (script) {
81
+ const rootKey = Object.keys(env).find((k) => k.toUpperCase() === "SYSTEMROOT");
82
+ const powershell = rootKey && env[rootKey]
83
+ ? path.win32.join(env[rootKey], "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
84
+ : "powershell.exe";
85
+ return {
86
+ command: powershell,
87
+ // cursor-agent.ps1 passes $args on to node; a .ps1 named directly may read them itself.
88
+ args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script, ...(direct ? args : args.map(escapeForPs51))],
89
+ options: { ...options, shell: false },
90
+ };
91
+ }
92
+ // One line and no args array: Node 24 warns (DEP0190) on args under shell:true.
93
+ return { command: [command, ...args].map(cmdQuote).join(" "), args: [], options };
94
+ }
95
+
96
+ // The .ps1 a .cmd passes its args to (powershell ... -File "%~dp0x.ps1" %*, or a variable set from
97
+ // %~dp0), else null. cursor-agent.cmd and its copy agent.cmd do this; cmd.exe and their delayed
98
+ // expansion rewrite !, %VAR%, ^ and quotes in the args, and the .ps1 repeats their update step.
99
+ function forwardedScript(file, env) {
100
+ if (!file || !/\.(cmd|bat)$/i.test(file)) return null;
101
+ let text;
102
+ try {
103
+ if (statSync(file).size > 64 * 1024) return null;
104
+ text = readFileSync(file, "latin1");
105
+ } catch {
106
+ return null;
107
+ }
108
+ const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
109
+ const dirVars = [...text.matchAll(/^\s*set\s+"?(\w+)=%~dp0"?\s*$/gim)].map((m) => `%${m[1]}%`);
110
+ const ownDir = ["%~dp0", ...dirVars].map(escape).join("|");
111
+ const forwards = new RegExp(`powershell(?:\\.exe)?"?[^\\r\\n]*\\s-File\\s+"(?:${ownDir})\\\\?([^"\\\\/:\\r\\n]+\\.ps1)"\\s+%\\*`, "i");
112
+ const target = text.match(forwards)?.[1];
113
+ return target ? findCommand(path.join(path.dirname(file), target), env, true) : null;
114
+ }
115
+
116
+ // Through a shell the spawn always succeeds (cmd.exe exits 1, "is not recognized"), so a missing
117
+ // launcher is looked up first to report it as not installed. Mirrors cmd: a path as given, a bare
118
+ // name on each PATH entry, each with and without each PATHEXT extension. Pass the env the child
119
+ // gets: on win32, agentEnv().
45
120
  export function commandExists(command, env = process.env) {
121
+ return findCommand(command, env) !== null;
122
+ }
123
+
124
+ /** The file that lookup lands on, or null. exact skips the PATHEXT extensions. */
125
+ function findCommand(command, env, exact = false) {
46
126
  const name = String(command || "").replace(/^["']|["']$/g, "");
47
- if (!name) return false;
127
+ if (!name) return null;
48
128
  const pathKey = Object.keys(env).find((k) => k.toUpperCase() === "PATH");
49
129
  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()));
130
+ const exts = exact ? [""] : ["", ...String((extKey && env[extKey]) || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)];
131
+ const isFile = (p) => {
132
+ try {
133
+ return statSync(p).isFile();
134
+ } catch (e) {
135
+ // A Store app's alias (WindowsApps\pwsh.exe) is a link into a folder this user cannot stat,
136
+ // so stat fails with EACCES, yet cmd runs it. A link to a missing file fails with ENOENT.
137
+ if (process.platform !== "win32" || (e.code !== "EACCES" && e.code !== "EPERM")) return false;
138
+ try { return lstatSync(p).isSymbolicLink(); } catch { return false; }
139
+ }
140
+ };
141
+ const hit = (base) => {
142
+ for (const ext of exts) {
143
+ for (const p of [base + ext, base + ext.toLowerCase()]) if (isFile(p)) return p;
144
+ }
145
+ return null;
146
+ };
53
147
  if (/[\\/]/.test(name)) return hit(name);
54
148
  const dirs = String((pathKey && env[pathKey]) || "").split(path.delimiter).filter(Boolean);
55
- return dirs.some((dir) => hit(path.join(dir.replace(/^"|"$/g, ""), name)));
149
+ for (const dir of dirs) {
150
+ const found = hit(path.join(dir.replace(/^"|"$/g, ""), name));
151
+ if (found) return found;
152
+ }
153
+ return null;
56
154
  }
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
  },
package/src/version.js CHANGED
@@ -11,10 +11,8 @@ function readVersion() {
11
11
  // Captured once, for the ACP/MCP identity handshake that is sent at connect and never re-read.
12
12
  export const VERSION = readVersion();
13
13
 
14
- // doctor reads fresh rather than using the constant: the MCP child is long-lived and
15
- // /reload-plugins does not restart it, so a version captured at process start goes stale after
16
- // an in-place upgrade — exactly when doctor is run to confirm the new version shipped. An
17
- // un-restarted child running old code stays a gap, but no in-process value can close that.
14
+ // Read fresh for doctor: /reload-plugins does not restart the server, so the constant goes stale
15
+ // after an in-place upgrade, just when doctor confirms it. The running code stays old until a restart.
18
16
  export function readPackageVersion() {
19
17
  try {
20
18
  return readVersion();