cursor-delegate-mcp 1.22.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursor-delegate-mcp",
3
- "version": "1.22.0",
3
+ "version": "2.0.0",
4
4
  "mcpName": "io.github.andreilungeanu/cursor-delegate-mcp",
5
5
  "type": "module",
6
6
  "description": "Delegate multi-file coding work from Claude Code, Codex, or Copilot to Cursor's CLI agent — structured results, plan mode, and changed files.",
@@ -44,7 +44,8 @@
44
44
  "PRIVACY.md",
45
45
  "SECURITY.md",
46
46
  "TERMS.md",
47
- "LICENSE"
47
+ "LICENSE",
48
+ "CHANGELOG.md"
48
49
  ],
49
50
  "scripts": {
50
51
  "test": "node scripts/run-tests.mjs",
package/src/acp-client.js CHANGED
@@ -34,6 +34,8 @@ export class AcpClient extends EventEmitter {
34
34
  this._stopping = null;
35
35
  }
36
36
 
37
+ // stderr is captured but does not count as activity: the supervisor measures ACP frames, and
38
+ // an agent writing diagnostics is not the same fact as a turn making progress.
37
39
  // The tail of stderr, which is what an exit error quotes. Kept as chunks and joined on read:
38
40
  // rebuilding a 64KB string per chunk was the whole cost of a noisy agent. A StringDecoder
39
41
  // holds partial UTF-8 across chunk boundaries, so a multi-byte character split by the pipe
@@ -61,7 +63,6 @@ export class AcpClient extends EventEmitter {
61
63
  this._stderrLength -= this._stderrChunks.shift().length;
62
64
  }
63
65
  }
64
- this.emit("activity");
65
66
  });
66
67
  this.child.stderr.on("error", () => {});
67
68
  // A supervisor trip writes session/cancel, which can land after the agent is already gone.
@@ -75,7 +76,10 @@ export class AcpClient extends EventEmitter {
75
76
  const stderr = this.stderrBuffer;
76
77
  const err = makeError(
77
78
  "agent-exit",
78
- `agent exited (code=${code}${signal ? ", signal=" + signal : ""})${stderr ? ": " + String(stderr).slice(-2000) : ""}`
79
+ // stderr kept whole. This is the one string that says why the agent died — the model
80
+ // that was rejected, the quota that ran out, the login that expired — and the part that
81
+ // names it can sit anywhere in it. The 64KB ring buffer above is the bound.
82
+ `agent exited (code=${code}${signal ? ", signal=" + signal : ""})${stderr ? ": " + String(stderr) : ""}`
79
83
  );
80
84
  // exit + rejectAllPending both settle the same Promise.race; second rejection is intentional.
81
85
  this.peer?.rejectAllPending(err);
package/src/delegate.js CHANGED
@@ -13,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);
@@ -240,6 +246,7 @@ async function applyEffort(client, sessionId, model, value, modelOptions) {
240
246
  * model?: string, fast?: boolean, effort?: string, context?: string,
241
247
  * contextFiles?: string[], clientFactory?: (opts: any) => any,
242
248
  * idleMs?: number, handshakeMs?: number, hardCapMs?: number, timeoutMs?: number,
249
+ * onClientReady?: (client: any) => void,
243
250
  * onSessionReady?: (sessionId: string, client: any) => void,
244
251
  * onProgress?: (message: string) => void,
245
252
  * progressThrottleMs?: number, heartbeatMs?: number, signal?: AbortSignal,
@@ -249,7 +256,7 @@ export async function runDelegate({
249
256
  spec, mode = "agent", resumeSessionId, workspace,
250
257
  model = DEFAULT_MODEL, fast = false, effort, context, contextFiles, clientFactory,
251
258
  idleMs, handshakeMs, hardCapMs, timeoutMs,
252
- onSessionReady, onProgress, progressThrottleMs = 2000,
259
+ onClientReady, onSessionReady, onProgress, progressThrottleMs = 2000,
253
260
  heartbeatMs = DEFAULT_HEARTBEAT_MS,
254
261
  signal,
255
262
  } = {}) {
@@ -330,6 +337,10 @@ export async function runDelegate({
330
337
 
331
338
  const make = clientFactory || ((opts) => new AcpClient(opts));
332
339
  const client = make({ mode, onCreatePlan: state.recordCreatePlan, onTodos: state.recordTodos });
340
+ // Handed over before the spawn, because from client.start() there is an agent process and the
341
+ // caller needs something that can stop it. onSessionReady is roughly 3.4s later — a host going
342
+ // away inside that window used to exit with the agent already running and nothing holding it.
343
+ onClientReady?.(client);
333
344
  const supervisor = new SessionSupervisor(client, { idleMs: turnIdleMs, handshakeMs: shakeMs, hardCapMs: capMs });
334
345
  const onAbort = () => supervisor.abort();
335
346
  signal?.addEventListener("abort", onAbort, { once: true });
@@ -354,6 +365,10 @@ export async function runDelegate({
354
365
  heartbeat.unref?.();
355
366
  };
356
367
 
368
+ // Malformed frames noticed as they arrive, where protocolWarnings does not exist yet. Merged
369
+ // into it with the rest below.
370
+ const frameWarnings = [];
371
+
357
372
  // session/load replays the previous turn as ordinary update frames, tool_call and diff blocks
358
373
  // included. state.reset() clears what they touch but cannot unsend a progress notification, so
359
374
  // the guard below is what stops a resume reporting last turn's edits as if they were happening.
@@ -361,7 +376,17 @@ export async function runDelegate({
361
376
  if (!promptInFlight) return;
362
377
  const up = u?.update || {};
363
378
  if (up.sessionUpdate === "plan") {
364
- state.planEntries = up.entries || [];
379
+ // ACP defines entries as an array. A non-array is truthy, so it was stored as-is and
380
+ // reached the sanitizer's forEach — throwing after the turn's work was done, which is the
381
+ // one thing the sanitizer exists to prevent. Drop it here and say so instead.
382
+ if (up.entries !== undefined && !Array.isArray(up.entries)) {
383
+ frameWarnings.push(
384
+ `plan entries dropped: ACP requires an array, got ${up.entries === null ? "null" : typeof up.entries}`
385
+ );
386
+ state.planEntries = [];
387
+ } else {
388
+ state.planEntries = up.entries || [];
389
+ }
365
390
  }
366
391
  // The agent titles the turn a beat after the prompt lands ("File Creator") — useful live,
367
392
  // when several delegations run, and in timeout forensics. Kept out of the result: there it
@@ -378,7 +403,10 @@ export async function runDelegate({
378
403
  state.startTool(up.toolCallId, up.status);
379
404
  const label = up.title || up.kind || "tool";
380
405
  const path = up.locations?.[0]?.path;
381
- state.lastToolLabel = String(label) + (path ? " — " + path : "");
406
+ // Collapsed onto one line the way both readers of this take it: a progress notification
407
+ // and the "last tool call" line in a stall error. A terminal tool's title is the command
408
+ // the agent sent, which it sends verbatim — a multi-line script arrives with its newlines.
409
+ state.lastToolLabel = (String(label) + (path ? " — " + path : "")).replace(/\s+/g, " ").trim();
382
410
  try { onProgress?.(("running: " + state.lastToolLabel).slice(0, 200)); } catch {}
383
411
  }
384
412
  if (up.sessionUpdate === "agent_message_chunk" && up.content?.text) {
@@ -388,7 +416,11 @@ export async function runDelegate({
388
416
  }
389
417
  if (up.sessionUpdate === "tool_call_update") {
390
418
  state.updateToolStatus(up.toolCallId, up.status);
391
- for (const c of up.content || []) {
419
+ // Array.isArray, not `|| []`: a non-array content is truthy and iterating it throws
420
+ // "object is not iterable" here, in the readline callback, where nothing awaits it. That
421
+ // is an uncaught exception — the whole server, not this one turn — and it also stops the
422
+ // reply on the next line from being read, so the turn hangs to its cap.
423
+ for (const c of Array.isArray(up.content) ? up.content : []) {
392
424
  if (c.type === "diff" && c.path) {
393
425
  state.touched.add(c.path);
394
426
  try { onProgress?.("editing " + c.path); } catch {}
@@ -517,6 +549,7 @@ export async function runDelegate({
517
549
  if (resumeError) protocolWarnings.push(`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`);
518
550
  for (const u of unsupportedOptions) protocolWarnings.push(unsupportedWarning(model, u));
519
551
  protocolWarnings.push(...contextWarnings);
552
+ protocolWarnings.push(...frameWarnings);
520
553
  if (state.planEntries.length > 0 || state.planOverview !== undefined || state.planDetail !== undefined) {
521
554
  // Sanitize even when the plan is discarded: the warnings it raises report malformed ACP
522
555
  // frames, which the caller needs whatever mode it asked for.
@@ -580,7 +613,7 @@ export async function runDelegate({
580
613
  }
581
614
  // Opt-in: the frames land in the caller's context and nothing there is actionable — the
582
615
  // forensics above already carry that. Raw frames only help someone debugging the bridge.
583
- const frames = Number(process.env.CURSOR_DELEGATE_TRANSCRIPT);
616
+ const frames = transcriptFrames();
584
617
  if (frames > 0) {
585
618
  try {
586
619
  const transcript = client.getTranscript?.(frames);
package/src/doctor.js CHANGED
@@ -8,6 +8,7 @@ import { allowedValues } from "./model-options.js";
8
8
 
9
9
  const HANDSHAKE_TIMEOUT_MS = 15_000;
10
10
  const VERSION_PROBE_TIMEOUT_MS = 10_000;
11
+ const PROBE_STDOUT_CAP = 64 * 1024;
11
12
  const DEFAULT_LOG_SIZE = "2000";
12
13
 
13
14
  function formatCommand({ command, args }) {
@@ -33,7 +34,16 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
33
34
  resolve(result);
34
35
  };
35
36
  const child = spawn(execCommand, execArgs, { ...options, detached: DETACHED, stdio: ["ignore", "pipe", "pipe"] });
36
- child.stdout?.on("data", (chunk) => { stdout += chunk.toString(); });
37
+ // Capped: a version string is a line, and a launcher that streams instead should not be
38
+ // accumulated whole while the probe waits out its timeout.
39
+ child.stdout?.on("data", (chunk) => {
40
+ if (stdout.length < PROBE_STDOUT_CAP) stdout += chunk.toString();
41
+ });
42
+ // Drained, not merely piped. An unread pipe fills, the launcher blocks writing to it and so
43
+ // never exits, and the probe can only report that as a timeout — a healthy but noisy
44
+ // launcher reads out identically to a wedged one. Nothing consumes the bytes.
45
+ child.stderr?.on("data", () => {});
46
+ child.stderr?.on("error", () => {});
37
47
  child.on("error", () => finish({ found: false, version: null }));
38
48
  child.on("close", (code) => {
39
49
  finish({
package/src/jsonrpc.js CHANGED
@@ -10,6 +10,23 @@ function readLogSize(raw) {
10
10
  return Math.floor(n);
11
11
  }
12
12
 
13
+ // Depth an unparseable CURSOR_DELEGATE_TRANSCRIPT reads as. Deliberately not DEFAULT_LOG_SIZE:
14
+ // that one bounds what the log retains in memory, this one is how much lands in the caller's
15
+ // context. 1.10.0 removed a 40-frame always-on dump from failure text; opt-in is what buys this
16
+ // budget, so keep it in that neighbourhood.
17
+ const TRANSCRIPT_DEFAULT_FRAMES = 50;
18
+
19
+ // Frames of transcript CURSOR_DELEGATE_TRANSCRIPT asks for. Unset or blank means none and a
20
+ // number is the count (0 = none); anything unparseable reads as on at the default depth —
21
+ // "true" and "yes" are natural things to set, and silently disabling the transcript on them is
22
+ // the opposite of what the setter wanted.
23
+ export function transcriptFrames(raw = process.env.CURSOR_DELEGATE_TRANSCRIPT) {
24
+ if (raw === undefined || raw.trim() === "") return 0;
25
+ const n = Number(raw);
26
+ if (!Number.isFinite(n)) return TRANSCRIPT_DEFAULT_FRAMES;
27
+ return Math.max(0, Math.floor(n));
28
+ }
29
+
13
30
  export class JsonRpcPeer {
14
31
  /**
15
32
  * @param {import("node:stream").Readable} input
@@ -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
  }
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
  }
@@ -151,7 +162,7 @@ export const delegateInputSchema = z.object({
151
162
  spec: z.string().trim().min(1, "spec must not be blank").describe("Task brief: goal, scope, fixed decisions quoted exactly, acceptance criteria. Sent as written. Point at files to read rather than pasting code, or attach them with contextFiles."),
152
163
  mode: z.enum(["agent", "plan", "ask"]).default("agent").describe("agent implements; plan and ask are instructions to the agent, not limits."),
153
164
  resumeSessionId: z.string().optional().describe("Continue an existing ACP session."),
154
- workspace: z.string().optional().describe("The agent's working directory, not a limit. Defaults to the server process cwd, which under npx is often not your project root — pass it explicitly. Must already exist; never create one for the call."),
165
+ workspace: z.string().trim().min(1, "workspace must not be blank").describe("The agent's working directory, not a limit. Smallest directory holding the task's files; with no such directory the project root is the floor. Must already exist; never create one for the call."),
155
166
  model: z.string().trim().min(1, "model must be a non-empty string").default(DEFAULT_MODEL).describe("Bare ACP family id, version included: composer-2.5, grok-4.5, claude-opus-5, gpt-5.6-sol. doctor deep:true lists every id."),
156
167
  fast: z.boolean().default(false).describe("Fast tier; higher cost — only when the user asks."),
157
168
  // Which values a model offers is only knowable after selecting it, so this stays an open
@@ -166,11 +177,12 @@ export const delegateInputSchema = z.object({
166
177
  * args: any, extra?: any,
167
178
  * runDelegate: (opts: any) => Promise<any>,
168
179
  * inFlight: Map<string, Set<any>>,
180
+ * pending?: Set<any>,
169
181
  * seenSessions?: Set<string>,
170
182
  * }} deps
171
183
  * @returns {Promise<import("@modelcontextprotocol/sdk/types.js").CallToolResult>}
172
184
  */
173
- export async function runDelegateTool({ args, extra, runDelegate, inFlight, seenSessions = new Set() }) {
185
+ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pending = new Set(), seenSessions = new Set() }) {
174
186
  const { spec, mode, resumeSessionId, workspace, model, fast, effort, context, contextFiles } = args;
175
187
 
176
188
  const progressToken = extra?._meta?.progressToken;
@@ -197,7 +209,7 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, seen
197
209
  spec,
198
210
  mode,
199
211
  resumeSessionId,
200
- workspace: workspace || process.cwd(),
212
+ workspace,
201
213
  model,
202
214
  fast,
203
215
  effort,
@@ -205,9 +217,16 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, seen
205
217
  contextFiles,
206
218
  onProgress,
207
219
  signal: extra?.signal,
220
+ onClientReady: (client) => {
221
+ handle = { client, cancelRequested: false };
222
+ pending.add(handle);
223
+ },
208
224
  onSessionReady: (sessionId, client) => {
209
225
  capturedSessionId = sessionId;
210
- handle = { client, cancelRequested: false };
226
+ // The same handle moves across, so a shutdown racing this boundary finds it on exactly
227
+ // one side of it rather than on neither.
228
+ handle ??= { client, cancelRequested: false };
229
+ pending.delete(handle);
211
230
  registerInFlight(inFlight, sessionId, handle);
212
231
  rememberSession(seenSessions, sessionId);
213
232
  // Emit the id the moment the session opens, before the turn finishes, so a host that
@@ -228,7 +247,9 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, seen
228
247
  };
229
248
  } finally {
230
249
  // Drops only this delegation's own handle; the id stays registered while another turn
231
- // is still running on it.
250
+ // is still running on it. A delegation that failed before its session opened is only ever
251
+ // in pending, and one that opened is only ever in the map — the delete covers both.
252
+ if (handle) pending.delete(handle);
232
253
  if (capturedSessionId) unregisterInFlight(inFlight, capturedSessionId, handle);
233
254
  }
234
255
  }
@@ -262,7 +283,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
262
283
  openWorldHint: true,
263
284
  },
264
285
  },
265
- async (args, extra) => runDelegateTool({ args, extra, runDelegate, inFlight, seenSessions })
286
+ async (args, extra) => runDelegateTool({ args, extra, runDelegate, inFlight, pending: pendingDelegations, seenSessions })
266
287
  );
267
288
 
268
289
  server.registerTool(
@@ -359,22 +380,55 @@ if (process.argv[1]) {
359
380
  }
360
381
  }
361
382
 
362
- // Each agent runs in its own process group on POSIX, so a SIGINT or SIGTERM aimed at this process
363
- // no longer reaches it the way it did when the two shared a group. Kill what is registered, then
364
- // exit explicitly: installing a handler replaces Node's default, and a server that swallows Ctrl-C
365
- // would be a worse bug than the agent it leaks. Delegations still in their handshake are not in
366
- // the map yet, so this covers the turn, not the first few seconds of it.
367
- export function installSignalCleanup(map, { exit = (code) => process.exit(code) } = {}) {
368
- if (!DETACHED) return;
369
- const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143]]);
370
- for (const [signal, code] of signals) {
371
- process.on(signal, () => {
372
- for (const handles of map.values()) {
373
- for (const handle of handles) { try { handle.client.stop(); } catch {} }
374
- }
375
- exit(code);
376
- });
383
+ // Kill what is still running, then exit, on any way the host has of going away.
384
+ export function installSignalCleanup(map, {
385
+ pending = new Set(),
386
+ exit = (code) => process.exit(code),
387
+ setExitCode = (code) => { process.exitCode = code; },
388
+ schedule = (fn) => setImmediate(fn),
389
+ stdin = process.stdin,
390
+ } = {}) {
391
+ let shuttingDown = false;
392
+ const shutdown = (code) => {
393
+ // A second trigger skips the wait below: the kills are already dispatched, and a caller
394
+ // that has asked twice wants out now.
395
+ if (shuttingDown) return exit(code);
396
+ shuttingDown = true;
397
+ // Set in the handler, not left to the exit below: a loop that runs dry on its own still
398
+ // has to die with the code the signal asked for, and the scheduled exit may never get a
399
+ // turn to run.
400
+ setExitCode(code);
401
+ const stops = [];
402
+ const dispatch = (handle) => {
403
+ try { stops.push(Promise.resolve(handle.client.stop()).catch(() => {})); } catch {}
404
+ };
405
+ for (const handles of map.values()) for (const handle of handles) dispatch(handle);
406
+ // Delegations still inside their handshake. The agent is already running for these, and this
407
+ // is the only place it is reachable from — they have no session id to be keyed under yet.
408
+ for (const handle of pending) dispatch(handle);
409
+ // On Windows the kill is a separate taskkill process: exiting before it walks the tree
410
+ // orphans everything below the shell wrapper — the ps1 launcher and the versioned agent
411
+ // were measured surviving the server's exit. stop() bounds itself (observed exit or its
412
+ // own deadline), so this wait is short and finite on every platform.
413
+ // Scheduled rather than called from the kill's own continuation, so the exit runs on a
414
+ // clean loop turn instead of on the settlement stack.
415
+ const leave = () => schedule(() => exit(code));
416
+ Promise.all(stops).then(leave, leave);
417
+ };
418
+ // Each agent runs in its own process group on POSIX, so a signal aimed at this process no
419
+ // longer reaches it the way it did when the two shared a group. Installing a handler replaces
420
+ // Node's default, and a server that swallows Ctrl-C would be a worse bug than the agent it
421
+ // leaks. Delegations still inside their handshake are reached through `pending`, so this
422
+ // covers the agent from the moment it is spawned, not from the moment its session opens.
423
+ if (DETACHED) {
424
+ const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143]]);
425
+ for (const [signal, code] of signals) process.on(signal, () => shutdown(code));
377
426
  }
427
+ // Closing the server's stdin is how a stdio host shuts the transport down, and it is what a
428
+ // host reaches for before it resorts to a signal. The SDK transport does not listen for it —
429
+ // it subscribes to `data` and `error` only — so EOF leaves this process up with a delegation
430
+ // still running and nobody left to hand it to.
431
+ stdin.on("end", () => shutdown(0));
378
432
  }
379
433
 
380
434
  if (isMain) {
@@ -382,11 +436,12 @@ if (isMain) {
382
436
  // so confirming an install meant wiring the server into a host first. Reads the package.json
383
437
  // beside this file, so it reports the code that is actually running rather than what a
384
438
  // manifest pinned. stdout is free here because the transport never starts.
385
- if (process.argv.slice(2).includes("--version")) {
439
+ const argv = process.argv.slice(2);
440
+ if (argv.includes("--version") || argv.includes("-v")) {
386
441
  console.log(readPackageVersion());
387
442
  } else {
388
443
  const server = buildServer();
389
- installSignalCleanup(inFlight);
444
+ installSignalCleanup(inFlight, { pending: pendingDelegations });
390
445
  await server.connect(new StdioServerTransport());
391
446
  }
392
447
  }
@@ -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.