cursor-delegate-mcp 1.6.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 +164 -15
- package/src/doctor.js +7 -1
- package/src/request-router.js +49 -42
- package/src/server.js +65 -25
- package/src/session-supervisor.js +41 -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,11 +64,20 @@ 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,
|
|
71
|
+
signal,
|
|
39
72
|
} = {}) {
|
|
40
|
-
|
|
73
|
+
if (signal?.aborted) {
|
|
74
|
+
const err = new Error("delegation aborted by MCP host");
|
|
75
|
+
err.reason = "aborted";
|
|
76
|
+
throw err;
|
|
77
|
+
}
|
|
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);
|
|
41
81
|
const MAX_OUTPUT = 10 * 1024 * 1024;
|
|
42
82
|
const TRUNCATION_MARKER = "\n\n[output truncated at 10MB]";
|
|
43
83
|
const questionsAsked = [];
|
|
@@ -51,6 +91,30 @@ export async function runDelegate({
|
|
|
51
91
|
? async (q) => { recordQuestions(q); return onElicit(q); }
|
|
52
92
|
: async (q) => { recordQuestions(q); return null; };
|
|
53
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
|
+
|
|
54
118
|
let planEntries = [];
|
|
55
119
|
let planOverview;
|
|
56
120
|
let planDetail;
|
|
@@ -94,9 +158,39 @@ export async function runDelegate({
|
|
|
94
158
|
return plan;
|
|
95
159
|
};
|
|
96
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
|
+
|
|
97
189
|
const make = clientFactory || ((opts) => new AcpClient(opts));
|
|
98
|
-
const client = make({ onElicit: wrappedElicit, mode, onCreatePlan: recordCreatePlan });
|
|
99
|
-
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 });
|
|
192
|
+
const onAbort = () => supervisor.abort();
|
|
193
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
100
194
|
|
|
101
195
|
const resultChunks = [];
|
|
102
196
|
let resultLength = 0;
|
|
@@ -187,6 +281,26 @@ export async function runDelegate({
|
|
|
187
281
|
const thoughtProgress = progressStream("thinking: ");
|
|
188
282
|
const messageProgress = progressStream("Cursor: ");
|
|
189
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
|
+
|
|
190
304
|
client.on("update", (u) => {
|
|
191
305
|
const up = u?.update || {};
|
|
192
306
|
if (up.sessionUpdate === "plan") {
|
|
@@ -199,8 +313,8 @@ export async function runDelegate({
|
|
|
199
313
|
startTool(up.toolCallId, up.status);
|
|
200
314
|
const label = up.title || up.kind || "tool";
|
|
201
315
|
const path = up.locations?.[0]?.path;
|
|
202
|
-
|
|
203
|
-
try { onProgress?.(
|
|
316
|
+
lastToolLabel = String(label) + (path ? " — " + path : "");
|
|
317
|
+
try { onProgress?.(("running: " + lastToolLabel).slice(0, 200)); } catch {}
|
|
204
318
|
}
|
|
205
319
|
if (up.sessionUpdate === "agent_message_chunk" && up.content?.text) {
|
|
206
320
|
const text = up.content.text;
|
|
@@ -214,13 +328,18 @@ export async function runDelegate({
|
|
|
214
328
|
touched.add(c.path);
|
|
215
329
|
try { onProgress?.("editing " + c.path); } catch {}
|
|
216
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
|
+
}
|
|
217
337
|
}
|
|
218
338
|
}
|
|
219
339
|
});
|
|
220
340
|
|
|
341
|
+
let sessionId;
|
|
221
342
|
try {
|
|
222
|
-
let sessionId;
|
|
223
|
-
const gitBefore = gitChangedSet(workspace);
|
|
224
343
|
const res = await supervisor.supervise(async () => {
|
|
225
344
|
await client.start();
|
|
226
345
|
await client.initialize();
|
|
@@ -228,6 +347,7 @@ export async function runDelegate({
|
|
|
228
347
|
sessionId = sess.sessionId;
|
|
229
348
|
supervisor.setSessionId(sessionId);
|
|
230
349
|
onSessionReady?.(sessionId, client);
|
|
350
|
+
assertKnownModel(client, model);
|
|
231
351
|
await client.setModel(sessionId, model);
|
|
232
352
|
if (composerFastToggleApplies(model)) await client.setFast(sessionId, fast);
|
|
233
353
|
await client.setMode(sessionId, mode);
|
|
@@ -240,7 +360,12 @@ export async function runDelegate({
|
|
|
240
360
|
planEntries = [];
|
|
241
361
|
planOverview = undefined;
|
|
242
362
|
planDetail = undefined;
|
|
363
|
+
todos = new Map();
|
|
364
|
+
sawTodoFrame = false;
|
|
243
365
|
touched.clear();
|
|
366
|
+
lastToolLabel = null;
|
|
367
|
+
supervisor.promptStarted();
|
|
368
|
+
startHeartbeat();
|
|
244
369
|
return client.prompt(sessionId, resolveSpec(spec));
|
|
245
370
|
});
|
|
246
371
|
thoughtProgress.end();
|
|
@@ -251,8 +376,6 @@ export async function runDelegate({
|
|
|
251
376
|
const resultSource = finalMessageAvailable
|
|
252
377
|
? (sawToolCall ? "post-tool" : "tool-free-stream")
|
|
253
378
|
: "none";
|
|
254
|
-
const gitAfter = gitChangedSet(workspace);
|
|
255
|
-
const touchedResult = computeTouched({ before: gitBefore, after: gitAfter, diffTouched: [...touched], workspace });
|
|
256
379
|
const protocolWarnings = [];
|
|
257
380
|
let stopReason;
|
|
258
381
|
if (res?.stopReason !== undefined) {
|
|
@@ -265,23 +388,49 @@ export async function runDelegate({
|
|
|
265
388
|
finalMessageAvailable,
|
|
266
389
|
stopReason,
|
|
267
390
|
sessionId,
|
|
268
|
-
|
|
269
|
-
touchedFilesSource: touchedResult.source,
|
|
391
|
+
filesReportedByAgent: normalizeAgentReportedFiles([...touched], workspace),
|
|
270
392
|
questionsAsked,
|
|
271
393
|
resumed: !!resumeSessionId && sessionId === resumeSessionId,
|
|
272
394
|
};
|
|
273
395
|
if (planEntries.length > 0 || planOverview !== undefined || planDetail !== undefined) {
|
|
274
396
|
out.plan = sanitizePlan(protocolWarnings);
|
|
275
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));
|
|
276
401
|
if (protocolWarnings.length) out.protocolWarnings = protocolWarnings;
|
|
277
402
|
return out;
|
|
278
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
|
+
}
|
|
279
426
|
try {
|
|
280
427
|
const transcript = client.getTranscript?.(40);
|
|
281
428
|
if (transcript) err.message += "\n\n--- recent ACP transcript (last 40 frames) ---\n" + transcript;
|
|
282
429
|
} catch {}
|
|
283
430
|
throw err;
|
|
284
431
|
} finally {
|
|
432
|
+
clearInterval(heartbeat);
|
|
433
|
+
signal?.removeEventListener("abort", onAbort);
|
|
285
434
|
try { supervisor.finish(); } catch {}
|
|
286
435
|
client.stop();
|
|
287
436
|
}
|
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,18 +31,33 @@ 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(),
|
|
39
40
|
fallbackAnswers: z.array(z.object({ prompt: z.string(), given: z.string(), chosen: z.string() })).optional(),
|
|
41
|
+
cancelRequested: z.boolean().optional(),
|
|
40
42
|
protocolWarnings: z.array(z.string()).optional(),
|
|
41
43
|
plan: z.object({
|
|
42
44
|
entries: z.array(planEntrySchema),
|
|
43
45
|
overview: z.string().optional(),
|
|
44
46
|
detail: z.string().optional(),
|
|
45
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(),
|
|
46
61
|
}).passthrough();
|
|
47
62
|
|
|
48
63
|
const doctorOutputSchema = z.object({
|
|
@@ -64,6 +79,15 @@ const doctorOutputSchema = z.object({
|
|
|
64
79
|
env: z.record(z.unknown()),
|
|
65
80
|
}).passthrough();
|
|
66
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
|
+
|
|
67
91
|
export async function runDelegateTool({ args, extra, server, runDelegate, inFlight }) {
|
|
68
92
|
const { spec, mode, resumeSessionId, workspace, model, fast } = args;
|
|
69
93
|
|
|
@@ -133,6 +157,7 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
|
|
|
133
157
|
};
|
|
134
158
|
|
|
135
159
|
let capturedSessionId;
|
|
160
|
+
let handle;
|
|
136
161
|
try {
|
|
137
162
|
const out = await runDelegate({
|
|
138
163
|
spec,
|
|
@@ -143,13 +168,16 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
|
|
|
143
168
|
fast,
|
|
144
169
|
onElicit,
|
|
145
170
|
onProgress,
|
|
171
|
+
signal: extra?.signal,
|
|
146
172
|
onSessionReady: (sessionId, client) => {
|
|
147
173
|
capturedSessionId = sessionId;
|
|
148
|
-
|
|
174
|
+
handle = { client, cancelRequested: false };
|
|
175
|
+
inFlight.set(sessionId, handle);
|
|
149
176
|
},
|
|
150
177
|
});
|
|
151
178
|
if (autoAnswered.length) out.autoAnswered = autoAnswered;
|
|
152
179
|
if (fallbackAnswers.length) out.fallbackAnswers = fallbackAnswers;
|
|
180
|
+
if (handle?.cancelRequested) out.cancelRequested = true;
|
|
153
181
|
return {
|
|
154
182
|
content: [{ type: "text", text: JSON.stringify(out, null, 2) }],
|
|
155
183
|
structuredContent: out,
|
|
@@ -164,7 +192,7 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
|
|
|
164
192
|
}
|
|
165
193
|
}
|
|
166
194
|
|
|
167
|
-
export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected } = {}) {
|
|
195
|
+
export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000 } = {}) {
|
|
168
196
|
const runDelegate = runDelegateInjected || runDelegateDefault;
|
|
169
197
|
const runDoctor = runDoctorInjected || runDoctorDefault;
|
|
170
198
|
const server = new McpServer(
|
|
@@ -176,15 +204,8 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
176
204
|
"delegate",
|
|
177
205
|
{
|
|
178
206
|
description:
|
|
179
|
-
|
|
180
|
-
inputSchema:
|
|
181
|
-
spec: z.string().describe("Inline task brief (default): goal, scope, acceptance criteria. Optional file path if the user wants a persisted spec."),
|
|
182
|
-
mode: z.enum(["agent", "plan", "ask"]).default("agent"),
|
|
183
|
-
resumeSessionId: z.string().optional().describe("Resume an existing ACP session instead of a new one"),
|
|
184
|
-
workspace: z.string().optional().describe("Working directory for the agent (defaults to cwd)"),
|
|
185
|
-
model: z.string().default("composer-2.5"),
|
|
186
|
-
fast: z.boolean().default(false).describe("Fast speed tier — higher cost; enable only when the user asks"),
|
|
187
|
-
},
|
|
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,
|
|
188
209
|
outputSchema: delegateOutputSchema,
|
|
189
210
|
annotations: {
|
|
190
211
|
title: "Delegate coding task to Cursor",
|
|
@@ -197,13 +218,16 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
197
218
|
async (args, extra) => runDelegateTool({ args, extra, server, runDelegate, inFlight })
|
|
198
219
|
);
|
|
199
220
|
|
|
200
|
-
// cancel is best-effort: MCP tool calls are serialized, so delegate must finish first.
|
|
201
221
|
server.registerTool(
|
|
202
222
|
"cancel",
|
|
203
223
|
{
|
|
204
|
-
description:
|
|
205
|
-
|
|
206
|
-
|
|
224
|
+
description:
|
|
225
|
+
"Best-effort cancel of an in-flight ACP delegation by sessionId. Sends session/cancel; the agent may finish the turn anyway. The delegate result carries cancelRequested: true when the turn was cancelled mid-run. MCP hosts that serialize tool calls cannot run this while delegate is in flight. With force: true, the agent process is killed if the turn is still running after a short grace period.",
|
|
226
|
+
inputSchema: {
|
|
227
|
+
sessionId: z.string(),
|
|
228
|
+
force: z.boolean().default(false).describe("After the cancel notify, wait a short grace period and kill the agent process if the delegation is still running"),
|
|
229
|
+
},
|
|
230
|
+
outputSchema: z.object({ status: z.enum(["cancelled", "killed", "not-found"]), sessionId: z.string() }),
|
|
207
231
|
annotations: {
|
|
208
232
|
title: "Cancel Cursor delegation",
|
|
209
233
|
readOnlyHint: false,
|
|
@@ -212,19 +236,35 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
212
236
|
openWorldHint: false,
|
|
213
237
|
},
|
|
214
238
|
},
|
|
215
|
-
async ({ sessionId }) => {
|
|
216
|
-
const
|
|
217
|
-
if (
|
|
218
|
-
|
|
239
|
+
async ({ sessionId, force }) => {
|
|
240
|
+
const handle = inFlight.get(sessionId);
|
|
241
|
+
if (!handle) {
|
|
242
|
+
return {
|
|
243
|
+
content: [{ type: "text", text: `no in-flight session ${sessionId}` }],
|
|
244
|
+
structuredContent: { status: "not-found", sessionId },
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
handle.cancelRequested = true;
|
|
248
|
+
await handle.client.cancel(sessionId).catch(() => {});
|
|
249
|
+
if (!force) {
|
|
219
250
|
inFlight.delete(sessionId);
|
|
220
251
|
return {
|
|
221
252
|
content: [{ type: "text", text: `cancelled ${sessionId}` }],
|
|
222
253
|
structuredContent: { status: "cancelled", sessionId },
|
|
223
254
|
};
|
|
224
255
|
}
|
|
256
|
+
await new Promise((r) => setTimeout(r, forceGraceMs));
|
|
257
|
+
if (!inFlight.has(sessionId)) {
|
|
258
|
+
return {
|
|
259
|
+
content: [{ type: "text", text: `cancelled ${sessionId}` }],
|
|
260
|
+
structuredContent: { status: "cancelled", sessionId },
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
handle.client.stop();
|
|
264
|
+
inFlight.delete(sessionId);
|
|
225
265
|
return {
|
|
226
|
-
content: [{ type: "text", text: `
|
|
227
|
-
structuredContent: { status: "
|
|
266
|
+
content: [{ type: "text", text: `killed ${sessionId}` }],
|
|
267
|
+
structuredContent: { status: "killed", sessionId },
|
|
228
268
|
};
|
|
229
269
|
}
|
|
230
270
|
);
|
|
@@ -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,47 +76,38 @@ 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);
|
|
71
93
|
}
|
|
72
94
|
|
|
95
|
+
abort() {
|
|
96
|
+
this._trip("aborted", "delegation aborted by MCP host");
|
|
97
|
+
}
|
|
98
|
+
|
|
73
99
|
_trip(reason, message) {
|
|
74
100
|
if (this._settled) return;
|
|
75
101
|
this._settled = true;
|
|
76
102
|
this.disarm();
|
|
77
103
|
const err = makeError(reason, message);
|
|
78
|
-
if (reason === "idle-timeout" || reason === "hard-cap") {
|
|
79
|
-
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 {} }
|
|
80
106
|
}
|
|
81
107
|
this._guardReject?.(err);
|
|
82
108
|
}
|
|
83
109
|
|
|
84
|
-
async _runEscalation() {
|
|
85
|
-
const { client, sessionId } = this;
|
|
86
|
-
if (sessionId) {
|
|
87
|
-
try { await client.cancel(sessionId); } catch {}
|
|
88
|
-
await sleep(this.cancelGraceMs);
|
|
89
|
-
}
|
|
90
|
-
const child = client.child;
|
|
91
|
-
if (!isChildAlive(child)) return;
|
|
92
|
-
try { child.kill(); } catch {}
|
|
93
|
-
await sleep(this.killGraceMs);
|
|
94
|
-
if (!isChildAlive(child)) return;
|
|
95
|
-
const pid = child.pid;
|
|
96
|
-
if (pid) await treeKill(pid);
|
|
97
|
-
}
|
|
98
|
-
|
|
99
110
|
finish() {
|
|
100
|
-
this._escalation?.catch(() => {});
|
|
101
111
|
this.disarm();
|
|
102
112
|
}
|
|
103
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
|
-
}
|