cursor-delegate-mcp 2.9.0 → 2.11.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 +66 -0
- package/package.json +3 -2
- package/src/acp-client.js +24 -30
- package/src/acp-enums.js +3 -8
- package/src/delegate.js +117 -129
- package/src/doctor.js +78 -31
- 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 +107 -119
- package/src/session-supervisor.js +4 -6
- package/src/spawn.js +124 -26
- package/src/turn-state.js +14 -22
- package/src/version.js +2 -4
package/src/delegate.js
CHANGED
|
@@ -2,9 +2,8 @@ import process from "node:process";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { pathToFileURL } from "node:url";
|
|
4
4
|
import { statSync, realpathSync } from "node:fs";
|
|
5
|
-
// Async: a sync read
|
|
6
|
-
//
|
|
7
|
-
// run before the spawn.
|
|
5
|
+
// Async: a sync read would stall every other delegation on this thread. The statSync calls stay
|
|
6
|
+
// sync: they validate arguments before the spawn.
|
|
8
7
|
import { readFile } from "node:fs/promises";
|
|
9
8
|
import { AcpClient } from "./acp-client.js";
|
|
10
9
|
import { DEFAULT_HARD_CAP_MS, SessionSupervisor } from "./session-supervisor.js";
|
|
@@ -22,9 +21,8 @@ const ROUTED_MODEL = "default";
|
|
|
22
21
|
export const DEFAULT_HANDSHAKE_MS = 60000;
|
|
23
22
|
export const DEFAULT_HEARTBEAT_MS = 30000;
|
|
24
23
|
|
|
25
|
-
//
|
|
26
|
-
//
|
|
27
|
-
// documented 0 comes from its own fallback being 0, not from an env value.
|
|
24
|
+
// A malformed or non-positive value falls back to the default, so a blank var (Number("") is 0)
|
|
25
|
+
// cannot arm a zero-length deadline. The idle guard is off because its own fallback is 0.
|
|
28
26
|
function envMs(name, fallback) {
|
|
29
27
|
const raw = process.env[name];
|
|
30
28
|
if (raw === undefined) return fallback;
|
|
@@ -37,19 +35,16 @@ function fmtDuration(ms) {
|
|
|
37
35
|
return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s`;
|
|
38
36
|
}
|
|
39
37
|
|
|
40
|
-
// A blank spec
|
|
41
|
-
// a billed turn for nothing. Reject it before the spawn, like a bad workspace.
|
|
38
|
+
// A blank spec costs a billed turn that only replies "No prompt content provided".
|
|
42
39
|
function assertSpec(spec) {
|
|
43
40
|
if (typeof spec === "string" && spec.trim() === "") {
|
|
44
41
|
throw makeError("invalid-spec", "spec is empty. Provide a task brief.");
|
|
45
42
|
}
|
|
46
43
|
}
|
|
47
44
|
|
|
48
|
-
//
|
|
49
|
-
//
|
|
50
|
-
//
|
|
51
|
-
// agent's first write creates the directory, so a typo spawns a parallel empty tree. Same check
|
|
52
|
-
// contextFiles applies.
|
|
45
|
+
// Required, never defaulted: under npx or a plugin launch the server's cwd is a cache directory or
|
|
46
|
+
// the user's home, where an auto-approved agent would then work. Must exist, or the agent's first
|
|
47
|
+
// write turns a typo into a new empty tree.
|
|
53
48
|
function assertWorkspace(workspace) {
|
|
54
49
|
if (typeof workspace !== "string" || workspace.trim() === "") {
|
|
55
50
|
throw makeError("invalid-workspace", "workspace is required. Name the directory the agent should work in.");
|
|
@@ -72,19 +67,15 @@ const IMAGE_MIME = {
|
|
|
72
67
|
// Base64 inflates by a third and every byte lands in the prompt, unlike a link.
|
|
73
68
|
const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
|
|
74
69
|
|
|
75
|
-
// A resource_link hands the agent a path,
|
|
76
|
-
//
|
|
77
|
-
//
|
|
78
|
-
// - gate images on the advertised capability: cursor-agent accepts unsupported blocks without
|
|
79
|
-
// error (embeddedContext:false raises nothing), so an ungated image vanishes silently;
|
|
80
|
-
// - report anything skipped — a dropped attachment is otherwise invisible.
|
|
70
|
+
// A resource_link hands the agent a path, so a file costs prompt space only if opened; it works
|
|
71
|
+
// outside the workspace too. Images have no such form and go inline, gated on the advertised
|
|
72
|
+
// capability: cursor-agent drops an unsupported block without error. Every skip is reported.
|
|
81
73
|
async function buildContextBlocks(contextFiles, workspace, client, warnings) {
|
|
82
74
|
const blocks = [];
|
|
83
75
|
// A glob plus an explicit path can resolve to one file; sending it twice wastes prompt space.
|
|
84
76
|
const seen = new Set();
|
|
85
|
-
//
|
|
86
|
-
//
|
|
87
|
-
// per-entry — they are individually distinct and never arrive in bulk.
|
|
77
|
+
// One warning for every miss, since a wrong workspace misses them all at once. Other skip
|
|
78
|
+
// reasons are reported per entry.
|
|
88
79
|
const notFound = [];
|
|
89
80
|
const root = path.resolve(workspace || process.cwd());
|
|
90
81
|
const identKey = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
|
|
@@ -143,11 +134,10 @@ async function buildContextBlocks(contextFiles, workspace, client, warnings) {
|
|
|
143
134
|
return blocks;
|
|
144
135
|
}
|
|
145
136
|
|
|
146
|
-
// Only a session
|
|
147
|
-
//
|
|
148
|
-
//
|
|
149
|
-
//
|
|
150
|
-
// same words. A missed match costs a recoverable resume-failed; a false match costs a silent turn.
|
|
137
|
+
// Only a missing session justifies a fresh one. Code and wording together: 2026.08.11 returns
|
|
138
|
+
// -32602 `Session "<id>" not found` when missing, but -32603 `Failed to load session "<id>": <cause>`
|
|
139
|
+
// when restore fails, and the cause can carry the same words. A missed match costs a recoverable
|
|
140
|
+
// resume-failed; a false one, a turn run without the caller's context.
|
|
151
141
|
function isMissingSession(err) {
|
|
152
142
|
const message = err?.message || "";
|
|
153
143
|
return err?.code === -32602
|
|
@@ -169,15 +159,13 @@ async function openSession(client, resumeSessionId, workspace) {
|
|
|
169
159
|
+ ` resumeSessionId to start fresh deliberately.`
|
|
170
160
|
);
|
|
171
161
|
}
|
|
172
|
-
//
|
|
173
|
-
// stale id from a typo'd one — keep why the load failed.
|
|
162
|
+
// Kept so the caller can tell a stale id from a mistyped one.
|
|
174
163
|
const fresh = await client.newSession(workspace);
|
|
175
164
|
return { ...fresh, resumeError: err?.message || String(err) };
|
|
176
165
|
}
|
|
177
166
|
}
|
|
178
167
|
|
|
179
|
-
// session/new
|
|
180
|
-
// where the real list can be named, rather than letting set_model fail without it.
|
|
168
|
+
// Rejected here, where session/new's model list can be named; set_model's own error does not.
|
|
181
169
|
// Agents that report no list are left alone.
|
|
182
170
|
function assertKnownModel(client, model) {
|
|
183
171
|
const available = client?.sessionModels?.availableModels;
|
|
@@ -187,11 +175,10 @@ function assertKnownModel(client, model) {
|
|
|
187
175
|
throw makeError("unknown-model", `Unknown model ${JSON.stringify(model)}. This agent offers: ${ids.join(", ")}.`);
|
|
188
176
|
}
|
|
189
177
|
|
|
190
|
-
//
|
|
191
|
-
//
|
|
192
|
-
//
|
|
193
|
-
//
|
|
194
|
-
// res echoes the now-current model's configOptions — the only place the served model id appears.
|
|
178
|
+
// Options are not discoverable up front (session/new reports only the default model's; set_model
|
|
179
|
+
// returns nothing), so probe and read the rejection. Measured -32602s: "Unknown model config
|
|
180
|
+
// option: X" means no such knob (report, carry on); "Invalid value for X: Y" propagates.
|
|
181
|
+
// res echoes the current model's configOptions, the only place the served model id appears.
|
|
195
182
|
async function applyConfig(client, sessionId, configId, value) {
|
|
196
183
|
try {
|
|
197
184
|
const res = await client.setConfigOption(sessionId, configId, value);
|
|
@@ -202,15 +189,14 @@ async function applyConfig(client, sessionId, configId, value) {
|
|
|
202
189
|
}
|
|
203
190
|
}
|
|
204
191
|
|
|
205
|
-
//
|
|
206
|
-
//
|
|
207
|
-
// session/new and session/load both report the values the session opens with, which is what makes
|
|
208
|
-
// a config round-trip skippable: the bridge can see it would set what is already set.
|
|
192
|
+
// session/new and session/load report the values the session opens with, so a set that would
|
|
193
|
+
// change nothing can be skipped.
|
|
209
194
|
function configOptionValue(configOptions, id) {
|
|
210
195
|
const opt = (Array.isArray(configOptions) ? configOptions : []).find((o) => o?.id === id);
|
|
211
196
|
return typeof opt?.currentValue === "string" ? opt.currentValue : undefined;
|
|
212
197
|
}
|
|
213
198
|
|
|
199
|
+
// Undefined when the model rejected every option sent; effectiveModel then stays off.
|
|
214
200
|
function servedModelFrom(res) {
|
|
215
201
|
const opts = optionsFrom(res);
|
|
216
202
|
if (opts === undefined) return undefined;
|
|
@@ -218,9 +204,8 @@ function servedModelFrom(res) {
|
|
|
218
204
|
return typeof m?.currentValue === "string" ? m.currentValue : undefined;
|
|
219
205
|
}
|
|
220
206
|
|
|
221
|
-
// Sent only
|
|
222
|
-
//
|
|
223
|
-
// billed prompt. Missing capability data is not mislabeled as a caller mistake.
|
|
207
|
+
// Sent only as an exact value of an effort option the selected model advertised, so a bad token
|
|
208
|
+
// never reaches a billed prompt. Missing capability data is not reported as a caller mistake.
|
|
224
209
|
async function applyEffort(client, sessionId, model, value, modelOptions) {
|
|
225
210
|
const resolved = resolveEffort(modelOptions, value);
|
|
226
211
|
if (resolved.status === "unavailable") {
|
|
@@ -266,6 +251,7 @@ async function applyEffort(client, sessionId, model, value, modelOptions) {
|
|
|
266
251
|
* idleMs?: number, handshakeMs?: number, hardCapMs?: number, timeoutMs?: number,
|
|
267
252
|
* onClientReady?: (client: any) => void,
|
|
268
253
|
* onSessionReady?: (sessionId: string, client: any) => void,
|
|
254
|
+
* onTurnEnd?: () => void,
|
|
269
255
|
* onProgress?: (message: string) => void,
|
|
270
256
|
* progressThrottleMs?: number, heartbeatMs?: number, signal?: AbortSignal,
|
|
271
257
|
* }} [opts]
|
|
@@ -274,14 +260,13 @@ export async function runDelegate({
|
|
|
274
260
|
spec, mode = "agent", resumeSessionId, workspace,
|
|
275
261
|
model = DEFAULT_MODEL, fast = false, effort, context, contextFiles, clientFactory,
|
|
276
262
|
idleMs, handshakeMs, hardCapMs, timeoutMs,
|
|
277
|
-
onClientReady, onSessionReady, onProgress, progressThrottleMs = 2000,
|
|
263
|
+
onClientReady, onSessionReady, onTurnEnd, onProgress, progressThrottleMs = 2000,
|
|
278
264
|
heartbeatMs = DEFAULT_HEARTBEAT_MS,
|
|
279
265
|
signal,
|
|
280
266
|
} = {}) {
|
|
281
|
-
//
|
|
282
|
-
//
|
|
283
|
-
//
|
|
284
|
-
// before supervise() installs its reject settles the supervisor with nothing listening.
|
|
267
|
+
// No await before the abort listener below: addEventListener does not replay an abort that
|
|
268
|
+
// already fired. Throw, not supervisor.abort(): tripping before supervise() installs its reject
|
|
269
|
+
// settles the supervisor with nothing listening.
|
|
285
270
|
if (signal?.aborted) {
|
|
286
271
|
throw makeError("aborted", "delegation aborted by MCP host");
|
|
287
272
|
}
|
|
@@ -356,9 +341,8 @@ export async function runDelegate({
|
|
|
356
341
|
|
|
357
342
|
const make = clientFactory || ((opts) => new AcpClient(opts));
|
|
358
343
|
const client = make({ mode, onCreatePlan: state.recordCreatePlan, onTodos: state.recordTodos });
|
|
359
|
-
//
|
|
360
|
-
//
|
|
361
|
-
// away inside that window used to exit with the agent already running and nothing holding it.
|
|
344
|
+
// Before the spawn, so the caller can stop the agent from its first moment; onSessionReady comes
|
|
345
|
+
// ~3.4s later, and a host exiting in between would leave the agent running.
|
|
362
346
|
onClientReady?.(client);
|
|
363
347
|
const supervisor = new SessionSupervisor(client, { idleMs: turnIdleMs, handshakeMs: shakeMs, hardCapMs: capMs });
|
|
364
348
|
const onAbort = () => supervisor.abort();
|
|
@@ -384,20 +368,26 @@ export async function runDelegate({
|
|
|
384
368
|
heartbeat.unref?.();
|
|
385
369
|
};
|
|
386
370
|
|
|
387
|
-
// Malformed frames
|
|
388
|
-
// into it with the rest below.
|
|
371
|
+
// Malformed frames seen mid-turn; merged into protocolWarnings at the end.
|
|
389
372
|
const frameWarnings = [];
|
|
390
373
|
|
|
391
|
-
//
|
|
392
|
-
//
|
|
393
|
-
|
|
374
|
+
// One line of at most 200 characters for progress and a stall error's "last tool call": a
|
|
375
|
+
// command's title is the command verbatim, a whole script included.
|
|
376
|
+
const labelTool = (started) => {
|
|
377
|
+
const { title, path } = state.lastTool;
|
|
378
|
+
const label = (String(title) + (path && !String(title).includes(path) ? " — " + path : "")).replace(/\s+/g, " ").trim().slice(0, 200);
|
|
379
|
+
if (!started && label === state.lastToolLabel) return;
|
|
380
|
+
state.lastToolLabel = label;
|
|
381
|
+
try { onProgress?.(("running: " + label).slice(0, 200)); } catch {}
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
// session/load replays the previous turn as ordinary updates. state.reset() clears what they
|
|
385
|
+
// set; only this guard keeps them out of progress.
|
|
394
386
|
client.on("update", (u) => {
|
|
395
387
|
if (!promptInFlight) return;
|
|
396
388
|
const up = u?.update || {};
|
|
397
389
|
if (up.sessionUpdate === "plan") {
|
|
398
|
-
//
|
|
399
|
-
// reached the sanitizer's forEach — throwing after the turn's work was done, which is the
|
|
400
|
-
// one thing the sanitizer exists to prevent. Drop it here and say so instead.
|
|
390
|
+
// A non-array would reach the sanitizer's forEach and throw after the work is done.
|
|
401
391
|
if (up.entries !== undefined && !Array.isArray(up.entries)) {
|
|
402
392
|
frameWarnings.push(
|
|
403
393
|
`plan entries dropped: ACP requires an array, got ${up.entries === null ? "null" : typeof up.entries}`
|
|
@@ -407,10 +397,8 @@ export async function runDelegate({
|
|
|
407
397
|
state.planEntries = up.entries || [];
|
|
408
398
|
}
|
|
409
399
|
}
|
|
410
|
-
// The agent
|
|
411
|
-
//
|
|
412
|
-
// arrives too late to tell anything apart, and was measured contradicting the answer
|
|
413
|
-
// ("No Image Detected" on a turn describing an image).
|
|
400
|
+
// The agent's turn title ("File Creator"): a live label and timeout forensics. Kept out of the
|
|
401
|
+
// result, where it has contradicted the answer ("No Image Detected" on an image turn).
|
|
414
402
|
if (up.sessionUpdate === "session_info_update" && typeof up.title === "string" && up.title) {
|
|
415
403
|
if (up.title !== state.sessionTitle) { try { onProgress?.(`turn titled: ${up.title}`.slice(0, 200)); } catch {} }
|
|
416
404
|
state.sessionTitle = up.title;
|
|
@@ -420,13 +408,8 @@ export async function runDelegate({
|
|
|
420
408
|
}
|
|
421
409
|
if (up.sessionUpdate === "tool_call") {
|
|
422
410
|
state.startTool(up.toolCallId, up.status);
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
// Collapsed onto one line the way both readers of this take it: a progress notification
|
|
426
|
-
// and the "last tool call" line in a stall error. A terminal tool's title is the command
|
|
427
|
-
// the agent sent, which it sends verbatim — a multi-line script arrives with its newlines.
|
|
428
|
-
state.lastToolLabel = (String(label) + (path ? " — " + path : "")).replace(/\s+/g, " ").trim();
|
|
429
|
-
try { onProgress?.(("running: " + state.lastToolLabel).slice(0, 200)); } catch {}
|
|
411
|
+
state.lastTool = { id: up.toolCallId, title: up.title || up.kind || "tool", path: up.locations?.[0]?.path };
|
|
412
|
+
labelTool(true);
|
|
430
413
|
}
|
|
431
414
|
if (up.sessionUpdate === "agent_message_chunk" && up.content?.text) {
|
|
432
415
|
const text = up.content.text;
|
|
@@ -435,10 +418,17 @@ export async function runDelegate({
|
|
|
435
418
|
}
|
|
436
419
|
if (up.sessionUpdate === "tool_call_update") {
|
|
437
420
|
state.updateToolStatus(up.toolCallId, up.status);
|
|
438
|
-
//
|
|
439
|
-
//
|
|
440
|
-
|
|
441
|
-
|
|
421
|
+
// tool_call names only the kind ("Terminal", "Edit File"); the command or path comes on a
|
|
422
|
+
// later update for the same id. Only the newest call is relabelled.
|
|
423
|
+
const tool = state.lastTool;
|
|
424
|
+
if (tool && up.toolCallId != null && up.toolCallId === tool.id) {
|
|
425
|
+
const path = up.locations?.[0]?.path;
|
|
426
|
+
if (typeof up.title === "string" && up.title.trim()) tool.title = up.title;
|
|
427
|
+
if (typeof path === "string" && path) tool.path = path;
|
|
428
|
+
labelTool(false);
|
|
429
|
+
}
|
|
430
|
+
// Array.isArray, not `|| []`: iterating a non-array throws in the readline callback, an
|
|
431
|
+
// uncaught exception that takes down the whole server.
|
|
442
432
|
for (const c of Array.isArray(up.content) ? up.content : []) {
|
|
443
433
|
if (!c || typeof c !== "object" || Array.isArray(c) || typeof c.type !== "string"
|
|
444
434
|
|| (c.type === "diff" && (typeof c.path !== "string" || !c.path))) {
|
|
@@ -460,6 +450,11 @@ export async function runDelegate({
|
|
|
460
450
|
let servedModel;
|
|
461
451
|
let effectiveEffort;
|
|
462
452
|
const contextWarnings = [];
|
|
453
|
+
// Set before the teardown in finally, which notes an unseen exit on whichever is going out.
|
|
454
|
+
/** @type {any} */
|
|
455
|
+
let out;
|
|
456
|
+
/** @type {any} */
|
|
457
|
+
let failed;
|
|
463
458
|
try {
|
|
464
459
|
const res = await supervisor.supervise(async () => {
|
|
465
460
|
await client.start();
|
|
@@ -470,25 +465,18 @@ export async function runDelegate({
|
|
|
470
465
|
supervisor.setSessionId(sessionId);
|
|
471
466
|
onSessionReady?.(sessionId, client);
|
|
472
467
|
assertKnownModel(client, model);
|
|
473
|
-
//
|
|
474
|
-
//
|
|
475
|
-
// nothing to change. Cursor carries the selection across sessions, so the common shape
|
|
476
|
-
// (same model twice running) hits this.
|
|
468
|
+
// A session serves the model it reports opening on, so a matching id needs no set_model
|
|
469
|
+
// (measured). Cursor carries the selection across sessions, which makes this the usual case.
|
|
477
470
|
const openedOnModel = client.sessionModels?.currentModelId === model;
|
|
478
471
|
if (!openedOnModel) await client.setModel(sessionId, model);
|
|
479
|
-
// The selected model's options as
|
|
480
|
-
//
|
|
481
|
-
// that succeeds replaces the snapshot with its reply, which may carry none, and then nothing
|
|
482
|
-
// is known; a refused set changed nothing, so the snapshot stands.
|
|
472
|
+
// The selected model's options as last reported, for effectiveEffort: dropped after a model
|
|
473
|
+
// switch, replaced by each accepted set's reply (which may carry none), kept through a refused one.
|
|
483
474
|
let observedOptions = openedOnModel ? client.configOptions : undefined;
|
|
484
|
-
// fast is
|
|
485
|
-
//
|
|
486
|
-
//
|
|
487
|
-
//
|
|
488
|
-
//
|
|
489
|
-
// is for, and send whenever the reply itself is read: effort needs its option list, and a
|
|
490
|
-
// routable id needs the served model. An absent value reads as a mismatch and sends. effort
|
|
491
|
-
// and context go only when the caller named one; the last reply seen wins.
|
|
475
|
+
// fast is always sent as meant, never probed. Cursor persists the tier per model (measured),
|
|
476
|
+
// so the opening value counts only when the session opened on this model. Skip the set only
|
|
477
|
+
// when it did and the value matches, and send anyway when the reply is needed: effort needs
|
|
478
|
+
// its option list, a routed id the served model. An absent value counts as a mismatch. effort
|
|
479
|
+
// and context go only when named; the last reply seen wins.
|
|
492
480
|
const openedFast = configOptionValue(client.configOptions, "fast");
|
|
493
481
|
let modelOptions;
|
|
494
482
|
if (!openedOnModel || openedFast !== String(fast) || effort !== undefined || model === ROUTED_MODEL) {
|
|
@@ -520,8 +508,7 @@ export async function runDelegate({
|
|
|
520
508
|
}
|
|
521
509
|
}
|
|
522
510
|
await client.setMode(sessionId, mode);
|
|
523
|
-
// What the agent reported
|
|
524
|
-
// standing in for a reply that did not confirm it.
|
|
511
|
+
// What the agent reported, never the requested value standing in for an unconfirmed one.
|
|
525
512
|
effectiveEffort = effortSettings(observedOptions);
|
|
526
513
|
// Everything a session/load replay may have written belongs to the previous turn.
|
|
527
514
|
state.reset();
|
|
@@ -530,10 +517,11 @@ export async function runDelegate({
|
|
|
530
517
|
promptInFlight = true;
|
|
531
518
|
try {
|
|
532
519
|
const blocks = await buildContextBlocks(contextFiles, workspace, client, contextWarnings);
|
|
520
|
+
// The caller has the id from session/new on, so a cancel can come before there is a turn.
|
|
521
|
+
if (client.cancelRequested) return { stopReason: "cancelled", cancelledBeforePrompt: true };
|
|
533
522
|
return await client.prompt(sessionId, [{ type: "text", text: promptText }, ...blocks]);
|
|
534
523
|
} finally {
|
|
535
|
-
// The result is assembled across awaits
|
|
536
|
-
// settled turn is still folded into it.
|
|
524
|
+
// The result is assembled across later awaits; a frame trailing the turn must not join it.
|
|
537
525
|
promptInFlight = false;
|
|
538
526
|
}
|
|
539
527
|
});
|
|
@@ -554,7 +542,7 @@ export async function runDelegate({
|
|
|
554
542
|
"the agent ran a tool after its last message and never spoke again, so no final message closed the turn."
|
|
555
543
|
+ " result carries the last message before that tool call — it may be a preamble rather than the answer."
|
|
556
544
|
);
|
|
557
|
-
} else if (!finalMessageAvailable) {
|
|
545
|
+
} else if (!finalMessageAvailable && !res?.cancelledBeforePrompt) {
|
|
558
546
|
protocolWarnings.push("the agent ended the turn without emitting any message; result is empty.");
|
|
559
547
|
}
|
|
560
548
|
let stopReason;
|
|
@@ -562,51 +550,41 @@ export async function runDelegate({
|
|
|
562
550
|
if (typeof res.stopReason !== "string") {
|
|
563
551
|
protocolWarnings.push("stopReason dropped: ACP requires a string stop reason");
|
|
564
552
|
} else if (res.stopReason !== "end_turn") {
|
|
565
|
-
// end_turn
|
|
566
|
-
// reason only when something happened: a refusal, a cancel, an output cap.
|
|
553
|
+
// end_turn is the normal case; only a refusal, a cancel or an output cap is surfaced.
|
|
567
554
|
stopReason = res.stopReason;
|
|
568
555
|
}
|
|
569
556
|
}
|
|
570
|
-
|
|
557
|
+
out = {
|
|
571
558
|
result,
|
|
572
559
|
sessionId,
|
|
573
560
|
};
|
|
574
|
-
//
|
|
575
|
-
// since shell-driven edits leave no diff event.
|
|
561
|
+
// Absent means nothing reported, not nothing changed: shell edits leave no diff event.
|
|
576
562
|
const filesReported = normalizeAgentReportedFiles([...state.touched], workspace);
|
|
577
563
|
if (filesReported.length) out.filesReportedByEditTools = filesReported;
|
|
578
|
-
// resultSource
|
|
579
|
-
//
|
|
580
|
-
// resume took — a fresh session or a failed one (which carries its own warning) leaves it off.
|
|
564
|
+
// resultSource appears only when it warns; resumed only when a resume took (a failed one has
|
|
565
|
+
// its own warning).
|
|
581
566
|
if (resultSource !== "post-tool" && resultSource !== "tool-free-stream") out.resultSource = resultSource;
|
|
582
567
|
if (!!resumeSessionId && sessionId === resumeSessionId) out.resumed = true;
|
|
583
|
-
// Only when the agent served
|
|
584
|
-
// concrete id, or a cross-model resume. Silence means the request was honored.
|
|
568
|
+
// Only when the agent served another model than asked ("default" routing, a cross-model resume).
|
|
585
569
|
if (servedModel !== undefined && servedModel !== model) out.effectiveModel = servedModel;
|
|
586
570
|
// Unlike effectiveModel, present whenever known: an omitted effort runs at whatever Cursor
|
|
587
571
|
// saved for the model, and this is the only place the caller can see what that was.
|
|
588
572
|
if (effectiveEffort !== undefined) out.effectiveEffort = effectiveEffort;
|
|
589
573
|
if (stopReason !== undefined) out.stopReason = stopReason;
|
|
590
|
-
// sessionTitle stays out of the result: it is a live label (progress) and a forensic one
|
|
591
|
-
// (timeout errors), not a fact about the finished turn.
|
|
592
574
|
if (resumeError) protocolWarnings.push(`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`);
|
|
593
575
|
for (const u of unsupportedOptions) protocolWarnings.push(unsupportedWarning(model, u));
|
|
594
576
|
protocolWarnings.push(...contextWarnings);
|
|
595
577
|
protocolWarnings.push(...frameWarnings);
|
|
596
578
|
if (state.planEntries.length > 0 || state.planOverview !== undefined || state.planDetail !== undefined) {
|
|
597
|
-
//
|
|
598
|
-
// frames, which the caller needs whatever mode it asked for.
|
|
579
|
+
// Sanitized even when dropped: its warnings report malformed frames in any mode.
|
|
599
580
|
const plan = sanitizePlan(protocolWarnings);
|
|
600
|
-
// In plan/ask
|
|
601
|
-
//
|
|
602
|
-
//
|
|
603
|
-
// implements reads the agent's own session, not this field. In agent mode result is the
|
|
604
|
-
// implementation report, a separate artifact from the plan, so the whole object stays.
|
|
581
|
+
// In plan/ask the result is the plan in prose; entries would put the same steps in context
|
|
582
|
+
// twice, and the implementing resume reads the session, not this field. In agent mode the
|
|
583
|
+
// result is the implementation report, so the plan stays.
|
|
605
584
|
if (!dropPlan) out.plan = plan;
|
|
606
585
|
}
|
|
607
|
-
//
|
|
608
|
-
//
|
|
609
|
-
// remain; on a fully-completed turn it just restates the counts.
|
|
586
|
+
// Only when the agent tracked todos: an empty list would read as "nothing done". The list
|
|
587
|
+
// itself only while items remain; once all are done it restates the counts.
|
|
610
588
|
if (state.sawTodoFrame) {
|
|
611
589
|
const { todos: todoList, todoProgress } = sanitizeTodos(protocolWarnings);
|
|
612
590
|
out.todoProgress = todoProgress;
|
|
@@ -637,25 +615,22 @@ export async function runDelegate({
|
|
|
637
615
|
const files = normalizeAgentReportedFiles([...state.touched], workspace);
|
|
638
616
|
if (files.length) err.message += ` Files reported edited: ${files.join(", ")}.`;
|
|
639
617
|
}
|
|
640
|
-
// Every failure after session/new leaves a live session, not just the stalls: the id is set
|
|
641
|
-
// before set_model/set_config_option/set_mode, so unknown-model and a rejected config value
|
|
642
|
-
// land here too and are abandoned without it.
|
|
643
618
|
if (resumeError) {
|
|
644
|
-
//
|
|
645
|
-
// session was never loaded.
|
|
619
|
+
// Otherwise the resume hint reads as continuing work this session never had.
|
|
646
620
|
err.message += ` Note: resuming ${resumeSessionId} had already failed (${resumeError}),`
|
|
647
621
|
+ ` so this ran as a fresh session and none of that earlier work was in context.`;
|
|
648
622
|
}
|
|
623
|
+
// Any failure after session/new leaves a resumable session, unknown-model and a rejected
|
|
624
|
+
// config value included, not just the stalls.
|
|
649
625
|
if (sessionId) err.message += ` Resume with resumeSessionId ${sessionId}.`;
|
|
650
626
|
if (isTimeout) {
|
|
651
|
-
// Name the knob that
|
|
652
|
-
// idle-timeout, whose ceiling is CURSOR_DELEGATE_IDLE_MS.
|
|
627
|
+
// Name the knob that fired: the hard cap does nothing for an idle-timeout.
|
|
653
628
|
const knob = err.reason === "idle-timeout" ? "CURSOR_DELEGATE_IDLE_MS" : "CURSOR_DELEGATE_HARD_CAP_MS";
|
|
654
629
|
err.message += " cursor-agent does not stream shell output over ACP, so a long-running command emits"
|
|
655
630
|
+ ` nothing until it exits. Split the command, run it in the background and poll, or raise ${knob}.`;
|
|
656
631
|
}
|
|
657
|
-
// Opt-in:
|
|
658
|
-
//
|
|
632
|
+
// Opt-in: raw frames add nothing actionable to the caller's context beyond the forensics
|
|
633
|
+
// above; they help only someone debugging the bridge.
|
|
659
634
|
const frames = transcriptFrames();
|
|
660
635
|
if (frames > 0) {
|
|
661
636
|
try {
|
|
@@ -663,13 +638,26 @@ export async function runDelegate({
|
|
|
663
638
|
if (transcript) err.message += `\n\n--- recent ACP transcript (last ${frames} frames) ---\n` + transcript;
|
|
664
639
|
} catch {}
|
|
665
640
|
}
|
|
641
|
+
failed = err;
|
|
666
642
|
throw err;
|
|
667
643
|
} finally {
|
|
644
|
+
// The turn is decided: from here a cancel finds nothing running.
|
|
645
|
+
try { onTurnEnd?.(); } catch {}
|
|
668
646
|
clearInterval(heartbeat);
|
|
669
647
|
signal?.removeEventListener("abort", onAbort);
|
|
670
648
|
try { supervisor.finish(); } catch {}
|
|
671
|
-
//
|
|
672
|
-
//
|
|
673
|
-
|
|
649
|
+
// Awaited: a host may close stdin on the result, and on Windows the server's exit does not take
|
|
650
|
+
// a running agent with it (server.smoke.test.js). An exit not seen is noted instead.
|
|
651
|
+
// A rejected stop counts as unseen; an unseen exit is not memoized, so a retry kills afresh.
|
|
652
|
+
const stopOnce = () => Promise.resolve(client.stop()).catch(() => false);
|
|
653
|
+
let exited = await stopOnce();
|
|
654
|
+
if (exited === false) exited = await stopOnce();
|
|
655
|
+
if (exited === false) {
|
|
656
|
+
const pid = client.child?.pid;
|
|
657
|
+
const note = `the bridge stopped cursor-agent${pid ? ` (pid ${pid})` : ""} but did not see it exit; it may still be running.`;
|
|
658
|
+
// A failure whose message cannot be written keeps its own error rather than a TypeError.
|
|
659
|
+
if (failed) { try { failed.message += ` Note: ${note}`; } catch {} }
|
|
660
|
+
else if (out) (out.protocolWarnings ??= []).push(note);
|
|
661
|
+
}
|
|
674
662
|
}
|
|
675
663
|
}
|