cursor-delegate-mcp 1.9.0 → 1.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursor-delegate-mcp",
3
- "version": "1.9.0",
3
+ "version": "1.11.0",
4
4
  "type": "module",
5
5
  "description": "MCP server bridging AI coding hosts to cursor-agent over the Agent Client Protocol (ACP).",
6
6
  "license": "MIT",
package/src/acp-client.js CHANGED
@@ -64,8 +64,8 @@ export class AcpClient extends EventEmitter {
64
64
  });
65
65
  }
66
66
 
67
- // The handshake replies carry the agent's live capabilities, model list and mode list.
68
- // Keep them; every caller still gets the reply unchanged.
67
+ // Stashed so the unknown-model pre-flight and doctor --deep can read the agent's real
68
+ // capability and model lists without paying for a second handshake.
69
69
  async initialize() {
70
70
  const res = await this.peer.request("initialize", { protocolVersion: 1, clientInfo: { name: "cursor-delegate-mcp", version: VERSION }, clientCapabilities: { _meta: { parameterizedModelPicker: true } } });
71
71
  this.protocolVersion = res?.protocolVersion;
@@ -83,7 +83,7 @@ export class AcpClient extends EventEmitter {
83
83
  setModel(sessionId, modelId) { return this.peer.request("session/set_model", { sessionId, modelId }); }
84
84
  setConfigOption(sessionId, configId, value) { return this.peer.request("session/set_config_option", { sessionId, configId, value: String(value) }); } // configId, not optionId; ACP wants a string value
85
85
  setMode(sessionId, modeId) { return this.peer.request("session/set_mode", { sessionId, modeId }); }
86
- prompt(sessionId, text) { return this.peer.request("session/prompt", { sessionId, prompt: [{ type: "text", text }] }); }
86
+ prompt(sessionId, blocks) { return this.peer.request("session/prompt", { sessionId, prompt: blocks }); }
87
87
  cancel(sessionId) { this.peer.notify("session/cancel", { sessionId }); return Promise.resolve(); }
88
88
 
89
89
  getTranscript(n) { return this.peer ? this.peer.formatLog(n) : ""; }
package/src/delegate.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import process from "node:process";
2
+ import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
2
4
  import { readFileSync, statSync } from "node:fs";
3
5
  import { AcpClient } from "./acp-client.js";
4
6
  import { SessionSupervisor } from "./session-supervisor.js";
@@ -21,17 +23,121 @@ function fmtDuration(ms) {
21
23
  return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s`;
22
24
  }
23
25
 
26
+ // Two different questions, and conflating them is what made a typo'd brief cost a live turn.
27
+ // "Could this be a path?" is deliberately loose — a one-line brief ending in .md is worth a
28
+ // stat. "Was a path clearly intended?" has to be strict, because an ordinary inline spec
29
+ // mentions files ("fix the bug in src/api.js") and must never be rejected for it. Whitespace
30
+ // is the discriminator: a path argument has none, a sentence about a path does.
31
+ function looksLikeSpecPath(spec) {
32
+ return !spec.includes("\n")
33
+ && (spec.includes("/") || spec.includes("\\") || spec.endsWith(".md") || spec.endsWith(".txt"));
34
+ }
35
+ const isBareSpecPath = (spec) => !/\s/.test(spec.trim());
36
+
24
37
  function resolveSpec(spec) {
25
38
  if (typeof spec !== "string") return spec;
26
- const looksLikePath = !spec.includes("\n")
27
- && (spec.includes("/") || spec.includes("\\") || spec.endsWith(".md") || spec.endsWith(".txt"));
28
- if (!looksLikePath) return spec;
39
+ // A blank spec spins up a live session that only replies "No prompt content provided" —
40
+ // a billed turn for nothing. Reject it here, before the spawn, like the other bad specs.
41
+ if (spec.trim() === "") {
42
+ const err = new Error("spec is empty. Provide a task brief inline, or a path to one.");
43
+ err.reason = "invalid-spec";
44
+ throw err;
45
+ }
46
+ if (!looksLikeSpecPath(spec)) return spec;
47
+ let stat;
29
48
  try {
30
- if (statSync(spec).isFile()) return readFileSync(spec, "utf8");
31
- } catch {}
49
+ stat = statSync(spec);
50
+ } catch {
51
+ // Only a bare path was unambiguously meant as one. Anything else is prose that happens
52
+ // to name a file, and prose is the common case.
53
+ if (!isBareSpecPath(spec)) return spec;
54
+ const err = new Error(`spec looks like a file path but nothing exists at ${spec}. Pass the brief inline, or fix the path.`);
55
+ err.reason = "invalid-spec";
56
+ throw err;
57
+ }
58
+ if (stat.isFile()) return readFileSync(spec, "utf8");
59
+ if (isBareSpecPath(spec)) {
60
+ const err = new Error(`spec looks like a file path but ${spec} is not a file. Pass the brief inline, or point at a file.`);
61
+ err.reason = "invalid-spec";
62
+ throw err;
63
+ }
32
64
  return spec;
33
65
  }
34
66
 
67
+ // A nonexistent workspace was accepted, then created by the agent's first write — a typo
68
+ // silently spawned a parallel empty tree and every layer reported success. contextFiles has
69
+ // always rejected the same mistakes; this is that check, applied to its sibling.
70
+ function assertWorkspace(workspace) {
71
+ if (workspace === undefined || workspace === null) return;
72
+ let stat;
73
+ try {
74
+ stat = statSync(workspace);
75
+ } catch {
76
+ const err = new Error(`workspace ${workspace} does not exist. Create it first, or point at an existing directory.`);
77
+ err.reason = "invalid-workspace";
78
+ throw err;
79
+ }
80
+ if (!stat.isDirectory()) {
81
+ const err = new Error(`workspace ${workspace} is not a directory.`);
82
+ err.reason = "invalid-workspace";
83
+ throw err;
84
+ }
85
+ }
86
+
87
+ const IMAGE_MIME = {
88
+ ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
89
+ ".gif": "image/gif", ".webp": "image/webp",
90
+ };
91
+ // Base64 inflates by a third and every byte lands in the prompt, unlike a link.
92
+ const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
93
+
94
+ // A resource_link hands the agent a path instead of the file's bytes, so a large brief costs
95
+ // prompt space only for what the agent decides to open. Images cannot work that way — they
96
+ // are sent inline. Both are measured working, including links to files outside the
97
+ // workspace. Two rules follow from the probe:
98
+ // - gate images on the advertised capability, because cursor-agent accepts blocks it does
99
+ // not support without any error (embeddedContext:false raises nothing), so an ungated
100
+ // image would silently vanish;
101
+ // - report anything skipped, since a dropped attachment is otherwise invisible.
102
+ function buildContextBlocks(contextFiles, workspace, client, warnings) {
103
+ const blocks = [];
104
+ // A glob plus an explicit path (or the same file named a few ways) resolves to one file;
105
+ // sending it several times just wastes prompt space. Collapse by resolved absolute path.
106
+ const seen = new Set();
107
+ for (const entry of contextFiles || []) {
108
+ if (typeof entry !== "string" || !entry.trim()) continue;
109
+ const abs = path.resolve(workspace || process.cwd(), entry);
110
+ if (seen.has(abs)) continue;
111
+ seen.add(abs);
112
+ let stat;
113
+ try {
114
+ stat = statSync(abs);
115
+ } catch {
116
+ warnings.push(`contextFile ${entry} skipped: not found at ${abs}`);
117
+ continue;
118
+ }
119
+ if (!stat.isFile()) {
120
+ warnings.push(`contextFile ${entry} skipped: not a file`);
121
+ continue;
122
+ }
123
+ const mimeType = IMAGE_MIME[path.extname(abs).toLowerCase()];
124
+ if (mimeType) {
125
+ if (!client?.agentCapabilities?.promptCapabilities?.image) {
126
+ warnings.push(`contextFile ${entry} skipped: this agent does not accept image prompts`);
127
+ continue;
128
+ }
129
+ if (stat.size > MAX_IMAGE_BYTES) {
130
+ warnings.push(`contextFile ${entry} skipped: ${Math.round(stat.size / 1024)}KB exceeds the ${MAX_IMAGE_BYTES / 1024 / 1024}MB image limit`);
131
+ continue;
132
+ }
133
+ blocks.push({ type: "image", mimeType, data: readFileSync(abs).toString("base64") });
134
+ continue;
135
+ }
136
+ blocks.push({ type: "resource_link", uri: pathToFileURL(abs).href, name: path.basename(abs) });
137
+ }
138
+ return blocks;
139
+ }
140
+
35
141
  async function openSession(client, resumeSessionId, workspace) {
36
142
  if (!resumeSessionId) return client.newSession(workspace);
37
143
  try {
@@ -75,8 +181,8 @@ async function applyConfig(client, sessionId, configId, value) {
75
181
  }
76
182
 
77
183
  export async function runDelegate({
78
- spec, mode = "agent", resumeSessionId, workspace,
79
- model = DEFAULT_MODEL, fast = false, reasoning, context, clientFactory, onElicit,
184
+ spec, mode = "agent", resumeSessionId, workspace, maxResultChars,
185
+ model = DEFAULT_MODEL, fast = false, reasoning, context, contextFiles, clientFactory, onElicit,
80
186
  idleMs, handshakeMs, hardCapMs, timeoutMs,
81
187
  onSessionReady, onProgress, progressThrottleMs = 2000,
82
188
  heartbeatMs = DEFAULT_HEARTBEAT_MS,
@@ -87,6 +193,10 @@ export async function runDelegate({
87
193
  err.reason = "aborted";
88
194
  throw err;
89
195
  }
196
+ // Before the spawn: a bad path is the caller's to fix, and finding out costs a process,
197
+ // a handshake and a billed turn if it waits until the prompt is assembled.
198
+ assertWorkspace(workspace);
199
+ const promptText = resolveSpec(spec);
90
200
  const capMs = hardCapMs ?? timeoutMs ?? envMs("CURSOR_DELEGATE_HARD_CAP_MS", 3600000);
91
201
  const shakeMs = handshakeMs ?? envMs("CURSOR_DELEGATE_HANDSHAKE_MS", DEFAULT_HANDSHAKE_MS);
92
202
  const turnIdleMs = idleMs ?? envMs("CURSOR_DELEGATE_IDLE_MS", 0);
@@ -212,7 +322,15 @@ export async function runDelegate({
212
322
  const activeToolCalls = new Set();
213
323
  const touched = new Set();
214
324
 
325
+ // Text superseded by a later tool call is normally a preamble ("Inspecting the
326
+ // implementation.") and returning it would be inventing a summary. But the rule cannot
327
+ // tell a preamble from the whole answer: an agent that replies and then runs one more
328
+ // command has its entire reply discarded, and the caller gets "" with stopReason end_turn
329
+ // and no error. So keep the last discarded segment and hand it back only when nothing
330
+ // survived — labelled, never blended with a real final message.
331
+ let discardedResult = "";
215
332
  const resetResult = () => {
333
+ if (resultLength > 0) discardedResult = resultChunks.join("");
216
334
  resultChunks.length = 0;
217
335
  resultLength = 0;
218
336
  truncated = false;
@@ -296,6 +414,18 @@ export async function runDelegate({
296
414
  // The bridge cannot see inside a running shell command, so a long silence is reported
297
415
  // rather than acted on: the caller gets elapsed time and frame age and can decide.
298
416
  let lastToolLabel = null;
417
+ // A shell write arrives as execute, a file write as edit; delete and move round out ACP's
418
+ // write-capable kinds. read, search, think and fetch stay out — a plan turn is expected
419
+ // to do those.
420
+ const WRITE_CAPABLE_KINDS = new Set(["edit", "delete", "move", "execute"]);
421
+ // Scoped to plan/ask deliberately. In agent mode this is every turn and carries nothing;
422
+ // in plan/ask a disk-touching turn is abnormal — the plan itself travels over ACP as a
423
+ // string via cursor/create_plan, not as a file — so the base rate makes it worth reading.
424
+ // It records what the agent *ran*, never what changed: a command is not a change list.
425
+ const WRITE_ACTIVITY_CAP = 20;
426
+ const watchingWrites = mode === "plan" || mode === "ask";
427
+ let writeCapableActivity = [];
428
+ let writeActivityById = new Map();
299
429
  let modeChanged;
300
430
  let sessionTitle;
301
431
  let promptInFlight = false;
@@ -345,6 +475,15 @@ export async function runDelegate({
345
475
  const label = up.title || up.kind || "tool";
346
476
  const path = up.locations?.[0]?.path;
347
477
  lastToolLabel = String(label) + (path ? " — " + path : "");
478
+ if (watchingWrites && WRITE_CAPABLE_KINDS.has(up.kind) && writeCapableActivity.length < WRITE_ACTIVITY_CAP) {
479
+ const entry = { kind: up.kind, detail: lastToolLabel.slice(0, 300) };
480
+ writeCapableActivity.push(entry);
481
+ // An execute call names itself — its title is the shell command. An edit call does
482
+ // not: the title is a bare "Edit File" and locations is empty, so the only thing
483
+ // separating docs/plan.md from src/api.js is the diff frame that follows. Keep the
484
+ // id so that frame can fill the path in.
485
+ if (up.toolCallId != null) writeActivityById.set(up.toolCallId, entry);
486
+ }
348
487
  try { onProgress?.(("running: " + lastToolLabel).slice(0, 200)); } catch {}
349
488
  }
350
489
  if (up.sessionUpdate === "agent_message_chunk" && up.content?.text) {
@@ -357,6 +496,10 @@ export async function runDelegate({
357
496
  for (const c of up.content || []) {
358
497
  if (c.type === "diff" && c.path) {
359
498
  touched.add(c.path);
499
+ const pending = writeActivityById.get(up.toolCallId);
500
+ if (pending && !pending.path) {
501
+ pending.path = normalizeAgentReportedFiles([c.path], workspace)[0];
502
+ }
360
503
  try { onProgress?.("editing " + c.path); } catch {}
361
504
  }
362
505
  // cursor-agent has never been observed emitting these; ACP allows an agent to
@@ -372,6 +515,7 @@ export async function runDelegate({
372
515
  let sessionId;
373
516
  let resumeError;
374
517
  const unsupportedOptions = [];
518
+ const contextWarnings = [];
375
519
  try {
376
520
  const res = await supervisor.supervise(async () => {
377
521
  await client.start();
@@ -402,6 +546,9 @@ export async function runDelegate({
402
546
  planDetail = undefined;
403
547
  todos = new Map();
404
548
  sawTodoFrame = false;
549
+ discardedResult = "";
550
+ writeCapableActivity = [];
551
+ writeActivityById = new Map();
405
552
  touched.clear();
406
553
  lastToolLabel = null;
407
554
  modeChanged = undefined;
@@ -409,41 +556,90 @@ export async function runDelegate({
409
556
  supervisor.promptStarted();
410
557
  startHeartbeat();
411
558
  promptInFlight = true;
412
- return client.prompt(sessionId, resolveSpec(spec));
559
+ return client.prompt(sessionId, [
560
+ { type: "text", text: promptText },
561
+ ...buildContextBlocks(contextFiles, workspace, client, contextWarnings),
562
+ ]);
413
563
  });
414
564
  thoughtProgress.end();
415
565
  messageProgress.end();
416
566
  let result = resultChunks.join("");
417
567
  if (truncated) result += TRUNCATION_MARKER;
418
568
  const finalMessageAvailable = result.length > 0;
419
- const resultSource = finalMessageAvailable
569
+ let resultSource = finalMessageAvailable
420
570
  ? (sawToolCall ? "post-tool" : "tool-free-stream")
421
571
  : "none";
422
572
  const protocolWarnings = [];
573
+ if (!finalMessageAvailable && discardedResult) {
574
+ result = discardedResult;
575
+ resultSource = "pre-tool-fallback";
576
+ protocolWarnings.push(
577
+ "the agent ran a tool after its last message and never spoke again, so no final message closed the turn."
578
+ + " result carries the last message before that tool call — it may be a preamble rather than the answer."
579
+ );
580
+ } else if (!finalMessageAvailable) {
581
+ protocolWarnings.push("the agent ended the turn without emitting any message; result is empty.");
582
+ }
583
+ // A runaway reply comes back whole and can blow the caller's context (104K chars in one
584
+ // test). When the caller sets a ceiling, cut the result to it and say so, so the truncation
585
+ // is never mistaken for a complete answer.
586
+ if (Number.isFinite(maxResultChars) && maxResultChars > 0 && result.length > maxResultChars) {
587
+ const original = result.length;
588
+ result = result.slice(0, maxResultChars) + `\n\n[result truncated at ${maxResultChars} chars]`;
589
+ protocolWarnings.push(
590
+ `result was ${original} chars and exceeded maxResultChars ${maxResultChars}; it was truncated.`
591
+ + " Raise maxResultChars or narrow the task if you need the full output."
592
+ );
593
+ }
423
594
  let stopReason;
424
595
  if (res?.stopReason !== undefined) {
425
- if (typeof res.stopReason === "string") stopReason = res.stopReason;
426
- else protocolWarnings.push("stopReason dropped: ACP requires a string stop reason");
596
+ if (typeof res.stopReason !== "string") {
597
+ protocolWarnings.push("stopReason dropped: ACP requires a string stop reason");
598
+ } else if (res.stopReason !== "end_turn") {
599
+ // end_turn is the near-universal default and carries no signal — it was end_turn on
600
+ // every call across the stress test. Surface a stop reason only when it says something
601
+ // happened: a refusal, a cancel, an output cap. Absence means the ordinary end_turn.
602
+ stopReason = res.stopReason;
603
+ }
427
604
  }
428
605
  const out = {
429
606
  result,
430
607
  resultSource,
431
608
  finalMessageAvailable,
432
- stopReason,
433
609
  sessionId,
434
610
  filesReportedByAgent: normalizeAgentReportedFiles([...touched], workspace),
435
- questionsAsked,
436
611
  resumed: !!resumeSessionId && sessionId === resumeSessionId,
437
612
  };
613
+ if (stopReason !== undefined) out.stopReason = stopReason;
614
+ // Elicitation almost never fires (the agent tends to ask in prose and end the turn), so an
615
+ // always-empty array is steady noise. Report it only when a question actually came through.
616
+ if (questionsAsked.length) out.questionsAsked = questionsAsked;
438
617
  if (sessionTitle) out.sessionTitle = sessionTitle;
439
618
  if (resumeError) protocolWarnings.push(`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`);
440
619
  for (const id of unsupportedOptions) protocolWarnings.push(`model ${model} has no ${id} option; the requested value was ignored`);
620
+ protocolWarnings.push(...contextWarnings);
441
621
  if (planEntries.length > 0 || planOverview !== undefined || planDetail !== undefined) {
442
622
  out.plan = sanitizePlan(protocolWarnings);
623
+ // plan.detail duplicated the prose already in result on every observed plan turn — the
624
+ // same plan in two forms, ~2x the context for one answer. Drop it when result is at least
625
+ // as long (result is carrying the plan), but keep it when result is too terse to be the
626
+ // plan itself, so a plan that lived only in the detail is never lost. entries and overview
627
+ // are structured and unique, and always stay.
628
+ if (typeof out.plan.detail === "string" && result.length >= out.plan.detail.length) {
629
+ delete out.plan.detail;
630
+ }
443
631
  }
444
632
  // Most successful turns emit no todos at all, so an empty list would read as "nothing
445
633
  // done" rather than "not tracked". Report only what the agent actually sent.
446
634
  if (sawTodoFrame) Object.assign(out, sanitizeTodos(protocolWarnings));
635
+ if (writeCapableActivity.length) {
636
+ out.writeCapableActivity = writeCapableActivity;
637
+ protocolWarnings.push(
638
+ `mode ${mode} asked the agent not to change anything, but it ran ${writeCapableActivity.length}`
639
+ + ` write-capable tool call${writeCapableActivity.length === 1 ? "" : "s"} — see writeCapableActivity`
640
+ + " for what ran, and the diff for what changed."
641
+ );
642
+ }
447
643
  if (modeChanged) {
448
644
  out.modeChanged = modeChanged;
449
645
  protocolWarnings.push(`agent switched mode from ${modeChanged.from} to ${modeChanged.to} mid-session`);
@@ -458,7 +654,12 @@ export async function runDelegate({
458
654
  // slow. Name what was outstanding so the caller can tell the two apart, and so a
459
655
  // retry can resume from the work already done instead of restarting blind.
460
656
  const isTimeout = err?.reason === "hard-cap" || err?.reason === "idle-timeout";
461
- if (isTimeout || err?.reason === "aborted" || err?.reason === "agent-exit") {
657
+ // A handshake timeout gets the forensics but not the long-command advice below: the
658
+ // session exists by then — it is set before set_model, set_config_option and set_mode,
659
+ // any of which can hang — so the resume hint is what the caller needs. No prompt was
660
+ // ever sent, so no shell command can be the reason for the silence.
661
+ const isStall = isTimeout || err?.reason === "handshake-timeout";
662
+ if (isStall || err?.reason === "aborted" || err?.reason === "agent-exit") {
462
663
  const age = fmtDuration(supervisor.msSinceActivity());
463
664
  err.message += `\n\nLast ACP frame ${age} ago${lastToolLabel ? `; last tool call: ${lastToolLabel}` : ""}.`;
464
665
  if (sessionTitle) err.message += ` The agent titled this turn ${JSON.stringify(sessionTitle)}.`;
@@ -483,10 +684,17 @@ export async function runDelegate({
483
684
  + " CURSOR_DELEGATE_HARD_CAP_MS.";
484
685
  }
485
686
  }
486
- try {
487
- const transcript = client.getTranscript?.(40);
488
- if (transcript) err.message += "\n\n--- recent ACP transcript (last 40 frames) ---\n" + transcript;
489
- } catch {}
687
+ // Opt-in, because the frames land in the caller's context and nothing there is
688
+ // actionable: the forensics above already carry everything a caller can act on. Raw
689
+ // frames only help someone debugging the bridge, and that has always been done with a
690
+ // protocol probe, never with an error dump.
691
+ const frames = Number(process.env.CURSOR_DELEGATE_TRANSCRIPT);
692
+ if (frames > 0) {
693
+ try {
694
+ const transcript = client.getTranscript?.(frames);
695
+ if (transcript) err.message += `\n\n--- recent ACP transcript (last ${frames} frames) ---\n` + transcript;
696
+ } catch {}
697
+ }
490
698
  throw err;
491
699
  } finally {
492
700
  clearInterval(heartbeat);
package/src/doctor.js CHANGED
@@ -2,7 +2,7 @@ import process from "node:process";
2
2
  import { spawn } from "node:child_process";
3
3
  import { AcpClient } from "./acp-client.js";
4
4
  import { resolveAcpSpawn } from "./spawn.js";
5
- import { VERSION } from "./version.js";
5
+ import { readPackageVersion } from "./version.js";
6
6
 
7
7
  const HANDSHAKE_TIMEOUT_MS = 15_000;
8
8
  const DEFAULT_LOG_SIZE = "2000";
@@ -75,12 +75,13 @@ export async function runDoctor({
75
75
  clientFactory = (opts) => new AcpClient(opts),
76
76
  workspace,
77
77
  handshakeTimeoutMs = HANDSHAKE_TIMEOUT_MS,
78
+ readVersion = readPackageVersion,
78
79
  } = {}) {
79
80
  const { capabilities, version } = getClientInfo();
80
81
  const agentProbe = await probeAgentVersion(spawnSpec);
81
82
 
82
83
  const out = {
83
- plugin: { version: VERSION },
84
+ plugin: { version: readVersion() },
84
85
  client: {
85
86
  name: version?.name ?? null,
86
87
  version: version?.version ?? null,
@@ -101,6 +102,7 @@ export async function runDoctor({
101
102
  },
102
103
  env: {
103
104
  ACP_LOG_SIZE: process.env.ACP_LOG_SIZE !== undefined ? process.env.ACP_LOG_SIZE : DEFAULT_LOG_SIZE,
105
+ CURSOR_DELEGATE_TRANSCRIPT: process.env.CURSOR_DELEGATE_TRANSCRIPT ?? null,
104
106
  },
105
107
  };
106
108
 
package/src/server.js CHANGED
@@ -16,8 +16,21 @@ if (nodeMajor < 22) {
16
16
  }
17
17
 
18
18
  const inFlight = new Map();
19
+ // Session ids seen this process, kept after the turn ends so cancel can tell a finished
20
+ // session (resumable, only the turn is over) from an id that never existed. Bounded so a
21
+ // long-lived server does not grow without limit.
22
+ const seenSessions = new Set();
23
+ const SEEN_SESSIONS_CAP = 500;
24
+ function rememberSession(set, id) {
25
+ if (id == null || set.has(id)) return;
26
+ set.add(id);
27
+ if (set.size > SEEN_SESSIONS_CAP) set.delete(set.values().next().value);
28
+ }
19
29
 
20
- export const SERVER_INSTRUCTIONS = `Delegate coding work to Cursor through the delegate tool. The delegate tool can create, modify, or delete files in its workspace, so scope workspace to the smallest relevant directory and review the git diff after every write-capable run; filesReportedByAgent lists the files the agent reported editing. For approval-gated work, call delegate with mode="plan", review the returned plan and sessionId, then resume with mode="agent" and resumeSessionId. Use mode="ask" for read-only questions and doctor for setup diagnostics.`;
30
+ // Loaded at connect, before any tool schema is, so this carries only pre-call facts: what a
31
+ // caller needs to decide whether to delegate at all. Call-time facts belong on the parameter
32
+ // descriptions, read while the call is being written.
33
+ export const SERVER_INSTRUCTIONS = `Delegate coding work to Cursor through the delegate tool. Every permission the agent requests is auto-approved, in every mode: mode="plan" and mode="ask" are instructions to the agent, not limits the bridge enforces, and the bridge cannot detect one being ignored. So scope workspace to the smallest relevant directory and review the git diff after every run, not only write-capable ones; filesReportedByAgent lists what the agent reported editing but the diff is authoritative.`;
21
34
 
22
35
  const planEntrySchema = z.object({
23
36
  content: z.string(),
@@ -27,14 +40,20 @@ const planEntrySchema = z.object({
27
40
 
28
41
  const delegateOutputSchema = z.object({
29
42
  result: z.string(),
30
- resultSource: z.enum(["tool-free-stream", "post-tool", "none"]).optional(),
43
+ resultSource: z.enum(["tool-free-stream", "post-tool", "pre-tool-fallback", "none"]).optional().describe(
44
+ "Where result came from. pre-tool-fallback means no final message closed the turn and result is the last message before the agent's final tool call — read protocolWarnings before trusting it as the answer."
45
+ ),
31
46
  finalMessageAvailable: z.boolean().optional(),
32
- stopReason: z.string().optional(),
47
+ stopReason: z.string().optional().describe(
48
+ "Present only when it is not the ordinary end_turn — a refusal, a cancel, or an output cap. Absence means the turn ended normally."
49
+ ),
33
50
  sessionId: z.string(),
34
51
  filesReportedByAgent: z.array(z.string()).describe(
35
52
  "Files the agent reported editing via native ACP diff events (may omit shell-driven edits)."
36
53
  ),
37
- questionsAsked: z.array(z.string()).optional(),
54
+ questionsAsked: z.array(z.string()).optional().describe(
55
+ "Clarifying questions the agent raised through elicitation. Absent on most turns — the agent usually asks in prose and ends the turn, which this does not capture; read result for that."
56
+ ),
38
57
  resumed: z.boolean().optional(),
39
58
  sessionTitle: z.string().optional().describe(
40
59
  "Short title the agent gave this turn. Present on most turns; purely a label."
@@ -42,7 +61,9 @@ const delegateOutputSchema = z.object({
42
61
  autoAnswered: z.array(z.object({ prompt: z.string(), chosen: z.string() })).optional(),
43
62
  fallbackAnswers: z.array(z.object({ prompt: z.string(), given: z.string(), chosen: z.string() })).optional(),
44
63
  cancelRequested: z.boolean().optional(),
45
- protocolWarnings: z.array(z.string()).optional(),
64
+ protocolWarnings: z.array(z.string()).optional().describe(
65
+ "Non-fatal diagnostics that did not justify failing the call — dropped or sanitized ACP fields, a failed resume, ignored model options, skipped contextFiles, a mid-session mode switch. Read whenever present."
66
+ ),
46
67
  plan: z.object({
47
68
  entries: z.array(planEntrySchema),
48
69
  overview: z.string().optional(),
@@ -56,7 +77,10 @@ const delegateOutputSchema = z.object({
56
77
  "Todo list the agent tracked for this turn. Absent when the agent tracked none, which is common on short tasks and does not imply incompleteness."
57
78
  ),
58
79
  modeChanged: z.object({ from: z.string(), to: z.string() }).optional().describe(
59
- "Set when the agent switched itself out of the requested mode mid-session."
80
+ "Set when the agent switched itself out of the requested mode mid-session. Absence does not mean the mode was honored — an agent can write while staying in plan."
81
+ ),
82
+ writeCapableActivity: z.array(z.object({ kind: z.string(), detail: z.string(), path: z.string().optional() })).optional().describe(
83
+ "Write-capable tool calls (edit/delete/move/execute) the agent ran during a plan or ask turn, which are expected to change nothing. Records what ran, not what changed — a shell command is not a change list. Only populated for mode plan and ask."
60
84
  ),
61
85
  todoProgress: z.object({
62
86
  total: z.number(),
@@ -86,16 +110,18 @@ const doctorOutputSchema = z.object({
86
110
  }).passthrough();
87
111
 
88
112
  export const delegateInputSchema = z.object({
89
- spec: z.string().describe("Inline task brief (default): goal, scope, decisions already made (constraints and fixed choices — quote the user's exact values verbatim), acceptance criteria. Point at files to read or mimic rather than pasting code. Optional file path if the user wants a persisted spec."),
90
- mode: z.enum(["agent", "plan", "ask"]).default("agent"),
113
+ spec: z.string().trim().min(1, "spec must not be blank").describe("Inline task brief (default): goal, scope, decisions already made (constraints and fixed choices — quote the user's exact values verbatim), acceptance criteria. Point at files to read or mimic rather than pasting code. Optional file path if the user wants a persisted spec."),
114
+ mode: z.enum(["agent", "plan", "ask"]).default("agent").describe("Requested agent mode. plan and ask are passed to the agent as instructions, not enforced by the bridge — the agent may write in any of them; modeChanged reports it if it switched."),
91
115
  resumeSessionId: z.string().optional().describe("Resume an existing ACP session instead of a new one"),
92
- workspace: z.string().optional().describe("Working directory for the agent (defaults to cwd)"),
116
+ workspace: z.string().optional().describe("Working directory for the agent (defaults to cwd). Must be an existing directory; the call fails rather than creating it."),
93
117
  model: z.string().trim().min(1, "model must be a non-empty string").default(DEFAULT_MODEL),
94
118
  fast: z.boolean().default(false).describe("Fast speed tier — higher cost; enable only when the user asks"),
95
119
  // Which options a model offers, and their valid values, are only knowable by asking the
96
120
  // agent, so these stay open strings and the agent rejects what it does not accept.
97
121
  reasoning: z.string().trim().min(1).optional().describe("Reasoning effort. Not offered by every model; gpt-5.x accepts none, low, medium, high, extra-high."),
98
122
  context: z.string().trim().min(1).optional().describe("Context window size. Not offered by every model; gpt-5.x accepts 272k and 1m."),
123
+ contextFiles: z.array(z.string()).optional().describe("Paths to attach instead of pasting file contents into spec. Text files are passed as references the agent may open; images (png, jpg, gif, webp, under 5MB) are sent inline. Relative paths resolve against workspace, and paths outside it are allowed — attach only files the agent should read. Anything skipped is reported in protocolWarnings, never fatal."),
124
+ maxResultChars: z.number().int().positive().optional().describe("Cap the returned result to this many characters. A longer result is truncated with a marker and a protocolWarning, so a runaway agent reply cannot blow up your context; the truncation is never reported as a complete answer."),
99
125
  });
100
126
 
101
127
  // A cursor/ask_question question is multi-select when it sets allowMultiple, and the answer
@@ -113,8 +139,8 @@ function matchOptions(choice, opts = [], allowMultiple = false) {
113
139
  return ids;
114
140
  }
115
141
 
116
- export async function runDelegateTool({ args, extra, server, runDelegate, inFlight }) {
117
- const { spec, mode, resumeSessionId, workspace, model, fast, reasoning, context } = args;
142
+ export async function runDelegateTool({ args, extra, server, runDelegate, inFlight, seenSessions = new Set() }) {
143
+ const { spec, mode, resumeSessionId, workspace, model, fast, reasoning, context, contextFiles, maxResultChars } = args;
118
144
 
119
145
  const progressToken = extra?._meta?.progressToken;
120
146
  let onProgress = () => {};
@@ -193,6 +219,8 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
193
219
  fast,
194
220
  reasoning,
195
221
  context,
222
+ contextFiles,
223
+ maxResultChars,
196
224
  onElicit,
197
225
  onProgress,
198
226
  signal: extra?.signal,
@@ -200,6 +228,12 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
200
228
  capturedSessionId = sessionId;
201
229
  handle = { client, cancelRequested: false };
202
230
  inFlight.set(sessionId, handle);
231
+ rememberSession(seenSessions, sessionId);
232
+ // Emit the id the moment the session opens, before the turn finishes, so a host that
233
+ // can call tools concurrently has something to pass to cancel mid-run — otherwise the
234
+ // id only arrives when delegate returns, by which point there is nothing to cancel.
235
+ // (Hosts that serialize tool calls still cannot cancel in flight; that is a host limit.)
236
+ onProgress(`session ready: ${sessionId}`);
203
237
  },
204
238
  });
205
239
  if (autoAnswered.length) out.autoAnswered = autoAnswered;
@@ -233,7 +267,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
233
267
  "delegate",
234
268
  {
235
269
  description:
236
- `Delegate a coding task to cursor-agent over ACP. Never shell out to cursor-agent — use this tool only. Pass structured task text inline in spec (default); a file path is optional when the user wants a persisted brief. Defaults: mode=agent, model=${DEFAULT_MODEL}, fast=false. Plan workflow: mode=plan, then resume with mode=agent and resumeSessionId. Auto-approves writes in workspace; uses MCP elicitation for clarifying questions and selects the first option when the client lacks elicitation. Returns the final result, selection source, stop reason, session ID, agent-reported files, and optional plan. See the delegate skill for orchestration.`,
270
+ `Delegate a coding task to cursor-agent over ACP. Never shell out to cursor-agent — use this tool only. Pass structured task text inline in spec (default); a file path is optional when the user wants a persisted brief. Defaults: mode=agent, model=${DEFAULT_MODEL}, fast=false. Plan workflow: mode=plan, then resume with mode=agent and resumeSessionId. Auto-approves every permission the agent requests, in any mode and anywhere on disk; uses MCP elicitation for clarifying questions and selects the first option when the client lacks elicitation. Returns the final result, selection source, stop reason, session ID, agent-reported files, and optional plan. See the delegate skill for orchestration.`,
237
271
  inputSchema: delegateInputSchema,
238
272
  outputSchema: delegateOutputSchema,
239
273
  annotations: {
@@ -244,19 +278,19 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
244
278
  openWorldHint: true,
245
279
  },
246
280
  },
247
- async (args, extra) => runDelegateTool({ args, extra, server, runDelegate, inFlight })
281
+ async (args, extra) => runDelegateTool({ args, extra, server, runDelegate, inFlight, seenSessions })
248
282
  );
249
283
 
250
284
  server.registerTool(
251
285
  "cancel",
252
286
  {
253
287
  description:
254
- "Best-effort cancel of an in-flight ACP delegation by sessionId. Sends session/cancel; the agent may finish the turn anyway. The delegate result carries cancelRequested: true when the turn was cancelled mid-run. MCP hosts that serialize tool calls cannot run this while delegate is in flight. With force: true, the agent process is killed if the turn is still running after a short grace period.",
288
+ "Best-effort cancel of an in-flight ACP delegation by sessionId. Sends session/cancel; the agent may finish the turn anyway. The delegate result carries cancelRequested: true when the turn was cancelled mid-run. MCP hosts that serialize tool calls cannot run this while delegate is in flight. With force: true, the agent process is killed if the turn is still running after a short grace period. Returns not-running for a session whose turn already ended (it is still resumable), and not-found for an id never seen this process.",
255
289
  inputSchema: {
256
290
  sessionId: z.string(),
257
291
  force: z.boolean().default(false).describe("After the cancel notify, wait a short grace period and kill the agent process if the delegation is still running"),
258
292
  },
259
- outputSchema: z.object({ status: z.enum(["cancelled", "killed", "not-found"]), sessionId: z.string() }),
293
+ outputSchema: z.object({ status: z.enum(["cancelled", "killed", "not-running", "not-found"]), sessionId: z.string() }),
260
294
  annotations: {
261
295
  title: "Cancel Cursor delegation",
262
296
  readOnlyHint: false,
@@ -268,15 +302,23 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
268
302
  async ({ sessionId, force }) => {
269
303
  const handle = inFlight.get(sessionId);
270
304
  if (!handle) {
305
+ // A finished session and a garbage id used to look identical (both not-found), which
306
+ // read as "bad id" for a session that in fact ran and is still resumable. Split them.
307
+ const known = seenSessions.has(sessionId);
271
308
  return {
272
- content: [{ type: "text", text: `no in-flight session ${sessionId}` }],
273
- structuredContent: { status: "not-found", sessionId },
309
+ content: [{ type: "text", text: known
310
+ ? `session ${sessionId} is not running; its turn already ended (still resumable via resumeSessionId)`
311
+ : `no in-flight session ${sessionId}` }],
312
+ structuredContent: { status: known ? "not-running" : "not-found", sessionId },
274
313
  };
275
314
  }
276
315
  handle.cancelRequested = true;
277
316
  await handle.client.cancel(sessionId).catch(() => {});
278
317
  if (!force) {
279
- inFlight.delete(sessionId);
318
+ // The handle stays registered: session/cancel is best-effort, so the turn may still
319
+ // be running. Dropping it here made the natural escalation — cancel, wait, cancel
320
+ // with force — report not-found while the agent was alive. The delegation's own
321
+ // finally removes the entry when the turn actually settles.
280
322
  return {
281
323
  content: [{ type: "text", text: `cancelled ${sessionId}` }],
282
324
  structuredContent: { status: "cancelled", sessionId },
@@ -15,7 +15,7 @@ export class SessionSupervisor {
15
15
  this.hardCapMs = hardCapMs;
16
16
  // Mid-turn idle detection is opt-in and off by default. cursor-agent emits no ACP
17
17
  // frames while a shell command runs, so silence during a prompt turn says nothing
18
- // about liveness — see docs/acp-probes/2026-07-21-client-terminal-capability.
18
+ // about liveness: a probe measured 26.9s of dead wire for a healthy 20s command.
19
19
  this.idleMs = idleMs > 0 ? idleMs : 0;
20
20
  this.sessionId = null;
21
21
  this.lastActivityAt = Date.now();
package/src/version.js CHANGED
@@ -2,6 +2,24 @@ import { readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
 
5
- export const VERSION = JSON.parse(
6
- readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8")
7
- ).version;
5
+ const PKG_PATH = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "package.json");
6
+
7
+ function readVersion() {
8
+ return JSON.parse(readFileSync(PKG_PATH, "utf8")).version;
9
+ }
10
+
11
+ // Captured once, for the ACP/MCP identity handshake that is sent at connect and never re-read.
12
+ export const VERSION = readVersion();
13
+
14
+ // doctor calls this instead of the constant. The MCP child is long-lived and /reload-plugins
15
+ // does not restart it, so a version captured at process start goes stale after an in-place
16
+ // upgrade — exactly when someone runs doctor to confirm the new version shipped. Reading fresh
17
+ // is truthful whenever the process was restarted (the normal case); the one residual gap is an
18
+ // un-restarted child running old code, where no in-process value can be authoritative anyway.
19
+ export function readPackageVersion() {
20
+ try {
21
+ return readVersion();
22
+ } catch {
23
+ return VERSION;
24
+ }
25
+ }