cursor-delegate-mcp 1.12.0 → 1.13.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/README.md +1 -1
- package/package.json +1 -1
- package/src/acp-client.js +1 -3
- package/src/delegate.js +60 -128
- package/src/doctor.js +0 -1
- package/src/request-router.js +1 -10
- package/src/server.js +11 -91
package/README.md
CHANGED
|
@@ -43,7 +43,7 @@ You → your agent (plans & reviews)
|
|
|
43
43
|
## Features
|
|
44
44
|
|
|
45
45
|
- 🤝 **Native plugins** — install into Claude Code, ChatGPT/Codex, or GitHub Copilot CLI and just say *"delegate this to Cursor"*. The shared skill teaches your agent how to delegate well.
|
|
46
|
-
- 💬 **No stalled runs** — if Cursor
|
|
46
|
+
- 💬 **No stalled runs** — if Cursor needs to clarify, it ends the turn and returns the question as a normal result. Your agent reads it and answers by resuming the same session — nothing blocks on a modal waiting for input.
|
|
47
47
|
- 📦 **Clean, typed results** — final answer, changed files, session id, and the plan, returned as validated structured output. Nothing to parse, nothing to guess.
|
|
48
48
|
- 📋 **Plan first** — `plan` mode: Cursor drafts a plan, you review it, then the same session implements it.
|
|
49
49
|
- 🔍 **Ask anything** — `ask` mode: read-only Q&A over your codebase, zero file changes.
|
package/package.json
CHANGED
package/src/acp-client.js
CHANGED
|
@@ -9,10 +9,9 @@ import { VERSION } from "./version.js";
|
|
|
9
9
|
const STDERR_CAP = 64 * 1024;
|
|
10
10
|
|
|
11
11
|
export class AcpClient extends EventEmitter {
|
|
12
|
-
constructor({ spawnSpec,
|
|
12
|
+
constructor({ spawnSpec, mode, onCreatePlan, onTodos } = {}) {
|
|
13
13
|
super();
|
|
14
14
|
this.spawnSpec = spawnSpec || resolveAcpSpawn();
|
|
15
|
-
this.onElicit = onElicit;
|
|
16
15
|
this.mode = mode;
|
|
17
16
|
this.onCreatePlan = onCreatePlan;
|
|
18
17
|
this.onTodos = onTodos;
|
|
@@ -51,7 +50,6 @@ export class AcpClient extends EventEmitter {
|
|
|
51
50
|
this.router = createRequestRouter({
|
|
52
51
|
respond: (id, r) => this.peer.respond(id, r),
|
|
53
52
|
respondError: (id, c, m) => this.peer.respondError(id, c, m),
|
|
54
|
-
onElicit: this.onElicit,
|
|
55
53
|
onCreatePlan: this.onCreatePlan,
|
|
56
54
|
onTodos: this.onTodos,
|
|
57
55
|
mode: this.mode,
|
package/src/delegate.js
CHANGED
|
@@ -23,6 +23,15 @@ function fmtDuration(ms) {
|
|
|
23
23
|
return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s`;
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
+
// Cutting a UTF-16 string at an arbitrary index can split a surrogate pair and leave a lone
|
|
27
|
+
// half-character — ill-formed Unicode that strict JSON consumers reject or mangle. Step back
|
|
28
|
+
// one unit when the boundary would land inside a pair.
|
|
29
|
+
function cutAtCodePoint(s, n) {
|
|
30
|
+
if (n >= s.length) return s;
|
|
31
|
+
const cu = s.charCodeAt(n - 1);
|
|
32
|
+
return s.slice(0, cu >= 0xd800 && cu <= 0xdbff ? n - 1 : n);
|
|
33
|
+
}
|
|
34
|
+
|
|
26
35
|
// Two different questions, and conflating them is what made a typo'd brief cost a live turn.
|
|
27
36
|
// "Could this be a path?" is deliberately loose — a one-line brief ending in .md is worth a
|
|
28
37
|
// stat. "Was a path clearly intended?" has to be strict, because an ordinary inline spec
|
|
@@ -169,20 +178,32 @@ function assertKnownModel(client, model) {
|
|
|
169
178
|
// rejection as the answer. Two distinct -32602s, both measured: "Unknown model config
|
|
170
179
|
// option: X" means this model has no such knob — report it and carry on. "Invalid value
|
|
171
180
|
// for X: Y" means the caller named a value the model rejects, which must not be swallowed.
|
|
172
|
-
// Returns true when the
|
|
181
|
+
// Returns { unsupported, res }: unsupported is true when the model has no such knob; res is the
|
|
182
|
+
// set_config_option reply, which echoes the now-current model's configOptions (incl. the served
|
|
183
|
+
// model id) — the only place the agent reports what model actually took after set_model.
|
|
173
184
|
async function applyConfig(client, sessionId, configId, value) {
|
|
174
185
|
try {
|
|
175
|
-
await client.setConfigOption(sessionId, configId, value);
|
|
176
|
-
return false;
|
|
186
|
+
const res = await client.setConfigOption(sessionId, configId, value);
|
|
187
|
+
return { unsupported: false, res };
|
|
177
188
|
} catch (err) {
|
|
178
189
|
if (err?.code !== -32602 || !/unknown model config option/i.test(err?.message || "")) throw err;
|
|
179
|
-
return true;
|
|
190
|
+
return { unsupported: true };
|
|
180
191
|
}
|
|
181
192
|
}
|
|
182
193
|
|
|
194
|
+
// The agent reports the resolved model only inside a set_config_option reply's configOptions
|
|
195
|
+
// (set_model itself returns nothing). Read it there when present; absent for models that reject
|
|
196
|
+
// every option we send, which is fine — the field then stays off.
|
|
197
|
+
function servedModelFrom(res) {
|
|
198
|
+
const opts = res?.configOptions;
|
|
199
|
+
if (!Array.isArray(opts)) return undefined;
|
|
200
|
+
const m = opts.find((o) => o?.id === "model");
|
|
201
|
+
return typeof m?.currentValue === "string" ? m.currentValue : undefined;
|
|
202
|
+
}
|
|
203
|
+
|
|
183
204
|
export async function runDelegate({
|
|
184
|
-
spec, mode = "agent", resumeSessionId, workspace,
|
|
185
|
-
model = DEFAULT_MODEL, fast = false, reasoning, context, contextFiles, clientFactory,
|
|
205
|
+
spec, mode = "agent", resumeSessionId, workspace,
|
|
206
|
+
model = DEFAULT_MODEL, fast = false, reasoning, context, contextFiles, clientFactory,
|
|
186
207
|
idleMs, handshakeMs, hardCapMs, timeoutMs,
|
|
187
208
|
onSessionReady, onProgress, progressThrottleMs = 2000,
|
|
188
209
|
heartbeatMs = DEFAULT_HEARTBEAT_MS,
|
|
@@ -202,17 +223,6 @@ export async function runDelegate({
|
|
|
202
223
|
const turnIdleMs = idleMs ?? envMs("CURSOR_DELEGATE_IDLE_MS", 0);
|
|
203
224
|
const MAX_OUTPUT = 10 * 1024 * 1024;
|
|
204
225
|
const TRUNCATION_MARKER = "\n\n[output truncated at 10MB]";
|
|
205
|
-
const questionsAsked = [];
|
|
206
|
-
const recordQuestions = (q) => {
|
|
207
|
-
if (q.kind !== "ask_question") return;
|
|
208
|
-
for (const question of q.questions || []) {
|
|
209
|
-
if (typeof question?.prompt === "string" && question.prompt) questionsAsked.push(question.prompt);
|
|
210
|
-
}
|
|
211
|
-
};
|
|
212
|
-
const wrappedElicit = onElicit
|
|
213
|
-
? async (q) => { recordQuestions(q); return onElicit(q); }
|
|
214
|
-
: async (q) => { recordQuestions(q); return null; };
|
|
215
|
-
|
|
216
226
|
// merge:false replaces the list, merge:true upserts by id. Entries always arrive complete,
|
|
217
227
|
// so a keyed set is enough — no field-level merging.
|
|
218
228
|
let todos = new Map();
|
|
@@ -309,7 +319,7 @@ export async function runDelegate({
|
|
|
309
319
|
};
|
|
310
320
|
|
|
311
321
|
const make = clientFactory || ((opts) => new AcpClient(opts));
|
|
312
|
-
const client = make({
|
|
322
|
+
const client = make({ mode, onCreatePlan: recordCreatePlan, onTodos: recordTodos });
|
|
313
323
|
const supervisor = new SessionSupervisor(client, { idleMs: turnIdleMs, handshakeMs: shakeMs, hardCapMs: capMs });
|
|
314
324
|
const onAbort = () => supervisor.abort();
|
|
315
325
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
@@ -342,8 +352,9 @@ export async function runDelegate({
|
|
|
342
352
|
resultChunks.push(text);
|
|
343
353
|
resultLength += text.length;
|
|
344
354
|
} else if (remaining > 0) {
|
|
345
|
-
|
|
346
|
-
|
|
355
|
+
const cut = cutAtCodePoint(text, remaining);
|
|
356
|
+
resultChunks.push(cut);
|
|
357
|
+
resultLength += cut.length;
|
|
347
358
|
truncated = true;
|
|
348
359
|
} else {
|
|
349
360
|
truncated = true;
|
|
@@ -414,19 +425,6 @@ export async function runDelegate({
|
|
|
414
425
|
// The bridge cannot see inside a running shell command, so a long silence is reported
|
|
415
426
|
// rather than acted on: the caller gets elapsed time and frame age and can decide.
|
|
416
427
|
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();
|
|
429
|
-
let modeChanged;
|
|
430
428
|
let sessionTitle;
|
|
431
429
|
let promptInFlight = false;
|
|
432
430
|
let heartbeat = null;
|
|
@@ -456,12 +454,6 @@ export async function runDelegate({
|
|
|
456
454
|
if (up.sessionUpdate === "plan") {
|
|
457
455
|
planEntries = up.entries || [];
|
|
458
456
|
}
|
|
459
|
-
// A plan-mode run that switches itself to agent mode becomes write-capable while the
|
|
460
|
-
// caller still believes nothing can change. No drift has been observed; report it so
|
|
461
|
-
// we find out rather than assume.
|
|
462
|
-
if (up.sessionUpdate === "current_mode_update" && up.currentModeId && up.currentModeId !== mode) {
|
|
463
|
-
modeChanged = { from: mode, to: up.currentModeId };
|
|
464
|
-
}
|
|
465
457
|
// The agent names the turn a beat after the prompt lands ("File Creator"). Useful as an
|
|
466
458
|
// ephemeral label while several delegations run, and in timeout forensics — but not in
|
|
467
459
|
// the result, where it arrives after there is nothing left to tell apart and has been
|
|
@@ -478,15 +470,6 @@ export async function runDelegate({
|
|
|
478
470
|
const label = up.title || up.kind || "tool";
|
|
479
471
|
const path = up.locations?.[0]?.path;
|
|
480
472
|
lastToolLabel = String(label) + (path ? " — " + path : "");
|
|
481
|
-
if (watchingWrites && WRITE_CAPABLE_KINDS.has(up.kind) && writeCapableActivity.length < WRITE_ACTIVITY_CAP) {
|
|
482
|
-
const entry = { kind: up.kind, detail: lastToolLabel.slice(0, 300) };
|
|
483
|
-
writeCapableActivity.push(entry);
|
|
484
|
-
// An execute call names itself — its title is the shell command. An edit call does
|
|
485
|
-
// not: the title is a bare "Edit File" and locations is empty, so the only thing
|
|
486
|
-
// separating docs/plan.md from src/api.js is the diff frame that follows. Keep the
|
|
487
|
-
// id so that frame can fill the path in.
|
|
488
|
-
if (up.toolCallId != null) writeActivityById.set(up.toolCallId, entry);
|
|
489
|
-
}
|
|
490
473
|
try { onProgress?.(("running: " + lastToolLabel).slice(0, 200)); } catch {}
|
|
491
474
|
}
|
|
492
475
|
if (up.sessionUpdate === "agent_message_chunk" && up.content?.text) {
|
|
@@ -499,18 +482,8 @@ export async function runDelegate({
|
|
|
499
482
|
for (const c of up.content || []) {
|
|
500
483
|
if (c.type === "diff" && c.path) {
|
|
501
484
|
touched.add(c.path);
|
|
502
|
-
const pending = writeActivityById.get(up.toolCallId);
|
|
503
|
-
if (pending && !pending.path) {
|
|
504
|
-
pending.path = normalizeAgentReportedFiles([c.path], workspace)[0];
|
|
505
|
-
}
|
|
506
485
|
try { onProgress?.("editing " + c.path); } catch {}
|
|
507
486
|
}
|
|
508
|
-
// cursor-agent has never been observed emitting these; ACP allows an agent to
|
|
509
|
-
// stream tool output this way, so treat it like message text rather than drop it.
|
|
510
|
-
if (c.type === "content" && typeof c.content?.text === "string") {
|
|
511
|
-
if (!sawToolCall || (collectingPostToolResult && activeToolCalls.size === 0)) appendResult(c.content.text);
|
|
512
|
-
messageProgress.push(c.content.text);
|
|
513
|
-
}
|
|
514
487
|
}
|
|
515
488
|
}
|
|
516
489
|
});
|
|
@@ -518,6 +491,7 @@ export async function runDelegate({
|
|
|
518
491
|
let sessionId;
|
|
519
492
|
let resumeError;
|
|
520
493
|
const unsupportedOptions = [];
|
|
494
|
+
let servedModel;
|
|
521
495
|
const contextWarnings = [];
|
|
522
496
|
try {
|
|
523
497
|
const res = await supervisor.supervise(async () => {
|
|
@@ -531,11 +505,16 @@ export async function runDelegate({
|
|
|
531
505
|
assertKnownModel(client, model);
|
|
532
506
|
await client.setModel(sessionId, model);
|
|
533
507
|
// fast is always sent: a resumed session may already have it on, so false is a real
|
|
534
|
-
// instruction. reasoning and context are only sent when the caller named one.
|
|
535
|
-
|
|
508
|
+
// instruction. reasoning and context are only sent when the caller named one. Each reply
|
|
509
|
+
// reports the now-current model; keep the last one seen as the served model.
|
|
510
|
+
const fastResult = await applyConfig(client, sessionId, "fast", fast);
|
|
511
|
+
if (fastResult.unsupported && fast) unsupportedOptions.push("fast");
|
|
512
|
+
else servedModel = servedModelFrom(fastResult.res) ?? servedModel;
|
|
536
513
|
for (const [id, value] of [["reasoning", reasoning], ["context", context]]) {
|
|
537
514
|
if (value === undefined) continue;
|
|
538
|
-
|
|
515
|
+
const r = await applyConfig(client, sessionId, id, value);
|
|
516
|
+
if (r.unsupported) unsupportedOptions.push(id);
|
|
517
|
+
else servedModel = servedModelFrom(r.res) ?? servedModel;
|
|
539
518
|
}
|
|
540
519
|
await client.setMode(sessionId, mode);
|
|
541
520
|
resetResult();
|
|
@@ -550,11 +529,8 @@ export async function runDelegate({
|
|
|
550
529
|
todos = new Map();
|
|
551
530
|
sawTodoFrame = false;
|
|
552
531
|
discardedResult = "";
|
|
553
|
-
writeCapableActivity = [];
|
|
554
|
-
writeActivityById = new Map();
|
|
555
532
|
touched.clear();
|
|
556
533
|
lastToolLabel = null;
|
|
557
|
-
modeChanged = undefined;
|
|
558
534
|
sessionTitle = undefined;
|
|
559
535
|
supervisor.promptStarted();
|
|
560
536
|
startHeartbeat();
|
|
@@ -574,44 +550,21 @@ export async function runDelegate({
|
|
|
574
550
|
: "none";
|
|
575
551
|
const protocolWarnings = [];
|
|
576
552
|
// plan.detail is the model restating — into chat's sibling channel — a plan it also filed via
|
|
577
|
-
// create_plan
|
|
578
|
-
// one ACP payload. The detail is never load-bearing: the plan lives in the agent's own session
|
|
553
|
+
// create_plan. The detail is never load-bearing: the plan lives in the agent's own session
|
|
579
554
|
// (which is what a resume-to-implement reads, not this field) and the orchestrator approves
|
|
580
|
-
// from result + plan.entries. So in plan/ask
|
|
581
|
-
//
|
|
582
|
-
//
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
dropPlanDetail = true;
|
|
588
|
-
if (!(finalMessageAvailable && result.length >= PLAN_TERSE_FLOOR)) {
|
|
589
|
-
result = planDetail;
|
|
590
|
-
resultSource = "plan-detail";
|
|
591
|
-
}
|
|
592
|
-
}
|
|
593
|
-
if (resultSource !== "plan-detail") {
|
|
594
|
-
if (!finalMessageAvailable && discardedResult) {
|
|
595
|
-
result = discardedResult;
|
|
596
|
-
resultSource = "pre-tool-fallback";
|
|
597
|
-
protocolWarnings.push(
|
|
598
|
-
"the agent ran a tool after its last message and never spoke again, so no final message closed the turn."
|
|
599
|
-
+ " result carries the last message before that tool call — it may be a preamble rather than the answer."
|
|
600
|
-
);
|
|
601
|
-
} else if (!finalMessageAvailable) {
|
|
602
|
-
protocolWarnings.push("the agent ended the turn without emitting any message; result is empty.");
|
|
603
|
-
}
|
|
604
|
-
}
|
|
605
|
-
// A runaway reply comes back whole and can blow the caller's context (104K chars in one
|
|
606
|
-
// test). When the caller sets a ceiling, cut the result to it and say so, so the truncation
|
|
607
|
-
// is never mistaken for a complete answer.
|
|
608
|
-
if (Number.isFinite(maxResultChars) && maxResultChars > 0 && result.length > maxResultChars) {
|
|
609
|
-
const original = result.length;
|
|
610
|
-
result = result.slice(0, maxResultChars) + `\n\n[result truncated at ${maxResultChars} chars]`;
|
|
555
|
+
// from result + plan.entries. So in plan/ask drop the detail and let result be the agent's own
|
|
556
|
+
// message verbatim — no bridge-side guess at whether that message "is really the plan". In
|
|
557
|
+
// agent mode the plan was accepted and result is the implementation report — both stay.
|
|
558
|
+
const dropPlanDetail = typeof planDetail === "string" && (mode === "plan" || mode === "ask");
|
|
559
|
+
if (!finalMessageAvailable && discardedResult) {
|
|
560
|
+
result = discardedResult;
|
|
561
|
+
resultSource = "pre-tool-fallback";
|
|
611
562
|
protocolWarnings.push(
|
|
612
|
-
|
|
613
|
-
+ "
|
|
563
|
+
"the agent ran a tool after its last message and never spoke again, so no final message closed the turn."
|
|
564
|
+
+ " result carries the last message before that tool call — it may be a preamble rather than the answer."
|
|
614
565
|
);
|
|
566
|
+
} else if (!finalMessageAvailable) {
|
|
567
|
+
protocolWarnings.push("the agent ended the turn without emitting any message; result is empty.");
|
|
615
568
|
}
|
|
616
569
|
let stopReason;
|
|
617
570
|
if (res?.stopReason !== undefined) {
|
|
@@ -635,16 +588,15 @@ export async function runDelegate({
|
|
|
635
588
|
if (filesReported.length) out.filesReportedByEditTools = filesReported;
|
|
636
589
|
// resultSource is a caveat, not a fact worth stating on every turn: on the happy path
|
|
637
590
|
// (post-tool / tool-free-stream) result is simply the answer, so say nothing. Surface it only
|
|
638
|
-
// when it warns — pre-tool-fallback,
|
|
639
|
-
//
|
|
640
|
-
//
|
|
641
|
-
// leaves it absent.
|
|
591
|
+
// when it warns — pre-tool-fallback, none. finalMessageAvailable is dropped outright: it
|
|
592
|
+
// stated the same thing in a second boolean. resumed is emitted only when a resume actually
|
|
593
|
+
// took; a fresh session or a failed resume (which carries its own warning) leaves it absent.
|
|
642
594
|
if (resultSource !== "post-tool" && resultSource !== "tool-free-stream") out.resultSource = resultSource;
|
|
643
595
|
if (!!resumeSessionId && sessionId === resumeSessionId) out.resumed = true;
|
|
596
|
+
// Only when the agent served a different model than asked — e.g. "default" routing to a
|
|
597
|
+
// concrete id, or a cross-model resume. Silence means the request was honored.
|
|
598
|
+
if (servedModel !== undefined && servedModel !== model) out.effectiveModel = servedModel;
|
|
644
599
|
if (stopReason !== undefined) out.stopReason = stopReason;
|
|
645
|
-
// Elicitation almost never fires (the agent tends to ask in prose and end the turn), so an
|
|
646
|
-
// always-empty array is steady noise. Report it only when a question actually came through.
|
|
647
|
-
if (questionsAsked.length) out.questionsAsked = questionsAsked;
|
|
648
600
|
// sessionTitle stays out of the result: it is a live label (progress) and a forensic one
|
|
649
601
|
// (timeout errors), not a fact about the finished turn.
|
|
650
602
|
if (resumeError) protocolWarnings.push(`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`);
|
|
@@ -652,9 +604,8 @@ export async function runDelegate({
|
|
|
652
604
|
protocolWarnings.push(...contextWarnings);
|
|
653
605
|
if (planEntries.length > 0 || planOverview !== undefined || planDetail !== undefined) {
|
|
654
606
|
out.plan = sanitizePlan(protocolWarnings);
|
|
655
|
-
// In plan/ask
|
|
656
|
-
//
|
|
657
|
-
// overview are structured and unique, and always stay.
|
|
607
|
+
// In plan/ask result already carries the agent's own plan message, so the detail here is a
|
|
608
|
+
// duplicate — drop it. entries and overview are structured and unique, and always stay.
|
|
658
609
|
if (dropPlanDetail) delete out.plan.detail;
|
|
659
610
|
}
|
|
660
611
|
// Most successful turns emit no todos at all, so an empty list would read as "nothing
|
|
@@ -666,25 +617,6 @@ export async function runDelegate({
|
|
|
666
617
|
out.todoProgress = todoProgress;
|
|
667
618
|
if (todoProgress.completed < todoProgress.total) out.todos = todoList;
|
|
668
619
|
}
|
|
669
|
-
if (writeCapableActivity.length) {
|
|
670
|
-
out.writeCapableActivity = writeCapableActivity;
|
|
671
|
-
// "the diff for what changed" overclaims when every entry is a pathless execute — live
|
|
672
|
-
// runs drew the same warning for read-only commands (git log, git show, ls -la) as for
|
|
673
|
-
// a real write. Hedge when nothing reported a path.
|
|
674
|
-
const anyPath = writeCapableActivity.some((a) => a.path);
|
|
675
|
-
protocolWarnings.push(
|
|
676
|
-
`mode ${mode} asked the agent not to change anything, but it ran ${writeCapableActivity.length}`
|
|
677
|
-
+ ` write-capable tool call${writeCapableActivity.length === 1 ? "" : "s"} — see writeCapableActivity`
|
|
678
|
-
+ " for what ran"
|
|
679
|
-
+ (anyPath
|
|
680
|
-
? ", and the diff for what changed."
|
|
681
|
-
: "; none reported touching a file, so this may be read-only activity — check the git diff to confirm nothing changed.")
|
|
682
|
-
);
|
|
683
|
-
}
|
|
684
|
-
if (modeChanged) {
|
|
685
|
-
out.modeChanged = modeChanged;
|
|
686
|
-
protocolWarnings.push(`agent switched mode from ${modeChanged.from} to ${modeChanged.to} mid-session`);
|
|
687
|
-
}
|
|
688
620
|
if (protocolWarnings.length) out.protocolWarnings = protocolWarnings;
|
|
689
621
|
return out;
|
|
690
622
|
} catch (err) {
|
package/src/doctor.js
CHANGED
package/src/request-router.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const ACK_METHODS = new Set(["cursor/task", "cursor/generate_image"]);
|
|
2
2
|
|
|
3
|
-
export function createRequestRouter({ respond, respondError,
|
|
3
|
+
export function createRequestRouter({ respond, respondError, onCreatePlan, onTodos, mode = "agent", log = () => {} }) {
|
|
4
4
|
return async function handle(id, method, params) {
|
|
5
5
|
try {
|
|
6
6
|
if (method === "session/request_permission") {
|
|
@@ -11,15 +11,6 @@ export function createRequestRouter({ respond, respondError, onElicit, onCreateP
|
|
|
11
11
|
opts[0];
|
|
12
12
|
return respond(id, { outcome: { outcome: "selected", optionId: pick?.optionId } });
|
|
13
13
|
}
|
|
14
|
-
if (method === "cursor/ask_question") {
|
|
15
|
-
const ans = onElicit
|
|
16
|
-
? await onElicit({ kind: "ask_question", title: params?.title, questions: params?.questions || [], raw: params })
|
|
17
|
-
: null;
|
|
18
|
-
if (ans?.answers?.length) {
|
|
19
|
-
return respond(id, { outcome: { outcome: "answered", answers: ans.answers } });
|
|
20
|
-
}
|
|
21
|
-
return respond(id, { outcome: { outcome: "cancelled" } });
|
|
22
|
-
}
|
|
23
14
|
if (method === "cursor/create_plan") {
|
|
24
15
|
onCreatePlan?.({
|
|
25
16
|
overview: params?.overview,
|
package/src/server.js
CHANGED
|
@@ -40,8 +40,11 @@ const planEntrySchema = z.object({
|
|
|
40
40
|
|
|
41
41
|
const delegateOutputSchema = z.object({
|
|
42
42
|
result: z.string(),
|
|
43
|
-
resultSource: z.enum(["pre-tool-fallback", "
|
|
44
|
-
"Present only as a caveat on result; absent on the happy path, where result is simply the agent's answer. pre-tool-fallback: no final message closed the turn and result is the last message before the agent's final tool call — read protocolWarnings before trusting it.
|
|
43
|
+
resultSource: z.enum(["pre-tool-fallback", "none"]).optional().describe(
|
|
44
|
+
"Present only as a caveat on result; absent on the happy path, where result is simply the agent's answer. pre-tool-fallback: no final message closed the turn and result is the last message before the agent's final tool call — read protocolWarnings before trusting it. none: the turn produced no message and result is empty."
|
|
45
|
+
),
|
|
46
|
+
effectiveModel: z.string().optional().describe(
|
|
47
|
+
"The model id the agent reported serving, present only when it differs from the model you requested — e.g. \"default\" resolving to a concrete id, or a cross-model resume. Read from the agent's post-set_model config report; absent when the agent confirmed the requested id or reported no model (some models report none)."
|
|
45
48
|
),
|
|
46
49
|
stopReason: z.string().optional().describe(
|
|
47
50
|
"Present only when it is not the ordinary end_turn — a refusal, a cancel, or an output cap. Absence means the turn ended normally."
|
|
@@ -50,24 +53,19 @@ const delegateOutputSchema = z.object({
|
|
|
50
53
|
filesReportedByEditTools: z.array(z.string()).optional().describe(
|
|
51
54
|
"Files the agent's edit tools reported changing, via native ACP diff events. Absent when they reported none — which is not proof nothing changed: shell-driven edits leave no diff event; the git diff is authoritative."
|
|
52
55
|
),
|
|
53
|
-
questionsAsked: z.array(z.string()).optional().describe(
|
|
54
|
-
"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."
|
|
55
|
-
),
|
|
56
56
|
resumed: z.boolean().optional().describe(
|
|
57
57
|
"Present and true only when a requested resume took (the returned session id matched resumeSessionId). Absent for a fresh session, or when a resume failed — a failed resume is reported in protocolWarnings."
|
|
58
58
|
),
|
|
59
|
-
autoAnswered: z.array(z.object({ prompt: z.string(), chosen: z.string() })).optional(),
|
|
60
|
-
fallbackAnswers: z.array(z.object({ prompt: z.string(), given: z.string(), chosen: z.string() })).optional(),
|
|
61
59
|
cancelRequested: z.boolean().optional(),
|
|
62
60
|
protocolWarnings: z.array(z.string()).optional().describe(
|
|
63
|
-
"Non-fatal diagnostics that did not justify failing the call — dropped or sanitized ACP fields, a failed resume, ignored model options, skipped contextFiles
|
|
61
|
+
"Non-fatal diagnostics that did not justify failing the call — dropped or sanitized ACP fields, a failed resume, ignored model options, skipped contextFiles. Read whenever present."
|
|
64
62
|
),
|
|
65
63
|
plan: z.object({
|
|
66
64
|
entries: z.array(planEntrySchema),
|
|
67
65
|
overview: z.string().optional(),
|
|
68
66
|
detail: z.string().optional(),
|
|
69
67
|
}).optional().describe(
|
|
70
|
-
"The agent's plan. entries and overview are the structured plan and always present when a plan exists. detail (a prose rendition the agent also filed) is kept only in agent mode; in plan/ask it is dropped because result already carries the
|
|
68
|
+
"The agent's plan. entries and overview are the structured plan and always present when a plan exists. detail (a prose rendition the agent also filed) is kept only in agent mode; in plan/ask it is dropped because result already carries the agent's own plan message. To act on a plan, resume the sessionId rather than forwarding detail: the plan lives in the agent's session."
|
|
71
69
|
),
|
|
72
70
|
todos: z.array(z.object({
|
|
73
71
|
id: z.string(),
|
|
@@ -76,12 +74,6 @@ const delegateOutputSchema = z.object({
|
|
|
76
74
|
})).optional().describe(
|
|
77
75
|
"Todo items the agent left unfinished, present only when todoProgress shows completed < total — read it to see what remains before resuming. Absent both when the agent tracked no todos (common on short tasks) and when everything tracked was completed; todoProgress tells those apart."
|
|
78
76
|
),
|
|
79
|
-
modeChanged: z.object({ from: z.string(), to: z.string() }).optional().describe(
|
|
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 — kind is what the tool could do, not proof it wrote: an execute entry may be a read-only command like `ls -la`. Read detail for the evidence and the git diff for the truth. Only populated for mode plan and ask."
|
|
84
|
-
),
|
|
85
77
|
todoProgress: z.object({
|
|
86
78
|
total: z.number(),
|
|
87
79
|
completed: z.number(),
|
|
@@ -96,7 +88,6 @@ const doctorOutputSchema = z.object({
|
|
|
96
88
|
name: z.string().nullable(),
|
|
97
89
|
version: z.string().nullable(),
|
|
98
90
|
capabilities: z.record(z.unknown()),
|
|
99
|
-
supportsElicitation: z.boolean(),
|
|
100
91
|
}).passthrough(),
|
|
101
92
|
agent: z.object({ found: z.boolean() }).passthrough(),
|
|
102
93
|
runtime: z.object({
|
|
@@ -111,7 +102,7 @@ const doctorOutputSchema = z.object({
|
|
|
111
102
|
|
|
112
103
|
export const delegateInputSchema = z.object({
|
|
113
104
|
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
|
|
105
|
+
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, so review the git diff after every run. ask held on every model tested while plan compliance varies by model, so prefer ask when you need the stricter read-only instruction."),
|
|
115
106
|
resumeSessionId: z.string().optional().describe("Resume an existing ACP session instead of a new one"),
|
|
116
107
|
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."),
|
|
117
108
|
model: z.string().trim().min(1, "model must be a non-empty string").default(DEFAULT_MODEL),
|
|
@@ -121,26 +112,10 @@ export const delegateInputSchema = z.object({
|
|
|
121
112
|
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."),
|
|
122
113
|
context: z.string().trim().min(1).optional().describe("Context window size. Not offered by every model; gpt-5.x accepts 272k and 1m."),
|
|
123
114
|
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."),
|
|
125
115
|
});
|
|
126
116
|
|
|
127
|
-
// A cursor/ask_question question is multi-select when it sets allowMultiple, and the answer
|
|
128
|
-
// field (selectedOptionIds) is a list either way. Only split on commas for those, so a
|
|
129
|
-
// single-select label that itself contains a comma still matches whole.
|
|
130
|
-
function matchOptions(choice, opts = [], allowMultiple = false) {
|
|
131
|
-
const norm = (s) => String(s ?? "").trim().toLowerCase();
|
|
132
|
-
const ids = [];
|
|
133
|
-
for (const part of allowMultiple ? String(choice).split(",") : [String(choice)]) {
|
|
134
|
-
const want = norm(part);
|
|
135
|
-
if (!want) continue;
|
|
136
|
-
const hit = opts.find((o) => norm(o.id) === want || norm(o.label) === want);
|
|
137
|
-
if (hit && !ids.includes(hit.id)) ids.push(hit.id);
|
|
138
|
-
}
|
|
139
|
-
return ids;
|
|
140
|
-
}
|
|
141
|
-
|
|
142
117
|
export async function runDelegateTool({ args, extra, server, runDelegate, inFlight, seenSessions = new Set() }) {
|
|
143
|
-
const { spec, mode, resumeSessionId, workspace, model, fast, reasoning, context, contextFiles
|
|
118
|
+
const { spec, mode, resumeSessionId, workspace, model, fast, reasoning, context, contextFiles } = args;
|
|
144
119
|
|
|
145
120
|
const progressToken = extra?._meta?.progressToken;
|
|
146
121
|
let onProgress = () => {};
|
|
@@ -156,57 +131,6 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
|
|
|
156
131
|
};
|
|
157
132
|
}
|
|
158
133
|
|
|
159
|
-
const supportsElicitation = !!server.server.getClientCapabilities?.()?.elicitation;
|
|
160
|
-
const autoAnswered = [];
|
|
161
|
-
const fallbackAnswers = [];
|
|
162
|
-
|
|
163
|
-
const onElicit = async ({ title, questions }) => {
|
|
164
|
-
const answers = [];
|
|
165
|
-
for (const q of questions || []) {
|
|
166
|
-
const opts = q.options || [];
|
|
167
|
-
if (!supportsElicitation) {
|
|
168
|
-
// There is no user to ask, so allowMultiple changes nothing here: selecting every
|
|
169
|
-
// option would consent to more than the caller asked for. Take the first and
|
|
170
|
-
// disclose it. An option-less question answers empty rather than [null].
|
|
171
|
-
const first = opts[0];
|
|
172
|
-
autoAnswered.push({ prompt: String(q.prompt ?? ""), chosen: String(first?.label || first?.id || "") });
|
|
173
|
-
answers.push({ questionId: q.id, selectedOptionIds: first?.id ? [first.id] : [] });
|
|
174
|
-
continue;
|
|
175
|
-
}
|
|
176
|
-
const listing = opts.map((o) => o.label || o.id).join(", ");
|
|
177
|
-
const result = await server.server.elicitInput({
|
|
178
|
-
message: title ? `${title}: ${q.prompt}` : `cursor-agent asks: ${q.prompt}`,
|
|
179
|
-
requestedSchema: {
|
|
180
|
-
type: "object",
|
|
181
|
-
properties: {
|
|
182
|
-
choice: {
|
|
183
|
-
type: "string",
|
|
184
|
-
description: !opts.length
|
|
185
|
-
? "your answer"
|
|
186
|
-
: q.allowMultiple
|
|
187
|
-
? `Options (pick one or more, comma-separated): ${listing}`
|
|
188
|
-
: `Options: ${listing}`,
|
|
189
|
-
},
|
|
190
|
-
},
|
|
191
|
-
required: ["choice"],
|
|
192
|
-
},
|
|
193
|
-
});
|
|
194
|
-
if (result.action !== "accept") return null;
|
|
195
|
-
const choice = result.content?.choice || "";
|
|
196
|
-
const selectedOptionIds = matchOptions(choice, opts, q.allowMultiple);
|
|
197
|
-
if (!selectedOptionIds.length && opts.length) {
|
|
198
|
-
selectedOptionIds.push(opts[0].id);
|
|
199
|
-
fallbackAnswers.push({
|
|
200
|
-
prompt: String(q.prompt ?? ""),
|
|
201
|
-
given: String(choice),
|
|
202
|
-
chosen: String(opts[0].label || opts[0].id || ""),
|
|
203
|
-
});
|
|
204
|
-
}
|
|
205
|
-
answers.push({ questionId: q.id, selectedOptionIds });
|
|
206
|
-
}
|
|
207
|
-
return { answers };
|
|
208
|
-
};
|
|
209
|
-
|
|
210
134
|
let capturedSessionId;
|
|
211
135
|
let handle;
|
|
212
136
|
try {
|
|
@@ -220,8 +144,6 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
|
|
|
220
144
|
reasoning,
|
|
221
145
|
context,
|
|
222
146
|
contextFiles,
|
|
223
|
-
maxResultChars,
|
|
224
|
-
onElicit,
|
|
225
147
|
onProgress,
|
|
226
148
|
signal: extra?.signal,
|
|
227
149
|
onSessionReady: (sessionId, client) => {
|
|
@@ -236,8 +158,6 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
|
|
|
236
158
|
onProgress(`session ready: ${sessionId}`);
|
|
237
159
|
},
|
|
238
160
|
});
|
|
239
|
-
if (autoAnswered.length) out.autoAnswered = autoAnswered;
|
|
240
|
-
if (fallbackAnswers.length) out.fallbackAnswers = fallbackAnswers;
|
|
241
161
|
if (handle?.cancelRequested) out.cancelRequested = true;
|
|
242
162
|
return {
|
|
243
163
|
content: [{ type: "text", text: JSON.stringify(out, null, 2) }],
|
|
@@ -267,7 +187,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
267
187
|
"delegate",
|
|
268
188
|
{
|
|
269
189
|
description:
|
|
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
|
|
190
|
+
`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. Clarifying questions arrive as prose in result — resume with resumeSessionId to answer. Returns the final result, selection source, stop reason, session ID, agent-reported files, and optional plan. See the delegate skill for orchestration.`,
|
|
271
191
|
inputSchema: delegateInputSchema,
|
|
272
192
|
outputSchema: delegateOutputSchema,
|
|
273
193
|
annotations: {
|
|
@@ -344,7 +264,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
344
264
|
"doctor",
|
|
345
265
|
{
|
|
346
266
|
description:
|
|
347
|
-
"Report setup and health diagnostics: plugin version, MCP client capabilities
|
|
267
|
+
"Report setup and health diagnostics: plugin version, MCP client capabilities, cursor-agent launcher resolution, and optional deep ACP handshake. Use when delegation fails or agent.found is false.",
|
|
348
268
|
inputSchema: {
|
|
349
269
|
deep: z
|
|
350
270
|
.boolean()
|