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/src/server.js CHANGED
@@ -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
  }
@@ -93,6 +104,7 @@ export const delegateOutputShape = {
93
104
  completed: z.number(),
94
105
  inProgress: z.number(),
95
106
  pending: z.number(),
107
+ cancelled: z.number(),
96
108
  }).optional(),
97
109
  };
98
110
 
@@ -151,7 +163,7 @@ export const delegateInputSchema = z.object({
151
163
  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
164
  mode: z.enum(["agent", "plan", "ask"]).default("agent").describe("agent implements; plan and ask are instructions to the agent, not limits."),
153
165
  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."),
166
+ 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
167
  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
168
  fast: z.boolean().default(false).describe("Fast tier; higher cost — only when the user asks."),
157
169
  // Which values a model offers is only knowable after selecting it, so this stays an open
@@ -166,11 +178,12 @@ export const delegateInputSchema = z.object({
166
178
  * args: any, extra?: any,
167
179
  * runDelegate: (opts: any) => Promise<any>,
168
180
  * inFlight: Map<string, Set<any>>,
181
+ * pending?: Set<any>,
169
182
  * seenSessions?: Set<string>,
170
183
  * }} deps
171
184
  * @returns {Promise<import("@modelcontextprotocol/sdk/types.js").CallToolResult>}
172
185
  */
173
- export async function runDelegateTool({ args, extra, runDelegate, inFlight, seenSessions = new Set() }) {
186
+ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pending = new Set(), seenSessions = new Set() }) {
174
187
  const { spec, mode, resumeSessionId, workspace, model, fast, effort, context, contextFiles } = args;
175
188
 
176
189
  const progressToken = extra?._meta?.progressToken;
@@ -197,7 +210,7 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, seen
197
210
  spec,
198
211
  mode,
199
212
  resumeSessionId,
200
- workspace: workspace || process.cwd(),
213
+ workspace,
201
214
  model,
202
215
  fast,
203
216
  effort,
@@ -205,9 +218,16 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, seen
205
218
  contextFiles,
206
219
  onProgress,
207
220
  signal: extra?.signal,
221
+ onClientReady: (client) => {
222
+ handle = { client, cancelRequested: false };
223
+ pending.add(handle);
224
+ },
208
225
  onSessionReady: (sessionId, client) => {
209
226
  capturedSessionId = sessionId;
210
- handle = { client, cancelRequested: false };
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.
229
+ handle ??= { client, cancelRequested: false };
230
+ pending.delete(handle);
211
231
  registerInFlight(inFlight, sessionId, handle);
212
232
  rememberSession(seenSessions, sessionId);
213
233
  // Emit the id the moment the session opens, before the turn finishes, so a host that
@@ -228,7 +248,9 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, seen
228
248
  };
229
249
  } finally {
230
250
  // Drops only this delegation's own handle; the id stays registered while another turn
231
- // is still running on it.
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.
253
+ if (handle) pending.delete(handle);
232
254
  if (capturedSessionId) unregisterInFlight(inFlight, capturedSessionId, handle);
233
255
  }
234
256
  }
@@ -262,7 +284,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
262
284
  openWorldHint: true,
263
285
  },
264
286
  },
265
- async (args, extra) => runDelegateTool({ args, extra, runDelegate, inFlight, seenSessions })
287
+ async (args, extra) => runDelegateTool({ args, extra, runDelegate, inFlight, pending: pendingDelegations, seenSessions })
266
288
  );
267
289
 
268
290
  server.registerTool(
@@ -304,13 +326,17 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
304
326
  await new Promise((r) => setTimeout(r, forceGraceMs));
305
327
  const stillRunning = inFlight.get(sessionId);
306
328
  if (!stillRunning || stillRunning.size === 0) return cancelResult("cancelled", sessionId);
329
+ // Snapshot before awaiting stop. A resume that registers during teardown must not be
330
+ // swept out of the map — it was never killed, and inFlight.delete(sessionId) would
331
+ // hide it from cancel and shutdown.
332
+ const toKill = [...stillRunning];
307
333
  const observed = await Promise.all(
308
- [...stillRunning].map((handle) => Promise.resolve(handle.client.stop()).catch(() => false))
334
+ toKill.map((handle) => Promise.resolve(handle.client.stop()).catch(() => false))
309
335
  );
310
336
  // "killed" claims the process is gone, so it needs the exit, not just a dispatched signal.
311
337
  // When one does not follow, the handles stay registered and force can be tried again.
312
338
  if (!observed.every(Boolean)) return cancelResult("cancelled", sessionId);
313
- inFlight.delete(sessionId);
339
+ for (const handle of toKill) unregisterInFlight(inFlight, sessionId, handle);
314
340
  return cancelResult("killed", sessionId);
315
341
  }
316
342
  );
@@ -359,22 +385,55 @@ if (process.argv[1]) {
359
385
  }
360
386
  }
361
387
 
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
- });
388
+ // Kill what is still running, then exit, on any way the host has of going away.
389
+ export function installSignalCleanup(map, {
390
+ pending = new Set(),
391
+ exit = (code) => process.exit(code),
392
+ setExitCode = (code) => { process.exitCode = code; },
393
+ schedule = (fn) => setImmediate(fn),
394
+ stdin = process.stdin,
395
+ } = {}) {
396
+ let shuttingDown = false;
397
+ const shutdown = (code) => {
398
+ // A second trigger skips the wait below: the kills are already dispatched, and a caller
399
+ // that has asked twice wants out now.
400
+ if (shuttingDown) return exit(code);
401
+ shuttingDown = true;
402
+ // Set in the handler, not left to the exit below: a loop that runs dry on its own still
403
+ // has to die with the code the signal asked for, and the scheduled exit may never get a
404
+ // turn to run.
405
+ setExitCode(code);
406
+ const stops = [];
407
+ const dispatch = (handle) => {
408
+ try { stops.push(Promise.resolve(handle.client.stop()).catch(() => {})); } catch {}
409
+ };
410
+ for (const handles of map.values()) for (const handle of handles) dispatch(handle);
411
+ // Delegations still inside their handshake. The agent is already running for these, and this
412
+ // is the only place it is reachable from — they have no session id to be keyed under yet.
413
+ for (const handle of pending) dispatch(handle);
414
+ // On Windows the kill is a separate taskkill process: exiting before it walks the tree
415
+ // orphans everything below the shell wrapper — the ps1 launcher and the versioned agent
416
+ // were measured surviving the server's exit. stop() bounds itself (observed exit or its
417
+ // own deadline), so this wait is short and finite on every platform.
418
+ // Scheduled rather than called from the kill's own continuation, so the exit runs on a
419
+ // clean loop turn instead of on the settlement stack.
420
+ const leave = () => schedule(() => exit(code));
421
+ Promise.all(stops).then(leave, leave);
422
+ };
423
+ // Each agent runs in its own process group on POSIX, so a signal aimed at this process no
424
+ // longer reaches it the way it did when the two shared a group. Installing a handler replaces
425
+ // Node's default, and a server that swallows Ctrl-C would be a worse bug than the agent it
426
+ // leaks. Delegations still inside their handshake are reached through `pending`, so this
427
+ // covers the agent from the moment it is spawned, not from the moment its session opens.
428
+ if (DETACHED) {
429
+ const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143]]);
430
+ for (const [signal, code] of signals) process.on(signal, () => shutdown(code));
377
431
  }
432
+ // Closing the server's stdin is how a stdio host shuts the transport down, and it is what a
433
+ // host reaches for before it resorts to a signal. The SDK transport does not listen for it —
434
+ // it subscribes to `data` and `error` only — so EOF leaves this process up with a delegation
435
+ // still running and nobody left to hand it to.
436
+ stdin.on("end", () => shutdown(0));
378
437
  }
379
438
 
380
439
  if (isMain) {
@@ -382,11 +441,12 @@ if (isMain) {
382
441
  // so confirming an install meant wiring the server into a host first. Reads the package.json
383
442
  // beside this file, so it reports the code that is actually running rather than what a
384
443
  // manifest pinned. stdout is free here because the transport never starts.
385
- if (process.argv.slice(2).includes("--version")) {
444
+ const argv = process.argv.slice(2);
445
+ if (argv.includes("--version") || argv.includes("-v")) {
386
446
  console.log(readPackageVersion());
387
447
  } else {
388
448
  const server = buildServer();
389
- installSignalCleanup(inFlight);
449
+ installSignalCleanup(inFlight, { pending: pendingDelegations });
390
450
  await server.connect(new StdioServerTransport());
391
451
  }
392
452
  }
@@ -29,7 +29,8 @@ export class SessionSupervisor {
29
29
  this._onExit = (info) => {
30
30
  this._trip(
31
31
  "agent-exit",
32
- `agent exited (code=${info.code}${info.signal ? ", signal=" + info.signal : ""})${info.stderr ? ": " + String(info.stderr).slice(-2000) : ""}`
32
+ // Kept whole, for the reason acp-client.js states where it builds the same message.
33
+ `agent exited (code=${info.code}${info.signal ? ", signal=" + info.signal : ""})${info.stderr ? ": " + String(info.stderr) : ""}`
33
34
  );
34
35
  };
35
36
  }
package/src/turn-state.js CHANGED
@@ -4,18 +4,6 @@
4
4
  // also what reset() applies — a field added there is reset for free, and one that is missed is a
5
5
  // silent stale-data bug on resume.
6
6
 
7
- const MAX_OUTPUT = 10 * 1024 * 1024;
8
- const TRUNCATION_MARKER = "\n\n[output truncated at 10MB]";
9
-
10
- // Cutting a UTF-16 string at an arbitrary index can split a surrogate pair and leave a lone
11
- // half-character — ill-formed Unicode that strict JSON consumers reject or mangle. Step back
12
- // one unit when the boundary would land inside a pair.
13
- function cutAtCodePoint(s, n) {
14
- if (n >= s.length) return s;
15
- const cu = s.charCodeAt(n - 1);
16
- return s.slice(0, cu >= 0xd800 && cu <= 0xdbff ? n - 1 : n);
17
- }
18
-
19
7
  const isTerminalToolStatus = (status) =>
20
8
  status === "completed" || status === "failed" || status === "cancelled";
21
9
 
@@ -58,8 +46,6 @@ function progressStream(prefix, onProgress, throttleMs) {
58
46
  function freshFields() {
59
47
  return {
60
48
  resultChunks: [],
61
- resultLength: 0,
62
- truncated: false,
63
49
  // Text superseded by a later tool call is normally a preamble ("Inspecting the
64
50
  // implementation."), but the rule cannot tell a preamble from the whole answer: an agent
65
51
  // that replies and then runs one more command has its entire reply discarded, leaving the
@@ -69,6 +55,10 @@ function freshFields() {
69
55
  sawToolCall: false,
70
56
  collectingPostToolResult: false,
71
57
  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.
61
+ finishedToolCalls: new Set(),
72
62
  planEntries: [],
73
63
  planOverview: undefined,
74
64
  planDetail: undefined,
@@ -97,51 +87,47 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
97
87
  state.messages.reset();
98
88
  },
99
89
 
100
- // The result text as it stands, truncation marker included.
90
+ // The result text as it stands.
101
91
  text() {
102
- const joined = state.resultChunks.join("");
103
- return state.truncated ? joined + TRUNCATION_MARKER : joined;
92
+ return state.resultChunks.join("");
104
93
  },
105
94
 
106
95
  resetResult() {
107
- if (state.resultLength > 0) state.discardedResult = state.resultChunks.join("");
96
+ if (state.resultChunks.length > 0) state.discardedResult = state.resultChunks.join("");
108
97
  state.resultChunks.length = 0;
109
- state.resultLength = 0;
110
- state.truncated = false;
111
98
  },
112
99
 
100
+ // The stream is the model's own message, bounded by its output limit; a byte cap
101
+ // here would hand back a partial answer as if it were the whole one.
113
102
  appendResult(text) {
114
- if (state.truncated) return;
115
- const remaining = MAX_OUTPUT - state.resultLength;
116
- if (text.length <= remaining) {
117
- state.resultChunks.push(text);
118
- state.resultLength += text.length;
119
- } else if (remaining > 0) {
120
- const cut = cutAtCodePoint(text, remaining);
121
- state.resultChunks.push(cut);
122
- state.resultLength += cut.length;
123
- state.truncated = true;
124
- } else {
125
- state.truncated = true;
126
- }
103
+ state.resultChunks.push(text);
127
104
  },
128
105
 
129
106
  startTool(toolCallId, status) {
130
107
  state.sawToolCall = true;
131
108
  state.collectingPostToolResult = false;
132
109
  state.resetResult();
133
- if (toolCallId != null && !isTerminalToolStatus(status)) state.activeToolCalls.add(toolCallId);
110
+ if (toolCallId != null && !isTerminalToolStatus(status)) {
111
+ state.activeToolCalls.add(toolCallId);
112
+ // A fresh tool_call frame for a finished id is the agent reusing it, not history.
113
+ state.finishedToolCalls.delete(toolCallId);
114
+ }
115
+ if (toolCallId != null && isTerminalToolStatus(status)) state.finishedToolCalls.add(toolCallId);
134
116
  if (isTerminalToolStatus(status) && state.activeToolCalls.size === 0) state.collectingPostToolResult = true;
135
117
  },
136
118
 
137
119
  updateToolStatus(toolCallId, status) {
138
120
  if (!status) return;
121
+ if (toolCallId != null && !isTerminalToolStatus(status) && state.finishedToolCalls.has(toolCallId)) return;
139
122
  if (!state.sawToolCall) {
140
123
  state.sawToolCall = true;
141
124
  state.resetResult();
142
125
  }
143
126
  if (isTerminalToolStatus(status)) {
144
- if (toolCallId != null) state.activeToolCalls.delete(toolCallId);
127
+ if (toolCallId != null) {
128
+ state.activeToolCalls.delete(toolCallId);
129
+ state.finishedToolCalls.add(toolCallId);
130
+ }
145
131
  if (state.activeToolCalls.size === 0 && !state.collectingPostToolResult) {
146
132
  // Discard any message text emitted while tools were still running.
147
133
  // A duplicate or late terminal update must not wipe an already-collected final message.