cursor-delegate-mcp 1.12.0 → 1.14.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
@@ -1,21 +1,32 @@
1
1
  import process from "node:process";
2
2
  import path from "node:path";
3
3
  import { pathToFileURL } from "node:url";
4
- import { readFileSync, statSync } from "node:fs";
4
+ import { statSync } from "node:fs";
5
+ // Reads happen on the server's only thread, where a synchronous one stalls every other
6
+ // delegation in flight and the progress notifications they are streaming. The stats stay
7
+ // synchronous: they are argument validation, and they run before the spawn.
8
+ import { readFile } from "node:fs/promises";
5
9
  import { AcpClient } from "./acp-client.js";
6
10
  import { SessionSupervisor } from "./session-supervisor.js";
7
11
  import { normalizeAgentReportedFiles } from "./agent-reported-files.js";
12
+ import { makeTurnState } from "./turn-state.js";
13
+ import { makeError } from "./errors.js";
14
+ import { PLAN_PRIORITIES, PLAN_STATUSES, TODO_STATUSES } from "./acp-enums.js";
8
15
 
9
16
  export const DEFAULT_MODEL = "composer-2.5";
10
17
  export const DEFAULT_HANDSHAKE_MS = 60000;
11
18
  export const DEFAULT_HEARTBEAT_MS = 30000;
12
19
 
13
- // Malformed values fall back to the default rather than failing the call.
20
+ // Malformed values fall back to the default rather than failing the call. Only a positive
21
+ // value counts: zero used to be taken literally, so CURSOR_DELEGATE_HARD_CAP_MS=0 — or an
22
+ // accidentally blank one, since Number("") is 0 — armed a zero-length deadline that failed
23
+ // every call instantly. Falling back keeps the one documented meaning of 0, the idle guard's,
24
+ // which gets it from its own fallback being 0.
14
25
  function envMs(name, fallback) {
15
26
  const raw = process.env[name];
16
27
  if (raw === undefined) return fallback;
17
28
  const n = Number(raw);
18
- return Number.isFinite(n) && n >= 0 ? n : fallback;
29
+ return Number.isFinite(n) && n > 0 ? n : fallback;
19
30
  }
20
31
 
21
32
  function fmtDuration(ms) {
@@ -34,14 +45,12 @@ function looksLikeSpecPath(spec) {
34
45
  }
35
46
  const isBareSpecPath = (spec) => !/\s/.test(spec.trim());
36
47
 
37
- function resolveSpec(spec) {
48
+ async function resolveSpec(spec) {
38
49
  if (typeof spec !== "string") return spec;
39
50
  // A blank spec spins up a live session that only replies "No prompt content provided" —
40
51
  // a billed turn for nothing. Reject it here, before the spawn, like the other bad specs.
41
52
  if (spec.trim() === "") {
42
- const err = new Error("spec is empty. Provide a task brief inline, or a path to one.");
43
- err.reason = "invalid-spec";
44
- throw err;
53
+ throw makeError("invalid-spec", "spec is empty. Provide a task brief inline, or a path to one.");
45
54
  }
46
55
  if (!looksLikeSpecPath(spec)) return spec;
47
56
  let stat;
@@ -51,15 +60,11 @@ function resolveSpec(spec) {
51
60
  // Only a bare path was unambiguously meant as one. Anything else is prose that happens
52
61
  // to name a file, and prose is the common case.
53
62
  if (!isBareSpecPath(spec)) return spec;
54
- const err = new Error(`spec looks like a file path but nothing exists at ${spec}. Pass the brief inline, or fix the path.`);
55
- err.reason = "invalid-spec";
56
- throw err;
63
+ throw makeError("invalid-spec", `spec looks like a file path but nothing exists at ${spec}. Pass the brief inline, or fix the path.`);
57
64
  }
58
- if (stat.isFile()) return readFileSync(spec, "utf8");
65
+ if (stat.isFile()) return readFile(spec, "utf8");
59
66
  if (isBareSpecPath(spec)) {
60
- const err = new Error(`spec looks like a file path but ${spec} is not a file. Pass the brief inline, or point at a file.`);
61
- err.reason = "invalid-spec";
62
- throw err;
67
+ throw makeError("invalid-spec", `spec looks like a file path but ${spec} is not a file. Pass the brief inline, or point at a file.`);
63
68
  }
64
69
  return spec;
65
70
  }
@@ -73,14 +78,10 @@ function assertWorkspace(workspace) {
73
78
  try {
74
79
  stat = statSync(workspace);
75
80
  } catch {
76
- const err = new Error(`workspace ${workspace} does not exist. Create it first, or point at an existing directory.`);
77
- err.reason = "invalid-workspace";
78
- throw err;
81
+ throw makeError("invalid-workspace", `workspace ${workspace} does not exist. Create it first, or point at an existing directory.`);
79
82
  }
80
83
  if (!stat.isDirectory()) {
81
- const err = new Error(`workspace ${workspace} is not a directory.`);
82
- err.reason = "invalid-workspace";
83
- throw err;
84
+ throw makeError("invalid-workspace", `workspace ${workspace} is not a directory.`);
84
85
  }
85
86
  }
86
87
 
@@ -99,7 +100,7 @@ const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
99
100
  // not support without any error (embeddedContext:false raises nothing), so an ungated
100
101
  // image would silently vanish;
101
102
  // - report anything skipped, since a dropped attachment is otherwise invisible.
102
- function buildContextBlocks(contextFiles, workspace, client, warnings) {
103
+ async function buildContextBlocks(contextFiles, workspace, client, warnings) {
103
104
  const blocks = [];
104
105
  // A glob plus an explicit path (or the same file named a few ways) resolves to one file;
105
106
  // sending it several times just wastes prompt space. Collapse by resolved absolute path.
@@ -130,7 +131,7 @@ function buildContextBlocks(contextFiles, workspace, client, warnings) {
130
131
  warnings.push(`contextFile ${entry} skipped: ${Math.round(stat.size / 1024)}KB exceeds the ${MAX_IMAGE_BYTES / 1024 / 1024}MB image limit`);
131
132
  continue;
132
133
  }
133
- blocks.push({ type: "image", mimeType, data: readFileSync(abs).toString("base64") });
134
+ blocks.push({ type: "image", mimeType, data: (await readFile(abs)).toString("base64") });
134
135
  continue;
135
136
  }
136
137
  blocks.push({ type: "resource_link", uri: pathToFileURL(abs).href, name: path.basename(abs) });
@@ -159,9 +160,7 @@ function assertKnownModel(client, model) {
159
160
  if (!Array.isArray(available) || available.length === 0) return;
160
161
  const ids = available.map((m) => m?.modelId).filter((id) => typeof id === "string");
161
162
  if (ids.length === 0 || ids.includes(model)) return;
162
- const err = new Error(`Unknown model ${JSON.stringify(model)}. This agent offers: ${ids.join(", ")}.`);
163
- err.reason = "unknown-model";
164
- throw err;
163
+ throw makeError("unknown-model", `Unknown model ${JSON.stringify(model)}. This agent offers: ${ids.join(", ")}.`);
165
164
  }
166
165
 
167
166
  // Which config options a model carries is not discoverable up front: session/new reports
@@ -169,90 +168,66 @@ function assertKnownModel(client, model) {
169
168
  // rejection as the answer. Two distinct -32602s, both measured: "Unknown model config
170
169
  // option: X" means this model has no such knob — report it and carry on. "Invalid value
171
170
  // for X: Y" means the caller named a value the model rejects, which must not be swallowed.
172
- // Returns true when the option is unsupported.
171
+ // Returns { unsupported, res }: unsupported is true when the model has no such knob; res is the
172
+ // set_config_option reply, which echoes the now-current model's configOptions (incl. the served
173
+ // model id) — the only place the agent reports what model actually took after set_model.
173
174
  async function applyConfig(client, sessionId, configId, value) {
174
175
  try {
175
- await client.setConfigOption(sessionId, configId, value);
176
- return false;
176
+ const res = await client.setConfigOption(sessionId, configId, value);
177
+ return { unsupported: false, res };
177
178
  } catch (err) {
178
179
  if (err?.code !== -32602 || !/unknown model config option/i.test(err?.message || "")) throw err;
179
- return true;
180
+ return { unsupported: true };
180
181
  }
181
182
  }
182
183
 
184
+ // The agent reports the resolved model only inside a set_config_option reply's configOptions
185
+ // (set_model itself returns nothing). Read it there when present; absent for models that reject
186
+ // every option we send, which is fine — the field then stays off.
187
+ function servedModelFrom(res) {
188
+ const opts = res?.configOptions;
189
+ if (!Array.isArray(opts)) return undefined;
190
+ const m = opts.find((o) => o?.id === "model");
191
+ return typeof m?.currentValue === "string" ? m.currentValue : undefined;
192
+ }
193
+
194
+ /**
195
+ * @param {{
196
+ * spec?: string, mode?: string, resumeSessionId?: string, workspace?: string,
197
+ * model?: string, fast?: boolean, reasoning?: string, context?: string,
198
+ * contextFiles?: string[], clientFactory?: (opts: any) => any,
199
+ * idleMs?: number, handshakeMs?: number, hardCapMs?: number, timeoutMs?: number,
200
+ * onSessionReady?: (sessionId: string, client: any) => void,
201
+ * onProgress?: (message: string) => void,
202
+ * progressThrottleMs?: number, heartbeatMs?: number, signal?: AbortSignal,
203
+ * }} [opts]
204
+ */
183
205
  export async function runDelegate({
184
- spec, mode = "agent", resumeSessionId, workspace, maxResultChars,
185
- model = DEFAULT_MODEL, fast = false, reasoning, context, contextFiles, clientFactory, onElicit,
206
+ spec, mode = "agent", resumeSessionId, workspace,
207
+ model = DEFAULT_MODEL, fast = false, reasoning, context, contextFiles, clientFactory,
186
208
  idleMs, handshakeMs, hardCapMs, timeoutMs,
187
209
  onSessionReady, onProgress, progressThrottleMs = 2000,
188
210
  heartbeatMs = DEFAULT_HEARTBEAT_MS,
189
211
  signal,
190
212
  } = {}) {
191
213
  if (signal?.aborted) {
192
- const err = new Error("delegation aborted by MCP host");
193
- err.reason = "aborted";
194
- throw err;
214
+ throw makeError("aborted", "delegation aborted by MCP host");
195
215
  }
196
216
  // Before the spawn: a bad path is the caller's to fix, and finding out costs a process,
197
217
  // a handshake and a billed turn if it waits until the prompt is assembled.
198
218
  assertWorkspace(workspace);
199
- const promptText = resolveSpec(spec);
219
+ const promptText = await resolveSpec(spec);
200
220
  const capMs = hardCapMs ?? timeoutMs ?? envMs("CURSOR_DELEGATE_HARD_CAP_MS", 3600000);
201
221
  const shakeMs = handshakeMs ?? envMs("CURSOR_DELEGATE_HANDSHAKE_MS", DEFAULT_HANDSHAKE_MS);
202
222
  const turnIdleMs = idleMs ?? envMs("CURSOR_DELEGATE_IDLE_MS", 0);
203
- const MAX_OUTPUT = 10 * 1024 * 1024;
204
- const TRUNCATION_MARKER = "\n\n[output truncated at 10MB]";
205
- const questionsAsked = [];
206
- const recordQuestions = (q) => {
207
- if (q.kind !== "ask_question") return;
208
- for (const question of q.questions || []) {
209
- if (typeof question?.prompt === "string" && question.prompt) questionsAsked.push(question.prompt);
210
- }
211
- };
212
- const wrappedElicit = onElicit
213
- ? async (q) => { recordQuestions(q); return onElicit(q); }
214
- : async (q) => { recordQuestions(q); return null; };
215
-
216
- // merge:false replaces the list, merge:true upserts by id. Entries always arrive complete,
217
- // so a keyed set is enough — no field-level merging.
218
- let todos = new Map();
219
- let sawTodoFrame = false;
220
- const todoLabel = () => {
221
- const entries = [...todos.values()].filter((t) => typeof t?.content === "string");
222
- if (!entries.length) return null;
223
- const i = entries.findIndex((t) => t.status === "in_progress");
224
- if (i !== -1) return `todo ${i + 1}/${entries.length}: ${entries[i].content}`;
225
- const done = entries.filter((t) => t.status === "completed").length;
226
- return `todos ${done}/${entries.length} complete`;
227
- };
228
- const recordTodos = ({ todos: incoming, merge }) => {
229
- if (!Array.isArray(incoming)) return;
230
- sawTodoFrame = true;
231
- if (merge === false) todos = new Map();
232
- for (const t of incoming) {
233
- if (t?.id === undefined || t?.id === null) continue;
234
- todos.set(String(t.id), t);
235
- }
236
- const label = todoLabel();
237
- if (label) { try { onProgress?.(label.slice(0, 200)); } catch {} }
238
- };
239
-
240
- let planEntries = [];
241
- let planOverview;
242
- let planDetail;
243
- const recordCreatePlan = (body) => {
244
- if (body?.overview !== undefined) planOverview = body.overview;
245
- if (body?.plan !== undefined) planDetail = body.plan;
246
- };
223
+ const state = makeTurnState({ onProgress, progressThrottleMs });
247
224
 
248
225
  // ACP requires plan entry content to be a string and bounds priority/status to
249
226
  // known values. Frames that violate that must not fail the MCP call after the
250
227
  // work is done — drop the bad data and report it as a protocol diagnostic.
251
- const PLAN_PRIORITIES = ["high", "medium", "low"];
252
- const PLAN_STATUSES = ["pending", "in_progress", "completed"];
253
228
  const sanitizePlan = (warnings) => {
254
229
  const entries = [];
255
- planEntries.forEach((raw, i) => {
230
+ state.planEntries.forEach((raw, i) => {
256
231
  if (typeof raw?.content !== "string") {
257
232
  warnings.push(`plan entry ${i} dropped: ACP requires string content, got ${raw === null ? "null" : typeof raw?.content}`);
258
233
  return;
@@ -269,22 +244,21 @@ export async function runDelegate({
269
244
  entries.push(entry);
270
245
  });
271
246
  const plan = { entries };
272
- if (planOverview !== undefined) {
273
- if (typeof planOverview === "string") plan.overview = planOverview;
247
+ if (state.planOverview !== undefined) {
248
+ if (typeof state.planOverview === "string") plan.overview = state.planOverview;
274
249
  else warnings.push("plan overview dropped: expected string");
275
250
  }
276
- if (planDetail !== undefined) {
277
- if (typeof planDetail === "string") plan.detail = planDetail;
251
+ if (state.planDetail !== undefined) {
252
+ if (typeof state.planDetail === "string") plan.detail = state.planDetail;
278
253
  else warnings.push("plan detail dropped: expected string");
279
254
  }
280
255
  return plan;
281
256
  };
282
257
 
283
- const TODO_STATUSES = ["pending", "in_progress", "completed"];
284
258
  const sanitizeTodos = (warnings) => {
285
259
  const entries = [];
286
260
  let i = -1;
287
- for (const raw of todos.values()) {
261
+ for (const raw of state.todos.values()) {
288
262
  i++;
289
263
  if (typeof raw?.content !== "string") {
290
264
  warnings.push(`todo ${i} dropped: expected string content, got ${raw === null ? "null" : typeof raw?.content}`);
@@ -309,125 +283,13 @@ export async function runDelegate({
309
283
  };
310
284
 
311
285
  const make = clientFactory || ((opts) => new AcpClient(opts));
312
- const client = make({ onElicit: wrappedElicit, mode, onCreatePlan: recordCreatePlan, onTodos: recordTodos });
286
+ const client = make({ mode, onCreatePlan: state.recordCreatePlan, onTodos: state.recordTodos });
313
287
  const supervisor = new SessionSupervisor(client, { idleMs: turnIdleMs, handshakeMs: shakeMs, hardCapMs: capMs });
314
288
  const onAbort = () => supervisor.abort();
315
289
  signal?.addEventListener("abort", onAbort, { once: true });
316
290
 
317
- const resultChunks = [];
318
- let resultLength = 0;
319
- let truncated = false;
320
- let sawToolCall = false;
321
- let collectingPostToolResult = false;
322
- const activeToolCalls = new Set();
323
- const touched = new Set();
324
-
325
- // Text superseded by a later tool call is normally a preamble ("Inspecting the
326
- // implementation.") and returning it would be inventing a summary. But the rule cannot
327
- // tell a preamble from the whole answer: an agent that replies and then runs one more
328
- // command has its entire reply discarded, and the caller gets "" with stopReason end_turn
329
- // and no error. So keep the last discarded segment and hand it back only when nothing
330
- // survived — labelled, never blended with a real final message.
331
- let discardedResult = "";
332
- const resetResult = () => {
333
- if (resultLength > 0) discardedResult = resultChunks.join("");
334
- resultChunks.length = 0;
335
- resultLength = 0;
336
- truncated = false;
337
- };
338
- const appendResult = (text) => {
339
- if (truncated) return;
340
- const remaining = MAX_OUTPUT - resultLength;
341
- if (text.length <= remaining) {
342
- resultChunks.push(text);
343
- resultLength += text.length;
344
- } else if (remaining > 0) {
345
- resultChunks.push(text.slice(0, remaining));
346
- resultLength += remaining;
347
- truncated = true;
348
- } else {
349
- truncated = true;
350
- }
351
- };
352
- const isTerminalToolStatus = (status) =>
353
- status === "completed" || status === "failed" || status === "cancelled";
354
- const startTool = (toolCallId, status) => {
355
- sawToolCall = true;
356
- collectingPostToolResult = false;
357
- resetResult();
358
- if (toolCallId != null && !isTerminalToolStatus(status)) activeToolCalls.add(toolCallId);
359
- if (isTerminalToolStatus(status) && activeToolCalls.size === 0) collectingPostToolResult = true;
360
- };
361
- const updateToolStatus = (toolCallId, status) => {
362
- if (!status) return;
363
- if (!sawToolCall) {
364
- sawToolCall = true;
365
- resetResult();
366
- }
367
- if (isTerminalToolStatus(status)) {
368
- if (toolCallId != null) activeToolCalls.delete(toolCallId);
369
- if (activeToolCalls.size === 0 && !collectingPostToolResult) {
370
- // Discard any message text emitted while tools were still running.
371
- // A duplicate or late terminal update must not wipe an already-collected final message.
372
- resetResult();
373
- collectingPostToolResult = true;
374
- }
375
- } else {
376
- collectingPostToolResult = false;
377
- resetResult();
378
- if (toolCallId != null) activeToolCalls.add(toolCallId);
379
- }
380
- };
381
-
382
- // Each stream reports its newest complete sentence, at most one per throttle window.
383
- // Capital-letter boundary: cursor-agent thoughts arrive as sentences with no separator.
384
- const SENTENCE_END = /[.!?](?=\s|[A-Z])|\n/;
385
- const MARKDOWN_LINE = /^(?:[|#>`~*_=+-]|\d+[.)]\s)/;
386
- const progressStream = (prefix) => {
387
- let buf = "", pending = null, lastEmit = 0;
388
- const flush = (force) => {
389
- if (pending === null || (!force && Date.now() - lastEmit < progressThrottleMs)) return;
390
- lastEmit = Date.now();
391
- try { onProgress?.(prefix + pending); } catch {}
392
- pending = null;
393
- };
394
- const take = (s) => {
395
- const line = s.replace(/\s+/g, " ").trim().slice(0, 200);
396
- if (line.length > 3 && !MARKDOWN_LINE.test(line)) pending = line;
397
- flush(false);
398
- };
399
- return {
400
- push(text) {
401
- buf += text;
402
- for (let m; (m = SENTENCE_END.exec(buf)); buf = buf.slice(m.index + 1)) {
403
- take(buf.slice(0, m.index + 1));
404
- }
405
- if (buf.length > 300) { take(buf); buf = ""; }
406
- },
407
- end() { take(buf); buf = ""; flush(true); },
408
- reset() { buf = ""; pending = null; },
409
- };
410
- };
411
- const thoughtProgress = progressStream("thinking: ");
412
- const messageProgress = progressStream("Cursor: ");
413
-
414
291
  // The bridge cannot see inside a running shell command, so a long silence is reported
415
292
  // rather than acted on: the caller gets elapsed time and frame age and can decide.
416
- let lastToolLabel = null;
417
- // A shell write arrives as execute, a file write as edit; delete and move round out ACP's
418
- // write-capable kinds. read, search, think and fetch stay out — a plan turn is expected
419
- // to do those.
420
- const WRITE_CAPABLE_KINDS = new Set(["edit", "delete", "move", "execute"]);
421
- // Scoped to plan/ask deliberately. In agent mode this is every turn and carries nothing;
422
- // in plan/ask a disk-touching turn is abnormal — the plan itself travels over ACP as a
423
- // string via cursor/create_plan, not as a file — so the base rate makes it worth reading.
424
- // It records what the agent *ran*, never what changed: a command is not a change list.
425
- const WRITE_ACTIVITY_CAP = 20;
426
- const watchingWrites = mode === "plan" || mode === "ask";
427
- let writeCapableActivity = [];
428
- let writeActivityById = new Map();
429
- let modeChanged;
430
- let sessionTitle;
431
293
  let promptInFlight = false;
432
294
  let heartbeat = null;
433
295
  const startHeartbeat = () => {
@@ -438,9 +300,9 @@ export async function runDelegate({
438
300
  `still working — ${fmtDuration(Date.now() - startedAt)} elapsed`,
439
301
  `last agent frame ${fmtDuration(supervisor.msSinceActivity())} ago`,
440
302
  ];
441
- const todo = todoLabel();
303
+ const todo = state.todoLabel();
442
304
  if (todo) parts.push(todo);
443
- if (lastToolLabel) parts.push(`running: ${lastToolLabel}`);
305
+ if (state.lastToolLabel) parts.push(`running: ${state.lastToolLabel}`);
444
306
  try { onProgress?.(parts.join(", ").slice(0, 200)); } catch {}
445
307
  }, heartbeatMs);
446
308
  heartbeat.unref?.();
@@ -454,63 +316,38 @@ export async function runDelegate({
454
316
  if (!promptInFlight) return;
455
317
  const up = u?.update || {};
456
318
  if (up.sessionUpdate === "plan") {
457
- planEntries = up.entries || [];
458
- }
459
- // A plan-mode run that switches itself to agent mode becomes write-capable while the
460
- // caller still believes nothing can change. No drift has been observed; report it so
461
- // we find out rather than assume.
462
- if (up.sessionUpdate === "current_mode_update" && up.currentModeId && up.currentModeId !== mode) {
463
- modeChanged = { from: mode, to: up.currentModeId };
319
+ state.planEntries = up.entries || [];
464
320
  }
465
321
  // The agent names the turn a beat after the prompt lands ("File Creator"). Useful as an
466
322
  // ephemeral label while several delegations run, and in timeout forensics — but not in
467
323
  // the result, where it arrives after there is nothing left to tell apart and has been
468
324
  // measured contradicting the answer ("No Image Detected" on a turn describing an image).
469
325
  if (up.sessionUpdate === "session_info_update" && typeof up.title === "string" && up.title) {
470
- if (up.title !== sessionTitle) { try { onProgress?.(`turn titled: ${up.title}`.slice(0, 200)); } catch {} }
471
- sessionTitle = up.title;
326
+ if (up.title !== state.sessionTitle) { try { onProgress?.(`turn titled: ${up.title}`.slice(0, 200)); } catch {} }
327
+ state.sessionTitle = up.title;
472
328
  }
473
329
  if (up.sessionUpdate === "agent_thought_chunk" && up.content?.text) {
474
- thoughtProgress.push(up.content.text);
330
+ state.thoughts.push(up.content.text);
475
331
  }
476
332
  if (up.sessionUpdate === "tool_call") {
477
- startTool(up.toolCallId, up.status);
333
+ state.startTool(up.toolCallId, up.status);
478
334
  const label = up.title || up.kind || "tool";
479
335
  const path = up.locations?.[0]?.path;
480
- lastToolLabel = String(label) + (path ? " — " + path : "");
481
- if (watchingWrites && WRITE_CAPABLE_KINDS.has(up.kind) && writeCapableActivity.length < WRITE_ACTIVITY_CAP) {
482
- const entry = { kind: up.kind, detail: lastToolLabel.slice(0, 300) };
483
- writeCapableActivity.push(entry);
484
- // An execute call names itself — its title is the shell command. An edit call does
485
- // not: the title is a bare "Edit File" and locations is empty, so the only thing
486
- // separating docs/plan.md from src/api.js is the diff frame that follows. Keep the
487
- // id so that frame can fill the path in.
488
- if (up.toolCallId != null) writeActivityById.set(up.toolCallId, entry);
489
- }
490
- try { onProgress?.(("running: " + lastToolLabel).slice(0, 200)); } catch {}
336
+ state.lastToolLabel = String(label) + (path ? " — " + path : "");
337
+ try { onProgress?.(("running: " + state.lastToolLabel).slice(0, 200)); } catch {}
491
338
  }
492
339
  if (up.sessionUpdate === "agent_message_chunk" && up.content?.text) {
493
340
  const text = up.content.text;
494
- if (!sawToolCall || (collectingPostToolResult && activeToolCalls.size === 0)) appendResult(text);
495
- messageProgress.push(text);
341
+ if (state.collectingResult()) state.appendResult(text);
342
+ state.messages.push(text);
496
343
  }
497
344
  if (up.sessionUpdate === "tool_call_update") {
498
- updateToolStatus(up.toolCallId, up.status);
345
+ state.updateToolStatus(up.toolCallId, up.status);
499
346
  for (const c of up.content || []) {
500
347
  if (c.type === "diff" && c.path) {
501
- touched.add(c.path);
502
- const pending = writeActivityById.get(up.toolCallId);
503
- if (pending && !pending.path) {
504
- pending.path = normalizeAgentReportedFiles([c.path], workspace)[0];
505
- }
348
+ state.touched.add(c.path);
506
349
  try { onProgress?.("editing " + c.path); } catch {}
507
350
  }
508
- // cursor-agent has never been observed emitting these; ACP allows an agent to
509
- // stream tool output this way, so treat it like message text rather than drop it.
510
- if (c.type === "content" && typeof c.content?.text === "string") {
511
- if (!sawToolCall || (collectingPostToolResult && activeToolCalls.size === 0)) appendResult(c.content.text);
512
- messageProgress.push(c.content.text);
513
- }
514
351
  }
515
352
  }
516
353
  });
@@ -518,6 +355,7 @@ export async function runDelegate({
518
355
  let sessionId;
519
356
  let resumeError;
520
357
  const unsupportedOptions = [];
358
+ let servedModel;
521
359
  const contextWarnings = [];
522
360
  try {
523
361
  const res = await supervisor.supervise(async () => {
@@ -531,87 +369,57 @@ export async function runDelegate({
531
369
  assertKnownModel(client, model);
532
370
  await client.setModel(sessionId, model);
533
371
  // fast is always sent: a resumed session may already have it on, so false is a real
534
- // instruction. reasoning and context are only sent when the caller named one.
535
- if (await applyConfig(client, sessionId, "fast", fast) && fast) unsupportedOptions.push("fast");
372
+ // instruction. reasoning and context are only sent when the caller named one. Each reply
373
+ // reports the now-current model; keep the last one seen as the served model.
374
+ const fastResult = await applyConfig(client, sessionId, "fast", fast);
375
+ if (fastResult.unsupported && fast) unsupportedOptions.push("fast");
376
+ else servedModel = servedModelFrom(fastResult.res) ?? servedModel;
536
377
  for (const [id, value] of [["reasoning", reasoning], ["context", context]]) {
537
378
  if (value === undefined) continue;
538
- if (await applyConfig(client, sessionId, id, value)) unsupportedOptions.push(id);
379
+ const r = await applyConfig(client, sessionId, id, value);
380
+ if (r.unsupported) unsupportedOptions.push(id);
381
+ else servedModel = servedModelFrom(r.res) ?? servedModel;
539
382
  }
540
383
  await client.setMode(sessionId, mode);
541
- resetResult();
542
- sawToolCall = false;
543
- collectingPostToolResult = false;
544
- activeToolCalls.clear();
545
- thoughtProgress.reset();
546
- messageProgress.reset();
547
- planEntries = [];
548
- planOverview = undefined;
549
- planDetail = undefined;
550
- todos = new Map();
551
- sawTodoFrame = false;
552
- discardedResult = "";
553
- writeCapableActivity = [];
554
- writeActivityById = new Map();
555
- touched.clear();
556
- lastToolLabel = null;
557
- modeChanged = undefined;
558
- sessionTitle = undefined;
384
+ // Everything a session/load replay may have written belongs to the previous turn.
385
+ state.reset();
559
386
  supervisor.promptStarted();
560
387
  startHeartbeat();
561
388
  promptInFlight = true;
562
- return client.prompt(sessionId, [
563
- { type: "text", text: promptText },
564
- ...buildContextBlocks(contextFiles, workspace, client, contextWarnings),
565
- ]);
389
+ try {
390
+ const blocks = await buildContextBlocks(contextFiles, workspace, client, contextWarnings);
391
+ return await client.prompt(sessionId, [{ type: "text", text: promptText }, ...blocks]);
392
+ } finally {
393
+ // The result is assembled across awaits below, so frames that trail the settled turn
394
+ // would otherwise still be folded into it — the same reason the flag exists for the
395
+ // frames session/load replays before it.
396
+ promptInFlight = false;
397
+ }
566
398
  });
567
- thoughtProgress.end();
568
- messageProgress.end();
569
- let result = resultChunks.join("");
570
- if (truncated) result += TRUNCATION_MARKER;
399
+ state.thoughts.end();
400
+ state.messages.end();
401
+ let result = state.text();
571
402
  const finalMessageAvailable = result.length > 0;
572
403
  let resultSource = finalMessageAvailable
573
- ? (sawToolCall ? "post-tool" : "tool-free-stream")
404
+ ? (state.sawToolCall ? "post-tool" : "tool-free-stream")
574
405
  : "none";
575
406
  const protocolWarnings = [];
576
407
  // plan.detail is the model restating — into chat's sibling channel — a plan it also filed via
577
- // create_plan; cursor-agent narrates across the IDE's two surfaces and here they flatten into
578
- // one ACP payload. The detail is never load-bearing: the plan lives in the agent's own session
408
+ // create_plan. The detail is never load-bearing: the plan lives in the agent's own session
579
409
  // (which is what a resume-to-implement reads, not this field) and the orchestrator approves
580
- // from result + plan.entries. So in plan/ask keep the plan in one prose channel — drop the
581
- // detail as a duplicate when result already is a real plan message, fold it into result when
582
- // the message is too terse (or a fallback preamble) to be the plan itself. In agent mode the
583
- // plan was accepted and result is the implementation report, a separate artifact — both stay.
584
- const PLAN_TERSE_FLOOR = 200;
585
- let dropPlanDetail = false;
586
- if (typeof planDetail === "string" && (mode === "plan" || mode === "ask")) {
587
- dropPlanDetail = true;
588
- if (!(finalMessageAvailable && result.length >= PLAN_TERSE_FLOOR)) {
589
- result = planDetail;
590
- resultSource = "plan-detail";
591
- }
592
- }
593
- if (resultSource !== "plan-detail") {
594
- if (!finalMessageAvailable && discardedResult) {
595
- result = discardedResult;
596
- resultSource = "pre-tool-fallback";
597
- protocolWarnings.push(
598
- "the agent ran a tool after its last message and never spoke again, so no final message closed the turn."
599
- + " result carries the last message before that tool call — it may be a preamble rather than the answer."
600
- );
601
- } else if (!finalMessageAvailable) {
602
- protocolWarnings.push("the agent ended the turn without emitting any message; result is empty.");
603
- }
604
- }
605
- // A runaway reply comes back whole and can blow the caller's context (104K chars in one
606
- // test). When the caller sets a ceiling, cut the result to it and say so, so the truncation
607
- // is never mistaken for a complete answer.
608
- if (Number.isFinite(maxResultChars) && maxResultChars > 0 && result.length > maxResultChars) {
609
- const original = result.length;
610
- result = result.slice(0, maxResultChars) + `\n\n[result truncated at ${maxResultChars} chars]`;
410
+ // from result + plan.entries. So in plan/ask drop the detail and let result be the agent's own
411
+ // message verbatim — no bridge-side guess at whether that message "is really the plan". In
412
+ // agent mode the plan was accepted and result is the implementation report — both stay.
413
+ const dropPlanDetail = typeof state.planDetail === "string" && (mode === "plan" || mode === "ask");
414
+ if (!finalMessageAvailable && state.discardedResult) {
415
+ result = state.discardedResult;
416
+ resultSource = "pre-tool-fallback";
611
417
  protocolWarnings.push(
612
- `result was ${original} chars and exceeded maxResultChars ${maxResultChars}; it was truncated.`
613
- + " Raise maxResultChars or narrow the task if you need the full output."
418
+ "the agent ran a tool after its last message and never spoke again, so no final message closed the turn."
419
+ + " result carries the last message before that tool call — it may be a preamble rather than the answer."
614
420
  );
421
+ } else if (!finalMessageAvailable) {
422
+ protocolWarnings.push("the agent ended the turn without emitting any message; result is empty.");
615
423
  }
616
424
  let stopReason;
617
425
  if (res?.stopReason !== undefined) {
@@ -631,60 +439,39 @@ export async function runDelegate({
631
439
  // Like every other collection here, absence means "nothing reported": an empty list on
632
440
  // every read-only turn read as a claim that nothing changed, which this field cannot make
633
441
  // (shell-driven edits leave no diff event).
634
- const filesReported = normalizeAgentReportedFiles([...touched], workspace);
442
+ const filesReported = normalizeAgentReportedFiles([...state.touched], workspace);
635
443
  if (filesReported.length) out.filesReportedByEditTools = filesReported;
636
444
  // resultSource is a caveat, not a fact worth stating on every turn: on the happy path
637
445
  // (post-tool / tool-free-stream) result is simply the answer, so say nothing. Surface it only
638
- // when it warns — pre-tool-fallback, plan-detail, none. finalMessageAvailable is dropped
639
- // outright: it stated the same thing in a second boolean. resumed is emitted only when a
640
- // resume actually took; a fresh session or a failed resume (which carries its own warning)
641
- // leaves it absent.
446
+ // when it warns — pre-tool-fallback, none. finalMessageAvailable is dropped outright: it
447
+ // stated the same thing in a second boolean. resumed is emitted only when a resume actually
448
+ // took; a fresh session or a failed resume (which carries its own warning) leaves it absent.
642
449
  if (resultSource !== "post-tool" && resultSource !== "tool-free-stream") out.resultSource = resultSource;
643
450
  if (!!resumeSessionId && sessionId === resumeSessionId) out.resumed = true;
451
+ // Only when the agent served a different model than asked — e.g. "default" routing to a
452
+ // concrete id, or a cross-model resume. Silence means the request was honored.
453
+ if (servedModel !== undefined && servedModel !== model) out.effectiveModel = servedModel;
644
454
  if (stopReason !== undefined) out.stopReason = stopReason;
645
- // Elicitation almost never fires (the agent tends to ask in prose and end the turn), so an
646
- // always-empty array is steady noise. Report it only when a question actually came through.
647
- if (questionsAsked.length) out.questionsAsked = questionsAsked;
648
455
  // sessionTitle stays out of the result: it is a live label (progress) and a forensic one
649
456
  // (timeout errors), not a fact about the finished turn.
650
457
  if (resumeError) protocolWarnings.push(`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`);
651
458
  for (const id of unsupportedOptions) protocolWarnings.push(`model ${model} has no ${id} option; the requested value was ignored`);
652
459
  protocolWarnings.push(...contextWarnings);
653
- if (planEntries.length > 0 || planOverview !== undefined || planDetail !== undefined) {
460
+ if (state.planEntries.length > 0 || state.planOverview !== undefined || state.planDetail !== undefined) {
654
461
  out.plan = sanitizePlan(protocolWarnings);
655
- // In plan/ask the plan is already carried by result (a real message, or folded in per the
656
- // one-plan contract above), so the detail here is a duplicate — drop it. entries and
657
- // overview are structured and unique, and always stay.
462
+ // In plan/ask result already carries the agent's own plan message, so the detail here is a
463
+ // duplicate — drop it. entries and overview are structured and unique, and always stay.
658
464
  if (dropPlanDetail) delete out.plan.detail;
659
465
  }
660
466
  // Most successful turns emit no todos at all, so an empty list would read as "nothing
661
467
  // done" rather than "not tracked". Report only what the agent actually sent — and of
662
468
  // that, the full list only when it says something todoProgress cannot: which items
663
469
  // remain. On a fully-completed turn the list restates the counts entry by entry.
664
- if (sawTodoFrame) {
470
+ if (state.sawTodoFrame) {
665
471
  const { todos: todoList, todoProgress } = sanitizeTodos(protocolWarnings);
666
472
  out.todoProgress = todoProgress;
667
473
  if (todoProgress.completed < todoProgress.total) out.todos = todoList;
668
474
  }
669
- if (writeCapableActivity.length) {
670
- out.writeCapableActivity = writeCapableActivity;
671
- // "the diff for what changed" overclaims when every entry is a pathless execute — live
672
- // runs drew the same warning for read-only commands (git log, git show, ls -la) as for
673
- // a real write. Hedge when nothing reported a path.
674
- const anyPath = writeCapableActivity.some((a) => a.path);
675
- protocolWarnings.push(
676
- `mode ${mode} asked the agent not to change anything, but it ran ${writeCapableActivity.length}`
677
- + ` write-capable tool call${writeCapableActivity.length === 1 ? "" : "s"} — see writeCapableActivity`
678
- + " for what ran"
679
- + (anyPath
680
- ? ", and the diff for what changed."
681
- : "; none reported touching a file, so this may be read-only activity — check the git diff to confirm nothing changed.")
682
- );
683
- }
684
- if (modeChanged) {
685
- out.modeChanged = modeChanged;
686
- protocolWarnings.push(`agent switched mode from ${modeChanged.from} to ${modeChanged.to} mid-session`);
687
- }
688
475
  if (protocolWarnings.length) out.protocolWarnings = protocolWarnings;
689
476
  return out;
690
477
  } catch (err) {
@@ -702,15 +489,15 @@ export async function runDelegate({
702
489
  const isStall = isTimeout || err?.reason === "handshake-timeout";
703
490
  if (isStall || err?.reason === "aborted" || err?.reason === "agent-exit") {
704
491
  const age = fmtDuration(supervisor.msSinceActivity());
705
- err.message += `\n\nLast ACP frame ${age} ago${lastToolLabel ? `; last tool call: ${lastToolLabel}` : ""}.`;
706
- if (sessionTitle) err.message += ` The agent titled this turn ${JSON.stringify(sessionTitle)}.`;
707
- if (sawTodoFrame) {
492
+ err.message += `\n\nLast ACP frame ${age} ago${state.lastToolLabel ? `; last tool call: ${state.lastToolLabel}` : ""}.`;
493
+ if (state.sessionTitle) err.message += ` The agent titled this turn ${JSON.stringify(state.sessionTitle)}.`;
494
+ if (state.sawTodoFrame) {
708
495
  const { todoProgress } = sanitizeTodos([]);
709
- const current = todoLabel();
496
+ const current = state.todoLabel();
710
497
  err.message += ` ${todoProgress.completed} of ${todoProgress.total} todos completed`
711
498
  + `${current ? `; ${current}` : ""}.`;
712
499
  }
713
- const files = normalizeAgentReportedFiles([...touched], workspace);
500
+ const files = normalizeAgentReportedFiles([...state.touched], workspace);
714
501
  if (files.length) err.message += ` Files reported edited: ${files.join(", ")}.`;
715
502
  // Without this the resume hint below reads as "carry on from where you were", when the
716
503
  // requested session was never loaded and this turn started from nothing.