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/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 on the server's only thread stalls every other in-flight delegation and
6
- // its progress stream. The statSync calls below stay sync — they are argument validation and
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
- // Malformed values fall back to the default rather than failing the call. Only a positive value
26
- // counts, so a blank var (Number("") is 0) cannot arm a zero-length deadline. The idle guard's
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 spins up a live session that only replies "No prompt content provided" —
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
- // Named, never defaulted: under npx or a plugin launch the server's own cwd is a cache directory
49
- // or the user's home, so a defaulted workspace put an auto-approved agent to work on a tree
50
- // nobody asked about while every layer reported success. And without the existence check the
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, not the file's bytes, so a large brief costs prompt
76
- // space only for what the agent opens. Images have no such form — they go inline. Both are
77
- // measured working, including links outside the workspace. Two rules from that probe:
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
- // Grouped, not one warning per file: a wrong workspace misses every attachment at once, and a
86
- // line each would repeat the same root N times for one root cause. The other skip reasons stay
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 the agent does not have justifies a fresh one; falling back on anything else
147
- // runs the task without the context the caller asked for. Code and wording together, never
148
- // either: 2026.08.11 returns -32602 `Session "<id>" not found` when it is missing, but -32603
149
- // `Failed to load session "<id>": <cause>` when restore fails, and that cause can carry the
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
- // Starting fresh is right, but silently doing so leaves the caller unable to tell a
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 reports the models the agent actually offers. Reject an unknown id here,
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
- // A model's config options are not discoverable up front (session/new reports only the default
191
- // model's; set_model returns nothing), so probe by asking and read the rejection. Both -32602s
192
- // are measured: "Unknown model config option: X" means no such knob — report and carry on;
193
- // "Invalid value for X: Y" is a caller error and must propagate.
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
- // The resolved model appears only in a set_config_option reply's configOptions (set_model
206
- // returns nothing). Absent for models that reject every option sent — the field then stays off.
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 when the exact value appears under a thought-level option the selected model
222
- // advertised. Local validation keeps a bad token out of ACP and, more importantly, out of a
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") {
@@ -278,10 +263,9 @@ export async function runDelegate({
278
263
  heartbeatMs = DEFAULT_HEARTBEAT_MS,
279
264
  signal,
280
265
  } = {}) {
281
- // Nothing between here and the abort listener below may await: addEventListener does not
282
- // replay an abort that already fired, so an abort landing in that window would be lost. A
283
- // spec read used to await here, and did lose one. Throwing, not supervisor.abort(): tripping
284
- // before supervise() installs its reject settles the supervisor with nothing listening.
266
+ // No await before the abort listener below: addEventListener does not replay an abort that
267
+ // already fired. Throw, not supervisor.abort(): tripping before supervise() installs its reject
268
+ // settles the supervisor with nothing listening.
285
269
  if (signal?.aborted) {
286
270
  throw makeError("aborted", "delegation aborted by MCP host");
287
271
  }
@@ -356,9 +340,8 @@ export async function runDelegate({
356
340
 
357
341
  const make = clientFactory || ((opts) => new AcpClient(opts));
358
342
  const client = make({ mode, onCreatePlan: state.recordCreatePlan, onTodos: state.recordTodos });
359
- // Handed over before the spawn, because from client.start() there is an agent process and the
360
- // caller needs something that can stop it. onSessionReady is roughly 3.4s later — a host going
361
- // away inside that window used to exit with the agent already running and nothing holding it.
343
+ // Before the spawn, so the caller can stop the agent from its first moment; onSessionReady comes
344
+ // ~3.4s later, and a host exiting in between would leave the agent running.
362
345
  onClientReady?.(client);
363
346
  const supervisor = new SessionSupervisor(client, { idleMs: turnIdleMs, handshakeMs: shakeMs, hardCapMs: capMs });
364
347
  const onAbort = () => supervisor.abort();
@@ -384,20 +367,26 @@ export async function runDelegate({
384
367
  heartbeat.unref?.();
385
368
  };
386
369
 
387
- // Malformed frames noticed as they arrive, where protocolWarnings does not exist yet. Merged
388
- // into it with the rest below.
370
+ // Malformed frames seen mid-turn; merged into protocolWarnings at the end.
389
371
  const frameWarnings = [];
390
372
 
391
- // session/load replays the previous turn as ordinary update frames, tool_call and diff blocks
392
- // included. state.reset() clears what they touch but cannot unsend a progress notification, so
393
- // the guard below is what stops a resume reporting last turn's edits as if they were happening.
373
+ // One line of at most 200 characters for progress and a stall error's "last tool call": a
374
+ // command's title is the command verbatim, a whole script included.
375
+ const labelTool = (started) => {
376
+ const { title, path } = state.lastTool;
377
+ const label = (String(title) + (path && !String(title).includes(path) ? " — " + path : "")).replace(/\s+/g, " ").trim().slice(0, 200);
378
+ if (!started && label === state.lastToolLabel) return;
379
+ state.lastToolLabel = label;
380
+ try { onProgress?.(("running: " + label).slice(0, 200)); } catch {}
381
+ };
382
+
383
+ // session/load replays the previous turn as ordinary updates. state.reset() clears what they
384
+ // set; only this guard keeps them out of progress.
394
385
  client.on("update", (u) => {
395
386
  if (!promptInFlight) return;
396
387
  const up = u?.update || {};
397
388
  if (up.sessionUpdate === "plan") {
398
- // ACP defines entries as an array. A non-array is truthy, so it was stored as-is and
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.
389
+ // A non-array would reach the sanitizer's forEach and throw after the work is done.
401
390
  if (up.entries !== undefined && !Array.isArray(up.entries)) {
402
391
  frameWarnings.push(
403
392
  `plan entries dropped: ACP requires an array, got ${up.entries === null ? "null" : typeof up.entries}`
@@ -407,10 +396,8 @@ export async function runDelegate({
407
396
  state.planEntries = up.entries || [];
408
397
  }
409
398
  }
410
- // The agent titles the turn a beat after the prompt lands ("File Creator") — useful live,
411
- // when several delegations run, and in timeout forensics. Kept out of the result: there it
412
- // arrives too late to tell anything apart, and was measured contradicting the answer
413
- // ("No Image Detected" on a turn describing an image).
399
+ // The agent's turn title ("File Creator"): a live label and timeout forensics. Kept out of the
400
+ // result, where it has contradicted the answer ("No Image Detected" on an image turn).
414
401
  if (up.sessionUpdate === "session_info_update" && typeof up.title === "string" && up.title) {
415
402
  if (up.title !== state.sessionTitle) { try { onProgress?.(`turn titled: ${up.title}`.slice(0, 200)); } catch {} }
416
403
  state.sessionTitle = up.title;
@@ -420,13 +407,8 @@ export async function runDelegate({
420
407
  }
421
408
  if (up.sessionUpdate === "tool_call") {
422
409
  state.startTool(up.toolCallId, up.status);
423
- const label = up.title || up.kind || "tool";
424
- const path = up.locations?.[0]?.path;
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 {}
410
+ state.lastTool = { id: up.toolCallId, title: up.title || up.kind || "tool", path: up.locations?.[0]?.path };
411
+ labelTool(true);
430
412
  }
431
413
  if (up.sessionUpdate === "agent_message_chunk" && up.content?.text) {
432
414
  const text = up.content.text;
@@ -435,10 +417,17 @@ export async function runDelegate({
435
417
  }
436
418
  if (up.sessionUpdate === "tool_call_update") {
437
419
  state.updateToolStatus(up.toolCallId, up.status);
438
- // Array.isArray, not `|| []`: a non-array content is truthy and iterating it throws
439
- // "object is not iterable" here, in the readline callback, where nothing awaits it. That
440
- // is an uncaught exception — the whole server, not this one turn — and it also stops the
441
- // reply on the next line from being read, so the turn hangs to its cap.
420
+ // tool_call names only the kind ("Terminal", "Edit File"); the command or path comes on a
421
+ // later update for the same id. Only the newest call is relabelled.
422
+ const tool = state.lastTool;
423
+ if (tool && up.toolCallId != null && up.toolCallId === tool.id) {
424
+ const path = up.locations?.[0]?.path;
425
+ if (typeof up.title === "string" && up.title.trim()) tool.title = up.title;
426
+ if (typeof path === "string" && path) tool.path = path;
427
+ labelTool(false);
428
+ }
429
+ // Array.isArray, not `|| []`: iterating a non-array throws in the readline callback, an
430
+ // uncaught exception that takes down the whole server.
442
431
  for (const c of Array.isArray(up.content) ? up.content : []) {
443
432
  if (!c || typeof c !== "object" || Array.isArray(c) || typeof c.type !== "string"
444
433
  || (c.type === "diff" && (typeof c.path !== "string" || !c.path))) {
@@ -470,25 +459,18 @@ export async function runDelegate({
470
459
  supervisor.setSessionId(sessionId);
471
460
  onSessionReady?.(sessionId, client);
472
461
  assertKnownModel(client, model);
473
- // session/new and session/load both report the model the session opened on, and an id that
474
- // already matches is served without an explicit set — measured, so this round-trip has
475
- // nothing to change. Cursor carries the selection across sessions, so the common shape
476
- // (same model twice running) hits this.
462
+ // A session serves the model it reports opening on, so a matching id needs no set_model
463
+ // (measured). Cursor carries the selection across sessions, which makes this the usual case.
477
464
  const openedOnModel = client.sessionModels?.currentModelId === model;
478
465
  if (!openedOnModel) await client.setModel(sessionId, model);
479
- // The selected model's options as the agent last reported them, read for effectiveEffort.
480
- // After a switch the opening snapshot describes the model we left, so it is dropped. A set
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.
466
+ // The selected model's options as last reported, for effectiveEffort: dropped after a model
467
+ // switch, replaced by each accepted set's reply (which may carry none), kept through a refused one.
483
468
  let observedOptions = openedOnModel ? client.configOptions : undefined;
484
- // fast is an instruction, not a probe. Cursor persists the tier, and persists it per model —
485
- // both measured: one fast:true turn leaves the next fresh session reporting fast=true, and a
486
- // set_model to another model reports that model's own tier. So the opening snapshot only
487
- // describes the tier in force when the session also opened on this model; after a switch it
488
- // describes the model we left. Skip only when both hold, which is the steady-state path this
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.
469
+ // fast is always sent as meant, never probed. Cursor persists the tier per model (measured),
470
+ // so the opening value counts only when the session opened on this model. Skip the set only
471
+ // when it did and the value matches, and send anyway when the reply is needed: effort needs
472
+ // its option list, a routed id the served model. An absent value counts as a mismatch. effort
473
+ // and context go only when named; the last reply seen wins.
492
474
  const openedFast = configOptionValue(client.configOptions, "fast");
493
475
  let modelOptions;
494
476
  if (!openedOnModel || openedFast !== String(fast) || effort !== undefined || model === ROUTED_MODEL) {
@@ -520,8 +502,7 @@ export async function runDelegate({
520
502
  }
521
503
  }
522
504
  await client.setMode(sessionId, mode);
523
- // What the agent reported in force as the prompt goes out — never the requested value
524
- // standing in for a reply that did not confirm it.
505
+ // What the agent reported, never the requested value standing in for an unconfirmed one.
525
506
  effectiveEffort = effortSettings(observedOptions);
526
507
  // Everything a session/load replay may have written belongs to the previous turn.
527
508
  state.reset();
@@ -530,10 +511,11 @@ export async function runDelegate({
530
511
  promptInFlight = true;
531
512
  try {
532
513
  const blocks = await buildContextBlocks(contextFiles, workspace, client, contextWarnings);
514
+ // The caller has the id from session/new on, so a cancel can come before there is a turn.
515
+ if (client.cancelRequested) return { stopReason: "cancelled", cancelledBeforePrompt: true };
533
516
  return await client.prompt(sessionId, [{ type: "text", text: promptText }, ...blocks]);
534
517
  } finally {
535
- // The result is assembled across awaits below, so without this a frame trailing the
536
- // settled turn is still folded into it.
518
+ // The result is assembled across later awaits; a frame trailing the turn must not join it.
537
519
  promptInFlight = false;
538
520
  }
539
521
  });
@@ -554,7 +536,7 @@ export async function runDelegate({
554
536
  "the agent ran a tool after its last message and never spoke again, so no final message closed the turn."
555
537
  + " result carries the last message before that tool call — it may be a preamble rather than the answer."
556
538
  );
557
- } else if (!finalMessageAvailable) {
539
+ } else if (!finalMessageAvailable && !res?.cancelledBeforePrompt) {
558
540
  protocolWarnings.push("the agent ended the turn without emitting any message; result is empty.");
559
541
  }
560
542
  let stopReason;
@@ -562,8 +544,7 @@ export async function runDelegate({
562
544
  if (typeof res.stopReason !== "string") {
563
545
  protocolWarnings.push("stopReason dropped: ACP requires a string stop reason");
564
546
  } else if (res.stopReason !== "end_turn") {
565
- // end_turn carries no signal (it was end_turn on every stress-test call). Surface a stop
566
- // reason only when something happened: a refusal, a cancel, an output cap.
547
+ // end_turn is the normal case; only a refusal, a cancel or an output cap is surfaced.
567
548
  stopReason = res.stopReason;
568
549
  }
569
550
  }
@@ -571,42 +552,33 @@ export async function runDelegate({
571
552
  result,
572
553
  sessionId,
573
554
  };
574
- // Absence means "nothing reported", not "nothing changed" — a claim this field cannot make,
575
- // since shell-driven edits leave no diff event.
555
+ // Absent means nothing reported, not nothing changed: shell edits leave no diff event.
576
556
  const filesReported = normalizeAgentReportedFiles([...state.touched], workspace);
577
557
  if (filesReported.length) out.filesReportedByEditTools = filesReported;
578
- // resultSource is a caveat, not a fact: on the happy path (post-tool / tool-free-stream)
579
- // result is just the answer. Emit it only when it warns. resumed likewise appears only when a
580
- // resume took — a fresh session or a failed one (which carries its own warning) leaves it off.
558
+ // resultSource appears only when it warns; resumed only when a resume took (a failed one has
559
+ // its own warning).
581
560
  if (resultSource !== "post-tool" && resultSource !== "tool-free-stream") out.resultSource = resultSource;
582
561
  if (!!resumeSessionId && sessionId === resumeSessionId) out.resumed = true;
583
- // Only when the agent served a different model than asked — e.g. "default" routing to a
584
- // concrete id, or a cross-model resume. Silence means the request was honored.
562
+ // Only when the agent served another model than asked ("default" routing, a cross-model resume).
585
563
  if (servedModel !== undefined && servedModel !== model) out.effectiveModel = servedModel;
586
564
  // Unlike effectiveModel, present whenever known: an omitted effort runs at whatever Cursor
587
565
  // saved for the model, and this is the only place the caller can see what that was.
588
566
  if (effectiveEffort !== undefined) out.effectiveEffort = effectiveEffort;
589
567
  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
568
  if (resumeError) protocolWarnings.push(`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`);
593
569
  for (const u of unsupportedOptions) protocolWarnings.push(unsupportedWarning(model, u));
594
570
  protocolWarnings.push(...contextWarnings);
595
571
  protocolWarnings.push(...frameWarnings);
596
572
  if (state.planEntries.length > 0 || state.planOverview !== undefined || state.planDetail !== undefined) {
597
- // Sanitize even when the plan is discarded: the warnings it raises report malformed ACP
598
- // frames, which the caller needs whatever mode it asked for.
573
+ // Sanitized even when dropped: its warnings report malformed frames in any mode.
599
574
  const plan = sanitizePlan(protocolWarnings);
600
- // In plan/ask, result IS the plan — the agent's own message, already prose and already
601
- // what gets shown to the user for approval. Returning entries alongside it puts the same
602
- // steps in the orchestrator's context twice, and nothing consumes them: the resume that
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.
575
+ // In plan/ask the result is the plan in prose; entries would put the same steps in context
576
+ // twice, and the implementing resume reads the session, not this field. In agent mode the
577
+ // result is the implementation report, so the plan stays.
605
578
  if (!dropPlan) out.plan = plan;
606
579
  }
607
- // Most turns emit no todos, so an empty list would read as "nothing done" rather than "not
608
- // tracked". The full list is carried only when it says what todoProgress cannot — which items
609
- // remain; on a fully-completed turn it just restates the counts.
580
+ // Only when the agent tracked todos: an empty list would read as "nothing done". The list
581
+ // itself only while items remain; once all are done it restates the counts.
610
582
  if (state.sawTodoFrame) {
611
583
  const { todos: todoList, todoProgress } = sanitizeTodos(protocolWarnings);
612
584
  out.todoProgress = todoProgress;
@@ -637,25 +609,22 @@ export async function runDelegate({
637
609
  const files = normalizeAgentReportedFiles([...state.touched], workspace);
638
610
  if (files.length) err.message += ` Files reported edited: ${files.join(", ")}.`;
639
611
  }
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
612
  if (resumeError) {
644
- // Without this the resume hint reads as "carry on from where you were", when the requested
645
- // session was never loaded.
613
+ // Otherwise the resume hint reads as continuing work this session never had.
646
614
  err.message += ` Note: resuming ${resumeSessionId} had already failed (${resumeError}),`
647
615
  + ` so this ran as a fresh session and none of that earlier work was in context.`;
648
616
  }
617
+ // Any failure after session/new leaves a resumable session, unknown-model and a rejected
618
+ // config value included, not just the stalls.
649
619
  if (sessionId) err.message += ` Resume with resumeSessionId ${sessionId}.`;
650
620
  if (isTimeout) {
651
- // Name the knob that actually fired: raising the hard cap does nothing for an
652
- // idle-timeout, whose ceiling is CURSOR_DELEGATE_IDLE_MS.
621
+ // Name the knob that fired: the hard cap does nothing for an idle-timeout.
653
622
  const knob = err.reason === "idle-timeout" ? "CURSOR_DELEGATE_IDLE_MS" : "CURSOR_DELEGATE_HARD_CAP_MS";
654
623
  err.message += " cursor-agent does not stream shell output over ACP, so a long-running command emits"
655
624
  + ` nothing until it exits. Split the command, run it in the background and poll, or raise ${knob}.`;
656
625
  }
657
- // Opt-in: the frames land in the caller's context and nothing there is actionable — the
658
- // forensics above already carry that. Raw frames only help someone debugging the bridge.
626
+ // Opt-in: raw frames add nothing actionable to the caller's context beyond the forensics
627
+ // above; they help only someone debugging the bridge.
659
628
  const frames = transcriptFrames();
660
629
  if (frames > 0) {
661
630
  try {