cursor-delegate-mcp 1.8.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 +1 -1
- package/src/acp-client.js +4 -4
- package/src/delegate.js +250 -21
- package/src/doctor.js +1 -0
- package/src/jsonrpc.js +7 -1
- package/src/server.js +74 -30
- package/src/session-supervisor.js +1 -1
package/package.json
CHANGED
package/src/acp-client.js
CHANGED
|
@@ -64,8 +64,8 @@ export class AcpClient extends EventEmitter {
|
|
|
64
64
|
});
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
-
//
|
|
68
|
-
//
|
|
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;
|
|
@@ -81,9 +81,9 @@ export class AcpClient extends EventEmitter {
|
|
|
81
81
|
async newSession(cwd) { return this._captureSession(await this.peer.request("session/new", { cwd, mcpServers: [] })); }
|
|
82
82
|
async loadSession(sessionId, cwd) { return this._captureSession(await this.peer.request("session/load", { sessionId, cwd, mcpServers: [] })); }
|
|
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,
|
|
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,26 +23,120 @@ 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
|
-
|
|
27
|
-
|
|
28
|
-
if (!looksLikePath) return spec;
|
|
39
|
+
if (!looksLikeSpecPath(spec)) return spec;
|
|
40
|
+
let stat;
|
|
29
41
|
try {
|
|
30
|
-
|
|
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 {
|
|
38
132
|
await client.loadSession(resumeSessionId, workspace);
|
|
39
133
|
return { sessionId: resumeSessionId }; // load does not echo sessionId
|
|
40
|
-
} catch {
|
|
41
|
-
//
|
|
134
|
+
} catch (err) {
|
|
135
|
+
// Starting fresh is right, but silently doing so leaves the caller unable to tell a
|
|
136
|
+
// stale id from a typo'd one — keep why the load failed.
|
|
137
|
+
const fresh = await client.newSession(workspace);
|
|
138
|
+
return { ...fresh, resumeError: err?.message || String(err) };
|
|
42
139
|
}
|
|
43
|
-
return client.newSession(workspace);
|
|
44
140
|
}
|
|
45
141
|
|
|
46
142
|
// session/new reports the models the agent actually offers. Reject an unknown id here,
|
|
@@ -56,15 +152,25 @@ function assertKnownModel(client, model) {
|
|
|
56
152
|
throw err;
|
|
57
153
|
}
|
|
58
154
|
|
|
59
|
-
//
|
|
60
|
-
//
|
|
61
|
-
|
|
62
|
-
|
|
155
|
+
// Which config options a model carries is not discoverable up front: session/new reports
|
|
156
|
+
// configOptions for the default model and set_model returns nothing. So ask, and read the
|
|
157
|
+
// rejection as the answer. Two distinct -32602s, both measured: "Unknown model config
|
|
158
|
+
// option: X" means this model has no such knob — report it and carry on. "Invalid value
|
|
159
|
+
// for X: Y" means the caller named a value the model rejects, which must not be swallowed.
|
|
160
|
+
// Returns true when the option is unsupported.
|
|
161
|
+
async function applyConfig(client, sessionId, configId, value) {
|
|
162
|
+
try {
|
|
163
|
+
await client.setConfigOption(sessionId, configId, value);
|
|
164
|
+
return false;
|
|
165
|
+
} catch (err) {
|
|
166
|
+
if (err?.code !== -32602 || !/unknown model config option/i.test(err?.message || "")) throw err;
|
|
167
|
+
return true;
|
|
168
|
+
}
|
|
63
169
|
}
|
|
64
170
|
|
|
65
171
|
export async function runDelegate({
|
|
66
172
|
spec, mode = "agent", resumeSessionId, workspace,
|
|
67
|
-
model = DEFAULT_MODEL, fast = false, clientFactory, onElicit,
|
|
173
|
+
model = DEFAULT_MODEL, fast = false, reasoning, context, contextFiles, clientFactory, onElicit,
|
|
68
174
|
idleMs, handshakeMs, hardCapMs, timeoutMs,
|
|
69
175
|
onSessionReady, onProgress, progressThrottleMs = 2000,
|
|
70
176
|
heartbeatMs = DEFAULT_HEARTBEAT_MS,
|
|
@@ -75,6 +181,10 @@ export async function runDelegate({
|
|
|
75
181
|
err.reason = "aborted";
|
|
76
182
|
throw err;
|
|
77
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);
|
|
78
188
|
const capMs = hardCapMs ?? timeoutMs ?? envMs("CURSOR_DELEGATE_HARD_CAP_MS", 3600000);
|
|
79
189
|
const shakeMs = handshakeMs ?? envMs("CURSOR_DELEGATE_HANDSHAKE_MS", DEFAULT_HANDSHAKE_MS);
|
|
80
190
|
const turnIdleMs = idleMs ?? envMs("CURSOR_DELEGATE_IDLE_MS", 0);
|
|
@@ -200,7 +310,15 @@ export async function runDelegate({
|
|
|
200
310
|
const activeToolCalls = new Set();
|
|
201
311
|
const touched = new Set();
|
|
202
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 = "";
|
|
203
320
|
const resetResult = () => {
|
|
321
|
+
if (resultLength > 0) discardedResult = resultChunks.join("");
|
|
204
322
|
resultChunks.length = 0;
|
|
205
323
|
resultLength = 0;
|
|
206
324
|
truncated = false;
|
|
@@ -284,6 +402,21 @@ export async function runDelegate({
|
|
|
284
402
|
// The bridge cannot see inside a running shell command, so a long silence is reported
|
|
285
403
|
// rather than acted on: the caller gets elapsed time and frame age and can decide.
|
|
286
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();
|
|
417
|
+
let modeChanged;
|
|
418
|
+
let sessionTitle;
|
|
419
|
+
let promptInFlight = false;
|
|
287
420
|
let heartbeat = null;
|
|
288
421
|
const startHeartbeat = () => {
|
|
289
422
|
if (!(heartbeatMs > 0)) return;
|
|
@@ -301,11 +434,27 @@ export async function runDelegate({
|
|
|
301
434
|
heartbeat.unref?.();
|
|
302
435
|
};
|
|
303
436
|
|
|
437
|
+
// session/load replays the previous turn as ordinary session/update frames, including
|
|
438
|
+
// tool_call and diff blocks. The reset before the prompt clears the state they touch,
|
|
439
|
+
// but it cannot unsend the progress notifications they already emitted — a resume
|
|
440
|
+
// otherwise reports the previous turn's tool calls and edits as if they were happening.
|
|
304
441
|
client.on("update", (u) => {
|
|
442
|
+
if (!promptInFlight) return;
|
|
305
443
|
const up = u?.update || {};
|
|
306
444
|
if (up.sessionUpdate === "plan") {
|
|
307
445
|
planEntries = up.entries || [];
|
|
308
446
|
}
|
|
447
|
+
// A plan-mode run that switches itself to agent mode becomes write-capable while the
|
|
448
|
+
// caller still believes nothing can change. No drift has been observed; report it so
|
|
449
|
+
// we find out rather than assume.
|
|
450
|
+
if (up.sessionUpdate === "current_mode_update" && up.currentModeId && up.currentModeId !== mode) {
|
|
451
|
+
modeChanged = { from: mode, to: up.currentModeId };
|
|
452
|
+
}
|
|
453
|
+
// The agent names the turn a beat after the prompt lands ("File Creator"). Cheap
|
|
454
|
+
// label for a caller juggling several delegations.
|
|
455
|
+
if (up.sessionUpdate === "session_info_update" && typeof up.title === "string" && up.title) {
|
|
456
|
+
sessionTitle = up.title;
|
|
457
|
+
}
|
|
309
458
|
if (up.sessionUpdate === "agent_thought_chunk" && up.content?.text) {
|
|
310
459
|
thoughtProgress.push(up.content.text);
|
|
311
460
|
}
|
|
@@ -314,6 +463,15 @@ export async function runDelegate({
|
|
|
314
463
|
const label = up.title || up.kind || "tool";
|
|
315
464
|
const path = up.locations?.[0]?.path;
|
|
316
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
|
+
}
|
|
317
475
|
try { onProgress?.(("running: " + lastToolLabel).slice(0, 200)); } catch {}
|
|
318
476
|
}
|
|
319
477
|
if (up.sessionUpdate === "agent_message_chunk" && up.content?.text) {
|
|
@@ -326,6 +484,10 @@ export async function runDelegate({
|
|
|
326
484
|
for (const c of up.content || []) {
|
|
327
485
|
if (c.type === "diff" && c.path) {
|
|
328
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
|
+
}
|
|
329
491
|
try { onProgress?.("editing " + c.path); } catch {}
|
|
330
492
|
}
|
|
331
493
|
// cursor-agent has never been observed emitting these; ACP allows an agent to
|
|
@@ -339,17 +501,27 @@ export async function runDelegate({
|
|
|
339
501
|
});
|
|
340
502
|
|
|
341
503
|
let sessionId;
|
|
504
|
+
let resumeError;
|
|
505
|
+
const unsupportedOptions = [];
|
|
506
|
+
const contextWarnings = [];
|
|
342
507
|
try {
|
|
343
508
|
const res = await supervisor.supervise(async () => {
|
|
344
509
|
await client.start();
|
|
345
510
|
await client.initialize();
|
|
346
511
|
const sess = await openSession(client, resumeSessionId, workspace);
|
|
347
512
|
sessionId = sess.sessionId;
|
|
513
|
+
resumeError = sess.resumeError;
|
|
348
514
|
supervisor.setSessionId(sessionId);
|
|
349
515
|
onSessionReady?.(sessionId, client);
|
|
350
516
|
assertKnownModel(client, model);
|
|
351
517
|
await client.setModel(sessionId, model);
|
|
352
|
-
|
|
518
|
+
// fast is always sent: a resumed session may already have it on, so false is a real
|
|
519
|
+
// instruction. reasoning and context are only sent when the caller named one.
|
|
520
|
+
if (await applyConfig(client, sessionId, "fast", fast) && fast) unsupportedOptions.push("fast");
|
|
521
|
+
for (const [id, value] of [["reasoning", reasoning], ["context", context]]) {
|
|
522
|
+
if (value === undefined) continue;
|
|
523
|
+
if (await applyConfig(client, sessionId, id, value)) unsupportedOptions.push(id);
|
|
524
|
+
}
|
|
353
525
|
await client.setMode(sessionId, mode);
|
|
354
526
|
resetResult();
|
|
355
527
|
sawToolCall = false;
|
|
@@ -362,21 +534,40 @@ export async function runDelegate({
|
|
|
362
534
|
planDetail = undefined;
|
|
363
535
|
todos = new Map();
|
|
364
536
|
sawTodoFrame = false;
|
|
537
|
+
discardedResult = "";
|
|
538
|
+
writeCapableActivity = [];
|
|
539
|
+
writeActivityById = new Map();
|
|
365
540
|
touched.clear();
|
|
366
541
|
lastToolLabel = null;
|
|
542
|
+
modeChanged = undefined;
|
|
543
|
+
sessionTitle = undefined;
|
|
367
544
|
supervisor.promptStarted();
|
|
368
545
|
startHeartbeat();
|
|
369
|
-
|
|
546
|
+
promptInFlight = true;
|
|
547
|
+
return client.prompt(sessionId, [
|
|
548
|
+
{ type: "text", text: promptText },
|
|
549
|
+
...buildContextBlocks(contextFiles, workspace, client, contextWarnings),
|
|
550
|
+
]);
|
|
370
551
|
});
|
|
371
552
|
thoughtProgress.end();
|
|
372
553
|
messageProgress.end();
|
|
373
554
|
let result = resultChunks.join("");
|
|
374
555
|
if (truncated) result += TRUNCATION_MARKER;
|
|
375
556
|
const finalMessageAvailable = result.length > 0;
|
|
376
|
-
|
|
557
|
+
let resultSource = finalMessageAvailable
|
|
377
558
|
? (sawToolCall ? "post-tool" : "tool-free-stream")
|
|
378
559
|
: "none";
|
|
379
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
|
+
}
|
|
380
571
|
let stopReason;
|
|
381
572
|
if (res?.stopReason !== undefined) {
|
|
382
573
|
if (typeof res.stopReason === "string") stopReason = res.stopReason;
|
|
@@ -392,22 +583,47 @@ export async function runDelegate({
|
|
|
392
583
|
questionsAsked,
|
|
393
584
|
resumed: !!resumeSessionId && sessionId === resumeSessionId,
|
|
394
585
|
};
|
|
586
|
+
if (sessionTitle) out.sessionTitle = sessionTitle;
|
|
587
|
+
if (resumeError) protocolWarnings.push(`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`);
|
|
588
|
+
for (const id of unsupportedOptions) protocolWarnings.push(`model ${model} has no ${id} option; the requested value was ignored`);
|
|
589
|
+
protocolWarnings.push(...contextWarnings);
|
|
395
590
|
if (planEntries.length > 0 || planOverview !== undefined || planDetail !== undefined) {
|
|
396
591
|
out.plan = sanitizePlan(protocolWarnings);
|
|
397
592
|
}
|
|
398
593
|
// Most successful turns emit no todos at all, so an empty list would read as "nothing
|
|
399
594
|
// done" rather than "not tracked". Report only what the agent actually sent.
|
|
400
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
|
+
}
|
|
604
|
+
if (modeChanged) {
|
|
605
|
+
out.modeChanged = modeChanged;
|
|
606
|
+
protocolWarnings.push(`agent switched mode from ${modeChanged.from} to ${modeChanged.to} mid-session`);
|
|
607
|
+
}
|
|
401
608
|
if (protocolWarnings.length) out.protocolWarnings = protocolWarnings;
|
|
402
609
|
return out;
|
|
403
610
|
} catch (err) {
|
|
611
|
+
// A JSON-RPC code means the agent rejected something rather than the bridge breaking.
|
|
612
|
+
// Classifying it here is what lets the caller tell "fix your arguments" from "retry".
|
|
613
|
+
if (!err?.reason && typeof err?.code === "number") err.reason = "agent-error";
|
|
404
614
|
// A bare duration says nothing about whether the agent wedged or a command was just
|
|
405
615
|
// slow. Name what was outstanding so the caller can tell the two apart, and so a
|
|
406
616
|
// retry can resume from the work already done instead of restarting blind.
|
|
407
617
|
const isTimeout = err?.reason === "hard-cap" || err?.reason === "idle-timeout";
|
|
408
|
-
|
|
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") {
|
|
409
624
|
const age = fmtDuration(supervisor.msSinceActivity());
|
|
410
625
|
err.message += `\n\nLast ACP frame ${age} ago${lastToolLabel ? `; last tool call: ${lastToolLabel}` : ""}.`;
|
|
626
|
+
if (sessionTitle) err.message += ` The agent titled this turn ${JSON.stringify(sessionTitle)}.`;
|
|
411
627
|
if (sawTodoFrame) {
|
|
412
628
|
const { todoProgress } = sanitizeTodos([]);
|
|
413
629
|
const current = todoLabel();
|
|
@@ -416,6 +632,12 @@ export async function runDelegate({
|
|
|
416
632
|
}
|
|
417
633
|
const files = normalizeAgentReportedFiles([...touched], workspace);
|
|
418
634
|
if (files.length) err.message += ` Files reported edited: ${files.join(", ")}.`;
|
|
635
|
+
// Without this the resume hint below reads as "carry on from where you were", when the
|
|
636
|
+
// requested session was never loaded and this turn started from nothing.
|
|
637
|
+
if (resumeError) {
|
|
638
|
+
err.message += ` Note: resuming ${resumeSessionId} had already failed (${resumeError}),`
|
|
639
|
+
+ ` so this ran as a fresh session and none of that earlier work was in context.`;
|
|
640
|
+
}
|
|
419
641
|
if (sessionId) err.message += ` Resume with resumeSessionId ${sessionId}.`;
|
|
420
642
|
if (isTimeout) {
|
|
421
643
|
err.message += " cursor-agent does not stream shell output over ACP, so a long-running command emits"
|
|
@@ -423,10 +645,17 @@ export async function runDelegate({
|
|
|
423
645
|
+ " CURSOR_DELEGATE_HARD_CAP_MS.";
|
|
424
646
|
}
|
|
425
647
|
}
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
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
|
+
}
|
|
430
659
|
throw err;
|
|
431
660
|
} finally {
|
|
432
661
|
clearInterval(heartbeat);
|
package/src/doctor.js
CHANGED
package/src/jsonrpc.js
CHANGED
|
@@ -44,7 +44,13 @@ export class JsonRpcPeer {
|
|
|
44
44
|
const p = this.pending.get(msg.id);
|
|
45
45
|
if (p) {
|
|
46
46
|
this.pending.delete(msg.id);
|
|
47
|
-
|
|
47
|
+
// cursor-agent puts the actual reason in error.data.message; error.message alone
|
|
48
|
+
// is a bare "Invalid params".
|
|
49
|
+
if (msg.error) {
|
|
50
|
+
const err = new Error([msg.error.message || "rpc error", msg.error.data?.message].filter(Boolean).join(": "));
|
|
51
|
+
err.code = msg.error.code;
|
|
52
|
+
p.reject(err);
|
|
53
|
+
}
|
|
48
54
|
else p.resolve(msg.result);
|
|
49
55
|
}
|
|
50
56
|
} else if (msg.method && hasId) {
|
package/src/server.js
CHANGED
|
@@ -17,7 +17,10 @@ if (nodeMajor < 22) {
|
|
|
17
17
|
|
|
18
18
|
const inFlight = new Map();
|
|
19
19
|
|
|
20
|
-
|
|
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(),
|
|
@@ -36,10 +41,15 @@ const delegateOutputSchema = z.object({
|
|
|
36
41
|
),
|
|
37
42
|
questionsAsked: z.array(z.string()).optional(),
|
|
38
43
|
resumed: z.boolean().optional(),
|
|
44
|
+
sessionTitle: z.string().optional().describe(
|
|
45
|
+
"Short title the agent gave this turn. Present on most turns; purely a label."
|
|
46
|
+
),
|
|
39
47
|
autoAnswered: z.array(z.object({ prompt: z.string(), chosen: z.string() })).optional(),
|
|
40
48
|
fallbackAnswers: z.array(z.object({ prompt: z.string(), given: z.string(), chosen: z.string() })).optional(),
|
|
41
49
|
cancelRequested: z.boolean().optional(),
|
|
42
|
-
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
|
+
),
|
|
43
53
|
plan: z.object({
|
|
44
54
|
entries: z.array(planEntrySchema),
|
|
45
55
|
overview: z.string().optional(),
|
|
@@ -52,6 +62,12 @@ const delegateOutputSchema = z.object({
|
|
|
52
62
|
})).optional().describe(
|
|
53
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."
|
|
54
64
|
),
|
|
65
|
+
modeChanged: z.object({ from: z.string(), to: z.string() }).optional().describe(
|
|
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."
|
|
70
|
+
),
|
|
55
71
|
todoProgress: z.object({
|
|
56
72
|
total: z.number(),
|
|
57
73
|
completed: z.number(),
|
|
@@ -81,15 +97,35 @@ const doctorOutputSchema = z.object({
|
|
|
81
97
|
|
|
82
98
|
export const delegateInputSchema = z.object({
|
|
83
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."),
|
|
84
|
-
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."),
|
|
85
101
|
resumeSessionId: z.string().optional().describe("Resume an existing ACP session instead of a new one"),
|
|
86
|
-
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."),
|
|
87
103
|
model: z.string().trim().min(1, "model must be a non-empty string").default(DEFAULT_MODEL),
|
|
88
104
|
fast: z.boolean().default(false).describe("Fast speed tier — higher cost; enable only when the user asks"),
|
|
105
|
+
// Which options a model offers, and their valid values, are only knowable by asking the
|
|
106
|
+
// agent, so these stay open strings and the agent rejects what it does not accept.
|
|
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."),
|
|
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."),
|
|
89
110
|
});
|
|
90
111
|
|
|
112
|
+
// A cursor/ask_question question is multi-select when it sets allowMultiple, and the answer
|
|
113
|
+
// field (selectedOptionIds) is a list either way. Only split on commas for those, so a
|
|
114
|
+
// single-select label that itself contains a comma still matches whole.
|
|
115
|
+
function matchOptions(choice, opts = [], allowMultiple = false) {
|
|
116
|
+
const norm = (s) => String(s ?? "").trim().toLowerCase();
|
|
117
|
+
const ids = [];
|
|
118
|
+
for (const part of allowMultiple ? String(choice).split(",") : [String(choice)]) {
|
|
119
|
+
const want = norm(part);
|
|
120
|
+
if (!want) continue;
|
|
121
|
+
const hit = opts.find((o) => norm(o.id) === want || norm(o.label) === want);
|
|
122
|
+
if (hit && !ids.includes(hit.id)) ids.push(hit.id);
|
|
123
|
+
}
|
|
124
|
+
return ids;
|
|
125
|
+
}
|
|
126
|
+
|
|
91
127
|
export async function runDelegateTool({ args, extra, server, runDelegate, inFlight }) {
|
|
92
|
-
const { spec, mode, resumeSessionId, workspace, model, fast } = args;
|
|
128
|
+
const { spec, mode, resumeSessionId, workspace, model, fast, reasoning, context, contextFiles } = args;
|
|
93
129
|
|
|
94
130
|
const progressToken = extra?._meta?.progressToken;
|
|
95
131
|
let onProgress = () => {};
|
|
@@ -114,12 +150,15 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
|
|
|
114
150
|
for (const q of questions || []) {
|
|
115
151
|
const opts = q.options || [];
|
|
116
152
|
if (!supportsElicitation) {
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
153
|
+
// There is no user to ask, so allowMultiple changes nothing here: selecting every
|
|
154
|
+
// option would consent to more than the caller asked for. Take the first and
|
|
155
|
+
// disclose it. An option-less question answers empty rather than [null].
|
|
156
|
+
const first = opts[0];
|
|
157
|
+
autoAnswered.push({ prompt: String(q.prompt ?? ""), chosen: String(first?.label || first?.id || "") });
|
|
158
|
+
answers.push({ questionId: q.id, selectedOptionIds: first?.id ? [first.id] : [] });
|
|
121
159
|
continue;
|
|
122
160
|
}
|
|
161
|
+
const listing = opts.map((o) => o.label || o.id).join(", ");
|
|
123
162
|
const result = await server.server.elicitInput({
|
|
124
163
|
message: title ? `${title}: ${q.prompt}` : `cursor-agent asks: ${q.prompt}`,
|
|
125
164
|
requestedSchema: {
|
|
@@ -127,7 +166,11 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
|
|
|
127
166
|
properties: {
|
|
128
167
|
choice: {
|
|
129
168
|
type: "string",
|
|
130
|
-
description: opts.length
|
|
169
|
+
description: !opts.length
|
|
170
|
+
? "your answer"
|
|
171
|
+
: q.allowMultiple
|
|
172
|
+
? `Options (pick one or more, comma-separated): ${listing}`
|
|
173
|
+
: `Options: ${listing}`,
|
|
131
174
|
},
|
|
132
175
|
},
|
|
133
176
|
required: ["choice"],
|
|
@@ -135,23 +178,16 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
|
|
|
135
178
|
});
|
|
136
179
|
if (result.action !== "accept") return null;
|
|
137
180
|
const choice = result.content?.choice || "";
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
matched = true;
|
|
147
|
-
break;
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
if (!matched && opts.length) {
|
|
151
|
-
const chosen = opts.find((o) => o.id === chosenOptionId)?.label || chosenOptionId || "";
|
|
152
|
-
fallbackAnswers.push({ prompt: String(q.prompt ?? ""), given: String(choice), chosen: String(chosen) });
|
|
181
|
+
const selectedOptionIds = matchOptions(choice, opts, q.allowMultiple);
|
|
182
|
+
if (!selectedOptionIds.length && opts.length) {
|
|
183
|
+
selectedOptionIds.push(opts[0].id);
|
|
184
|
+
fallbackAnswers.push({
|
|
185
|
+
prompt: String(q.prompt ?? ""),
|
|
186
|
+
given: String(choice),
|
|
187
|
+
chosen: String(opts[0].label || opts[0].id || ""),
|
|
188
|
+
});
|
|
153
189
|
}
|
|
154
|
-
answers.push({ questionId: q.id, selectedOptionIds
|
|
190
|
+
answers.push({ questionId: q.id, selectedOptionIds });
|
|
155
191
|
}
|
|
156
192
|
return { answers };
|
|
157
193
|
};
|
|
@@ -166,6 +202,9 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
|
|
|
166
202
|
workspace: workspace || process.cwd(),
|
|
167
203
|
model,
|
|
168
204
|
fast,
|
|
205
|
+
reasoning,
|
|
206
|
+
context,
|
|
207
|
+
contextFiles,
|
|
169
208
|
onElicit,
|
|
170
209
|
onProgress,
|
|
171
210
|
signal: extra?.signal,
|
|
@@ -184,7 +223,9 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
|
|
|
184
223
|
};
|
|
185
224
|
} catch (err) {
|
|
186
225
|
return {
|
|
187
|
-
|
|
226
|
+
// The reason is already decided upstream; naming it here saves the caller parsing
|
|
227
|
+
// prose to tell a timeout from a rejected argument.
|
|
228
|
+
content: [{ type: "text", text: `delegate failed${err?.reason ? ` [${err.reason}]` : ""}: ` + (err?.message || String(err)) }],
|
|
188
229
|
isError: true,
|
|
189
230
|
};
|
|
190
231
|
} finally {
|
|
@@ -204,7 +245,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
204
245
|
"delegate",
|
|
205
246
|
{
|
|
206
247
|
description:
|
|
207
|
-
`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
|
|
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.`,
|
|
208
249
|
inputSchema: delegateInputSchema,
|
|
209
250
|
outputSchema: delegateOutputSchema,
|
|
210
251
|
annotations: {
|
|
@@ -247,7 +288,10 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
247
288
|
handle.cancelRequested = true;
|
|
248
289
|
await handle.client.cancel(sessionId).catch(() => {});
|
|
249
290
|
if (!force) {
|
|
250
|
-
|
|
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.
|
|
251
295
|
return {
|
|
252
296
|
content: [{ type: "text", text: `cancelled ${sessionId}` }],
|
|
253
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
|
|
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();
|