cursor-delegate-mcp 1.9.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursor-delegate-mcp",
3
- "version": "1.9.0",
3
+ "version": "1.10.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,109 @@ 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
+ if (!looksLikeSpecPath(spec)) return spec;
40
+ let stat;
29
41
  try {
30
- if (statSync(spec).isFile()) return readFileSync(spec, "utf8");
31
- } catch {}
42
+ stat = statSync(spec);
43
+ } catch {
44
+ // Only a bare path was unambiguously meant as one. Anything else is prose that happens
45
+ // to name a file, and prose is the common case.
46
+ if (!isBareSpecPath(spec)) return spec;
47
+ const err = new Error(`spec looks like a file path but nothing exists at ${spec}. Pass the brief inline, or fix the path.`);
48
+ err.reason = "invalid-spec";
49
+ throw err;
50
+ }
51
+ if (stat.isFile()) return readFileSync(spec, "utf8");
52
+ if (isBareSpecPath(spec)) {
53
+ 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.`);
54
+ err.reason = "invalid-spec";
55
+ throw err;
56
+ }
32
57
  return spec;
33
58
  }
34
59
 
60
+ // A nonexistent workspace was accepted, then created by the agent's first write — a typo
61
+ // silently spawned a parallel empty tree and every layer reported success. contextFiles has
62
+ // always rejected the same mistakes; this is that check, applied to its sibling.
63
+ function assertWorkspace(workspace) {
64
+ if (workspace === undefined || workspace === null) return;
65
+ let stat;
66
+ try {
67
+ stat = statSync(workspace);
68
+ } catch {
69
+ const err = new Error(`workspace ${workspace} does not exist. Create it first, or point at an existing directory.`);
70
+ err.reason = "invalid-workspace";
71
+ throw err;
72
+ }
73
+ if (!stat.isDirectory()) {
74
+ const err = new Error(`workspace ${workspace} is not a directory.`);
75
+ err.reason = "invalid-workspace";
76
+ throw err;
77
+ }
78
+ }
79
+
80
+ const IMAGE_MIME = {
81
+ ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
82
+ ".gif": "image/gif", ".webp": "image/webp",
83
+ };
84
+ // Base64 inflates by a third and every byte lands in the prompt, unlike a link.
85
+ const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
86
+
87
+ // A resource_link hands the agent a path instead of the file's bytes, so a large brief costs
88
+ // prompt space only for what the agent decides to open. Images cannot work that way — they
89
+ // are sent inline. Both are measured working, including links to files outside the
90
+ // workspace. Two rules follow from the probe:
91
+ // - gate images on the advertised capability, because cursor-agent accepts blocks it does
92
+ // not support without any error (embeddedContext:false raises nothing), so an ungated
93
+ // image would silently vanish;
94
+ // - report anything skipped, since a dropped attachment is otherwise invisible.
95
+ function buildContextBlocks(contextFiles, workspace, client, warnings) {
96
+ const blocks = [];
97
+ for (const entry of contextFiles || []) {
98
+ if (typeof entry !== "string" || !entry.trim()) continue;
99
+ const abs = path.resolve(workspace || process.cwd(), entry);
100
+ let stat;
101
+ try {
102
+ stat = statSync(abs);
103
+ } catch {
104
+ warnings.push(`contextFile ${entry} skipped: not found at ${abs}`);
105
+ continue;
106
+ }
107
+ if (!stat.isFile()) {
108
+ warnings.push(`contextFile ${entry} skipped: not a file`);
109
+ continue;
110
+ }
111
+ const mimeType = IMAGE_MIME[path.extname(abs).toLowerCase()];
112
+ if (mimeType) {
113
+ if (!client?.agentCapabilities?.promptCapabilities?.image) {
114
+ warnings.push(`contextFile ${entry} skipped: this agent does not accept image prompts`);
115
+ continue;
116
+ }
117
+ if (stat.size > MAX_IMAGE_BYTES) {
118
+ warnings.push(`contextFile ${entry} skipped: ${Math.round(stat.size / 1024)}KB exceeds the ${MAX_IMAGE_BYTES / 1024 / 1024}MB image limit`);
119
+ continue;
120
+ }
121
+ blocks.push({ type: "image", mimeType, data: readFileSync(abs).toString("base64") });
122
+ continue;
123
+ }
124
+ blocks.push({ type: "resource_link", uri: pathToFileURL(abs).href, name: path.basename(abs) });
125
+ }
126
+ return blocks;
127
+ }
128
+
35
129
  async function openSession(client, resumeSessionId, workspace) {
36
130
  if (!resumeSessionId) return client.newSession(workspace);
37
131
  try {
@@ -76,7 +170,7 @@ async function applyConfig(client, sessionId, configId, value) {
76
170
 
77
171
  export async function runDelegate({
78
172
  spec, mode = "agent", resumeSessionId, workspace,
79
- model = DEFAULT_MODEL, fast = false, reasoning, context, clientFactory, onElicit,
173
+ model = DEFAULT_MODEL, fast = false, reasoning, context, contextFiles, clientFactory, onElicit,
80
174
  idleMs, handshakeMs, hardCapMs, timeoutMs,
81
175
  onSessionReady, onProgress, progressThrottleMs = 2000,
82
176
  heartbeatMs = DEFAULT_HEARTBEAT_MS,
@@ -87,6 +181,10 @@ export async function runDelegate({
87
181
  err.reason = "aborted";
88
182
  throw err;
89
183
  }
184
+ // Before the spawn: a bad path is the caller's to fix, and finding out costs a process,
185
+ // a handshake and a billed turn if it waits until the prompt is assembled.
186
+ assertWorkspace(workspace);
187
+ const promptText = resolveSpec(spec);
90
188
  const capMs = hardCapMs ?? timeoutMs ?? envMs("CURSOR_DELEGATE_HARD_CAP_MS", 3600000);
91
189
  const shakeMs = handshakeMs ?? envMs("CURSOR_DELEGATE_HANDSHAKE_MS", DEFAULT_HANDSHAKE_MS);
92
190
  const turnIdleMs = idleMs ?? envMs("CURSOR_DELEGATE_IDLE_MS", 0);
@@ -212,7 +310,15 @@ export async function runDelegate({
212
310
  const activeToolCalls = new Set();
213
311
  const touched = new Set();
214
312
 
313
+ // Text superseded by a later tool call is normally a preamble ("Inspecting the
314
+ // implementation.") and returning it would be inventing a summary. But the rule cannot
315
+ // tell a preamble from the whole answer: an agent that replies and then runs one more
316
+ // command has its entire reply discarded, and the caller gets "" with stopReason end_turn
317
+ // and no error. So keep the last discarded segment and hand it back only when nothing
318
+ // survived — labelled, never blended with a real final message.
319
+ let discardedResult = "";
215
320
  const resetResult = () => {
321
+ if (resultLength > 0) discardedResult = resultChunks.join("");
216
322
  resultChunks.length = 0;
217
323
  resultLength = 0;
218
324
  truncated = false;
@@ -296,6 +402,18 @@ export async function runDelegate({
296
402
  // The bridge cannot see inside a running shell command, so a long silence is reported
297
403
  // rather than acted on: the caller gets elapsed time and frame age and can decide.
298
404
  let lastToolLabel = null;
405
+ // A shell write arrives as execute, a file write as edit; delete and move round out ACP's
406
+ // write-capable kinds. read, search, think and fetch stay out — a plan turn is expected
407
+ // to do those.
408
+ const WRITE_CAPABLE_KINDS = new Set(["edit", "delete", "move", "execute"]);
409
+ // Scoped to plan/ask deliberately. In agent mode this is every turn and carries nothing;
410
+ // in plan/ask a disk-touching turn is abnormal — the plan itself travels over ACP as a
411
+ // string via cursor/create_plan, not as a file — so the base rate makes it worth reading.
412
+ // It records what the agent *ran*, never what changed: a command is not a change list.
413
+ const WRITE_ACTIVITY_CAP = 20;
414
+ const watchingWrites = mode === "plan" || mode === "ask";
415
+ let writeCapableActivity = [];
416
+ let writeActivityById = new Map();
299
417
  let modeChanged;
300
418
  let sessionTitle;
301
419
  let promptInFlight = false;
@@ -345,6 +463,15 @@ export async function runDelegate({
345
463
  const label = up.title || up.kind || "tool";
346
464
  const path = up.locations?.[0]?.path;
347
465
  lastToolLabel = String(label) + (path ? " — " + path : "");
466
+ if (watchingWrites && WRITE_CAPABLE_KINDS.has(up.kind) && writeCapableActivity.length < WRITE_ACTIVITY_CAP) {
467
+ const entry = { kind: up.kind, detail: lastToolLabel.slice(0, 300) };
468
+ writeCapableActivity.push(entry);
469
+ // An execute call names itself — its title is the shell command. An edit call does
470
+ // not: the title is a bare "Edit File" and locations is empty, so the only thing
471
+ // separating docs/plan.md from src/api.js is the diff frame that follows. Keep the
472
+ // id so that frame can fill the path in.
473
+ if (up.toolCallId != null) writeActivityById.set(up.toolCallId, entry);
474
+ }
348
475
  try { onProgress?.(("running: " + lastToolLabel).slice(0, 200)); } catch {}
349
476
  }
350
477
  if (up.sessionUpdate === "agent_message_chunk" && up.content?.text) {
@@ -357,6 +484,10 @@ export async function runDelegate({
357
484
  for (const c of up.content || []) {
358
485
  if (c.type === "diff" && c.path) {
359
486
  touched.add(c.path);
487
+ const pending = writeActivityById.get(up.toolCallId);
488
+ if (pending && !pending.path) {
489
+ pending.path = normalizeAgentReportedFiles([c.path], workspace)[0];
490
+ }
360
491
  try { onProgress?.("editing " + c.path); } catch {}
361
492
  }
362
493
  // cursor-agent has never been observed emitting these; ACP allows an agent to
@@ -372,6 +503,7 @@ export async function runDelegate({
372
503
  let sessionId;
373
504
  let resumeError;
374
505
  const unsupportedOptions = [];
506
+ const contextWarnings = [];
375
507
  try {
376
508
  const res = await supervisor.supervise(async () => {
377
509
  await client.start();
@@ -402,6 +534,9 @@ export async function runDelegate({
402
534
  planDetail = undefined;
403
535
  todos = new Map();
404
536
  sawTodoFrame = false;
537
+ discardedResult = "";
538
+ writeCapableActivity = [];
539
+ writeActivityById = new Map();
405
540
  touched.clear();
406
541
  lastToolLabel = null;
407
542
  modeChanged = undefined;
@@ -409,17 +544,30 @@ export async function runDelegate({
409
544
  supervisor.promptStarted();
410
545
  startHeartbeat();
411
546
  promptInFlight = true;
412
- return client.prompt(sessionId, resolveSpec(spec));
547
+ return client.prompt(sessionId, [
548
+ { type: "text", text: promptText },
549
+ ...buildContextBlocks(contextFiles, workspace, client, contextWarnings),
550
+ ]);
413
551
  });
414
552
  thoughtProgress.end();
415
553
  messageProgress.end();
416
554
  let result = resultChunks.join("");
417
555
  if (truncated) result += TRUNCATION_MARKER;
418
556
  const finalMessageAvailable = result.length > 0;
419
- const resultSource = finalMessageAvailable
557
+ let resultSource = finalMessageAvailable
420
558
  ? (sawToolCall ? "post-tool" : "tool-free-stream")
421
559
  : "none";
422
560
  const protocolWarnings = [];
561
+ if (!finalMessageAvailable && discardedResult) {
562
+ result = discardedResult;
563
+ resultSource = "pre-tool-fallback";
564
+ protocolWarnings.push(
565
+ "the agent ran a tool after its last message and never spoke again, so no final message closed the turn."
566
+ + " result carries the last message before that tool call — it may be a preamble rather than the answer."
567
+ );
568
+ } else if (!finalMessageAvailable) {
569
+ protocolWarnings.push("the agent ended the turn without emitting any message; result is empty.");
570
+ }
423
571
  let stopReason;
424
572
  if (res?.stopReason !== undefined) {
425
573
  if (typeof res.stopReason === "string") stopReason = res.stopReason;
@@ -438,12 +586,21 @@ export async function runDelegate({
438
586
  if (sessionTitle) out.sessionTitle = sessionTitle;
439
587
  if (resumeError) protocolWarnings.push(`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`);
440
588
  for (const id of unsupportedOptions) protocolWarnings.push(`model ${model} has no ${id} option; the requested value was ignored`);
589
+ protocolWarnings.push(...contextWarnings);
441
590
  if (planEntries.length > 0 || planOverview !== undefined || planDetail !== undefined) {
442
591
  out.plan = sanitizePlan(protocolWarnings);
443
592
  }
444
593
  // Most successful turns emit no todos at all, so an empty list would read as "nothing
445
594
  // done" rather than "not tracked". Report only what the agent actually sent.
446
595
  if (sawTodoFrame) Object.assign(out, sanitizeTodos(protocolWarnings));
596
+ if (writeCapableActivity.length) {
597
+ out.writeCapableActivity = writeCapableActivity;
598
+ protocolWarnings.push(
599
+ `mode ${mode} asked the agent not to change anything, but it ran ${writeCapableActivity.length}`
600
+ + ` write-capable tool call${writeCapableActivity.length === 1 ? "" : "s"} — see writeCapableActivity`
601
+ + " for what ran, and the diff for what changed."
602
+ );
603
+ }
447
604
  if (modeChanged) {
448
605
  out.modeChanged = modeChanged;
449
606
  protocolWarnings.push(`agent switched mode from ${modeChanged.from} to ${modeChanged.to} mid-session`);
@@ -458,7 +615,12 @@ export async function runDelegate({
458
615
  // slow. Name what was outstanding so the caller can tell the two apart, and so a
459
616
  // retry can resume from the work already done instead of restarting blind.
460
617
  const isTimeout = err?.reason === "hard-cap" || err?.reason === "idle-timeout";
461
- if (isTimeout || err?.reason === "aborted" || err?.reason === "agent-exit") {
618
+ // A handshake timeout gets the forensics but not the long-command advice below: the
619
+ // session exists by then — it is set before set_model, set_config_option and set_mode,
620
+ // any of which can hang — so the resume hint is what the caller needs. No prompt was
621
+ // ever sent, so no shell command can be the reason for the silence.
622
+ const isStall = isTimeout || err?.reason === "handshake-timeout";
623
+ if (isStall || err?.reason === "aborted" || err?.reason === "agent-exit") {
462
624
  const age = fmtDuration(supervisor.msSinceActivity());
463
625
  err.message += `\n\nLast ACP frame ${age} ago${lastToolLabel ? `; last tool call: ${lastToolLabel}` : ""}.`;
464
626
  if (sessionTitle) err.message += ` The agent titled this turn ${JSON.stringify(sessionTitle)}.`;
@@ -483,10 +645,17 @@ export async function runDelegate({
483
645
  + " CURSOR_DELEGATE_HARD_CAP_MS.";
484
646
  }
485
647
  }
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 {}
648
+ // Opt-in, because the frames land in the caller's context and nothing there is
649
+ // actionable: the forensics above already carry everything a caller can act on. Raw
650
+ // frames only help someone debugging the bridge, and that has always been done with a
651
+ // protocol probe, never with an error dump.
652
+ const frames = Number(process.env.CURSOR_DELEGATE_TRANSCRIPT);
653
+ if (frames > 0) {
654
+ try {
655
+ const transcript = client.getTranscript?.(frames);
656
+ if (transcript) err.message += `\n\n--- recent ACP transcript (last ${frames} frames) ---\n` + transcript;
657
+ } catch {}
658
+ }
490
659
  throw err;
491
660
  } finally {
492
661
  clearInterval(heartbeat);
package/src/doctor.js CHANGED
@@ -101,6 +101,7 @@ export async function runDoctor({
101
101
  },
102
102
  env: {
103
103
  ACP_LOG_SIZE: process.env.ACP_LOG_SIZE !== undefined ? process.env.ACP_LOG_SIZE : DEFAULT_LOG_SIZE,
104
+ CURSOR_DELEGATE_TRANSCRIPT: process.env.CURSOR_DELEGATE_TRANSCRIPT ?? null,
104
105
  },
105
106
  };
106
107
 
package/src/server.js CHANGED
@@ -17,7 +17,10 @@ if (nodeMajor < 22) {
17
17
 
18
18
  const inFlight = new Map();
19
19
 
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.`;
20
+ // Loaded at connect, before any tool schema is, so this carries only pre-call facts: what a
21
+ // caller needs to decide whether to delegate at all. Call-time facts belong on the parameter
22
+ // descriptions, read while the call is being written.
23
+ 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
24
 
22
25
  const planEntrySchema = z.object({
23
26
  content: z.string(),
@@ -27,7 +30,9 @@ const planEntrySchema = z.object({
27
30
 
28
31
  const delegateOutputSchema = z.object({
29
32
  result: z.string(),
30
- resultSource: z.enum(["tool-free-stream", "post-tool", "none"]).optional(),
33
+ resultSource: z.enum(["tool-free-stream", "post-tool", "pre-tool-fallback", "none"]).optional().describe(
34
+ "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."
35
+ ),
31
36
  finalMessageAvailable: z.boolean().optional(),
32
37
  stopReason: z.string().optional(),
33
38
  sessionId: z.string(),
@@ -42,7 +47,9 @@ const delegateOutputSchema = z.object({
42
47
  autoAnswered: z.array(z.object({ prompt: z.string(), chosen: z.string() })).optional(),
43
48
  fallbackAnswers: z.array(z.object({ prompt: z.string(), given: z.string(), chosen: z.string() })).optional(),
44
49
  cancelRequested: z.boolean().optional(),
45
- protocolWarnings: z.array(z.string()).optional(),
50
+ protocolWarnings: z.array(z.string()).optional().describe(
51
+ "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."
52
+ ),
46
53
  plan: z.object({
47
54
  entries: z.array(planEntrySchema),
48
55
  overview: z.string().optional(),
@@ -56,7 +63,10 @@ const delegateOutputSchema = z.object({
56
63
  "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
64
  ),
58
65
  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."
66
+ "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."
67
+ ),
68
+ writeCapableActivity: z.array(z.object({ kind: z.string(), detail: z.string(), path: z.string().optional() })).optional().describe(
69
+ "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
70
  ),
61
71
  todoProgress: z.object({
62
72
  total: z.number(),
@@ -87,15 +97,16 @@ const doctorOutputSchema = z.object({
87
97
 
88
98
  export const delegateInputSchema = z.object({
89
99
  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"),
100
+ 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
101
  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)"),
102
+ 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
103
  model: z.string().trim().min(1, "model must be a non-empty string").default(DEFAULT_MODEL),
94
104
  fast: z.boolean().default(false).describe("Fast speed tier — higher cost; enable only when the user asks"),
95
105
  // Which options a model offers, and their valid values, are only knowable by asking the
96
106
  // agent, so these stay open strings and the agent rejects what it does not accept.
97
107
  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
108
  context: z.string().trim().min(1).optional().describe("Context window size. Not offered by every model; gpt-5.x accepts 272k and 1m."),
109
+ 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."),
99
110
  });
100
111
 
101
112
  // A cursor/ask_question question is multi-select when it sets allowMultiple, and the answer
@@ -114,7 +125,7 @@ function matchOptions(choice, opts = [], allowMultiple = false) {
114
125
  }
115
126
 
116
127
  export async function runDelegateTool({ args, extra, server, runDelegate, inFlight }) {
117
- const { spec, mode, resumeSessionId, workspace, model, fast, reasoning, context } = args;
128
+ const { spec, mode, resumeSessionId, workspace, model, fast, reasoning, context, contextFiles } = args;
118
129
 
119
130
  const progressToken = extra?._meta?.progressToken;
120
131
  let onProgress = () => {};
@@ -193,6 +204,7 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
193
204
  fast,
194
205
  reasoning,
195
206
  context,
207
+ contextFiles,
196
208
  onElicit,
197
209
  onProgress,
198
210
  signal: extra?.signal,
@@ -233,7 +245,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
233
245
  "delegate",
234
246
  {
235
247
  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.`,
248
+ `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
249
  inputSchema: delegateInputSchema,
238
250
  outputSchema: delegateOutputSchema,
239
251
  annotations: {
@@ -276,7 +288,10 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
276
288
  handle.cancelRequested = true;
277
289
  await handle.client.cancel(sessionId).catch(() => {});
278
290
  if (!force) {
279
- inFlight.delete(sessionId);
291
+ // The handle stays registered: session/cancel is best-effort, so the turn may still
292
+ // be running. Dropping it here made the natural escalation — cancel, wait, cancel
293
+ // with force — report not-found while the agent was alive. The delegation's own
294
+ // finally removes the entry when the turn actually settles.
280
295
  return {
281
296
  content: [{ type: "text", text: `cancelled ${sessionId}` }],
282
297
  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();