cursor-delegate-mcp 1.19.0 → 1.21.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 +5 -3
- package/SECURITY.md +14 -6
- package/package.json +1 -1
- package/src/acp-client.js +48 -10
- package/src/delegate.js +86 -28
- package/src/doctor.js +8 -4
- package/src/model-options.js +20 -25
- package/src/proc.js +14 -2
- package/src/server.js +61 -33
package/README.md
CHANGED
|
@@ -24,7 +24,7 @@ Cursor Delegate is the MCP bridge that lets Claude Code, ChatGPT/Codex, Copilot
|
|
|
24
24
|
|
|
25
25
|
## 🧠 Frontier quality, kept
|
|
26
26
|
|
|
27
|
-
Your assistant does what frontier models are
|
|
27
|
+
Your assistant does what frontier models are for: understands the task, writes a precise brief, reviews the finished diff. **Composer 2.5** runs the implementation loop under that brief. The bundled skill puts the review step in the loop — the agent that scoped the work reads the changed files back before reporting.
|
|
28
28
|
|
|
29
29
|
## ⚡ Done faster
|
|
30
30
|
|
|
@@ -42,12 +42,14 @@ Composer and Grok run on their **own usage allowance** on every Cursor plan —
|
|
|
42
42
|
|
|
43
43
|
- 🤝 **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.
|
|
44
44
|
- 💬 **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.
|
|
45
|
-
- 📦 **Clean, named results** — final answer, changed files, session id, and the plan, returned as one compact JSON payload. Nothing to scrape
|
|
45
|
+
- 📦 **Clean, named results** — final answer, changed files, session id, and the plan, returned as one compact JSON payload. Nothing to scrape.
|
|
46
46
|
- 📋 **Plan first** — `plan` mode: Cursor drafts a plan, you review it, then the same session implements it.
|
|
47
|
-
- 🔍 **Ask anything** — `ask` mode:
|
|
47
|
+
- 🔍 **Ask anything** — `ask` mode: Q&A over your codebase.
|
|
48
48
|
- 🩺 **Self-diagnosing** — a `doctor` tool that tells you exactly what's missing if setup isn't right.
|
|
49
49
|
- 🔌 **Portable** — plain stdio MCP, so it runs anywhere: VS Code, JetBrains, Windsurf, Visual Studio, and more.
|
|
50
50
|
|
|
51
|
+
`plan` and `ask` are instructions to the agent, and `workspace` is its working directory — [Security](SECURITY.md) and the [delegate reference](skills/delegate/reference.md) spell out what the bridge enforces and what it reports back.
|
|
52
|
+
|
|
51
53
|
## Install
|
|
52
54
|
|
|
53
55
|
You need [Node.js 20+](https://nodejs.org/) and the [Cursor CLI](https://cursor.com/docs/cli/overview), logged in (`cursor-agent login`).
|
package/SECURITY.md
CHANGED
|
@@ -2,17 +2,25 @@
|
|
|
2
2
|
|
|
3
3
|
## What this plugin does
|
|
4
4
|
|
|
5
|
-
`cursor-delegate-mcp` spawns **cursor-agent** in your workspace and **auto-approves
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
`cursor-delegate-mcp` spawns **cursor-agent** in your workspace and **auto-approves every
|
|
6
|
+
permission it requests** over ACP, in every mode — `agent`, `plan` and `ask`. Each request is
|
|
7
|
+
answered with the broadest allow option the agent offered (`allow_always`, else `allow_once`).
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
`workspace` is the agent's working directory, and a run can reach outside it. `mode` is
|
|
10
|
+
passed to the agent as an instruction, so `plan` and `ask` describe how it behaves rather
|
|
11
|
+
than what it is permitted to do. Delegated tasks can create, modify, or delete files
|
|
12
|
+
anywhere your user account can reach, and reach the network.
|
|
13
|
+
|
|
14
|
+
Treat every `delegate` call like handing an engineer a shell on your machine. Your MCP host
|
|
15
|
+
is the orchestrator: it should scope the brief, then review `filesReportedByEditTools` and
|
|
16
|
+
the git diff. That field lists what the agent's edit tools reported touching; the git diff
|
|
17
|
+
is authoritative.
|
|
10
18
|
|
|
11
19
|
## Recommendations
|
|
12
20
|
|
|
13
21
|
- Point `workspace` at the smallest directory that contains the task (not `$HOME` or `/`).
|
|
14
|
-
|
|
15
|
-
-
|
|
22
|
+
It scopes what the agent works on, not what it can reach.
|
|
23
|
+
- Review the git diff before committing, after every run — including `plan` and `ask` ones.
|
|
16
24
|
- Run verification (tests, lint) after delegation — the delegate skill asks Claude to do
|
|
17
25
|
this, but automated gates in CI are still your backstop.
|
|
18
26
|
- Do not commit secrets (`.env`, credentials, tokens). The bridge does not redact them from
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cursor-delegate-mcp",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.21.0",
|
|
4
4
|
"mcpName": "io.github.andreilungeanu/cursor-delegate-mcp",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Delegate multi-file coding work from Claude Code, Codex, or Copilot to Cursor's CLI agent — structured results, plan mode, and changed files.",
|
package/src/acp-client.js
CHANGED
|
@@ -4,11 +4,14 @@ import { StringDecoder } from "node:string_decoder";
|
|
|
4
4
|
import { JsonRpcPeer } from "./jsonrpc.js";
|
|
5
5
|
import { createRequestRouter } from "./request-router.js";
|
|
6
6
|
import { resolveAcpSpawn } from "./spawn.js";
|
|
7
|
-
import { isChildAlive, treeKill } from "./proc.js";
|
|
7
|
+
import { DETACHED, isChildAlive, treeKill } from "./proc.js";
|
|
8
8
|
import { VERSION } from "./version.js";
|
|
9
9
|
import { makeError } from "./errors.js";
|
|
10
10
|
|
|
11
11
|
const STDERR_CAP = 64 * 1024;
|
|
12
|
+
// How long stop() waits for the child to actually exit after the kill is dispatched. SIGKILL and
|
|
13
|
+
// taskkill /F land in milliseconds, so this only ever elapses when the kill did not work.
|
|
14
|
+
const STOP_EXIT_TIMEOUT_MS = 2000;
|
|
12
15
|
|
|
13
16
|
export class AcpClient extends EventEmitter {
|
|
14
17
|
/**
|
|
@@ -27,6 +30,8 @@ export class AcpClient extends EventEmitter {
|
|
|
27
30
|
this.onTodos = onTodos;
|
|
28
31
|
this._stderrChunks = [];
|
|
29
32
|
this._stderrLength = 0;
|
|
33
|
+
/** @type {Promise<boolean> | null} */
|
|
34
|
+
this._stopping = null;
|
|
30
35
|
}
|
|
31
36
|
|
|
32
37
|
// The tail of stderr, which is what an exit error quotes. Kept as chunks and joined on read:
|
|
@@ -44,7 +49,7 @@ export class AcpClient extends EventEmitter {
|
|
|
44
49
|
this._stderrLength = 0;
|
|
45
50
|
const stderrDecoder = new StringDecoder("utf8");
|
|
46
51
|
this._exitEmitted = false;
|
|
47
|
-
this.child = spawn(command, args, { ...options, stdio: ["pipe", "pipe", "pipe"] });
|
|
52
|
+
this.child = spawn(command, args, { ...options, detached: DETACHED, stdio: ["pipe", "pipe", "pipe"] });
|
|
48
53
|
this.child.stderr.on("data", (chunk) => {
|
|
49
54
|
const text = stderrDecoder.write(chunk);
|
|
50
55
|
if (text) {
|
|
@@ -61,8 +66,9 @@ export class AcpClient extends EventEmitter {
|
|
|
61
66
|
this.child.stderr.on("error", () => {});
|
|
62
67
|
// A supervisor trip writes session/cancel, which can land after the agent is already gone.
|
|
63
68
|
// Without a handler that surfaces as an unhandled 'error' event on some platforms, taking
|
|
64
|
-
// the whole MCP server down with it.
|
|
69
|
+
// the whole MCP server down with it. stdout needs the same guard; readline adds none.
|
|
65
70
|
this.child.stdin.on("error", () => {});
|
|
71
|
+
this.child.stdout.on("error", () => {});
|
|
66
72
|
const emitExit = (code, signal) => {
|
|
67
73
|
if (this._exitEmitted) return;
|
|
68
74
|
this._exitEmitted = true;
|
|
@@ -80,7 +86,11 @@ export class AcpClient extends EventEmitter {
|
|
|
80
86
|
this.router = null; // set before first stdout line
|
|
81
87
|
this.peer = new JsonRpcPeer(this.child.stdout, this.child.stdin, {
|
|
82
88
|
onNotification: (method, params) => { if (method === "session/update") this.emit("update", params); },
|
|
83
|
-
|
|
89
|
+
// The router is async and its result discarded, so a throw from its own catch would reject
|
|
90
|
+
// unobserved and exit the process. Promise.resolve covers a sync router in tests.
|
|
91
|
+
onRequest: (id, method, params) => {
|
|
92
|
+
if (this.router) Promise.resolve(this.router(id, method, params)).catch(() => {});
|
|
93
|
+
},
|
|
84
94
|
onActivity: () => this.emit("activity"),
|
|
85
95
|
});
|
|
86
96
|
this.router = createRequestRouter({
|
|
@@ -126,12 +136,40 @@ export class AcpClient extends EventEmitter {
|
|
|
126
136
|
|
|
127
137
|
getTranscript(n) { return this.peer ? this.peer.formatLog(n) : ""; }
|
|
128
138
|
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
139
|
+
// Idempotent, so a force-cancel racing the delegation's own finally tears down once and both
|
|
140
|
+
// see the same answer. Resolves true when the child was observed to exit, false when the bound
|
|
141
|
+
// elapsed first: dispatching a signal is not the same fact as the process being gone, and
|
|
142
|
+
// cancel reports the difference rather than calling both "killed".
|
|
143
|
+
stop({ timeoutMs = STOP_EXIT_TIMEOUT_MS } = {}) {
|
|
144
|
+
if (!this._stopping) this._stopping = this._teardown(timeoutMs);
|
|
145
|
+
return this._stopping;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async _teardown(timeoutMs) {
|
|
149
|
+
const child = this.child;
|
|
150
|
+
if (!child?.pid) {
|
|
151
|
+
try { this.peer?.close(); } catch {}
|
|
152
|
+
return true;
|
|
135
153
|
}
|
|
154
|
+
const alive = isChildAlive(child);
|
|
155
|
+
// Subscribed before the kill is dispatched. A child that dies immediately would otherwise
|
|
156
|
+
// exit in the gap and leave this waiting on an event that has already fired.
|
|
157
|
+
const exited = alive
|
|
158
|
+
? /** @type {Promise<boolean>} */ (new Promise((resolve) => child.once("exit", () => resolve(true))))
|
|
159
|
+
: Promise.resolve(true);
|
|
160
|
+
// Runs for an exited child too: the agent can be gone while the commands it spawned are still
|
|
161
|
+
// running, and on POSIX they stay in its process group, which is the only handle left on them.
|
|
162
|
+
treeKill(child.pid, { childAlive: alive }).catch(() => {});
|
|
163
|
+
/** @type {NodeJS.Timeout | undefined} */
|
|
164
|
+
let timer;
|
|
165
|
+
const bounded = /** @type {Promise<boolean>} */ (new Promise((resolve) => {
|
|
166
|
+
timer = setTimeout(() => resolve(false), timeoutMs);
|
|
167
|
+
}));
|
|
168
|
+
const observed = await Promise.race([exited, bounded]);
|
|
169
|
+
clearTimeout(timer);
|
|
170
|
+
// Pending RPCs are left to the exit handler, which rejects them with agent-exit. Rejecting
|
|
171
|
+
// them here too would settle the same promises twice for no new information.
|
|
172
|
+
try { this.peer?.close(); } catch {}
|
|
173
|
+
return observed;
|
|
136
174
|
}
|
|
137
175
|
}
|
package/src/delegate.js
CHANGED
|
@@ -12,7 +12,7 @@ import { normalizeAgentReportedFiles } from "./agent-reported-files.js";
|
|
|
12
12
|
import { makeTurnState } from "./turn-state.js";
|
|
13
13
|
import { makeError } from "./errors.js";
|
|
14
14
|
import { PLAN_PRIORITIES, PLAN_STATUSES, TODO_STATUSES } from "./acp-enums.js";
|
|
15
|
-
import { optionsFrom,
|
|
15
|
+
import { optionsFrom, resolveEffort, unsupportedWarning } from "./model-options.js";
|
|
16
16
|
|
|
17
17
|
export const DEFAULT_MODEL = "composer-2.5";
|
|
18
18
|
export const DEFAULT_HANDSHAKE_MS = 60000;
|
|
@@ -143,12 +143,32 @@ async function buildContextBlocks(contextFiles, workspace, client, warnings) {
|
|
|
143
143
|
return blocks;
|
|
144
144
|
}
|
|
145
145
|
|
|
146
|
+
// Only a session the agent does not have justifies a fresh one; falling back on anything else
|
|
147
|
+
// runs the task without the context the caller asked for. Code and wording together, never
|
|
148
|
+
// either: 2026.08.11 returns -32602 `Session "<id>" not found` when it is missing, but -32603
|
|
149
|
+
// `Failed to load session "<id>": <cause>` when restore fails, and that cause can carry the
|
|
150
|
+
// same words. A missed match costs a recoverable resume-failed; a false match costs a silent turn.
|
|
151
|
+
function isMissingSession(err) {
|
|
152
|
+
const message = err?.message || "";
|
|
153
|
+
return err?.code === -32602
|
|
154
|
+
&& /\bsession\b/i.test(message)
|
|
155
|
+
&& /\bnot found\b|\bdoes not exist\b|\bunknown session\b|\bno such session\b/i.test(message);
|
|
156
|
+
}
|
|
157
|
+
|
|
146
158
|
async function openSession(client, resumeSessionId, workspace) {
|
|
147
159
|
if (!resumeSessionId) return client.newSession(workspace);
|
|
148
160
|
try {
|
|
149
161
|
await client.loadSession(resumeSessionId, workspace);
|
|
150
162
|
return { sessionId: resumeSessionId }; // load does not echo sessionId
|
|
151
163
|
} catch (err) {
|
|
164
|
+
if (!isMissingSession(err)) {
|
|
165
|
+
throw makeError(
|
|
166
|
+
"resume-failed",
|
|
167
|
+
`session ${resumeSessionId} could not be loaded: ${err?.message || String(err)}.`
|
|
168
|
+
+ ` The session was not resumed and no fresh session was started — retry, or omit`
|
|
169
|
+
+ ` resumeSessionId to start fresh deliberately.`
|
|
170
|
+
);
|
|
171
|
+
}
|
|
152
172
|
// Starting fresh is right, but silently doing so leaves the caller unable to tell a
|
|
153
173
|
// stale id from a typo'd one — keep why the load failed.
|
|
154
174
|
const fresh = await client.newSession(workspace);
|
|
@@ -191,13 +211,42 @@ function servedModelFrom(res) {
|
|
|
191
211
|
return typeof m?.currentValue === "string" ? m.currentValue : undefined;
|
|
192
212
|
}
|
|
193
213
|
|
|
194
|
-
// Sent
|
|
195
|
-
//
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
214
|
+
// Sent only when the exact value appears under a thought-level option the selected model
|
|
215
|
+
// advertised. Local validation keeps a bad token out of ACP and, more importantly, out of a
|
|
216
|
+
// billed prompt. Missing capability data is not mislabeled as a caller mistake.
|
|
217
|
+
async function applyEffort(client, sessionId, model, value, modelOptions) {
|
|
218
|
+
const resolved = resolveEffort(modelOptions, value);
|
|
219
|
+
if (resolved.status === "unavailable") {
|
|
220
|
+
throw makeError(
|
|
221
|
+
"effort-options-unavailable",
|
|
222
|
+
`Cannot validate effort ${JSON.stringify(value)} for ${JSON.stringify(model)}:`
|
|
223
|
+
+ " the selected model did not report a usable effort option list."
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
if (resolved.status === "unsupported") {
|
|
227
|
+
throw makeError(
|
|
228
|
+
"invalid-effort",
|
|
229
|
+
`Model ${JSON.stringify(model)} does not advertise configurable effort.`
|
|
230
|
+
+ ` Accepted: none. Omit effort; do not send ${JSON.stringify("none")}.`
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
if (resolved.status === "invalid") {
|
|
234
|
+
throw makeError(
|
|
235
|
+
"invalid-effort",
|
|
236
|
+
`Invalid effort ${JSON.stringify(value)} for ${JSON.stringify(model)}.`
|
|
237
|
+
+ ` Accepted: ${JSON.stringify(resolved.accepted)}.`
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const r = await applyConfig(client, sessionId, resolved.id, resolved.value);
|
|
242
|
+
if (r.unsupported) {
|
|
243
|
+
throw makeError(
|
|
244
|
+
"effort-options-unavailable",
|
|
245
|
+
`Cannot apply effort ${JSON.stringify(value)} for ${JSON.stringify(model)}:`
|
|
246
|
+
+ ` the selected model advertised option ${JSON.stringify(resolved.id)} but rejected it.`
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
return r.res;
|
|
201
250
|
}
|
|
202
251
|
|
|
203
252
|
/**
|
|
@@ -225,6 +274,12 @@ export async function runDelegate({
|
|
|
225
274
|
// Before the spawn: validating later costs a process, a handshake and a billed turn.
|
|
226
275
|
assertWorkspace(workspace);
|
|
227
276
|
const promptText = await resolveSpec(spec);
|
|
277
|
+
// addEventListener does not replay an abort that already fired, and the listener is registered
|
|
278
|
+
// below, so an abort during the await above is otherwise lost. Throwing, not supervisor.abort():
|
|
279
|
+
// tripping before supervise() installs its reject settles the supervisor with nothing listening.
|
|
280
|
+
if (signal?.aborted) {
|
|
281
|
+
throw makeError("aborted", "delegation aborted by MCP host");
|
|
282
|
+
}
|
|
228
283
|
const capMs = hardCapMs ?? timeoutMs ?? envMs("CURSOR_DELEGATE_HARD_CAP_MS", 3600000);
|
|
229
284
|
const shakeMs = handshakeMs ?? envMs("CURSOR_DELEGATE_HANDSHAKE_MS", DEFAULT_HANDSHAKE_MS);
|
|
230
285
|
const turnIdleMs = idleMs ?? envMs("CURSOR_DELEGATE_IDLE_MS", 0);
|
|
@@ -390,9 +445,8 @@ export async function runDelegate({
|
|
|
390
445
|
servedModel = servedModelFrom(reasserted.res) ?? servedModel;
|
|
391
446
|
}
|
|
392
447
|
if (effort !== undefined) {
|
|
393
|
-
const
|
|
394
|
-
|
|
395
|
-
else servedModel = servedModelFrom(applied.res) ?? servedModel;
|
|
448
|
+
const r = await applyEffort(client, sessionId, model, effort, modelOptions);
|
|
449
|
+
servedModel = servedModelFrom(r) ?? servedModel;
|
|
396
450
|
}
|
|
397
451
|
if (context !== undefined) {
|
|
398
452
|
const r = await applyConfig(client, sessionId, "context", context);
|
|
@@ -495,8 +549,7 @@ export async function runDelegate({
|
|
|
495
549
|
// outstanding — it also lets a retry resume the work already done.
|
|
496
550
|
const isTimeout = err?.reason === "hard-cap" || err?.reason === "idle-timeout";
|
|
497
551
|
// A handshake timeout gets the forensics but not the long-command advice: no prompt was sent,
|
|
498
|
-
// so no shell command explains the silence.
|
|
499
|
-
// set_model/set_config_option/set_mode, any of which can hang), so the resume hint applies.
|
|
552
|
+
// so no shell command explains the silence.
|
|
500
553
|
const isStall = isTimeout || err?.reason === "handshake-timeout";
|
|
501
554
|
if (isStall || err?.reason === "aborted" || err?.reason === "agent-exit") {
|
|
502
555
|
const age = fmtDuration(supervisor.msSinceActivity());
|
|
@@ -510,20 +563,23 @@ export async function runDelegate({
|
|
|
510
563
|
}
|
|
511
564
|
const files = normalizeAgentReportedFiles([...state.touched], workspace);
|
|
512
565
|
if (files.length) err.message += ` Files reported edited: ${files.join(", ")}.`;
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
566
|
+
}
|
|
567
|
+
// Every failure after session/new leaves a live session, not just the stalls: the id is set
|
|
568
|
+
// before set_model/set_config_option/set_mode, so unknown-model and a rejected config value
|
|
569
|
+
// land here too and are abandoned without it.
|
|
570
|
+
if (resumeError) {
|
|
571
|
+
// Without this the resume hint reads as "carry on from where you were", when the requested
|
|
572
|
+
// session was never loaded.
|
|
573
|
+
err.message += ` Note: resuming ${resumeSessionId} had already failed (${resumeError}),`
|
|
574
|
+
+ ` so this ran as a fresh session and none of that earlier work was in context.`;
|
|
575
|
+
}
|
|
576
|
+
if (sessionId) err.message += ` Resume with resumeSessionId ${sessionId}.`;
|
|
577
|
+
if (isTimeout) {
|
|
578
|
+
// Name the knob that actually fired: raising the hard cap does nothing for an
|
|
579
|
+
// idle-timeout, whose ceiling is CURSOR_DELEGATE_IDLE_MS.
|
|
580
|
+
const knob = err.reason === "idle-timeout" ? "CURSOR_DELEGATE_IDLE_MS" : "CURSOR_DELEGATE_HARD_CAP_MS";
|
|
581
|
+
err.message += " cursor-agent does not stream shell output over ACP, so a long-running command emits"
|
|
582
|
+
+ ` nothing until it exits. Split the command, run it in the background and poll, or raise ${knob}.`;
|
|
527
583
|
}
|
|
528
584
|
// Opt-in: the frames land in the caller's context and nothing there is actionable — the
|
|
529
585
|
// forensics above already carry that. Raw frames only help someone debugging the bridge.
|
|
@@ -539,6 +595,8 @@ export async function runDelegate({
|
|
|
539
595
|
clearInterval(heartbeat);
|
|
540
596
|
signal?.removeEventListener("abort", onAbort);
|
|
541
597
|
try { supervisor.finish(); } catch {}
|
|
542
|
-
|
|
598
|
+
// Deliberately not awaited: stop() waits for the child to exit, and every turn — success as
|
|
599
|
+
// much as failure — would pay that before returning. Nothing here reads whether it landed.
|
|
600
|
+
Promise.resolve(client.stop()).catch(() => {});
|
|
543
601
|
}
|
|
544
602
|
}
|
package/src/doctor.js
CHANGED
|
@@ -2,7 +2,7 @@ import process from "node:process";
|
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
3
|
import { AcpClient } from "./acp-client.js";
|
|
4
4
|
import { resolveAcpSpawn } from "./spawn.js";
|
|
5
|
-
import { treeKill } from "./proc.js";
|
|
5
|
+
import { DETACHED, treeKill } from "./proc.js";
|
|
6
6
|
import { readPackageVersion } from "./version.js";
|
|
7
7
|
import { allowedValues } from "./model-options.js";
|
|
8
8
|
|
|
@@ -32,7 +32,7 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
|
|
|
32
32
|
clearTimeout(timer);
|
|
33
33
|
resolve(result);
|
|
34
34
|
};
|
|
35
|
-
const child = spawn(execCommand, execArgs, { ...options, stdio: ["ignore", "pipe", "pipe"] });
|
|
35
|
+
const child = spawn(execCommand, execArgs, { ...options, detached: DETACHED, stdio: ["ignore", "pipe", "pipe"] });
|
|
36
36
|
child.stdout?.on("data", (chunk) => { stdout += chunk.toString(); });
|
|
37
37
|
child.on("error", () => finish({ found: false, version: null }));
|
|
38
38
|
child.on("close", (code) => {
|
|
@@ -77,7 +77,9 @@ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs
|
|
|
77
77
|
})();
|
|
78
78
|
const timeout = new Promise((_, reject) => {
|
|
79
79
|
timer = setTimeout(() => {
|
|
80
|
-
|
|
80
|
+
// Not awaited, so the timeout still rejects at its stated deadline rather than at the
|
|
81
|
+
// deadline plus teardown. The finally below awaits the same idempotent promise.
|
|
82
|
+
try { Promise.resolve(client.stop()).catch(() => {}); } catch {}
|
|
81
83
|
reject(new Error(`Handshake timed out after ${timeoutMs}ms`));
|
|
82
84
|
}, timeoutMs);
|
|
83
85
|
});
|
|
@@ -87,7 +89,9 @@ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs
|
|
|
87
89
|
return { ok: false, error: err?.message || String(err) };
|
|
88
90
|
} finally {
|
|
89
91
|
clearTimeout(timer);
|
|
90
|
-
|
|
92
|
+
// Awaited so doctor does not return while the agent it spawned is still being torn down.
|
|
93
|
+
// A killed child exits in milliseconds; only one that ignores the kill costs the full bound.
|
|
94
|
+
try { await Promise.resolve(client.stop()); } catch {}
|
|
91
95
|
}
|
|
92
96
|
}
|
|
93
97
|
|
package/src/model-options.js
CHANGED
|
@@ -21,32 +21,27 @@ export function allowedValues(opt) {
|
|
|
21
21
|
.filter((v) => typeof v === "string");
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
24
|
+
// Resolve only values the selected model advertised. This keeps future vocabularies working
|
|
25
|
+
// without aliases or a ranking table: xhigh, extra-high, max and ultra are just exact tokens.
|
|
26
|
+
// A reported config list with no thought-level option is authoritative (unsupported); no list,
|
|
27
|
+
// an empty list, or a thought-level option with no usable id/values is not.
|
|
28
|
+
export function resolveEffort(options, value) {
|
|
29
|
+
if (!Array.isArray(options) || options.length === 0) return { status: "unavailable" };
|
|
30
|
+
|
|
31
|
+
const candidates = options.filter(isThoughtLevel);
|
|
32
|
+
if (candidates.length === 0) return { status: "unsupported", accepted: [] };
|
|
33
|
+
|
|
34
|
+
const usable = candidates.filter((o) => typeof o?.id === "string");
|
|
35
|
+
const accepted = [...new Set(usable.flatMap(allowedValues))];
|
|
36
|
+
if (usable.length === 0 || accepted.length === 0) return { status: "unavailable" };
|
|
28
37
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
// nothing — sending a level there is a guaranteed invalid value, which would fail the run.
|
|
33
|
-
export function resolveEffortId(options, value) {
|
|
34
|
-
const candidates = (Array.isArray(options) ? options : []).filter(isThoughtLevel);
|
|
35
|
-
if (candidates.length === 0) return undefined;
|
|
36
|
-
const pick = candidates.find((o) => allowedValues(o).includes(value))
|
|
37
|
-
?? candidates.find((o) => !isBoolean(o));
|
|
38
|
-
return typeof pick?.id === "string" ? pick.id : undefined;
|
|
38
|
+
const pick = usable.find((o) => allowedValues(o).includes(value));
|
|
39
|
+
if (pick === undefined) return { status: "invalid", accepted };
|
|
40
|
+
return { status: "matched", id: pick.id, value };
|
|
39
41
|
}
|
|
40
42
|
|
|
41
|
-
//
|
|
42
|
-
// under their own names.
|
|
43
|
-
export function unsupportedWarning(model, { arg
|
|
44
|
-
|
|
45
|
-
// No reply carried a list, so claiming the model declares nothing would assert a capability
|
|
46
|
-
// never observed.
|
|
47
|
-
if (modelOptions === undefined) return `effort ignored: ${model} did not report its option list`;
|
|
48
|
-
const ids = modelOptions.filter(isThoughtLevel).map((o) => o?.id).filter(Boolean);
|
|
49
|
-
return ids.length
|
|
50
|
-
? `effort ignored: ${model} declares ${ids.join(", ")}, which did not take the requested value`
|
|
51
|
-
: `effort ignored: ${model} declares no thinking or reasoning option`;
|
|
43
|
+
// Effort failures are fatal before the prompt. Only fast and context reach this soft-diagnostic
|
|
44
|
+
// path, and both are sent under their own names.
|
|
45
|
+
export function unsupportedWarning(model, { arg }) {
|
|
46
|
+
return `model ${model} has no ${arg} option; the requested value was ignored`;
|
|
52
47
|
}
|
package/src/proc.js
CHANGED
|
@@ -5,14 +5,26 @@ export function isChildAlive(child) {
|
|
|
5
5
|
return child && child.exitCode === null && child.signalCode === null;
|
|
6
6
|
}
|
|
7
7
|
|
|
8
|
+
// POSIX only: detached makes the child a process group leader (setsid), which is what lets
|
|
9
|
+
// treeKill reach the agent's own children. On win32 it would mean a separate console instead,
|
|
10
|
+
// and taskkill /T already walks the tree. Every spawn site applies it, not resolveAcpSpawn —
|
|
11
|
+
// an injected spawnSpec has to become a group leader too or the group kill finds nothing.
|
|
12
|
+
export const DETACHED = process.platform !== "win32";
|
|
13
|
+
|
|
8
14
|
// On win32 a plain child.kill() only reaches the shell wrapper (spawn uses shell: true);
|
|
9
15
|
// taskkill /T takes the whole tree so the agent itself dies too.
|
|
10
|
-
export async function treeKill(pid) {
|
|
16
|
+
export async function treeKill(pid, { childAlive = true } = {}) {
|
|
11
17
|
if (process.platform === "win32") {
|
|
12
18
|
await /** @type {Promise<void>} */ (new Promise((resolve) => {
|
|
13
19
|
execFile("taskkill", ["/PID", String(pid), "/T", "/F"], () => resolve());
|
|
14
20
|
}));
|
|
15
21
|
return;
|
|
16
22
|
}
|
|
17
|
-
|
|
23
|
+
// Negative pid signals the whole group, so the agent's descendants go with it. A group outlives
|
|
24
|
+
// its leader while any member is left, which is why this runs even for an exited child: that is
|
|
25
|
+
// the case where descendants are the only thing still running.
|
|
26
|
+
try { process.kill(-pid, "SIGKILL"); } catch {}
|
|
27
|
+
// Reaches a child that is not a group leader, where the group kill raised ESRCH. Skipped once
|
|
28
|
+
// the child is gone, since a reaped pid can already belong to something else.
|
|
29
|
+
if (childAlive) { try { process.kill(pid, "SIGKILL"); } catch {} }
|
|
18
30
|
}
|
package/src/server.js
CHANGED
|
@@ -8,6 +8,7 @@ import { z } from "zod";
|
|
|
8
8
|
import { DEFAULT_MODEL, runDelegate as runDelegateDefault } from "./delegate.js";
|
|
9
9
|
import { runDoctor as runDoctorDefault } from "./doctor.js";
|
|
10
10
|
import { VERSION } from "./version.js";
|
|
11
|
+
import { DETACHED } from "./proc.js";
|
|
11
12
|
import { PLAN_PRIORITIES, PLAN_STATUSES, TODO_STATUSES } from "./acp-enums.js";
|
|
12
13
|
|
|
13
14
|
const nodeMajor = Number(process.versions.node.split(".")[0]);
|
|
@@ -50,7 +51,7 @@ function rememberSession(set, id) {
|
|
|
50
51
|
// Loaded at connect, before any tool schema is, so this carries only pre-call facts: what a
|
|
51
52
|
// caller needs to decide whether to delegate at all. Call-time facts belong on the parameter
|
|
52
53
|
// descriptions, read while the call is being written.
|
|
53
|
-
export const SERVER_INSTRUCTIONS = `Delegate coding work to Cursor through the delegate tool. Every permission the agent requests is auto-approved, in every mode:
|
|
54
|
+
export const SERVER_INSTRUCTIONS = `Delegate coding work to Cursor through the delegate tool. Every permission the agent requests is auto-approved, in every mode: agent/plan/ask reach any file the user account can, and mode instructs the agent rather than limiting it. Scope workspace tightly and review the git diff after every run — filesReportedByEditTools carries only what the agent's edit tools reported; the diff is authoritative.`;
|
|
54
55
|
|
|
55
56
|
const planEntrySchema = z.object({
|
|
56
57
|
content: z.string(),
|
|
@@ -103,20 +104,26 @@ export const delegateOutputShape = {
|
|
|
103
104
|
// doctor.test.js parses every result against a strict copy of this shape.
|
|
104
105
|
//
|
|
105
106
|
// Types only; what the fields mean is documented once, in TECHNICAL.md.
|
|
107
|
+
// Split out so the drift guard can make it strict on its own: a .strict() on agent does not look
|
|
108
|
+
// inside handshake, which is the level this schema has drifted at twice.
|
|
109
|
+
export const doctorHandshakeShape = {
|
|
110
|
+
ok: z.boolean(),
|
|
111
|
+
error: z.string().optional(),
|
|
112
|
+
protocolVersion: z.unknown().optional(),
|
|
113
|
+
agentCapabilities: z.unknown().optional(),
|
|
114
|
+
models: z.array(z.unknown()).optional(),
|
|
115
|
+
currentModel: z.unknown().optional(),
|
|
116
|
+
modes: z.array(z.unknown()).optional(),
|
|
117
|
+
// Built here rather than relayed, so it gets a real type where its neighbours get z.unknown().
|
|
118
|
+
currentModelOptions: z.array(z.object({ id: z.string(), values: z.array(z.string()) })).optional(),
|
|
119
|
+
};
|
|
120
|
+
|
|
106
121
|
export const doctorAgentShape = {
|
|
107
122
|
found: z.boolean(),
|
|
108
123
|
command: z.string(),
|
|
109
124
|
version: z.string().nullable(),
|
|
110
125
|
error: z.string().optional(),
|
|
111
|
-
handshake: z.object(
|
|
112
|
-
ok: z.boolean(),
|
|
113
|
-
error: z.string().optional(),
|
|
114
|
-
protocolVersion: z.unknown().optional(),
|
|
115
|
-
agentCapabilities: z.unknown().optional(),
|
|
116
|
-
models: z.array(z.unknown()).optional(),
|
|
117
|
-
currentModel: z.unknown().optional(),
|
|
118
|
-
modes: z.array(z.unknown()).optional(),
|
|
119
|
-
}).passthrough().optional(),
|
|
126
|
+
handshake: z.object(doctorHandshakeShape).passthrough().optional(),
|
|
120
127
|
};
|
|
121
128
|
|
|
122
129
|
// Exported as a shape for the same reason as delegateOutputShape, and with agent split out
|
|
@@ -141,22 +148,17 @@ export const doctorOutputShape = {
|
|
|
141
148
|
};
|
|
142
149
|
|
|
143
150
|
export const delegateInputSchema = z.object({
|
|
144
|
-
spec: z.string().trim().min(1, "spec must not be blank").describe("
|
|
145
|
-
mode: z.enum(["agent", "plan", "ask"]).default("agent").describe("
|
|
146
|
-
resumeSessionId: z.string().optional().describe("
|
|
147
|
-
workspace: z.string().optional().describe("
|
|
151
|
+
spec: z.string().trim().min(1, "spec must not be blank").describe("Task brief: goal, scope, fixed decisions quoted exactly, acceptance criteria. Point at files to read rather than pasting code. A lone file path is read as the brief."),
|
|
152
|
+
mode: z.enum(["agent", "plan", "ask"]).default("agent").describe("agent implements; plan and ask are instructions to the agent, not limits."),
|
|
153
|
+
resumeSessionId: z.string().optional().describe("Continue an existing ACP session."),
|
|
154
|
+
workspace: z.string().optional().describe("The agent's working directory, not a limit. Defaults to the server process cwd, which under npx is often not your project root — pass it explicitly. Must already exist; never create one for the call."),
|
|
148
155
|
model: z.string().trim().min(1, "model must be a non-empty string").default(DEFAULT_MODEL).describe("Bare ACP family id, version included: composer-2.5, grok-4.5, claude-opus-5, gpt-5.6-sol. doctor deep:true lists every id."),
|
|
149
|
-
fast: z.boolean().default(false).describe("Fast
|
|
150
|
-
// Which
|
|
151
|
-
//
|
|
152
|
-
effort: z.string().trim().min(1).optional().describe("
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
reasoning: z.string().trim().min(1).optional()
|
|
156
|
-
.refine((v) => v === undefined, { message: "reasoning was renamed to effort; pass effort instead" })
|
|
157
|
-
.describe("Removed — use effort."),
|
|
158
|
-
context: z.string().trim().min(1).optional().describe("Context window size. Not offered by every model; gpt-5.x accepts 272k and 1m."),
|
|
159
|
-
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."),
|
|
156
|
+
fast: z.boolean().default(false).describe("Fast tier; higher cost — only when the user asks."),
|
|
157
|
+
// Which values a model offers is only knowable after selecting it, so this stays an open
|
|
158
|
+
// string and the bridge validates the exact token against the live option list.
|
|
159
|
+
effort: z.string().trim().min(1).optional().describe("Exact Cursor thinking-effort value for the selected model. Values differ per model and some expose no effort option; invalid values fail before the prompt and name the accepted set. Pass only when the user asks for Cursor effort — the host's own reasoning setting is unrelated."),
|
|
160
|
+
context: z.string().trim().min(1).optional().describe("Context window size; gpt-5.x accepts 272k and 1m. Do not pass speculatively."),
|
|
161
|
+
contextFiles: z.array(z.string()).optional().describe("Paths to attach instead of pasting contents into spec. Text becomes references the agent may open; images (png/jpg/gif/webp, <5MB) are sent inline. Relative paths resolve against workspace but are not limited to it. Skips are reported in protocolWarnings, never fatal."),
|
|
160
162
|
});
|
|
161
163
|
|
|
162
164
|
/**
|
|
@@ -177,11 +179,13 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, seen
|
|
|
177
179
|
if (progressToken != null) {
|
|
178
180
|
let progress = 0;
|
|
179
181
|
onProgress = (message) => {
|
|
182
|
+
// sendNotification is async: its rejection settles outside this try and would exit the
|
|
183
|
+
// server. The try stays for a sync throw, which lands before Promise.resolve can wrap it.
|
|
180
184
|
try {
|
|
181
|
-
extra.sendNotification({
|
|
185
|
+
Promise.resolve(extra.sendNotification({
|
|
182
186
|
method: "notifications/progress",
|
|
183
187
|
params: { progressToken, progress: ++progress, message },
|
|
184
|
-
});
|
|
188
|
+
})).catch(() => {});
|
|
185
189
|
} catch {}
|
|
186
190
|
};
|
|
187
191
|
}
|
|
@@ -248,7 +252,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
248
252
|
"delegate",
|
|
249
253
|
{
|
|
250
254
|
description:
|
|
251
|
-
`Delegate a coding task to cursor-agent over ACP. Never shell out to cursor-agent — use this tool only.
|
|
255
|
+
`Delegate a coding task to cursor-agent over ACP. Never shell out to cursor-agent — use this tool only. 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. Keep model (${DEFAULT_MODEL}), fast and effort at their defaults unless the user explicitly asks. See the delegate skill.`,
|
|
252
256
|
inputSchema: delegateInputSchema,
|
|
253
257
|
annotations: {
|
|
254
258
|
title: "Delegate coding task to Cursor",
|
|
@@ -265,10 +269,10 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
265
269
|
"cancel",
|
|
266
270
|
{
|
|
267
271
|
description:
|
|
268
|
-
"Best-effort cancel of an in-flight
|
|
272
|
+
"Best-effort cancel of an in-flight delegation by sessionId. session/cancel is advisory — the agent may finish the turn anyway, and the delegate result then carries cancelRequested. Status: cancelled, killed (agent process observed to exit), not-running (turn already ended, still resumable), not-found (id not in this process's recent session history).",
|
|
269
273
|
inputSchema: {
|
|
270
274
|
sessionId: z.string(),
|
|
271
|
-
force: z.boolean().default(false).describe("
|
|
275
|
+
force: z.boolean().default(false).describe("Kill the agent process if the turn is still running after a short grace period."),
|
|
272
276
|
},
|
|
273
277
|
annotations: {
|
|
274
278
|
title: "Cancel Cursor delegation",
|
|
@@ -300,7 +304,12 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
300
304
|
await new Promise((r) => setTimeout(r, forceGraceMs));
|
|
301
305
|
const stillRunning = inFlight.get(sessionId);
|
|
302
306
|
if (!stillRunning || stillRunning.size === 0) return cancelResult("cancelled", sessionId);
|
|
303
|
-
|
|
307
|
+
const observed = await Promise.all(
|
|
308
|
+
[...stillRunning].map((handle) => Promise.resolve(handle.client.stop()).catch(() => false))
|
|
309
|
+
);
|
|
310
|
+
// "killed" claims the process is gone, so it needs the exit, not just a dispatched signal.
|
|
311
|
+
// When one does not follow, the handles stay registered and force can be tried again.
|
|
312
|
+
if (!observed.every(Boolean)) return cancelResult("cancelled", sessionId);
|
|
304
313
|
inFlight.delete(sessionId);
|
|
305
314
|
return cancelResult("killed", sessionId);
|
|
306
315
|
}
|
|
@@ -310,12 +319,12 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
310
319
|
"doctor",
|
|
311
320
|
{
|
|
312
321
|
description:
|
|
313
|
-
"
|
|
322
|
+
"Setup diagnostics: plugin version, MCP client capabilities, cursor-agent launcher resolution. Run when delegation fails or agent.found is false.",
|
|
314
323
|
inputSchema: {
|
|
315
324
|
deep: z
|
|
316
325
|
.boolean()
|
|
317
326
|
.default(false)
|
|
318
|
-
.describe("
|
|
327
|
+
.describe("Run an ACP handshake (start → initialize → newSession) to verify the agent is usable; adds models, modes and the current model's options."),
|
|
319
328
|
},
|
|
320
329
|
annotations: {
|
|
321
330
|
title: "Diagnose Cursor delegation setup",
|
|
@@ -350,7 +359,26 @@ if (process.argv[1]) {
|
|
|
350
359
|
}
|
|
351
360
|
}
|
|
352
361
|
|
|
362
|
+
// Each agent runs in its own process group on POSIX, so a SIGINT or SIGTERM aimed at this process
|
|
363
|
+
// no longer reaches it the way it did when the two shared a group. Kill what is registered, then
|
|
364
|
+
// exit explicitly: installing a handler replaces Node's default, and a server that swallows Ctrl-C
|
|
365
|
+
// would be a worse bug than the agent it leaks. Delegations still in their handshake are not in
|
|
366
|
+
// the map yet, so this covers the turn, not the first few seconds of it.
|
|
367
|
+
export function installSignalCleanup(map, { exit = (code) => process.exit(code) } = {}) {
|
|
368
|
+
if (!DETACHED) return;
|
|
369
|
+
const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143]]);
|
|
370
|
+
for (const [signal, code] of signals) {
|
|
371
|
+
process.on(signal, () => {
|
|
372
|
+
for (const handles of map.values()) {
|
|
373
|
+
for (const handle of handles) { try { handle.client.stop(); } catch {} }
|
|
374
|
+
}
|
|
375
|
+
exit(code);
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
353
380
|
if (isMain) {
|
|
354
381
|
const server = buildServer();
|
|
382
|
+
installSignalCleanup(inFlight);
|
|
355
383
|
await server.connect(new StdioServerTransport());
|
|
356
384
|
}
|