cursor-delegate-mcp 2.8.0 → 2.10.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/CHANGELOG.md +47 -0
- package/package.json +1 -1
- package/src/acp-client.js +28 -30
- package/src/acp-enums.js +3 -8
- package/src/delegate.js +93 -124
- package/src/doctor.js +76 -29
- package/src/errors.js +2 -4
- package/src/jsonrpc.js +14 -26
- package/src/model-options.js +9 -14
- package/src/proc.js +8 -13
- package/src/request-router.js +4 -11
- package/src/server.js +81 -101
- package/src/session-supervisor.js +4 -6
- package/src/spawn.js +121 -14
- package/src/turn-state.js +14 -22
- package/src/version.js +2 -4
package/src/server.js
CHANGED
|
@@ -24,10 +24,8 @@ if (nodeMajor < 20) {
|
|
|
24
24
|
process.exit(1);
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
-
// sessionId -> the
|
|
28
|
-
//
|
|
29
|
-
// keying one handle per id let whichever finished first deregister the other — after which
|
|
30
|
-
// cancel reported a running session as already ended.
|
|
27
|
+
// sessionId -> the delegations running on it. A set because a resume can race the turn it
|
|
28
|
+
// resumes; with one handle per id, whichever finished first deregistered the other.
|
|
31
29
|
const inFlight = new Map();
|
|
32
30
|
function registerInFlight(map, sessionId, handle) {
|
|
33
31
|
const handles = map.get(sessionId);
|
|
@@ -44,31 +42,24 @@ function unregisterInFlight(map, sessionId, handle) {
|
|
|
44
42
|
handles.delete(handle);
|
|
45
43
|
if (handles.size === 0) map.delete(sessionId);
|
|
46
44
|
}
|
|
47
|
-
// Delegations whose session has not opened yet
|
|
48
|
-
//
|
|
49
|
-
// there is a live, auto-approved agent that the map cannot name. Shutdown walks this too.
|
|
50
|
-
// cancel deliberately does not: an id the caller has never been given is not one it can pass.
|
|
45
|
+
// Delegations whose session has not opened yet: the agent runs ~3.4s before inFlight can key it.
|
|
46
|
+
// Shutdown walks this; cancel cannot, since the caller has no id for these yet.
|
|
51
47
|
const pendingDelegations = new Set();
|
|
52
48
|
|
|
53
|
-
// Session ids seen this process, kept after the turn ends so cancel can tell a finished
|
|
54
|
-
//
|
|
55
|
-
// long-lived server does not grow without limit.
|
|
49
|
+
// Session ids seen by this process, kept after the turn ends so cancel can tell a finished
|
|
50
|
+
// (still resumable) session from an id that never existed. Bounded.
|
|
56
51
|
const seenSessions = new Set();
|
|
57
52
|
const SEEN_SESSIONS_CAP = 500;
|
|
58
53
|
function rememberSession(set, id) {
|
|
59
54
|
if (id == null) return;
|
|
60
|
-
//
|
|
61
|
-
// resumed moves back to the recent end, so it outlives an equally old id that was seen once
|
|
62
|
-
// and never again. Without it the id a caller is actually working with ages out on insertion
|
|
63
|
-
// order alone, and cancel then calls a live, resumable session one that never existed.
|
|
55
|
+
// Delete-then-add makes the Set an LRU, so a session still being resumed outlives one seen once.
|
|
64
56
|
if (set.has(id)) set.delete(id);
|
|
65
57
|
set.add(id);
|
|
66
58
|
if (set.size > SEEN_SESSIONS_CAP) set.delete(set.values().next().value);
|
|
67
59
|
}
|
|
68
60
|
|
|
69
|
-
//
|
|
70
|
-
//
|
|
71
|
-
// descriptions, read while the call is being written.
|
|
61
|
+
// Read at connect, so only what decides whether to delegate at all. Call-time facts belong on
|
|
62
|
+
// the parameter descriptions.
|
|
72
63
|
export const SERVER_INSTRUCTIONS = `Delegate coding work to Cursor through the delegate tool. Every permission the agent requests is auto-approved, in every mode: agent/plan/ask reach any file the user account can, and mode instructs the agent rather than limiting it. Scope workspace tightly and review the git diff after every run — filesReportedByEditTools carries only what the agent's edit tools reported; the diff is authoritative.`;
|
|
73
64
|
|
|
74
65
|
const planEntrySchema = z.object({
|
|
@@ -77,10 +68,9 @@ const planEntrySchema = z.object({
|
|
|
77
68
|
status: z.enum(PLAN_STATUSES).optional(),
|
|
78
69
|
}).passthrough();
|
|
79
70
|
|
|
80
|
-
// No outputSchema:
|
|
81
|
-
//
|
|
82
|
-
//
|
|
83
|
-
// its tool description.
|
|
71
|
+
// No outputSchema: it requires structuredContent too, and a host that reads both (Codex) puts the
|
|
72
|
+
// payload in context twice. Strict copy in delegate.test.js; field meanings in
|
|
73
|
+
// skills/delegate/reference.md.
|
|
84
74
|
export const delegateOutputShape = {
|
|
85
75
|
result: z.string(),
|
|
86
76
|
resultSource: z.enum(["pre-tool-fallback", "none"]).optional(),
|
|
@@ -111,9 +101,9 @@ export const delegateOutputShape = {
|
|
|
111
101
|
}).optional(),
|
|
112
102
|
};
|
|
113
103
|
|
|
114
|
-
// Same
|
|
115
|
-
//
|
|
116
|
-
//
|
|
104
|
+
// Same contract as delegateOutputShape; strict copy in doctor.test.js. Relayed agent fields stay
|
|
105
|
+
// unknown so an odd protocolVersion is a diagnostic, not a failed call. Handshake is its own
|
|
106
|
+
// shape because .strict() does not look inside a nested object.
|
|
117
107
|
export const doctorHandshakeShape = {
|
|
118
108
|
ok: z.boolean(),
|
|
119
109
|
error: z.string().optional(),
|
|
@@ -122,7 +112,7 @@ export const doctorHandshakeShape = {
|
|
|
122
112
|
models: z.array(z.unknown()).optional(),
|
|
123
113
|
currentModel: z.unknown().optional(),
|
|
124
114
|
modes: z.array(z.unknown()).optional(),
|
|
125
|
-
// Built here
|
|
115
|
+
// Built here, not relayed, so it gets a real type.
|
|
126
116
|
currentModelOptions: z.array(z.object({
|
|
127
117
|
id: z.string(),
|
|
128
118
|
name: z.string().optional(),
|
|
@@ -140,7 +130,7 @@ export const doctorAgentShape = {
|
|
|
140
130
|
handshake: z.object(doctorHandshakeShape).passthrough().optional(),
|
|
141
131
|
};
|
|
142
132
|
|
|
143
|
-
// agent is split out
|
|
133
|
+
// agent is split out for the same reason as handshake.
|
|
144
134
|
export const doctorOutputShape = {
|
|
145
135
|
plugin: z.object({ version: z.string() }).passthrough(),
|
|
146
136
|
client: z.object({
|
|
@@ -166,8 +156,7 @@ export const delegateInputSchema = z.object({
|
|
|
166
156
|
workspace: z.string().trim().min(1, "workspace must not be blank").describe("The agent's working directory, not a limit. Smallest directory holding the task's files; with no such directory the project root is the floor. Must already exist; never create one for the call."),
|
|
167
157
|
model: z.string().trim().min(1, "model must be a non-empty string").default(DEFAULT_MODEL).describe("Bare ACP family id, version included: composer-2.5, grok-4.5, claude-opus-5, gpt-5.6-sol. doctor deep:true lists every id."),
|
|
168
158
|
fast: z.boolean().default(false).describe("Fast tier; higher cost — only when the user asks."),
|
|
169
|
-
//
|
|
170
|
-
// string and the bridge validates the exact token against the live option list.
|
|
159
|
+
// Open string: a model's values are known only once it is selected, then validated live.
|
|
171
160
|
effort: z.string().trim().min(1).optional().describe("Exact Cursor thinking-effort value for the selected model. Values differ per model and some expose no effort option; invalid values fail before the prompt and name the accepted set. Pass only when the user asks for Cursor effort — the host's own reasoning setting is unrelated."),
|
|
172
161
|
context: z.string().trim().min(1).optional().describe("Context window size; gpt-5.x accepts 272k and 1m. Do not pass speculatively."),
|
|
173
162
|
contextFiles: z.array(z.string()).optional().describe("Paths to attach instead of pasting contents into spec. Text becomes references the agent may open; images (png/jpg/gif/webp, <5MB) are sent inline. Relative paths resolve against workspace but are not limited to it. Skips are reported in protocolWarnings, never fatal."),
|
|
@@ -192,8 +181,8 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
|
|
|
192
181
|
if (progressToken != null) {
|
|
193
182
|
let progress = 0;
|
|
194
183
|
onProgress = (message) => {
|
|
195
|
-
//
|
|
196
|
-
//
|
|
184
|
+
// An unhandled rejection from sendNotification would exit the server; the try catches a
|
|
185
|
+
// sync throw.
|
|
197
186
|
try {
|
|
198
187
|
Promise.resolve(extra.sendNotification({
|
|
199
188
|
method: "notifications/progress",
|
|
@@ -224,16 +213,12 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
|
|
|
224
213
|
},
|
|
225
214
|
onSessionReady: (sessionId, client) => {
|
|
226
215
|
capturedSessionId = sessionId;
|
|
227
|
-
// The same handle moves across, so a
|
|
228
|
-
// one side of it rather than on neither.
|
|
216
|
+
// The same handle moves across, so a racing shutdown finds it on exactly one side.
|
|
229
217
|
handle ??= { client, cancelRequested: false };
|
|
230
218
|
pending.delete(handle);
|
|
231
219
|
registerInFlight(inFlight, sessionId, handle);
|
|
232
220
|
rememberSession(seenSessions, sessionId);
|
|
233
|
-
//
|
|
234
|
-
// can call tools concurrently has something to pass to cancel mid-run — otherwise the
|
|
235
|
-
// id only arrives when delegate returns, by which point there is nothing to cancel.
|
|
236
|
-
// (Hosts that serialize tool calls still cannot cancel in flight; that is a host limit.)
|
|
221
|
+
// Sent now so a host that can call tools concurrently has an id to cancel mid-run.
|
|
237
222
|
onProgress(`session ready: ${sessionId}`);
|
|
238
223
|
},
|
|
239
224
|
});
|
|
@@ -241,15 +226,13 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
|
|
|
241
226
|
return { content: [{ type: "text", text: JSON.stringify(out) }] };
|
|
242
227
|
} catch (err) {
|
|
243
228
|
return {
|
|
244
|
-
// The reason
|
|
245
|
-
// prose to tell a timeout from a rejected argument.
|
|
229
|
+
// The reason up front, so the caller need not parse prose to tell a timeout from a bad argument.
|
|
246
230
|
content: [{ type: "text", text: `delegate failed${err?.reason ? ` [${err.reason}]` : ""}: ` + (err?.message || String(err)) }],
|
|
247
231
|
isError: true,
|
|
248
232
|
};
|
|
249
233
|
} finally {
|
|
250
|
-
// Drops only this delegation's
|
|
251
|
-
//
|
|
252
|
-
// in pending, and one that opened is only ever in the map — the delete covers both.
|
|
234
|
+
// Drops only this delegation's handle, from whichever of pending or the map holds it; the id
|
|
235
|
+
// stays registered while another turn runs on it.
|
|
253
236
|
if (handle) pending.delete(handle);
|
|
254
237
|
if (capturedSessionId) unregisterInFlight(inFlight, capturedSessionId, handle);
|
|
255
238
|
}
|
|
@@ -260,9 +243,10 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
|
|
|
260
243
|
* runDelegate?: (opts: any) => Promise<any>,
|
|
261
244
|
* runDoctor?: (opts: any) => Promise<any>,
|
|
262
245
|
* forceGraceMs?: number,
|
|
246
|
+
* pending?: Set<any>,
|
|
263
247
|
* }} [opts]
|
|
264
248
|
*/
|
|
265
|
-
export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000 } = {}) {
|
|
249
|
+
export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000, pending = pendingDelegations } = {}) {
|
|
266
250
|
const runDelegate = runDelegateInjected || runDelegateDefault;
|
|
267
251
|
const runDoctor = runDoctorInjected || runDoctorDefault;
|
|
268
252
|
const server = new McpServer(
|
|
@@ -284,7 +268,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
284
268
|
openWorldHint: true,
|
|
285
269
|
},
|
|
286
270
|
},
|
|
287
|
-
async (args, extra) => runDelegateTool({ args, extra, runDelegate, inFlight, pending
|
|
271
|
+
async (args, extra) => runDelegateTool({ args, extra, runDelegate, inFlight, pending, seenSessions })
|
|
288
272
|
);
|
|
289
273
|
|
|
290
274
|
server.registerTool(
|
|
@@ -293,7 +277,8 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
293
277
|
description:
|
|
294
278
|
"Best-effort cancel of an in-flight delegation by sessionId. session/cancel is advisory — the agent may finish the turn anyway, and the delegate result then carries cancelRequested. Status: cancelled, killed (agent process observed to exit), not-running (turn already ended, still resumable), not-found (id not in this process's recent session history).",
|
|
295
279
|
inputSchema: {
|
|
296
|
-
|
|
280
|
+
// Blank is a malformed call, not a stale id.
|
|
281
|
+
sessionId: z.string().trim().min(1, "sessionId must not be blank"),
|
|
297
282
|
force: z.boolean().default(false).describe("Kill the agent process if the turn is still running after a short grace period."),
|
|
298
283
|
},
|
|
299
284
|
annotations: {
|
|
@@ -307,34 +292,32 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
307
292
|
async ({ sessionId, force }) => {
|
|
308
293
|
const handles = inFlight.get(sessionId);
|
|
309
294
|
if (!handles || handles.size === 0) {
|
|
310
|
-
// A finished session
|
|
311
|
-
// would read as "bad id" for a session that ran and is still resumable.
|
|
295
|
+
// A finished session is still resumable; only an unknown id is not-found.
|
|
312
296
|
const known = seenSessions.has(sessionId);
|
|
313
297
|
return cancelResult(known ? "not-running" : "not-found", sessionId);
|
|
314
298
|
}
|
|
315
|
-
//
|
|
316
|
-
//
|
|
317
|
-
|
|
318
|
-
|
|
299
|
+
// Every turn on the id (the caller named a session), taken now: a resume that registers during
|
|
300
|
+
// the grace or the kill is not swept in.
|
|
301
|
+
const targeted = [...handles];
|
|
302
|
+
for (const handle of targeted) handle.cancelRequested = true;
|
|
303
|
+
await Promise.all(targeted.map((handle) => handle.client.cancel(sessionId).catch(() => {})));
|
|
319
304
|
if (!force) {
|
|
320
|
-
//
|
|
321
|
-
//
|
|
322
|
-
// with force — report not-found while the agent was alive. Each delegation's own
|
|
323
|
-
// finally removes its handle when the turn actually settles.
|
|
305
|
+
// Handles stay registered: session/cancel is advisory, and a later force must still find
|
|
306
|
+
// the turn. Each delegation's finally removes its handle when the turn settles.
|
|
324
307
|
return cancelResult("cancelled", sessionId);
|
|
325
308
|
}
|
|
326
|
-
|
|
327
|
-
const
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
const toKill =
|
|
309
|
+
// Polled, not slept through: the turn often settles well inside the grace.
|
|
310
|
+
const running = () => targeted.filter((handle) => inFlight.get(sessionId)?.has(handle));
|
|
311
|
+
const graceEnds = Date.now() + forceGraceMs;
|
|
312
|
+
while (Date.now() < graceEnds && running().length) {
|
|
313
|
+
await new Promise((r) => setTimeout(r, Math.min(50, Math.max(1, graceEnds - Date.now()))));
|
|
314
|
+
}
|
|
315
|
+
const toKill = running();
|
|
316
|
+
if (toKill.length === 0) return cancelResult("cancelled", sessionId);
|
|
333
317
|
const observed = await Promise.all(
|
|
334
318
|
toKill.map((handle) => Promise.resolve(handle.client.stop()).catch(() => false))
|
|
335
319
|
);
|
|
336
|
-
// "killed"
|
|
337
|
-
// When one does not follow, the handles stay registered and force can be tried again.
|
|
320
|
+
// "killed" needs an observed exit; without one the handles stay and force can be retried.
|
|
338
321
|
if (!observed.every(Boolean)) return cancelResult("cancelled", sessionId);
|
|
339
322
|
for (const handle of toKill) unregisterInFlight(inFlight, sessionId, handle);
|
|
340
323
|
return cancelResult("killed", sessionId);
|
|
@@ -360,15 +343,23 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
360
343
|
openWorldHint: false,
|
|
361
344
|
},
|
|
362
345
|
},
|
|
363
|
-
async ({ deep }) => {
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
346
|
+
async ({ deep }, extra) => {
|
|
347
|
+
// doctor's processes sit in pending while it runs, where shutdown already looks.
|
|
348
|
+
const handles = [];
|
|
349
|
+
try {
|
|
350
|
+
const out = await runDoctor({
|
|
351
|
+
deep,
|
|
352
|
+
signal: extra?.signal,
|
|
353
|
+
onClientReady: (client) => { const handle = { client }; handles.push(handle); pending.add(handle); },
|
|
354
|
+
getClientInfo: () => ({
|
|
355
|
+
capabilities: server.server.getClientCapabilities(),
|
|
356
|
+
version: server.server.getClientVersion(),
|
|
357
|
+
}),
|
|
358
|
+
});
|
|
359
|
+
return { content: [{ type: "text", text: JSON.stringify(out) }] };
|
|
360
|
+
} finally {
|
|
361
|
+
for (const handle of handles) pending.delete(handle);
|
|
362
|
+
}
|
|
372
363
|
}
|
|
373
364
|
);
|
|
374
365
|
|
|
@@ -394,51 +385,40 @@ export function installSignalCleanup(map, {
|
|
|
394
385
|
stdin = process.stdin,
|
|
395
386
|
} = {}) {
|
|
396
387
|
let shuttingDown = false;
|
|
397
|
-
const shutdown = (code) => {
|
|
398
|
-
// A second
|
|
399
|
-
//
|
|
400
|
-
if (shuttingDown) return exit(code);
|
|
388
|
+
const shutdown = (code, fromSignal = false) => {
|
|
389
|
+
// A second signal exits without the wait, the kills already sent. A stdin EOF does not: a
|
|
390
|
+
// hangup closes stdin right after its SIGHUP.
|
|
391
|
+
if (shuttingDown) return fromSignal ? exit(code) : undefined;
|
|
401
392
|
shuttingDown = true;
|
|
402
|
-
// Set
|
|
403
|
-
// has to die with the code the signal asked for, and the scheduled exit may never get a
|
|
404
|
-
// turn to run.
|
|
393
|
+
// Set now: the loop may run dry before the scheduled exit gets a turn.
|
|
405
394
|
setExitCode(code);
|
|
406
395
|
const stops = [];
|
|
407
396
|
const dispatch = (handle) => {
|
|
408
397
|
try { stops.push(Promise.resolve(handle.client.stop()).catch(() => {})); } catch {}
|
|
409
398
|
};
|
|
410
399
|
for (const handles of map.values()) for (const handle of handles) dispatch(handle);
|
|
411
|
-
// Delegations still
|
|
412
|
-
// is the only place it is reachable from — they have no session id to be keyed under yet.
|
|
400
|
+
// Delegations still in their handshake: their agent runs, and only pending reaches it.
|
|
413
401
|
for (const handle of pending) dispatch(handle);
|
|
414
|
-
//
|
|
415
|
-
//
|
|
416
|
-
//
|
|
417
|
-
// own deadline), so this wait is short and finite on every platform.
|
|
418
|
-
// Scheduled rather than called from the kill's own continuation, so the exit runs on a
|
|
419
|
-
// clean loop turn instead of on the settlement stack.
|
|
402
|
+
// Waits for the kills: on Windows taskkill is a separate process, and exiting first orphans the
|
|
403
|
+
// launcher and agent below the shell (measured). stop() bounds itself, so the wait is finite.
|
|
404
|
+
// The exit is scheduled onto a clean loop turn rather than run on the settlement stack.
|
|
420
405
|
const leave = () => schedule(() => exit(code));
|
|
421
406
|
Promise.all(stops).then(leave, leave);
|
|
422
407
|
};
|
|
423
|
-
//
|
|
424
|
-
//
|
|
425
|
-
// leak the agent. shutdown() already walks pending, so this covers spawn through session/new.
|
|
408
|
+
// On POSIX each agent has its own process group, which a signal to this process misses, so the
|
|
409
|
+
// handler kills them first. SIGHUP too: a closed terminal, whose default leaves them running.
|
|
426
410
|
if (DETACHED) {
|
|
427
|
-
const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143]]);
|
|
428
|
-
for (const [signal, code] of signals) process.on(signal, () => shutdown(code));
|
|
411
|
+
const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]]);
|
|
412
|
+
for (const [signal, code] of signals) process.on(signal, () => shutdown(code, true));
|
|
429
413
|
}
|
|
430
|
-
//
|
|
431
|
-
//
|
|
432
|
-
// it subscribes to `data` and `error` only — so EOF leaves this process up with a delegation
|
|
433
|
-
// still running and nobody left to hand it to.
|
|
414
|
+
// A stdio host closes stdin before it resorts to a signal, and the SDK transport ignores EOF
|
|
415
|
+
// (it listens for `data` and `error` only).
|
|
434
416
|
stdin.on("end", () => shutdown(0));
|
|
435
417
|
}
|
|
436
418
|
|
|
437
419
|
if (isMain) {
|
|
438
|
-
//
|
|
439
|
-
//
|
|
440
|
-
// beside this file, so it reports the code that is actually running rather than what a
|
|
441
|
-
// manifest pinned. stdout is free here because the transport never starts.
|
|
420
|
+
// Answered before the transport starts, so an install can be checked without a host. Reads the
|
|
421
|
+
// package.json beside this file: the code actually running, not what a manifest pinned.
|
|
442
422
|
const argv = process.argv.slice(2);
|
|
443
423
|
if (argv.includes("--version") || argv.includes("-v")) {
|
|
444
424
|
console.log(readPackageVersion());
|
|
@@ -11,9 +11,8 @@ export class SessionSupervisor {
|
|
|
11
11
|
this.client = client;
|
|
12
12
|
this.handshakeMs = handshakeMs;
|
|
13
13
|
this.hardCapMs = hardCapMs;
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
// about liveness: a probe measured 26.9s of dead wire for a healthy 20s command.
|
|
14
|
+
// Idle detection is opt-in: cursor-agent sends no frames while a shell command runs (26.9s of
|
|
15
|
+
// silence measured for a healthy 20s command).
|
|
17
16
|
this.idleMs = idleMs > 0 ? idleMs : 0;
|
|
18
17
|
this.sessionId = null;
|
|
19
18
|
this.lastActivityAt = Date.now();
|
|
@@ -58,9 +57,8 @@ export class SessionSupervisor {
|
|
|
58
57
|
}, this.handshakeMs);
|
|
59
58
|
}
|
|
60
59
|
|
|
61
|
-
//
|
|
62
|
-
//
|
|
63
|
-
// must come off.
|
|
60
|
+
// Silence in the request/response handshake means a wedged agent; once the prompt is in flight
|
|
61
|
+
// it does not, so the deadline comes off.
|
|
64
62
|
promptStarted() {
|
|
65
63
|
if (this._promptStarted) return;
|
|
66
64
|
this._promptStarted = true;
|
package/src/spawn.js
CHANGED
|
@@ -1,30 +1,39 @@
|
|
|
1
1
|
import process from "node:process";
|
|
2
|
+
import { lstatSync, readFileSync, statSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
2
4
|
|
|
5
|
+
// Splits on whitespace outside quotes. A closed quote at an argument's start or after "=" groups
|
|
6
|
+
// and is removed (--log-file="C:\a b\x.log"); elsewhere it is a character (O'Brien). \ is literal.
|
|
3
7
|
export function splitArgs(raw) {
|
|
8
|
+
const s = String(raw || "");
|
|
4
9
|
const args = [];
|
|
5
|
-
|
|
6
|
-
for (
|
|
7
|
-
|
|
10
|
+
let i = 0;
|
|
11
|
+
for (;;) {
|
|
12
|
+
while (i < s.length && /\s/.test(s[i])) i++;
|
|
13
|
+
if (i >= s.length) return args;
|
|
14
|
+
let arg = "";
|
|
15
|
+
while (i < s.length && !/\s/.test(s[i])) {
|
|
16
|
+
const end = (s[i] === '"' || s[i] === "'") && (arg === "" || arg.endsWith("=")) ? s.indexOf(s[i], i + 1) : -1;
|
|
17
|
+
if (end === -1) { arg += s[i++]; continue; }
|
|
18
|
+
arg += s.slice(i + 1, end);
|
|
19
|
+
i = end + 1;
|
|
20
|
+
}
|
|
21
|
+
args.push(arg);
|
|
8
22
|
}
|
|
9
|
-
return args;
|
|
10
23
|
}
|
|
11
24
|
|
|
12
|
-
// On Windows cursor-agent writes
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
// reports every hooked tool call as blocked. Dropped, the agent falls back to PowerShell, the
|
|
16
|
-
// shell it uses when started outside Git Bash.
|
|
25
|
+
// On Windows cursor-agent writes hook commands as PowerShell but runs them in Git Bash when it sees
|
|
26
|
+
// MSYSTEM or a Git Bash SHELL, which a host in Git Bash (Claude Code) passes down; bash then blocks
|
|
27
|
+
// every hooked tool call. Without the two vars the agent uses PowerShell.
|
|
17
28
|
const WIN32_DROPPED_ENV = new Set(["MSYSTEM", "SHELL"]);
|
|
18
29
|
|
|
19
30
|
function agentEnv(env = process.env) {
|
|
20
31
|
return Object.fromEntries(Object.entries(env).filter(([key]) => !WIN32_DROPPED_ENV.has(key.toUpperCase())));
|
|
21
32
|
}
|
|
22
33
|
|
|
23
|
-
// shell:true on win32
|
|
24
|
-
//
|
|
25
|
-
//
|
|
26
|
-
// anyway. Routing host- or caller-supplied values into either variable would turn this into a
|
|
27
|
-
// command-injection path, so don't.
|
|
34
|
+
// shell:true on win32 lets a .cmd launcher resolve, and means cmd.exe parses the command line.
|
|
35
|
+
// Safe only because both values come from the environment, already as trusted as this process.
|
|
36
|
+
// Never route host- or caller-supplied values into them: that is command injection.
|
|
28
37
|
export function resolveAcpSpawn() {
|
|
29
38
|
const command = process.env.ACP_AGENT_COMMAND || "cursor-agent";
|
|
30
39
|
const args = process.env.ACP_AGENT_ARGS
|
|
@@ -33,3 +42,101 @@ export function resolveAcpSpawn() {
|
|
|
33
42
|
const win32 = process.platform === "win32";
|
|
34
43
|
return { command, args, options: { shell: win32, ...(win32 ? { env: agentEnv() } : {}) } };
|
|
35
44
|
}
|
|
45
|
+
|
|
46
|
+
// Under shell:true Node hands cmd.exe one unquoted line, so a value with a space or metacharacter
|
|
47
|
+
// splits there. Quoted at the spawn sites, so the spec keeps plain args. A value already holding a
|
|
48
|
+
// quote passes as given: cmd cannot nest them, and pre-quoted paths worked before. cmd still
|
|
49
|
+
// expands %VAR% inside quotes.
|
|
50
|
+
function cmdQuote(value) {
|
|
51
|
+
const s = String(value);
|
|
52
|
+
if (s.includes('"') || (s !== "" && !/[\s&|<>^(),;=]/.test(s))) return s;
|
|
53
|
+
// Doubled so the child's argv parser does not read a trailing backslash as escaping the quote.
|
|
54
|
+
return `"${s.replace(/(\\+)$/, "$1$1")}"`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* What to hand spawn() for a spec, at each spawn site so doctor reads the spec as configured.
|
|
59
|
+
* @param {string} command @param {string[]} args
|
|
60
|
+
* @param {{ shell?: boolean | string, env?: NodeJS.ProcessEnv } | undefined} options
|
|
61
|
+
*/
|
|
62
|
+
export function spawnArgv(command, args, options) {
|
|
63
|
+
if (!(options?.shell && process.platform === "win32")) return { command, args, options };
|
|
64
|
+
const env = options.env || process.env;
|
|
65
|
+
// cmd.exe opens a .ps1 with its file association, so a .ps1, or the one a forwarding .cmd runs,
|
|
66
|
+
// goes to powershell.exe -File as cursor-agent.cmd does. Only x.ps1 itself: x.ps1.cmd stays cmd's.
|
|
67
|
+
const name = String(command).replace(/^["']|["']$/g, "");
|
|
68
|
+
const script = /\.ps1$/i.test(name) ? findCommand(name, env, true) : forwardedScript(findCommand(name, env), env);
|
|
69
|
+
if (script) {
|
|
70
|
+
const rootKey = Object.keys(env).find((k) => k.toUpperCase() === "SYSTEMROOT");
|
|
71
|
+
const powershell = rootKey && env[rootKey]
|
|
72
|
+
? path.win32.join(env[rootKey], "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
|
|
73
|
+
: "powershell.exe";
|
|
74
|
+
return {
|
|
75
|
+
command: powershell,
|
|
76
|
+
args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script, ...args],
|
|
77
|
+
options: { ...options, shell: false },
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
// One line and no args array: Node 24 warns (DEP0190) on args under shell:true.
|
|
81
|
+
return { command: [command, ...args].map(cmdQuote).join(" "), args: [], options };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// The .ps1 a .cmd passes its args to (powershell ... -File "%~dp0x.ps1" %*, or a variable set from
|
|
85
|
+
// %~dp0), else null. cursor-agent.cmd and its copy agent.cmd do this; cmd.exe and their delayed
|
|
86
|
+
// expansion rewrite !, %VAR%, ^ and quotes in the args, and the .ps1 repeats their update step.
|
|
87
|
+
function forwardedScript(file, env) {
|
|
88
|
+
if (!file || !/\.(cmd|bat)$/i.test(file)) return null;
|
|
89
|
+
let text;
|
|
90
|
+
try {
|
|
91
|
+
if (statSync(file).size > 64 * 1024) return null;
|
|
92
|
+
text = readFileSync(file, "latin1");
|
|
93
|
+
} catch {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
97
|
+
const dirVars = [...text.matchAll(/^\s*set\s+"?(\w+)=%~dp0"?\s*$/gim)].map((m) => `%${m[1]}%`);
|
|
98
|
+
const ownDir = ["%~dp0", ...dirVars].map(escape).join("|");
|
|
99
|
+
const forwards = new RegExp(`powershell(?:\\.exe)?"?[^\\r\\n]*\\s-File\\s+"(?:${ownDir})\\\\?([^"\\\\/:\\r\\n]+\\.ps1)"\\s+%\\*`, "i");
|
|
100
|
+
const target = text.match(forwards)?.[1];
|
|
101
|
+
return target ? findCommand(path.join(path.dirname(file), target), env, true) : null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Through a shell the spawn always succeeds (cmd.exe exits 1, "is not recognized"), so a missing
|
|
105
|
+
// launcher is looked up first to report it as not installed. Mirrors cmd: a path as given, a bare
|
|
106
|
+
// name on each PATH entry, each with and without each PATHEXT extension. Pass the env the child
|
|
107
|
+
// gets: on win32, agentEnv().
|
|
108
|
+
export function commandExists(command, env = process.env) {
|
|
109
|
+
return findCommand(command, env) !== null;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The file that lookup lands on, or null. exact skips the PATHEXT extensions. */
|
|
113
|
+
function findCommand(command, env, exact = false) {
|
|
114
|
+
const name = String(command || "").replace(/^["']|["']$/g, "");
|
|
115
|
+
if (!name) return null;
|
|
116
|
+
const pathKey = Object.keys(env).find((k) => k.toUpperCase() === "PATH");
|
|
117
|
+
const extKey = Object.keys(env).find((k) => k.toUpperCase() === "PATHEXT");
|
|
118
|
+
const exts = exact ? [""] : ["", ...String((extKey && env[extKey]) || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)];
|
|
119
|
+
const isFile = (p) => {
|
|
120
|
+
try {
|
|
121
|
+
return statSync(p).isFile();
|
|
122
|
+
} catch (e) {
|
|
123
|
+
// A Store app's alias (WindowsApps\pwsh.exe) is a link into a folder this user cannot stat,
|
|
124
|
+
// so stat fails with EACCES, yet cmd runs it. A link to a missing file fails with ENOENT.
|
|
125
|
+
if (process.platform !== "win32" || (e.code !== "EACCES" && e.code !== "EPERM")) return false;
|
|
126
|
+
try { return lstatSync(p).isSymbolicLink(); } catch { return false; }
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
const hit = (base) => {
|
|
130
|
+
for (const ext of exts) {
|
|
131
|
+
for (const p of [base + ext, base + ext.toLowerCase()]) if (isFile(p)) return p;
|
|
132
|
+
}
|
|
133
|
+
return null;
|
|
134
|
+
};
|
|
135
|
+
if (/[\\/]/.test(name)) return hit(name);
|
|
136
|
+
const dirs = String((pathKey && env[pathKey]) || "").split(path.delimiter).filter(Boolean);
|
|
137
|
+
for (const dir of dirs) {
|
|
138
|
+
const found = hit(path.join(dir.replace(/^"|"$/g, ""), name));
|
|
139
|
+
if (found) return found;
|
|
140
|
+
}
|
|
141
|
+
return null;
|
|
142
|
+
}
|
package/src/turn-state.js
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
// also what reset() applies — a field added there is reset for free, and one that is missed is a
|
|
5
|
-
// silent stale-data bug on resume.
|
|
1
|
+
// The turn in progress, in one object so it can be wiped as one: session/load replays the
|
|
2
|
+
// previous turn as ordinary updates. Declare every field in freshFields(), which reset() applies;
|
|
3
|
+
// a field kept elsewhere leaks stale data into a resumed turn.
|
|
6
4
|
|
|
7
5
|
const isTerminalToolStatus = (status) =>
|
|
8
6
|
status === "completed" || status === "failed" || status === "cancelled";
|
|
@@ -42,31 +40,27 @@ function progressStream(prefix, onProgress, throttleMs) {
|
|
|
42
40
|
};
|
|
43
41
|
}
|
|
44
42
|
|
|
45
|
-
// The single declaration of what a turn accumulates.
|
|
46
43
|
function freshFields() {
|
|
47
44
|
return {
|
|
48
45
|
resultChunks: [],
|
|
49
|
-
// Text
|
|
50
|
-
//
|
|
51
|
-
// that replies and then runs one more command has its entire reply discarded, leaving the
|
|
52
|
-
// caller "" with stopReason end_turn and no error. Kept so it can be handed back when
|
|
53
|
-
// nothing survived — labelled, never blended with a real final message.
|
|
46
|
+
// Text a later tool call superseded: usually a preamble, but the whole answer when the agent
|
|
47
|
+
// replied and then ran one more command. Handed back, labelled, only when nothing followed.
|
|
54
48
|
discardedResult: "",
|
|
55
49
|
sawToolCall: false,
|
|
56
50
|
collectingPostToolResult: false,
|
|
57
51
|
activeToolCalls: new Set(),
|
|
58
|
-
// Ids
|
|
59
|
-
//
|
|
60
|
-
// to discardedResult and mislabel it pre-tool-fallback.
|
|
52
|
+
// Ids seen terminal, so a stale non-terminal re-send is dropped instead of restarting
|
|
53
|
+
// collection and demoting the collected final message.
|
|
61
54
|
finishedToolCalls: new Set(),
|
|
62
55
|
planEntries: [],
|
|
63
56
|
planOverview: undefined,
|
|
64
57
|
planDetail: undefined,
|
|
65
|
-
// merge:false replaces the list, merge:true upserts by id
|
|
66
|
-
// so a keyed set is enough — no field-level merging.
|
|
58
|
+
// merge:false replaces the list, merge:true upserts by id; entries arrive complete.
|
|
67
59
|
todos: new Map(),
|
|
68
60
|
sawTodoFrame: false,
|
|
69
61
|
touched: new Set(),
|
|
62
|
+
// The newest tool call's id, title and path; its updates refine the title and path.
|
|
63
|
+
lastTool: null,
|
|
70
64
|
lastToolLabel: null,
|
|
71
65
|
sessionTitle: undefined,
|
|
72
66
|
};
|
|
@@ -96,8 +90,7 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
|
|
|
96
90
|
state.resultChunks.length = 0;
|
|
97
91
|
},
|
|
98
92
|
|
|
99
|
-
//
|
|
100
|
-
// here would hand back a partial answer as if it were the whole one.
|
|
93
|
+
// Uncapped: the model's output limit bounds it, and a cap would pass off a partial answer.
|
|
101
94
|
appendResult(text) {
|
|
102
95
|
state.resultChunks.push(text);
|
|
103
96
|
},
|
|
@@ -128,8 +121,8 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
|
|
|
128
121
|
state.finishedToolCalls.add(toolCallId);
|
|
129
122
|
}
|
|
130
123
|
if (state.activeToolCalls.size === 0 && !state.collectingPostToolResult) {
|
|
131
|
-
//
|
|
132
|
-
//
|
|
124
|
+
// Drops text emitted while tools ran. Guarded so a duplicate or late terminal update
|
|
125
|
+
// cannot wipe a collected final message.
|
|
133
126
|
state.resetResult();
|
|
134
127
|
state.collectingPostToolResult = true;
|
|
135
128
|
}
|
|
@@ -140,8 +133,7 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
|
|
|
140
133
|
}
|
|
141
134
|
},
|
|
142
135
|
|
|
143
|
-
//
|
|
144
|
-
// the last one finished.
|
|
136
|
+
// A chunk belongs in the result before any tool ran or after the last one finished.
|
|
145
137
|
collectingResult() {
|
|
146
138
|
return !state.sawToolCall || (state.collectingPostToolResult && state.activeToolCalls.size === 0);
|
|
147
139
|
},
|
package/src/version.js
CHANGED
|
@@ -11,10 +11,8 @@ function readVersion() {
|
|
|
11
11
|
// Captured once, for the ACP/MCP identity handshake that is sent at connect and never re-read.
|
|
12
12
|
export const VERSION = readVersion();
|
|
13
13
|
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
// an in-place upgrade — exactly when doctor is run to confirm the new version shipped. An
|
|
17
|
-
// un-restarted child running old code stays a gap, but no in-process value can close that.
|
|
14
|
+
// Read fresh for doctor: /reload-plugins does not restart the server, so the constant goes stale
|
|
15
|
+
// after an in-place upgrade, just when doctor confirms it. The running code stays old until a restart.
|
|
18
16
|
export function readPackageVersion() {
|
|
19
17
|
try {
|
|
20
18
|
return readVersion();
|