cursor-delegate-mcp 1.7.0 → 1.9.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 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 `touchedFiles` and the git diff before committing.
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursor-delegate-mcp",
3
- "version": "1.7.0",
3
+ "version": "1.9.0",
4
4
  "type": "module",
5
5
  "description": "MCP server bridging AI coding hosts to cursor-agent over the Agent Client Protocol (ACP).",
6
6
  "license": "MIT",
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,11 +64,24 @@ export class AcpClient extends EventEmitter {
62
64
  });
63
65
  }
64
66
 
65
- initialize() { return this.peer.request("initialize", { protocolVersion: 1, clientInfo: { name: "cursor-delegate-mcp", version: VERSION }, clientCapabilities: { _meta: { parameterizedModelPicker: true } } }); }
66
- newSession(cwd) { return this.peer.request("session/new", { cwd, mcpServers: [] }); }
67
- loadSession(sessionId, cwd) { return this.peer.request("session/load", { sessionId, cwd, mcpServers: [] }); }
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
- 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
84
+ setConfigOption(sessionId, configId, value) { return this.peer.request("session/set_config_option", { sessionId, configId, value: String(value) }); } // configId, not optionId; ACP wants a string value
70
85
  setMode(sessionId, modeId) { return this.peer.request("session/set_mode", { sessionId, modeId }); }
71
86
  prompt(sessionId, text) { return this.peer.request("session/prompt", { sessionId, prompt: [{ type: "text", text }] }); }
72
87
  cancel(sessionId) { this.peer.notify("session/cancel", { sessionId }); return Promise.resolve(); }
@@ -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) && process.platform === "win32" && this.child.pid) {
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 { gitChangedSet as gitChangedSetReal, computeTouched } from "./touched-files.js";
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;
@@ -19,23 +37,49 @@ async function openSession(client, resumeSessionId, workspace) {
19
37
  try {
20
38
  await client.loadSession(resumeSessionId, workspace);
21
39
  return { sessionId: resumeSessionId }; // load does not echo sessionId
22
- } catch {
23
- // stale or unknown session — start fresh
40
+ } catch (err) {
41
+ // Starting fresh is right, but silently doing so leaves the caller unable to tell a
42
+ // stale id from a typo'd one — keep why the load failed.
43
+ const fresh = await client.newSession(workspace);
44
+ return { ...fresh, resumeError: err?.message || String(err) };
24
45
  }
25
- return client.newSession(workspace);
26
46
  }
27
47
 
28
- // Composer bare ids (e.g. composer-2.5) expose standard vs fast via set_config_option.
29
- // Other models use separate ids (e.g. gpt-5-fast) — see cursor-agent --list-models.
30
- function composerFastToggleApplies(model) {
31
- return /^composer-\d+(?:\.\d+)?$/i.test(model);
48
+ // session/new reports the models the agent actually offers. Reject an unknown id here,
49
+ // where the real list can be named, rather than letting set_model fail without it.
50
+ // Agents that report no list are left alone.
51
+ function assertKnownModel(client, model) {
52
+ const available = client?.sessionModels?.availableModels;
53
+ if (!Array.isArray(available) || available.length === 0) return;
54
+ const ids = available.map((m) => m?.modelId).filter((id) => typeof id === "string");
55
+ if (ids.length === 0 || ids.includes(model)) return;
56
+ const err = new Error(`Unknown model ${JSON.stringify(model)}. This agent offers: ${ids.join(", ")}.`);
57
+ err.reason = "unknown-model";
58
+ throw err;
59
+ }
60
+
61
+ // Which config options a model carries is not discoverable up front: session/new reports
62
+ // configOptions for the default model and set_model returns nothing. So ask, and read the
63
+ // rejection as the answer. Two distinct -32602s, both measured: "Unknown model config
64
+ // option: X" means this model has no such knob — report it and carry on. "Invalid value
65
+ // for X: Y" means the caller named a value the model rejects, which must not be swallowed.
66
+ // Returns true when the option is unsupported.
67
+ async function applyConfig(client, sessionId, configId, value) {
68
+ try {
69
+ await client.setConfigOption(sessionId, configId, value);
70
+ return false;
71
+ } catch (err) {
72
+ if (err?.code !== -32602 || !/unknown model config option/i.test(err?.message || "")) throw err;
73
+ return true;
74
+ }
32
75
  }
33
76
 
34
77
  export async function runDelegate({
35
78
  spec, mode = "agent", resumeSessionId, workspace,
36
- model = "composer-2.5", fast = false, clientFactory, onElicit,
37
- idleMs = 90000, hardCapMs, timeoutMs, cancelGraceMs = 10000, killGraceMs = 5000,
38
- onSessionReady, onProgress, progressThrottleMs = 2000, gitChangedSet = gitChangedSetReal,
79
+ model = DEFAULT_MODEL, fast = false, reasoning, context, clientFactory, onElicit,
80
+ idleMs, handshakeMs, hardCapMs, timeoutMs,
81
+ onSessionReady, onProgress, progressThrottleMs = 2000,
82
+ heartbeatMs = DEFAULT_HEARTBEAT_MS,
39
83
  signal,
40
84
  } = {}) {
41
85
  if (signal?.aborted) {
@@ -43,7 +87,9 @@ export async function runDelegate({
43
87
  err.reason = "aborted";
44
88
  throw err;
45
89
  }
46
- const capMs = hardCapMs ?? timeoutMs ?? 3600000;
90
+ const capMs = hardCapMs ?? timeoutMs ?? envMs("CURSOR_DELEGATE_HARD_CAP_MS", 3600000);
91
+ const shakeMs = handshakeMs ?? envMs("CURSOR_DELEGATE_HANDSHAKE_MS", DEFAULT_HANDSHAKE_MS);
92
+ const turnIdleMs = idleMs ?? envMs("CURSOR_DELEGATE_IDLE_MS", 0);
47
93
  const MAX_OUTPUT = 10 * 1024 * 1024;
48
94
  const TRUNCATION_MARKER = "\n\n[output truncated at 10MB]";
49
95
  const questionsAsked = [];
@@ -57,6 +103,30 @@ export async function runDelegate({
57
103
  ? async (q) => { recordQuestions(q); return onElicit(q); }
58
104
  : async (q) => { recordQuestions(q); return null; };
59
105
 
106
+ // merge:false replaces the list, merge:true upserts by id. Entries always arrive complete,
107
+ // so a keyed set is enough — no field-level merging.
108
+ let todos = new Map();
109
+ let sawTodoFrame = false;
110
+ const todoLabel = () => {
111
+ const entries = [...todos.values()].filter((t) => typeof t?.content === "string");
112
+ if (!entries.length) return null;
113
+ const i = entries.findIndex((t) => t.status === "in_progress");
114
+ if (i !== -1) return `todo ${i + 1}/${entries.length}: ${entries[i].content}`;
115
+ const done = entries.filter((t) => t.status === "completed").length;
116
+ return `todos ${done}/${entries.length} complete`;
117
+ };
118
+ const recordTodos = ({ todos: incoming, merge }) => {
119
+ if (!Array.isArray(incoming)) return;
120
+ sawTodoFrame = true;
121
+ if (merge === false) todos = new Map();
122
+ for (const t of incoming) {
123
+ if (t?.id === undefined || t?.id === null) continue;
124
+ todos.set(String(t.id), t);
125
+ }
126
+ const label = todoLabel();
127
+ if (label) { try { onProgress?.(label.slice(0, 200)); } catch {} }
128
+ };
129
+
60
130
  let planEntries = [];
61
131
  let planOverview;
62
132
  let planDetail;
@@ -100,9 +170,37 @@ export async function runDelegate({
100
170
  return plan;
101
171
  };
102
172
 
173
+ const TODO_STATUSES = ["pending", "in_progress", "completed"];
174
+ const sanitizeTodos = (warnings) => {
175
+ const entries = [];
176
+ let i = -1;
177
+ for (const raw of todos.values()) {
178
+ i++;
179
+ if (typeof raw?.content !== "string") {
180
+ warnings.push(`todo ${i} dropped: expected string content, got ${raw === null ? "null" : typeof raw?.content}`);
181
+ continue;
182
+ }
183
+ const status = TODO_STATUSES.includes(raw.status) ? raw.status : undefined;
184
+ if (raw.status !== undefined && status === undefined) {
185
+ warnings.push(`todo ${i}: unknown status ${JSON.stringify(raw.status)} removed`);
186
+ }
187
+ entries.push({ id: String(raw.id), content: raw.content, ...(status ? { status } : {}) });
188
+ }
189
+ const count = (s) => entries.filter((e) => e.status === s).length;
190
+ return {
191
+ todos: entries,
192
+ todoProgress: {
193
+ total: entries.length,
194
+ completed: count("completed"),
195
+ inProgress: count("in_progress"),
196
+ pending: count("pending"),
197
+ },
198
+ };
199
+ };
200
+
103
201
  const make = clientFactory || ((opts) => new AcpClient(opts));
104
- const client = make({ onElicit: wrappedElicit, mode, onCreatePlan: recordCreatePlan });
105
- const supervisor = new SessionSupervisor(client, { idleMs, hardCapMs: capMs, cancelGraceMs, killGraceMs });
202
+ const client = make({ onElicit: wrappedElicit, mode, onCreatePlan: recordCreatePlan, onTodos: recordTodos });
203
+ const supervisor = new SessionSupervisor(client, { idleMs: turnIdleMs, handshakeMs: shakeMs, hardCapMs: capMs });
106
204
  const onAbort = () => supervisor.abort();
107
205
  signal?.addEventListener("abort", onAbort, { once: true });
108
206
 
@@ -195,11 +293,50 @@ export async function runDelegate({
195
293
  const thoughtProgress = progressStream("thinking: ");
196
294
  const messageProgress = progressStream("Cursor: ");
197
295
 
296
+ // The bridge cannot see inside a running shell command, so a long silence is reported
297
+ // rather than acted on: the caller gets elapsed time and frame age and can decide.
298
+ let lastToolLabel = null;
299
+ let modeChanged;
300
+ let sessionTitle;
301
+ let promptInFlight = false;
302
+ let heartbeat = null;
303
+ const startHeartbeat = () => {
304
+ if (!(heartbeatMs > 0)) return;
305
+ const startedAt = Date.now();
306
+ heartbeat = setInterval(() => {
307
+ const parts = [
308
+ `still working — ${fmtDuration(Date.now() - startedAt)} elapsed`,
309
+ `last agent frame ${fmtDuration(supervisor.msSinceActivity())} ago`,
310
+ ];
311
+ const todo = todoLabel();
312
+ if (todo) parts.push(todo);
313
+ if (lastToolLabel) parts.push(`running: ${lastToolLabel}`);
314
+ try { onProgress?.(parts.join(", ").slice(0, 200)); } catch {}
315
+ }, heartbeatMs);
316
+ heartbeat.unref?.();
317
+ };
318
+
319
+ // session/load replays the previous turn as ordinary session/update frames, including
320
+ // tool_call and diff blocks. The reset before the prompt clears the state they touch,
321
+ // but it cannot unsend the progress notifications they already emitted — a resume
322
+ // otherwise reports the previous turn's tool calls and edits as if they were happening.
198
323
  client.on("update", (u) => {
324
+ if (!promptInFlight) return;
199
325
  const up = u?.update || {};
200
326
  if (up.sessionUpdate === "plan") {
201
327
  planEntries = up.entries || [];
202
328
  }
329
+ // A plan-mode run that switches itself to agent mode becomes write-capable while the
330
+ // caller still believes nothing can change. No drift has been observed; report it so
331
+ // we find out rather than assume.
332
+ if (up.sessionUpdate === "current_mode_update" && up.currentModeId && up.currentModeId !== mode) {
333
+ modeChanged = { from: mode, to: up.currentModeId };
334
+ }
335
+ // The agent names the turn a beat after the prompt lands ("File Creator"). Cheap
336
+ // label for a caller juggling several delegations.
337
+ if (up.sessionUpdate === "session_info_update" && typeof up.title === "string" && up.title) {
338
+ sessionTitle = up.title;
339
+ }
203
340
  if (up.sessionUpdate === "agent_thought_chunk" && up.content?.text) {
204
341
  thoughtProgress.push(up.content.text);
205
342
  }
@@ -207,8 +344,8 @@ export async function runDelegate({
207
344
  startTool(up.toolCallId, up.status);
208
345
  const label = up.title || up.kind || "tool";
209
346
  const path = up.locations?.[0]?.path;
210
- const line = "running: " + String(label) + (path ? " — " + path : "");
211
- try { onProgress?.(line.slice(0, 200)); } catch {}
347
+ lastToolLabel = String(label) + (path ? " — " + path : "");
348
+ try { onProgress?.(("running: " + lastToolLabel).slice(0, 200)); } catch {}
212
349
  }
213
350
  if (up.sessionUpdate === "agent_message_chunk" && up.content?.text) {
214
351
  const text = up.content.text;
@@ -222,22 +359,37 @@ export async function runDelegate({
222
359
  touched.add(c.path);
223
360
  try { onProgress?.("editing " + c.path); } catch {}
224
361
  }
362
+ // cursor-agent has never been observed emitting these; ACP allows an agent to
363
+ // stream tool output this way, so treat it like message text rather than drop it.
364
+ if (c.type === "content" && typeof c.content?.text === "string") {
365
+ if (!sawToolCall || (collectingPostToolResult && activeToolCalls.size === 0)) appendResult(c.content.text);
366
+ messageProgress.push(c.content.text);
367
+ }
225
368
  }
226
369
  }
227
370
  });
228
371
 
372
+ let sessionId;
373
+ let resumeError;
374
+ const unsupportedOptions = [];
229
375
  try {
230
- let sessionId;
231
- const gitBefore = gitChangedSet(workspace);
232
376
  const res = await supervisor.supervise(async () => {
233
377
  await client.start();
234
378
  await client.initialize();
235
379
  const sess = await openSession(client, resumeSessionId, workspace);
236
380
  sessionId = sess.sessionId;
381
+ resumeError = sess.resumeError;
237
382
  supervisor.setSessionId(sessionId);
238
383
  onSessionReady?.(sessionId, client);
384
+ assertKnownModel(client, model);
239
385
  await client.setModel(sessionId, model);
240
- if (composerFastToggleApplies(model)) await client.setFast(sessionId, fast);
386
+ // fast is always sent: a resumed session may already have it on, so false is a real
387
+ // instruction. reasoning and context are only sent when the caller named one.
388
+ if (await applyConfig(client, sessionId, "fast", fast) && fast) unsupportedOptions.push("fast");
389
+ for (const [id, value] of [["reasoning", reasoning], ["context", context]]) {
390
+ if (value === undefined) continue;
391
+ if (await applyConfig(client, sessionId, id, value)) unsupportedOptions.push(id);
392
+ }
241
393
  await client.setMode(sessionId, mode);
242
394
  resetResult();
243
395
  sawToolCall = false;
@@ -248,7 +400,15 @@ export async function runDelegate({
248
400
  planEntries = [];
249
401
  planOverview = undefined;
250
402
  planDetail = undefined;
403
+ todos = new Map();
404
+ sawTodoFrame = false;
251
405
  touched.clear();
406
+ lastToolLabel = null;
407
+ modeChanged = undefined;
408
+ sessionTitle = undefined;
409
+ supervisor.promptStarted();
410
+ startHeartbeat();
411
+ promptInFlight = true;
252
412
  return client.prompt(sessionId, resolveSpec(spec));
253
413
  });
254
414
  thoughtProgress.end();
@@ -259,8 +419,6 @@ export async function runDelegate({
259
419
  const resultSource = finalMessageAvailable
260
420
  ? (sawToolCall ? "post-tool" : "tool-free-stream")
261
421
  : "none";
262
- const gitAfter = gitChangedSet(workspace);
263
- const touchedResult = computeTouched({ before: gitBefore, after: gitAfter, diffTouched: [...touched], workspace });
264
422
  const protocolWarnings = [];
265
423
  let stopReason;
266
424
  if (res?.stopReason !== undefined) {
@@ -273,23 +431,65 @@ export async function runDelegate({
273
431
  finalMessageAvailable,
274
432
  stopReason,
275
433
  sessionId,
276
- touchedFiles: touchedResult.files,
277
- touchedFilesSource: touchedResult.source,
434
+ filesReportedByAgent: normalizeAgentReportedFiles([...touched], workspace),
278
435
  questionsAsked,
279
436
  resumed: !!resumeSessionId && sessionId === resumeSessionId,
280
437
  };
438
+ if (sessionTitle) out.sessionTitle = sessionTitle;
439
+ if (resumeError) protocolWarnings.push(`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`);
440
+ for (const id of unsupportedOptions) protocolWarnings.push(`model ${model} has no ${id} option; the requested value was ignored`);
281
441
  if (planEntries.length > 0 || planOverview !== undefined || planDetail !== undefined) {
282
442
  out.plan = sanitizePlan(protocolWarnings);
283
443
  }
444
+ // Most successful turns emit no todos at all, so an empty list would read as "nothing
445
+ // done" rather than "not tracked". Report only what the agent actually sent.
446
+ if (sawTodoFrame) Object.assign(out, sanitizeTodos(protocolWarnings));
447
+ if (modeChanged) {
448
+ out.modeChanged = modeChanged;
449
+ protocolWarnings.push(`agent switched mode from ${modeChanged.from} to ${modeChanged.to} mid-session`);
450
+ }
284
451
  if (protocolWarnings.length) out.protocolWarnings = protocolWarnings;
285
452
  return out;
286
453
  } catch (err) {
454
+ // A JSON-RPC code means the agent rejected something rather than the bridge breaking.
455
+ // Classifying it here is what lets the caller tell "fix your arguments" from "retry".
456
+ if (!err?.reason && typeof err?.code === "number") err.reason = "agent-error";
457
+ // A bare duration says nothing about whether the agent wedged or a command was just
458
+ // slow. Name what was outstanding so the caller can tell the two apart, and so a
459
+ // retry can resume from the work already done instead of restarting blind.
460
+ const isTimeout = err?.reason === "hard-cap" || err?.reason === "idle-timeout";
461
+ if (isTimeout || err?.reason === "aborted" || err?.reason === "agent-exit") {
462
+ const age = fmtDuration(supervisor.msSinceActivity());
463
+ err.message += `\n\nLast ACP frame ${age} ago${lastToolLabel ? `; last tool call: ${lastToolLabel}` : ""}.`;
464
+ if (sessionTitle) err.message += ` The agent titled this turn ${JSON.stringify(sessionTitle)}.`;
465
+ if (sawTodoFrame) {
466
+ const { todoProgress } = sanitizeTodos([]);
467
+ const current = todoLabel();
468
+ err.message += ` ${todoProgress.completed} of ${todoProgress.total} todos completed`
469
+ + `${current ? `; ${current}` : ""}.`;
470
+ }
471
+ const files = normalizeAgentReportedFiles([...touched], workspace);
472
+ if (files.length) err.message += ` Files reported edited: ${files.join(", ")}.`;
473
+ // Without this the resume hint below reads as "carry on from where you were", when the
474
+ // requested session was never loaded and this turn started from nothing.
475
+ if (resumeError) {
476
+ err.message += ` Note: resuming ${resumeSessionId} had already failed (${resumeError}),`
477
+ + ` so this ran as a fresh session and none of that earlier work was in context.`;
478
+ }
479
+ if (sessionId) err.message += ` Resume with resumeSessionId ${sessionId}.`;
480
+ if (isTimeout) {
481
+ err.message += " cursor-agent does not stream shell output over ACP, so a long-running command emits"
482
+ + " nothing until it exits. Split the command, run it in the background and poll, or raise"
483
+ + " CURSOR_DELEGATE_HARD_CAP_MS.";
484
+ }
485
+ }
287
486
  try {
288
487
  const transcript = client.getTranscript?.(40);
289
488
  if (transcript) err.message += "\n\n--- recent ACP transcript (last 40 frames) ---\n" + transcript;
290
489
  } catch {}
291
490
  throw err;
292
491
  } finally {
492
+ clearInterval(heartbeat);
293
493
  signal?.removeEventListener("abort", onAbort);
294
494
  try { supervisor.finish(); } catch {}
295
495
  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/jsonrpc.js CHANGED
@@ -44,7 +44,13 @@ export class JsonRpcPeer {
44
44
  const p = this.pending.get(msg.id);
45
45
  if (p) {
46
46
  this.pending.delete(msg.id);
47
- if (msg.error) p.reject(new Error(msg.error.message || "rpc error"));
47
+ // cursor-agent puts the actual reason in error.data.message; error.message alone
48
+ // is a bare "Invalid params".
49
+ if (msg.error) {
50
+ const err = new Error([msg.error.message || "rpc error", msg.error.data?.message].filter(Boolean).join(": "));
51
+ err.code = msg.error.code;
52
+ p.reject(err);
53
+ }
48
54
  else p.resolve(msg.result);
49
55
  }
50
56
  } else if (msg.method && hasId) {
@@ -1,42 +1,49 @@
1
- const ACK_METHODS = new Set(["cursor/update_todos", "cursor/task", "cursor/generate_image"]);
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 (ACK_METHODS.has(method)) {
34
- log({ method, params });
35
- return respond(id, {});
36
- }
37
- return respondError(id, -32601, `Unhandled method: ${method}`);
38
- } catch (err) {
39
- return respondError(id, -32000, `Router error: ${err?.message || err}`);
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 touchedFiles plus the git diff after every write-capable run. 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.`;
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,10 +31,14 @@ const delegateOutputSchema = z.object({
31
31
  finalMessageAvailable: z.boolean().optional(),
32
32
  stopReason: z.string().optional(),
33
33
  sessionId: z.string(),
34
- touchedFiles: z.array(z.string()),
35
- touchedFilesSource: z.enum(["git", "diff-only"]).optional(),
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(),
39
+ sessionTitle: z.string().optional().describe(
40
+ "Short title the agent gave this turn. Present on most turns; purely a label."
41
+ ),
38
42
  autoAnswered: z.array(z.object({ prompt: z.string(), chosen: z.string() })).optional(),
39
43
  fallbackAnswers: z.array(z.object({ prompt: z.string(), given: z.string(), chosen: z.string() })).optional(),
40
44
  cancelRequested: z.boolean().optional(),
@@ -44,6 +48,22 @@ const delegateOutputSchema = z.object({
44
48
  overview: z.string().optional(),
45
49
  detail: z.string().optional(),
46
50
  }).optional(),
51
+ todos: z.array(z.object({
52
+ id: z.string(),
53
+ content: z.string(),
54
+ status: z.enum(["pending", "in_progress", "completed"]).optional(),
55
+ })).optional().describe(
56
+ "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."
57
+ ),
58
+ modeChanged: z.object({ from: z.string(), to: z.string() }).optional().describe(
59
+ "Set when the agent switched itself out of the requested mode mid-session."
60
+ ),
61
+ todoProgress: z.object({
62
+ total: z.number(),
63
+ completed: z.number(),
64
+ inProgress: z.number(),
65
+ pending: z.number(),
66
+ }).optional(),
47
67
  }).passthrough();
48
68
 
49
69
  const doctorOutputSchema = z.object({
@@ -65,8 +85,36 @@ const doctorOutputSchema = z.object({
65
85
  env: z.record(z.unknown()),
66
86
  }).passthrough();
67
87
 
88
+ export const delegateInputSchema = z.object({
89
+ 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."),
90
+ mode: z.enum(["agent", "plan", "ask"]).default("agent"),
91
+ resumeSessionId: z.string().optional().describe("Resume an existing ACP session instead of a new one"),
92
+ workspace: z.string().optional().describe("Working directory for the agent (defaults to cwd)"),
93
+ model: z.string().trim().min(1, "model must be a non-empty string").default(DEFAULT_MODEL),
94
+ fast: z.boolean().default(false).describe("Fast speed tier — higher cost; enable only when the user asks"),
95
+ // Which options a model offers, and their valid values, are only knowable by asking the
96
+ // agent, so these stay open strings and the agent rejects what it does not accept.
97
+ reasoning: z.string().trim().min(1).optional().describe("Reasoning effort. Not offered by every model; gpt-5.x accepts none, low, medium, high, extra-high."),
98
+ context: z.string().trim().min(1).optional().describe("Context window size. Not offered by every model; gpt-5.x accepts 272k and 1m."),
99
+ });
100
+
101
+ // A cursor/ask_question question is multi-select when it sets allowMultiple, and the answer
102
+ // field (selectedOptionIds) is a list either way. Only split on commas for those, so a
103
+ // single-select label that itself contains a comma still matches whole.
104
+ function matchOptions(choice, opts = [], allowMultiple = false) {
105
+ const norm = (s) => String(s ?? "").trim().toLowerCase();
106
+ const ids = [];
107
+ for (const part of allowMultiple ? String(choice).split(",") : [String(choice)]) {
108
+ const want = norm(part);
109
+ if (!want) continue;
110
+ const hit = opts.find((o) => norm(o.id) === want || norm(o.label) === want);
111
+ if (hit && !ids.includes(hit.id)) ids.push(hit.id);
112
+ }
113
+ return ids;
114
+ }
115
+
68
116
  export async function runDelegateTool({ args, extra, server, runDelegate, inFlight }) {
69
- const { spec, mode, resumeSessionId, workspace, model, fast } = args;
117
+ const { spec, mode, resumeSessionId, workspace, model, fast, reasoning, context } = args;
70
118
 
71
119
  const progressToken = extra?._meta?.progressToken;
72
120
  let onProgress = () => {};
@@ -91,12 +139,15 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
91
139
  for (const q of questions || []) {
92
140
  const opts = q.options || [];
93
141
  if (!supportsElicitation) {
94
- const chosenOptionId = opts[0]?.id;
95
- const chosen = opts.find((o) => o.id === chosenOptionId)?.label || chosenOptionId || "";
96
- autoAnswered.push({ prompt: String(q.prompt ?? ""), chosen: String(chosen) });
97
- answers.push({ questionId: q.id, selectedOptionIds: [chosenOptionId] });
142
+ // There is no user to ask, so allowMultiple changes nothing here: selecting every
143
+ // option would consent to more than the caller asked for. Take the first and
144
+ // disclose it. An option-less question answers empty rather than [null].
145
+ const first = opts[0];
146
+ autoAnswered.push({ prompt: String(q.prompt ?? ""), chosen: String(first?.label || first?.id || "") });
147
+ answers.push({ questionId: q.id, selectedOptionIds: first?.id ? [first.id] : [] });
98
148
  continue;
99
149
  }
150
+ const listing = opts.map((o) => o.label || o.id).join(", ");
100
151
  const result = await server.server.elicitInput({
101
152
  message: title ? `${title}: ${q.prompt}` : `cursor-agent asks: ${q.prompt}`,
102
153
  requestedSchema: {
@@ -104,7 +155,11 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
104
155
  properties: {
105
156
  choice: {
106
157
  type: "string",
107
- description: opts.length ? `Options: ${opts.map((o) => o.label || o.id).join(", ")}` : "your answer",
158
+ description: !opts.length
159
+ ? "your answer"
160
+ : q.allowMultiple
161
+ ? `Options (pick one or more, comma-separated): ${listing}`
162
+ : `Options: ${listing}`,
108
163
  },
109
164
  },
110
165
  required: ["choice"],
@@ -112,23 +167,16 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
112
167
  });
113
168
  if (result.action !== "accept") return null;
114
169
  const choice = result.content?.choice || "";
115
- let chosenOptionId = opts[0]?.id;
116
- let matched = false;
117
- for (const o of opts) {
118
- if (
119
- choice.toLowerCase() === String(o.id || "").toLowerCase() ||
120
- choice.toLowerCase() === String(o.label || "").toLowerCase()
121
- ) {
122
- chosenOptionId = o.id;
123
- matched = true;
124
- break;
125
- }
126
- }
127
- if (!matched && opts.length) {
128
- const chosen = opts.find((o) => o.id === chosenOptionId)?.label || chosenOptionId || "";
129
- fallbackAnswers.push({ prompt: String(q.prompt ?? ""), given: String(choice), chosen: String(chosen) });
170
+ const selectedOptionIds = matchOptions(choice, opts, q.allowMultiple);
171
+ if (!selectedOptionIds.length && opts.length) {
172
+ selectedOptionIds.push(opts[0].id);
173
+ fallbackAnswers.push({
174
+ prompt: String(q.prompt ?? ""),
175
+ given: String(choice),
176
+ chosen: String(opts[0].label || opts[0].id || ""),
177
+ });
130
178
  }
131
- answers.push({ questionId: q.id, selectedOptionIds: [chosenOptionId] });
179
+ answers.push({ questionId: q.id, selectedOptionIds });
132
180
  }
133
181
  return { answers };
134
182
  };
@@ -143,6 +191,8 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
143
191
  workspace: workspace || process.cwd(),
144
192
  model,
145
193
  fast,
194
+ reasoning,
195
+ context,
146
196
  onElicit,
147
197
  onProgress,
148
198
  signal: extra?.signal,
@@ -161,7 +211,9 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
161
211
  };
162
212
  } catch (err) {
163
213
  return {
164
- content: [{ type: "text", text: "delegate failed: " + (err?.message || String(err)) }],
214
+ // The reason is already decided upstream; naming it here saves the caller parsing
215
+ // prose to tell a timeout from a rejected argument.
216
+ content: [{ type: "text", text: `delegate failed${err?.reason ? ` [${err.reason}]` : ""}: ` + (err?.message || String(err)) }],
165
217
  isError: true,
166
218
  };
167
219
  } finally {
@@ -181,15 +233,8 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
181
233
  "delegate",
182
234
  {
183
235
  description:
184
- "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=composer-2.5, 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, changed files, and optional plan. See the delegate skill for orchestration.",
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
- },
236
+ `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.`,
237
+ inputSchema: delegateInputSchema,
193
238
  outputSchema: delegateOutputSchema,
194
239
  annotations: {
195
240
  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
- idleMs = 90000,
9
+ handshakeMs = 60000,
14
10
  hardCapMs = 3600000,
15
- cancelGraceMs = 10000,
16
- killGraceMs = 5000,
11
+ idleMs = 0,
17
12
  } = {}) {
18
13
  this.client = client;
19
- this.idleMs = idleMs;
14
+ this.handshakeMs = handshakeMs;
20
15
  this.hardCapMs = hardCapMs;
21
- this.cancelGraceMs = cancelGraceMs;
22
- this.killGraceMs = killGraceMs;
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._escalation = null;
27
+ this._promptStarted = false;
29
28
  this._guardReject = null;
30
- this._onActivity = () => this._resetIdle();
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
- if (!this._armed || this._settled) return;
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 (!this._escalation) this._escalation = this._runEscalation();
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
 
@@ -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
- }