cursor-delegate-mcp 1.7.0 → 1.8.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/SECURITY.md +1 -1
- package/package.json +1 -1
- package/src/acp-client.js +20 -5
- package/src/agent-reported-files.js +17 -0
- package/src/delegate.js +155 -15
- package/src/doctor.js +7 -1
- package/src/request-router.js +49 -42
- package/src/server.js +29 -13
- package/src/session-supervisor.js +37 -31
- package/src/touched-files.js +0 -59
package/SECURITY.md
CHANGED
|
@@ -11,7 +11,7 @@ Treat every `delegate` call like handing an engineer write access to that tree.
|
|
|
11
11
|
## Recommendations
|
|
12
12
|
|
|
13
13
|
- Point `workspace` at the smallest directory that contains the task (not `$HOME` or `/`).
|
|
14
|
-
- Review `
|
|
14
|
+
- Review `filesReportedByAgent` and the git diff before committing.
|
|
15
15
|
- Use `mode: "plan"` when you only want a plan, not file changes.
|
|
16
16
|
- Run verification (tests, lint) after delegation — the delegate skill asks Claude to do
|
|
17
17
|
this, but automated gates in CI are still your backstop.
|
package/package.json
CHANGED
package/src/acp-client.js
CHANGED
|
@@ -9,12 +9,13 @@ import { VERSION } from "./version.js";
|
|
|
9
9
|
const STDERR_CAP = 64 * 1024;
|
|
10
10
|
|
|
11
11
|
export class AcpClient extends EventEmitter {
|
|
12
|
-
constructor({ spawnSpec, onElicit, mode, onCreatePlan } = {}) {
|
|
12
|
+
constructor({ spawnSpec, onElicit, mode, onCreatePlan, onTodos } = {}) {
|
|
13
13
|
super();
|
|
14
14
|
this.spawnSpec = spawnSpec || resolveAcpSpawn();
|
|
15
15
|
this.onElicit = onElicit;
|
|
16
16
|
this.mode = mode;
|
|
17
17
|
this.onCreatePlan = onCreatePlan;
|
|
18
|
+
this.onTodos = onTodos;
|
|
18
19
|
}
|
|
19
20
|
|
|
20
21
|
start() {
|
|
@@ -52,6 +53,7 @@ export class AcpClient extends EventEmitter {
|
|
|
52
53
|
respondError: (id, c, m) => this.peer.respondError(id, c, m),
|
|
53
54
|
onElicit: this.onElicit,
|
|
54
55
|
onCreatePlan: this.onCreatePlan,
|
|
56
|
+
onTodos: this.onTodos,
|
|
55
57
|
mode: this.mode,
|
|
56
58
|
log: (e) => this.emit("ack", e),
|
|
57
59
|
});
|
|
@@ -62,9 +64,22 @@ export class AcpClient extends EventEmitter {
|
|
|
62
64
|
});
|
|
63
65
|
}
|
|
64
66
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
67
|
+
// The handshake replies carry the agent's live capabilities, model list and mode list.
|
|
68
|
+
// Keep them; every caller still gets the reply unchanged.
|
|
69
|
+
async initialize() {
|
|
70
|
+
const res = await this.peer.request("initialize", { protocolVersion: 1, clientInfo: { name: "cursor-delegate-mcp", version: VERSION }, clientCapabilities: { _meta: { parameterizedModelPicker: true } } });
|
|
71
|
+
this.protocolVersion = res?.protocolVersion;
|
|
72
|
+
this.agentCapabilities = res?.agentCapabilities;
|
|
73
|
+
return res;
|
|
74
|
+
}
|
|
75
|
+
_captureSession(res) {
|
|
76
|
+
this.sessionModels = res?.models;
|
|
77
|
+
this.sessionModes = res?.modes;
|
|
78
|
+
this.configOptions = res?.configOptions;
|
|
79
|
+
return res;
|
|
80
|
+
}
|
|
81
|
+
async newSession(cwd) { return this._captureSession(await this.peer.request("session/new", { cwd, mcpServers: [] })); }
|
|
82
|
+
async loadSession(sessionId, cwd) { return this._captureSession(await this.peer.request("session/load", { sessionId, cwd, mcpServers: [] })); }
|
|
68
83
|
setModel(sessionId, modelId) { return this.peer.request("session/set_model", { sessionId, modelId }); }
|
|
69
84
|
setFast(sessionId, value) { return this.peer.request("session/set_config_option", { sessionId, configId: "fast", value: String(value) }); } // configId, not optionId; ACP wants a string value
|
|
70
85
|
setMode(sessionId, modeId) { return this.peer.request("session/set_mode", { sessionId, modeId }); }
|
|
@@ -75,7 +90,7 @@ export class AcpClient extends EventEmitter {
|
|
|
75
90
|
|
|
76
91
|
stop() {
|
|
77
92
|
try { this.peer?.close(); } catch {}
|
|
78
|
-
if (isChildAlive(this.child) &&
|
|
93
|
+
if (isChildAlive(this.child) && this.child.pid) {
|
|
79
94
|
treeKill(this.child.pid).catch(() => {});
|
|
80
95
|
} else {
|
|
81
96
|
try { this.child?.kill(); } catch {}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
|
|
3
|
+
// Attribution rule: a path is agent-reported only via a native ACP diff event.
|
|
4
|
+
// Never add paths from git, the final message, or shell output — the orchestrator
|
|
5
|
+
// owns workspace diff review.
|
|
6
|
+
|
|
7
|
+
function relativize(abs, workspace) {
|
|
8
|
+
if (!workspace) return abs;
|
|
9
|
+
const r = path.relative(workspace, abs);
|
|
10
|
+
if (!r || r.startsWith("..") || path.isAbsolute(r)) return abs;
|
|
11
|
+
return r.split(path.sep).join("/");
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function normalizeAgentReportedFiles(paths, workspace) {
|
|
15
|
+
const abs = paths.map((p) => (workspace ? path.resolve(workspace, p) : path.resolve(p)));
|
|
16
|
+
return [...new Set(abs)].map((f) => relativize(f, workspace));
|
|
17
|
+
}
|
package/src/delegate.js
CHANGED
|
@@ -1,7 +1,25 @@
|
|
|
1
|
+
import process from "node:process";
|
|
1
2
|
import { readFileSync, statSync } from "node:fs";
|
|
2
3
|
import { AcpClient } from "./acp-client.js";
|
|
3
4
|
import { SessionSupervisor } from "./session-supervisor.js";
|
|
4
|
-
import {
|
|
5
|
+
import { normalizeAgentReportedFiles } from "./agent-reported-files.js";
|
|
6
|
+
|
|
7
|
+
export const DEFAULT_MODEL = "composer-2.5";
|
|
8
|
+
export const DEFAULT_HANDSHAKE_MS = 60000;
|
|
9
|
+
export const DEFAULT_HEARTBEAT_MS = 30000;
|
|
10
|
+
|
|
11
|
+
// Malformed values fall back to the default rather than failing the call.
|
|
12
|
+
function envMs(name, fallback) {
|
|
13
|
+
const raw = process.env[name];
|
|
14
|
+
if (raw === undefined) return fallback;
|
|
15
|
+
const n = Number(raw);
|
|
16
|
+
return Number.isFinite(n) && n >= 0 ? n : fallback;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function fmtDuration(ms) {
|
|
20
|
+
const s = Math.round(ms / 1000);
|
|
21
|
+
return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s`;
|
|
22
|
+
}
|
|
5
23
|
|
|
6
24
|
function resolveSpec(spec) {
|
|
7
25
|
if (typeof spec !== "string") return spec;
|
|
@@ -25,6 +43,19 @@ async function openSession(client, resumeSessionId, workspace) {
|
|
|
25
43
|
return client.newSession(workspace);
|
|
26
44
|
}
|
|
27
45
|
|
|
46
|
+
// session/new reports the models the agent actually offers. Reject an unknown id here,
|
|
47
|
+
// where the real list can be named, rather than letting set_model fail without it.
|
|
48
|
+
// Agents that report no list are left alone.
|
|
49
|
+
function assertKnownModel(client, model) {
|
|
50
|
+
const available = client?.sessionModels?.availableModels;
|
|
51
|
+
if (!Array.isArray(available) || available.length === 0) return;
|
|
52
|
+
const ids = available.map((m) => m?.modelId).filter((id) => typeof id === "string");
|
|
53
|
+
if (ids.length === 0 || ids.includes(model)) return;
|
|
54
|
+
const err = new Error(`Unknown model ${JSON.stringify(model)}. This agent offers: ${ids.join(", ")}.`);
|
|
55
|
+
err.reason = "unknown-model";
|
|
56
|
+
throw err;
|
|
57
|
+
}
|
|
58
|
+
|
|
28
59
|
// Composer bare ids (e.g. composer-2.5) expose standard vs fast via set_config_option.
|
|
29
60
|
// Other models use separate ids (e.g. gpt-5-fast) — see cursor-agent --list-models.
|
|
30
61
|
function composerFastToggleApplies(model) {
|
|
@@ -33,9 +64,10 @@ function composerFastToggleApplies(model) {
|
|
|
33
64
|
|
|
34
65
|
export async function runDelegate({
|
|
35
66
|
spec, mode = "agent", resumeSessionId, workspace,
|
|
36
|
-
model =
|
|
37
|
-
idleMs
|
|
38
|
-
onSessionReady, onProgress, progressThrottleMs = 2000,
|
|
67
|
+
model = DEFAULT_MODEL, fast = false, clientFactory, onElicit,
|
|
68
|
+
idleMs, handshakeMs, hardCapMs, timeoutMs,
|
|
69
|
+
onSessionReady, onProgress, progressThrottleMs = 2000,
|
|
70
|
+
heartbeatMs = DEFAULT_HEARTBEAT_MS,
|
|
39
71
|
signal,
|
|
40
72
|
} = {}) {
|
|
41
73
|
if (signal?.aborted) {
|
|
@@ -43,7 +75,9 @@ export async function runDelegate({
|
|
|
43
75
|
err.reason = "aborted";
|
|
44
76
|
throw err;
|
|
45
77
|
}
|
|
46
|
-
const capMs = hardCapMs ?? timeoutMs ?? 3600000;
|
|
78
|
+
const capMs = hardCapMs ?? timeoutMs ?? envMs("CURSOR_DELEGATE_HARD_CAP_MS", 3600000);
|
|
79
|
+
const shakeMs = handshakeMs ?? envMs("CURSOR_DELEGATE_HANDSHAKE_MS", DEFAULT_HANDSHAKE_MS);
|
|
80
|
+
const turnIdleMs = idleMs ?? envMs("CURSOR_DELEGATE_IDLE_MS", 0);
|
|
47
81
|
const MAX_OUTPUT = 10 * 1024 * 1024;
|
|
48
82
|
const TRUNCATION_MARKER = "\n\n[output truncated at 10MB]";
|
|
49
83
|
const questionsAsked = [];
|
|
@@ -57,6 +91,30 @@ export async function runDelegate({
|
|
|
57
91
|
? async (q) => { recordQuestions(q); return onElicit(q); }
|
|
58
92
|
: async (q) => { recordQuestions(q); return null; };
|
|
59
93
|
|
|
94
|
+
// merge:false replaces the list, merge:true upserts by id. Entries always arrive complete,
|
|
95
|
+
// so a keyed set is enough — no field-level merging.
|
|
96
|
+
let todos = new Map();
|
|
97
|
+
let sawTodoFrame = false;
|
|
98
|
+
const todoLabel = () => {
|
|
99
|
+
const entries = [...todos.values()].filter((t) => typeof t?.content === "string");
|
|
100
|
+
if (!entries.length) return null;
|
|
101
|
+
const i = entries.findIndex((t) => t.status === "in_progress");
|
|
102
|
+
if (i !== -1) return `todo ${i + 1}/${entries.length}: ${entries[i].content}`;
|
|
103
|
+
const done = entries.filter((t) => t.status === "completed").length;
|
|
104
|
+
return `todos ${done}/${entries.length} complete`;
|
|
105
|
+
};
|
|
106
|
+
const recordTodos = ({ todos: incoming, merge }) => {
|
|
107
|
+
if (!Array.isArray(incoming)) return;
|
|
108
|
+
sawTodoFrame = true;
|
|
109
|
+
if (merge === false) todos = new Map();
|
|
110
|
+
for (const t of incoming) {
|
|
111
|
+
if (t?.id === undefined || t?.id === null) continue;
|
|
112
|
+
todos.set(String(t.id), t);
|
|
113
|
+
}
|
|
114
|
+
const label = todoLabel();
|
|
115
|
+
if (label) { try { onProgress?.(label.slice(0, 200)); } catch {} }
|
|
116
|
+
};
|
|
117
|
+
|
|
60
118
|
let planEntries = [];
|
|
61
119
|
let planOverview;
|
|
62
120
|
let planDetail;
|
|
@@ -100,9 +158,37 @@ export async function runDelegate({
|
|
|
100
158
|
return plan;
|
|
101
159
|
};
|
|
102
160
|
|
|
161
|
+
const TODO_STATUSES = ["pending", "in_progress", "completed"];
|
|
162
|
+
const sanitizeTodos = (warnings) => {
|
|
163
|
+
const entries = [];
|
|
164
|
+
let i = -1;
|
|
165
|
+
for (const raw of todos.values()) {
|
|
166
|
+
i++;
|
|
167
|
+
if (typeof raw?.content !== "string") {
|
|
168
|
+
warnings.push(`todo ${i} dropped: expected string content, got ${raw === null ? "null" : typeof raw?.content}`);
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
const status = TODO_STATUSES.includes(raw.status) ? raw.status : undefined;
|
|
172
|
+
if (raw.status !== undefined && status === undefined) {
|
|
173
|
+
warnings.push(`todo ${i}: unknown status ${JSON.stringify(raw.status)} removed`);
|
|
174
|
+
}
|
|
175
|
+
entries.push({ id: String(raw.id), content: raw.content, ...(status ? { status } : {}) });
|
|
176
|
+
}
|
|
177
|
+
const count = (s) => entries.filter((e) => e.status === s).length;
|
|
178
|
+
return {
|
|
179
|
+
todos: entries,
|
|
180
|
+
todoProgress: {
|
|
181
|
+
total: entries.length,
|
|
182
|
+
completed: count("completed"),
|
|
183
|
+
inProgress: count("in_progress"),
|
|
184
|
+
pending: count("pending"),
|
|
185
|
+
},
|
|
186
|
+
};
|
|
187
|
+
};
|
|
188
|
+
|
|
103
189
|
const make = clientFactory || ((opts) => new AcpClient(opts));
|
|
104
|
-
const client = make({ onElicit: wrappedElicit, mode, onCreatePlan: recordCreatePlan });
|
|
105
|
-
const supervisor = new SessionSupervisor(client, { idleMs,
|
|
190
|
+
const client = make({ onElicit: wrappedElicit, mode, onCreatePlan: recordCreatePlan, onTodos: recordTodos });
|
|
191
|
+
const supervisor = new SessionSupervisor(client, { idleMs: turnIdleMs, handshakeMs: shakeMs, hardCapMs: capMs });
|
|
106
192
|
const onAbort = () => supervisor.abort();
|
|
107
193
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
108
194
|
|
|
@@ -195,6 +281,26 @@ export async function runDelegate({
|
|
|
195
281
|
const thoughtProgress = progressStream("thinking: ");
|
|
196
282
|
const messageProgress = progressStream("Cursor: ");
|
|
197
283
|
|
|
284
|
+
// The bridge cannot see inside a running shell command, so a long silence is reported
|
|
285
|
+
// rather than acted on: the caller gets elapsed time and frame age and can decide.
|
|
286
|
+
let lastToolLabel = null;
|
|
287
|
+
let heartbeat = null;
|
|
288
|
+
const startHeartbeat = () => {
|
|
289
|
+
if (!(heartbeatMs > 0)) return;
|
|
290
|
+
const startedAt = Date.now();
|
|
291
|
+
heartbeat = setInterval(() => {
|
|
292
|
+
const parts = [
|
|
293
|
+
`still working — ${fmtDuration(Date.now() - startedAt)} elapsed`,
|
|
294
|
+
`last agent frame ${fmtDuration(supervisor.msSinceActivity())} ago`,
|
|
295
|
+
];
|
|
296
|
+
const todo = todoLabel();
|
|
297
|
+
if (todo) parts.push(todo);
|
|
298
|
+
if (lastToolLabel) parts.push(`running: ${lastToolLabel}`);
|
|
299
|
+
try { onProgress?.(parts.join(", ").slice(0, 200)); } catch {}
|
|
300
|
+
}, heartbeatMs);
|
|
301
|
+
heartbeat.unref?.();
|
|
302
|
+
};
|
|
303
|
+
|
|
198
304
|
client.on("update", (u) => {
|
|
199
305
|
const up = u?.update || {};
|
|
200
306
|
if (up.sessionUpdate === "plan") {
|
|
@@ -207,8 +313,8 @@ export async function runDelegate({
|
|
|
207
313
|
startTool(up.toolCallId, up.status);
|
|
208
314
|
const label = up.title || up.kind || "tool";
|
|
209
315
|
const path = up.locations?.[0]?.path;
|
|
210
|
-
|
|
211
|
-
try { onProgress?.(
|
|
316
|
+
lastToolLabel = String(label) + (path ? " — " + path : "");
|
|
317
|
+
try { onProgress?.(("running: " + lastToolLabel).slice(0, 200)); } catch {}
|
|
212
318
|
}
|
|
213
319
|
if (up.sessionUpdate === "agent_message_chunk" && up.content?.text) {
|
|
214
320
|
const text = up.content.text;
|
|
@@ -222,13 +328,18 @@ export async function runDelegate({
|
|
|
222
328
|
touched.add(c.path);
|
|
223
329
|
try { onProgress?.("editing " + c.path); } catch {}
|
|
224
330
|
}
|
|
331
|
+
// cursor-agent has never been observed emitting these; ACP allows an agent to
|
|
332
|
+
// stream tool output this way, so treat it like message text rather than drop it.
|
|
333
|
+
if (c.type === "content" && typeof c.content?.text === "string") {
|
|
334
|
+
if (!sawToolCall || (collectingPostToolResult && activeToolCalls.size === 0)) appendResult(c.content.text);
|
|
335
|
+
messageProgress.push(c.content.text);
|
|
336
|
+
}
|
|
225
337
|
}
|
|
226
338
|
}
|
|
227
339
|
});
|
|
228
340
|
|
|
341
|
+
let sessionId;
|
|
229
342
|
try {
|
|
230
|
-
let sessionId;
|
|
231
|
-
const gitBefore = gitChangedSet(workspace);
|
|
232
343
|
const res = await supervisor.supervise(async () => {
|
|
233
344
|
await client.start();
|
|
234
345
|
await client.initialize();
|
|
@@ -236,6 +347,7 @@ export async function runDelegate({
|
|
|
236
347
|
sessionId = sess.sessionId;
|
|
237
348
|
supervisor.setSessionId(sessionId);
|
|
238
349
|
onSessionReady?.(sessionId, client);
|
|
350
|
+
assertKnownModel(client, model);
|
|
239
351
|
await client.setModel(sessionId, model);
|
|
240
352
|
if (composerFastToggleApplies(model)) await client.setFast(sessionId, fast);
|
|
241
353
|
await client.setMode(sessionId, mode);
|
|
@@ -248,7 +360,12 @@ export async function runDelegate({
|
|
|
248
360
|
planEntries = [];
|
|
249
361
|
planOverview = undefined;
|
|
250
362
|
planDetail = undefined;
|
|
363
|
+
todos = new Map();
|
|
364
|
+
sawTodoFrame = false;
|
|
251
365
|
touched.clear();
|
|
366
|
+
lastToolLabel = null;
|
|
367
|
+
supervisor.promptStarted();
|
|
368
|
+
startHeartbeat();
|
|
252
369
|
return client.prompt(sessionId, resolveSpec(spec));
|
|
253
370
|
});
|
|
254
371
|
thoughtProgress.end();
|
|
@@ -259,8 +376,6 @@ export async function runDelegate({
|
|
|
259
376
|
const resultSource = finalMessageAvailable
|
|
260
377
|
? (sawToolCall ? "post-tool" : "tool-free-stream")
|
|
261
378
|
: "none";
|
|
262
|
-
const gitAfter = gitChangedSet(workspace);
|
|
263
|
-
const touchedResult = computeTouched({ before: gitBefore, after: gitAfter, diffTouched: [...touched], workspace });
|
|
264
379
|
const protocolWarnings = [];
|
|
265
380
|
let stopReason;
|
|
266
381
|
if (res?.stopReason !== undefined) {
|
|
@@ -273,23 +388,48 @@ export async function runDelegate({
|
|
|
273
388
|
finalMessageAvailable,
|
|
274
389
|
stopReason,
|
|
275
390
|
sessionId,
|
|
276
|
-
|
|
277
|
-
touchedFilesSource: touchedResult.source,
|
|
391
|
+
filesReportedByAgent: normalizeAgentReportedFiles([...touched], workspace),
|
|
278
392
|
questionsAsked,
|
|
279
393
|
resumed: !!resumeSessionId && sessionId === resumeSessionId,
|
|
280
394
|
};
|
|
281
395
|
if (planEntries.length > 0 || planOverview !== undefined || planDetail !== undefined) {
|
|
282
396
|
out.plan = sanitizePlan(protocolWarnings);
|
|
283
397
|
}
|
|
398
|
+
// Most successful turns emit no todos at all, so an empty list would read as "nothing
|
|
399
|
+
// done" rather than "not tracked". Report only what the agent actually sent.
|
|
400
|
+
if (sawTodoFrame) Object.assign(out, sanitizeTodos(protocolWarnings));
|
|
284
401
|
if (protocolWarnings.length) out.protocolWarnings = protocolWarnings;
|
|
285
402
|
return out;
|
|
286
403
|
} catch (err) {
|
|
404
|
+
// A bare duration says nothing about whether the agent wedged or a command was just
|
|
405
|
+
// slow. Name what was outstanding so the caller can tell the two apart, and so a
|
|
406
|
+
// retry can resume from the work already done instead of restarting blind.
|
|
407
|
+
const isTimeout = err?.reason === "hard-cap" || err?.reason === "idle-timeout";
|
|
408
|
+
if (isTimeout || err?.reason === "aborted" || err?.reason === "agent-exit") {
|
|
409
|
+
const age = fmtDuration(supervisor.msSinceActivity());
|
|
410
|
+
err.message += `\n\nLast ACP frame ${age} ago${lastToolLabel ? `; last tool call: ${lastToolLabel}` : ""}.`;
|
|
411
|
+
if (sawTodoFrame) {
|
|
412
|
+
const { todoProgress } = sanitizeTodos([]);
|
|
413
|
+
const current = todoLabel();
|
|
414
|
+
err.message += ` ${todoProgress.completed} of ${todoProgress.total} todos completed`
|
|
415
|
+
+ `${current ? `; ${current}` : ""}.`;
|
|
416
|
+
}
|
|
417
|
+
const files = normalizeAgentReportedFiles([...touched], workspace);
|
|
418
|
+
if (files.length) err.message += ` Files reported edited: ${files.join(", ")}.`;
|
|
419
|
+
if (sessionId) err.message += ` Resume with resumeSessionId ${sessionId}.`;
|
|
420
|
+
if (isTimeout) {
|
|
421
|
+
err.message += " cursor-agent does not stream shell output over ACP, so a long-running command emits"
|
|
422
|
+
+ " nothing until it exits. Split the command, run it in the background and poll, or raise"
|
|
423
|
+
+ " CURSOR_DELEGATE_HARD_CAP_MS.";
|
|
424
|
+
}
|
|
425
|
+
}
|
|
287
426
|
try {
|
|
288
427
|
const transcript = client.getTranscript?.(40);
|
|
289
428
|
if (transcript) err.message += "\n\n--- recent ACP transcript (last 40 frames) ---\n" + transcript;
|
|
290
429
|
} catch {}
|
|
291
430
|
throw err;
|
|
292
431
|
} finally {
|
|
432
|
+
clearInterval(heartbeat);
|
|
293
433
|
signal?.removeEventListener("abort", onAbort);
|
|
294
434
|
try { supervisor.finish(); } catch {}
|
|
295
435
|
client.stop();
|
package/src/doctor.js
CHANGED
|
@@ -41,10 +41,16 @@ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs
|
|
|
41
41
|
const workspaceDir = workspace || process.cwd();
|
|
42
42
|
let timer;
|
|
43
43
|
try {
|
|
44
|
+
const details = {};
|
|
44
45
|
const work = (async () => {
|
|
45
46
|
await client.start();
|
|
46
47
|
await client.initialize();
|
|
47
48
|
await client.newSession(workspaceDir);
|
|
49
|
+
details.protocolVersion = client.protocolVersion ?? null;
|
|
50
|
+
details.agentCapabilities = client.agentCapabilities ?? {};
|
|
51
|
+
details.models = (client.sessionModels?.availableModels ?? []).map((m) => m?.modelId).filter(Boolean);
|
|
52
|
+
details.currentModel = client.sessionModels?.currentModelId ?? null;
|
|
53
|
+
details.modes = (client.sessionModes?.availableModes ?? []).map((m) => m?.id).filter(Boolean);
|
|
48
54
|
})();
|
|
49
55
|
const timeout = new Promise((_, reject) => {
|
|
50
56
|
timer = setTimeout(() => {
|
|
@@ -53,7 +59,7 @@ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs
|
|
|
53
59
|
}, timeoutMs);
|
|
54
60
|
});
|
|
55
61
|
await Promise.race([work, timeout]);
|
|
56
|
-
return { ok: true };
|
|
62
|
+
return { ok: true, ...details };
|
|
57
63
|
} catch (err) {
|
|
58
64
|
return { ok: false, error: err?.message || String(err) };
|
|
59
65
|
} finally {
|
package/src/request-router.js
CHANGED
|
@@ -1,42 +1,49 @@
|
|
|
1
|
-
const ACK_METHODS = new Set(["cursor/
|
|
2
|
-
|
|
3
|
-
export function createRequestRouter({ respond, respondError, onElicit, onCreatePlan, mode = "agent", log = () => {} }) {
|
|
4
|
-
return async function handle(id, method, params) {
|
|
5
|
-
try {
|
|
6
|
-
if (method === "session/request_permission") {
|
|
7
|
-
const opts = params?.options || [];
|
|
8
|
-
const pick =
|
|
9
|
-
opts.find((o) => o.kind === "allow_always") ||
|
|
10
|
-
opts.find((o) => o.kind === "allow_once") ||
|
|
11
|
-
opts[0];
|
|
12
|
-
return respond(id, { outcome: { outcome: "selected", optionId: pick?.optionId } });
|
|
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
|
-
if (method === "cursor/create_plan") {
|
|
24
|
-
onCreatePlan?.({
|
|
25
|
-
overview: params?.overview,
|
|
26
|
-
plan: params?.plan,
|
|
27
|
-
name: params?.name,
|
|
28
|
-
raw: params,
|
|
29
|
-
});
|
|
30
|
-
const outcome = mode === "agent" ? "accepted" : "rejected";
|
|
31
|
-
return respond(id, { outcome: { outcome } });
|
|
32
|
-
}
|
|
33
|
-
if (
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
}
|
|
1
|
+
const ACK_METHODS = new Set(["cursor/task", "cursor/generate_image"]);
|
|
2
|
+
|
|
3
|
+
export function createRequestRouter({ respond, respondError, onElicit, onCreatePlan, onTodos, mode = "agent", log = () => {} }) {
|
|
4
|
+
return async function handle(id, method, params) {
|
|
5
|
+
try {
|
|
6
|
+
if (method === "session/request_permission") {
|
|
7
|
+
const opts = params?.options || [];
|
|
8
|
+
const pick =
|
|
9
|
+
opts.find((o) => o.kind === "allow_always") ||
|
|
10
|
+
opts.find((o) => o.kind === "allow_once") ||
|
|
11
|
+
opts[0];
|
|
12
|
+
return respond(id, { outcome: { outcome: "selected", optionId: pick?.optionId } });
|
|
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
|
+
if (method === "cursor/create_plan") {
|
|
24
|
+
onCreatePlan?.({
|
|
25
|
+
overview: params?.overview,
|
|
26
|
+
plan: params?.plan,
|
|
27
|
+
name: params?.name,
|
|
28
|
+
raw: params,
|
|
29
|
+
});
|
|
30
|
+
const outcome = mode === "agent" ? "accepted" : "rejected";
|
|
31
|
+
return respond(id, { outcome: { outcome } });
|
|
32
|
+
}
|
|
33
|
+
if (method === "cursor/update_todos") {
|
|
34
|
+
onTodos?.({ todos: params?.todos, merge: params?.merge, toolCallId: params?.toolCallId });
|
|
35
|
+
log({ method, params });
|
|
36
|
+
// The documented response is {outcome:{outcome:"accepted", todos}}; the bare {} we
|
|
37
|
+
// have always sent is accepted by cursor-agent, so it stays until that changes.
|
|
38
|
+
return respond(id, {});
|
|
39
|
+
}
|
|
40
|
+
if (ACK_METHODS.has(method)) {
|
|
41
|
+
log({ method, params });
|
|
42
|
+
return respond(id, {});
|
|
43
|
+
}
|
|
44
|
+
return respondError(id, -32601, `Unhandled method: ${method}`);
|
|
45
|
+
} catch (err) {
|
|
46
|
+
return respondError(id, -32000, `Router error: ${err?.message || err}`);
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
}
|
package/src/server.js
CHANGED
|
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
|
|
|
5
5
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
6
6
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
7
7
|
import { z } from "zod";
|
|
8
|
-
import { runDelegate as runDelegateDefault } from "./delegate.js";
|
|
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
11
|
|
|
@@ -17,7 +17,7 @@ if (nodeMajor < 22) {
|
|
|
17
17
|
|
|
18
18
|
const inFlight = new Map();
|
|
19
19
|
|
|
20
|
-
export const SERVER_INSTRUCTIONS = `Delegate coding work to Cursor through the delegate tool. The delegate tool can create, modify, or delete files in its workspace, so scope workspace to the smallest relevant directory and review
|
|
20
|
+
export const SERVER_INSTRUCTIONS = `Delegate coding work to Cursor through the delegate tool. The delegate tool can create, modify, or delete files in its workspace, so scope workspace to the smallest relevant directory and review the git diff after every write-capable run; filesReportedByAgent lists the files the agent reported editing. For approval-gated work, call delegate with mode="plan", review the returned plan and sessionId, then resume with mode="agent" and resumeSessionId. Use mode="ask" for read-only questions and doctor for setup diagnostics.`;
|
|
21
21
|
|
|
22
22
|
const planEntrySchema = z.object({
|
|
23
23
|
content: z.string(),
|
|
@@ -31,8 +31,9 @@ const delegateOutputSchema = z.object({
|
|
|
31
31
|
finalMessageAvailable: z.boolean().optional(),
|
|
32
32
|
stopReason: z.string().optional(),
|
|
33
33
|
sessionId: z.string(),
|
|
34
|
-
|
|
35
|
-
|
|
34
|
+
filesReportedByAgent: z.array(z.string()).describe(
|
|
35
|
+
"Files the agent reported editing via native ACP diff events (may omit shell-driven edits)."
|
|
36
|
+
),
|
|
36
37
|
questionsAsked: z.array(z.string()).optional(),
|
|
37
38
|
resumed: z.boolean().optional(),
|
|
38
39
|
autoAnswered: z.array(z.object({ prompt: z.string(), chosen: z.string() })).optional(),
|
|
@@ -44,6 +45,19 @@ const delegateOutputSchema = z.object({
|
|
|
44
45
|
overview: z.string().optional(),
|
|
45
46
|
detail: z.string().optional(),
|
|
46
47
|
}).optional(),
|
|
48
|
+
todos: z.array(z.object({
|
|
49
|
+
id: z.string(),
|
|
50
|
+
content: z.string(),
|
|
51
|
+
status: z.enum(["pending", "in_progress", "completed"]).optional(),
|
|
52
|
+
})).optional().describe(
|
|
53
|
+
"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
|
+
),
|
|
55
|
+
todoProgress: z.object({
|
|
56
|
+
total: z.number(),
|
|
57
|
+
completed: z.number(),
|
|
58
|
+
inProgress: z.number(),
|
|
59
|
+
pending: z.number(),
|
|
60
|
+
}).optional(),
|
|
47
61
|
}).passthrough();
|
|
48
62
|
|
|
49
63
|
const doctorOutputSchema = z.object({
|
|
@@ -65,6 +79,15 @@ const doctorOutputSchema = z.object({
|
|
|
65
79
|
env: z.record(z.unknown()),
|
|
66
80
|
}).passthrough();
|
|
67
81
|
|
|
82
|
+
export const delegateInputSchema = z.object({
|
|
83
|
+
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"),
|
|
85
|
+
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)"),
|
|
87
|
+
model: z.string().trim().min(1, "model must be a non-empty string").default(DEFAULT_MODEL),
|
|
88
|
+
fast: z.boolean().default(false).describe("Fast speed tier — higher cost; enable only when the user asks"),
|
|
89
|
+
});
|
|
90
|
+
|
|
68
91
|
export async function runDelegateTool({ args, extra, server, runDelegate, inFlight }) {
|
|
69
92
|
const { spec, mode, resumeSessionId, workspace, model, fast } = args;
|
|
70
93
|
|
|
@@ -181,15 +204,8 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
181
204
|
"delegate",
|
|
182
205
|
{
|
|
183
206
|
description:
|
|
184
|
-
|
|
185
|
-
inputSchema:
|
|
186
|
-
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."),
|
|
187
|
-
mode: z.enum(["agent", "plan", "ask"]).default("agent"),
|
|
188
|
-
resumeSessionId: z.string().optional().describe("Resume an existing ACP session instead of a new one"),
|
|
189
|
-
workspace: z.string().optional().describe("Working directory for the agent (defaults to cwd)"),
|
|
190
|
-
model: z.string().trim().min(1, "model must be a non-empty string").default("composer-2.5"),
|
|
191
|
-
fast: z.boolean().default(false).describe("Fast speed tier — higher cost; enable only when the user asks"),
|
|
192
|
-
},
|
|
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 writes in workspace; uses MCP elicitation for clarifying questions and selects the first option when the client lacks elicitation. Returns the final result, selection source, stop reason, session ID, agent-reported files, and optional plan. See the delegate skill for orchestration.`,
|
|
208
|
+
inputSchema: delegateInputSchema,
|
|
193
209
|
outputSchema: delegateOutputSchema,
|
|
194
210
|
annotations: {
|
|
195
211
|
title: "Delegate coding task to Cursor",
|
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
import { isChildAlive, treeKill } from "./proc.js";
|
|
2
|
-
|
|
3
|
-
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
4
|
-
|
|
5
1
|
function makeError(reason, message) {
|
|
6
2
|
const err = new Error(message);
|
|
7
3
|
err.reason = reason;
|
|
@@ -10,24 +6,30 @@ function makeError(reason, message) {
|
|
|
10
6
|
|
|
11
7
|
export class SessionSupervisor {
|
|
12
8
|
constructor(client, {
|
|
13
|
-
|
|
9
|
+
handshakeMs = 60000,
|
|
14
10
|
hardCapMs = 3600000,
|
|
15
|
-
|
|
16
|
-
killGraceMs = 5000,
|
|
11
|
+
idleMs = 0,
|
|
17
12
|
} = {}) {
|
|
18
13
|
this.client = client;
|
|
19
|
-
this.
|
|
14
|
+
this.handshakeMs = handshakeMs;
|
|
20
15
|
this.hardCapMs = hardCapMs;
|
|
21
|
-
|
|
22
|
-
|
|
16
|
+
// Mid-turn idle detection is opt-in and off by default. cursor-agent emits no ACP
|
|
17
|
+
// frames while a shell command runs, so silence during a prompt turn says nothing
|
|
18
|
+
// about liveness — see docs/acp-probes/2026-07-21-client-terminal-capability.
|
|
19
|
+
this.idleMs = idleMs > 0 ? idleMs : 0;
|
|
23
20
|
this.sessionId = null;
|
|
21
|
+
this.lastActivityAt = Date.now();
|
|
24
22
|
this._idleTimer = null;
|
|
23
|
+
this._handshakeTimer = null;
|
|
25
24
|
this._hardCapTimer = null;
|
|
26
25
|
this._armed = false;
|
|
27
26
|
this._settled = false;
|
|
28
|
-
this.
|
|
27
|
+
this._promptStarted = false;
|
|
29
28
|
this._guardReject = null;
|
|
30
|
-
this._onActivity = () =>
|
|
29
|
+
this._onActivity = () => {
|
|
30
|
+
this.lastActivityAt = Date.now();
|
|
31
|
+
this._resetIdle();
|
|
32
|
+
};
|
|
31
33
|
this._onExit = (info) => {
|
|
32
34
|
this._trip(
|
|
33
35
|
"agent-exit",
|
|
@@ -40,6 +42,10 @@ export class SessionSupervisor {
|
|
|
40
42
|
this.sessionId = sessionId;
|
|
41
43
|
}
|
|
42
44
|
|
|
45
|
+
msSinceActivity() {
|
|
46
|
+
return Date.now() - this.lastActivityAt;
|
|
47
|
+
}
|
|
48
|
+
|
|
43
49
|
arm() {
|
|
44
50
|
if (this._armed) return;
|
|
45
51
|
this._armed = true;
|
|
@@ -48,6 +54,19 @@ export class SessionSupervisor {
|
|
|
48
54
|
this._hardCapTimer = setTimeout(() => {
|
|
49
55
|
this._trip("hard-cap", `Session hard-cap exceeded after ${this.hardCapMs}ms`);
|
|
50
56
|
}, this.hardCapMs);
|
|
57
|
+
this._handshakeTimer = setTimeout(() => {
|
|
58
|
+
this._trip("handshake-timeout", `Agent handshake timeout after ${this.handshakeMs}ms (no prompt in flight)`);
|
|
59
|
+
}, this.handshakeMs);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// The handshake is strict request/response, so silence there is real evidence of a
|
|
63
|
+
// wedged agent. Once the prompt is in flight that stops being true, and the deadline
|
|
64
|
+
// must come off.
|
|
65
|
+
promptStarted() {
|
|
66
|
+
if (this._promptStarted) return;
|
|
67
|
+
this._promptStarted = true;
|
|
68
|
+
clearTimeout(this._handshakeTimer);
|
|
69
|
+
this._handshakeTimer = null;
|
|
51
70
|
this._resetIdle();
|
|
52
71
|
}
|
|
53
72
|
|
|
@@ -57,14 +76,17 @@ export class SessionSupervisor {
|
|
|
57
76
|
this.client.off("activity", this._onActivity);
|
|
58
77
|
this.client.off("exit", this._onExit);
|
|
59
78
|
clearTimeout(this._idleTimer);
|
|
79
|
+
clearTimeout(this._handshakeTimer);
|
|
60
80
|
clearTimeout(this._hardCapTimer);
|
|
61
81
|
this._idleTimer = null;
|
|
82
|
+
this._handshakeTimer = null;
|
|
62
83
|
this._hardCapTimer = null;
|
|
63
84
|
}
|
|
64
85
|
|
|
65
86
|
_resetIdle() {
|
|
66
87
|
clearTimeout(this._idleTimer);
|
|
67
|
-
|
|
88
|
+
this._idleTimer = null;
|
|
89
|
+
if (!this.idleMs || !this._promptStarted || !this._armed || this._settled) return;
|
|
68
90
|
this._idleTimer = setTimeout(() => {
|
|
69
91
|
this._trip("idle-timeout", `Session idle timeout after ${this.idleMs}ms`);
|
|
70
92
|
}, this.idleMs);
|
|
@@ -79,29 +101,13 @@ export class SessionSupervisor {
|
|
|
79
101
|
this._settled = true;
|
|
80
102
|
this.disarm();
|
|
81
103
|
const err = makeError(reason, message);
|
|
82
|
-
if (reason === "idle-timeout" || reason === "hard-cap" || reason === "aborted") {
|
|
83
|
-
if (
|
|
104
|
+
if (reason === "idle-timeout" || reason === "handshake-timeout" || reason === "hard-cap" || reason === "aborted") {
|
|
105
|
+
if (this.sessionId) { try { this.client.cancel(this.sessionId); } catch {} }
|
|
84
106
|
}
|
|
85
107
|
this._guardReject?.(err);
|
|
86
108
|
}
|
|
87
109
|
|
|
88
|
-
async _runEscalation() {
|
|
89
|
-
const { client, sessionId } = this;
|
|
90
|
-
if (sessionId) {
|
|
91
|
-
try { await client.cancel(sessionId); } catch {}
|
|
92
|
-
await sleep(this.cancelGraceMs);
|
|
93
|
-
}
|
|
94
|
-
const child = client.child;
|
|
95
|
-
if (!isChildAlive(child)) return;
|
|
96
|
-
try { child.kill(); } catch {}
|
|
97
|
-
await sleep(this.killGraceMs);
|
|
98
|
-
if (!isChildAlive(child)) return;
|
|
99
|
-
const pid = child.pid;
|
|
100
|
-
if (pid) await treeKill(pid);
|
|
101
|
-
}
|
|
102
|
-
|
|
103
110
|
finish() {
|
|
104
|
-
this._escalation?.catch(() => {});
|
|
105
111
|
this.disarm();
|
|
106
112
|
}
|
|
107
113
|
|
package/src/touched-files.js
DELETED
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
import { execFileSync } from "node:child_process";
|
|
2
|
-
import path from "node:path";
|
|
3
|
-
|
|
4
|
-
// Diff blocks miss shell-driven edits; git before/after delta is the primary signal.
|
|
5
|
-
|
|
6
|
-
function defaultRun(cmd, args) {
|
|
7
|
-
return execFileSync(cmd, args, { encoding: "utf8", windowsHide: true });
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
export function parsePorcelain(stdout, repoRoot) {
|
|
11
|
-
const set = new Set();
|
|
12
|
-
for (const raw of String(stdout || "").split("\n")) {
|
|
13
|
-
if (!raw.trim()) continue;
|
|
14
|
-
const rest = raw.slice(3);
|
|
15
|
-
const arrow = rest.indexOf(" -> ");
|
|
16
|
-
const p = (arrow !== -1 ? rest.slice(arrow + 4) : rest).trim();
|
|
17
|
-
if (p) set.add(path.resolve(repoRoot, p));
|
|
18
|
-
}
|
|
19
|
-
return set;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export function gitChangedSet(workspace, run = defaultRun) {
|
|
23
|
-
if (!workspace) return null;
|
|
24
|
-
try {
|
|
25
|
-
const root = run("git", ["-C", workspace, "rev-parse", "--show-toplevel"]).trim();
|
|
26
|
-
const out = run("git", [
|
|
27
|
-
"-C", workspace, "-c", "core.quotepath=false",
|
|
28
|
-
"status", "--porcelain=v1", "--untracked-files=all",
|
|
29
|
-
]);
|
|
30
|
-
return parsePorcelain(out, root);
|
|
31
|
-
} catch {
|
|
32
|
-
return null;
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
function relativize(abs, workspace) {
|
|
37
|
-
if (!workspace) return abs;
|
|
38
|
-
const r = path.relative(workspace, abs);
|
|
39
|
-
if (!r || r.startsWith("..") || path.isAbsolute(r)) return abs;
|
|
40
|
-
return r.split(path.sep).join("/");
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export function computeTouched({ before, after, diffTouched = [], workspace } = {}) {
|
|
44
|
-
const diffAbs = diffTouched.map((p) => (workspace ? path.resolve(workspace, p) : path.resolve(p)));
|
|
45
|
-
let files;
|
|
46
|
-
let source;
|
|
47
|
-
if (!after) {
|
|
48
|
-
files = [...new Set(diffAbs)];
|
|
49
|
-
source = "diff-only";
|
|
50
|
-
} else {
|
|
51
|
-
const beforeSet = before || new Set();
|
|
52
|
-
const out = new Set();
|
|
53
|
-
for (const f of after) if (!beforeSet.has(f)) out.add(f);
|
|
54
|
-
for (const f of diffAbs) if (after.has(f)) out.add(f);
|
|
55
|
-
files = [...out];
|
|
56
|
-
source = "git";
|
|
57
|
-
}
|
|
58
|
-
return { files: files.map((f) => relativize(f, workspace)), source };
|
|
59
|
-
}
|