cursor-delegate-mcp 1.13.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/jsonrpc.js CHANGED
@@ -1,8 +1,25 @@
1
1
  import readline from "node:readline";
2
2
 
3
3
  const FRAME_CAP = 2048;
4
+ const DEFAULT_LOG_SIZE = 2000;
5
+
6
+ function readLogSize(raw) {
7
+ if (raw === undefined) return DEFAULT_LOG_SIZE;
8
+ const n = Number(raw);
9
+ if (!Number.isFinite(n) || n < 0) return DEFAULT_LOG_SIZE;
10
+ return Math.floor(n);
11
+ }
4
12
 
5
13
  export class JsonRpcPeer {
14
+ /**
15
+ * @param {import("node:stream").Readable} input
16
+ * @param {import("node:stream").Writable} output
17
+ * @param {{
18
+ * onNotification?: (method: string, params: any) => void,
19
+ * onRequest?: (id: any, method: string, params: any) => void,
20
+ * onActivity?: () => void,
21
+ * }} handlers
22
+ */
6
23
  constructor(input, output, { onNotification, onRequest, onActivity } = {}) {
7
24
  this.output = output;
8
25
  this.onNotification = onNotification || (() => {});
@@ -10,26 +27,34 @@ export class JsonRpcPeer {
10
27
  this.onActivity = onActivity || (() => {});
11
28
  this.nextId = 1;
12
29
  this.pending = new Map();
13
- const rawSize = process.env.ACP_LOG_SIZE !== undefined ? Number(process.env.ACP_LOG_SIZE) : 2000;
14
- this._logSize = rawSize > 0 && !Number.isNaN(rawSize) ? rawSize : 0;
30
+ // 0 disables recording and is documented; anything unparseable is a typo, and silently
31
+ // disabling the transcript on a typo is the opposite of what the setter wanted.
32
+ this._logSize = readLogSize(process.env.ACP_LOG_SIZE);
15
33
  this._log = [];
16
34
  this.rl = readline.createInterface({ input });
17
35
  this.rl.on("line", (line) => this._onLine(line));
18
36
  }
19
37
 
38
+ // Trimming to the cap on every frame meant shifting a 2000-entry array per frame, which on a
39
+ // chatty turn cost more than parsing the frames. Let the array overshoot by a quarter and trim
40
+ // in one batch; readers below take the last _logSize, so what the log reports is unchanged.
20
41
  _record(dir, line) {
21
42
  if (this._logSize <= 0) return;
22
43
  const truncated = line.length > FRAME_CAP ? line.slice(0, FRAME_CAP) : line;
23
44
  this._log.push({ t: Date.now(), dir, line: truncated });
24
- if (this._log.length > this._logSize) {
25
- this._log.splice(0, this._log.length - this._logSize);
45
+ if (this._log.length > this._logSize + (this._logSize >> 2)) {
46
+ this._log = this._log.slice(-this._logSize);
26
47
  }
27
48
  }
28
49
 
29
- getLog() { return [...this._log]; }
50
+ _entries() {
51
+ return this._log.length > this._logSize ? this._log.slice(-this._logSize) : this._log;
52
+ }
53
+
54
+ getLog() { return [...this._entries()]; }
30
55
 
31
56
  formatLog(n) {
32
- const entries = n !== undefined ? this._log.slice(-n) : this._log;
57
+ const entries = n !== undefined ? this._entries().slice(-n) : this._entries();
33
58
  return entries.map((e) => `${new Date(e.t).toISOString()} ${e.dir} ${e.line}`).join("\n");
34
59
  }
35
60
 
@@ -41,12 +66,16 @@ export class JsonRpcPeer {
41
66
  try { msg = JSON.parse(line); } catch { return; }
42
67
  const hasId = msg.id !== undefined && msg.id !== null;
43
68
  if (hasId && (msg.result !== undefined || msg.error !== undefined)) {
44
- const p = this.pending.get(msg.id);
69
+ // Keyed by string: a peer that echoes "1" for the id 1 is still answering that request,
70
+ // and matching by identity left it pending until a timeout fired an hour later.
71
+ const key = String(msg.id);
72
+ const p = this.pending.get(key);
45
73
  if (p) {
46
- this.pending.delete(msg.id);
74
+ this.pending.delete(key);
47
75
  // cursor-agent puts the actual reason in error.data.message; error.message alone
48
76
  // is a bare "Invalid params".
49
77
  if (msg.error) {
78
+ /** @type {import("./errors.js").DelegateError} */
50
79
  const err = new Error([msg.error.message || "rpc error", msg.error.data?.message].filter(Boolean).join(": "));
51
80
  err.code = msg.error.code;
52
81
  p.reject(err);
@@ -69,7 +98,7 @@ export class JsonRpcPeer {
69
98
  request(method, params) {
70
99
  const id = this.nextId++;
71
100
  return new Promise((resolve, reject) => {
72
- this.pending.set(id, { resolve, reject });
101
+ this.pending.set(String(id), { resolve, reject });
73
102
  this._write({ jsonrpc: "2.0", id, method, params });
74
103
  });
75
104
  }
package/src/proc.js CHANGED
@@ -9,9 +9,9 @@ export function isChildAlive(child) {
9
9
  // taskkill /T takes the whole tree so the agent itself dies too.
10
10
  export async function treeKill(pid) {
11
11
  if (process.platform === "win32") {
12
- await new Promise((resolve) => {
12
+ await /** @type {Promise<void>} */ (new Promise((resolve) => {
13
13
  execFile("taskkill", ["/PID", String(pid), "/T", "/F"], () => resolve());
14
- });
14
+ }));
15
15
  return;
16
16
  }
17
17
  try { process.kill(pid, "SIGKILL"); } catch {}
@@ -1,5 +1,15 @@
1
1
  const ACK_METHODS = new Set(["cursor/task", "cursor/generate_image"]);
2
2
 
3
+ /**
4
+ * @param {{
5
+ * respond: (id: any, result: any) => void,
6
+ * respondError: (id: any, code: number, message: string) => void,
7
+ * onCreatePlan?: (body: any) => void,
8
+ * onTodos?: (body: any) => void,
9
+ * mode?: string,
10
+ * log?: (entry: any) => void,
11
+ * }} deps
12
+ */
3
13
  export function createRequestRouter({ respond, respondError, onCreatePlan, onTodos, mode = "agent", log = () => {} }) {
4
14
  return async function handle(id, method, params) {
5
15
  try {
@@ -9,7 +19,11 @@ export function createRequestRouter({ respond, respondError, onCreatePlan, onTod
9
19
  opts.find((o) => o.kind === "allow_always") ||
10
20
  opts.find((o) => o.kind === "allow_once") ||
11
21
  opts[0];
12
- return respond(id, { outcome: { outcome: "selected", optionId: pick?.optionId } });
22
+ // Selecting nothing is not a selection: an options-less request answered with
23
+ // optionId undefined is a malformed ACP response. Say cancelled and let the agent
24
+ // decide what to do about it.
25
+ if (!pick?.optionId) return respond(id, { outcome: { outcome: "cancelled" } });
26
+ return respond(id, { outcome: { outcome: "selected", optionId: pick.optionId } });
13
27
  }
14
28
  if (method === "cursor/create_plan") {
15
29
  onCreatePlan?.({
package/src/server.js CHANGED
@@ -8,6 +8,7 @@ import { z } from "zod";
8
8
  import { DEFAULT_MODEL, runDelegate as runDelegateDefault } from "./delegate.js";
9
9
  import { runDoctor as runDoctorDefault } from "./doctor.js";
10
10
  import { VERSION } from "./version.js";
11
+ import { PLAN_PRIORITIES, PLAN_STATUSES, TODO_STATUSES } from "./acp-enums.js";
11
12
 
12
13
  const nodeMajor = Number(process.versions.node.split(".")[0]);
13
14
  if (nodeMajor < 22) {
@@ -15,7 +16,22 @@ if (nodeMajor < 22) {
15
16
  process.exit(1);
16
17
  }
17
18
 
19
+ // sessionId -> the set of delegations currently running on it. A set, not a single handle,
20
+ // because a resume can race the turn it resumes: both are live, both are cancellable, and
21
+ // keying one handle per id let whichever finished first deregister the other — after which
22
+ // cancel reported a running session as already ended.
18
23
  const inFlight = new Map();
24
+ function registerInFlight(map, sessionId, handle) {
25
+ const handles = map.get(sessionId);
26
+ if (handles) handles.add(handle);
27
+ else map.set(sessionId, new Set([handle]));
28
+ }
29
+ function unregisterInFlight(map, sessionId, handle) {
30
+ const handles = map.get(sessionId);
31
+ if (!handles) return;
32
+ handles.delete(handle);
33
+ if (handles.size === 0) map.delete(sessionId);
34
+ }
19
35
  // Session ids seen this process, kept after the turn ends so cancel can tell a finished
20
36
  // session (resumable, only the turn is over) from an id that never existed. Bounded so a
21
37
  // long-lived server does not grow without limit.
@@ -34,11 +50,15 @@ export const SERVER_INSTRUCTIONS = `Delegate coding work to Cursor through the d
34
50
 
35
51
  const planEntrySchema = z.object({
36
52
  content: z.string(),
37
- priority: z.enum(["high", "medium", "low"]).optional(),
38
- status: z.enum(["pending", "in_progress", "completed"]).optional(),
53
+ priority: z.enum(PLAN_PRIORITIES).optional(),
54
+ status: z.enum(PLAN_STATUSES).optional(),
39
55
  }).passthrough();
40
56
 
41
- const delegateOutputSchema = z.object({
57
+ // Exported as a plain shape so tests can build a .strict() copy of it. Production stays
58
+ // passthrough — a field the agent adds must not fail a finished call — but that same
59
+ // tolerance means a field added in delegate.js and forgotten here would never be advertised
60
+ // to hosts, and nothing would complain. The strict copy is what complains.
61
+ export const delegateOutputShape = {
42
62
  result: z.string(),
43
63
  resultSource: z.enum(["pre-tool-fallback", "none"]).optional().describe(
44
64
  "Present only as a caveat on result; absent on the happy path, where result is simply the agent's answer. pre-tool-fallback: no final message closed the turn and result is the last message before the agent's final tool call — read protocolWarnings before trusting it. none: the turn produced no message and result is empty."
@@ -70,7 +90,7 @@ const delegateOutputSchema = z.object({
70
90
  todos: z.array(z.object({
71
91
  id: z.string(),
72
92
  content: z.string(),
73
- status: z.enum(["pending", "in_progress", "completed"]).optional(),
93
+ status: z.enum(TODO_STATUSES).optional(),
74
94
  })).optional().describe(
75
95
  "Todo items the agent left unfinished, present only when todoProgress shows completed < total — read it to see what remains before resuming. Absent both when the agent tracked no todos (common on short tasks) and when everything tracked was completed; todoProgress tells those apart."
76
96
  ),
@@ -80,16 +100,47 @@ const delegateOutputSchema = z.object({
80
100
  inProgress: z.number(),
81
101
  pending: z.number(),
82
102
  }).optional(),
83
- }).passthrough();
103
+ };
104
+
105
+ const delegateOutputSchema = z.object(delegateOutputShape).passthrough();
84
106
 
85
- const doctorOutputSchema = z.object({
107
+ // What doctor reports about the launcher. Only `found` was advertised before, so `command`,
108
+ // `version`, `error` and the whole deep handshake reached hosts undeclared — the same drift
109
+ // delegateOutputShape exists to prevent, one level further down.
110
+ //
111
+ // Fields this bridge computes are typed; fields relayed verbatim from the agent are left
112
+ // unknown on purpose. The SDK validates structuredContent against this schema and throws when
113
+ // it does not fit, and doctor is what you run when the agent is already misbehaving: a schema
114
+ // tight enough to reject a weird protocolVersion would turn the diagnostic into a crash.
115
+ export const doctorAgentShape = {
116
+ found: z.boolean().describe("Whether the launcher command could be spawned at all."),
117
+ command: z.string().describe("The resolved launcher command line, with ACP_AGENT_COMMAND/ACP_AGENT_ARGS applied."),
118
+ version: z.string().nullable().describe(
119
+ "The launcher's --version output, or null when it could not be read. found:false means it is not installed; found:true with a null version means it exists but did not answer — error says why."
120
+ ),
121
+ error: z.string().optional().describe("Why version is null on a launcher that does exist, e.g. the probe timed out."),
122
+ handshake: z.object({
123
+ ok: z.boolean(),
124
+ error: z.string().optional().describe("Present when ok is false: what the handshake failed on, e.g. not logged in, or a timeout."),
125
+ protocolVersion: z.unknown().optional().describe("As reported by the agent; null when it reported none."),
126
+ agentCapabilities: z.unknown().optional(),
127
+ models: z.array(z.unknown()).optional().describe("Model ids the agent offers for a new session."),
128
+ currentModel: z.unknown().optional(),
129
+ modes: z.array(z.unknown()).optional().describe("Session mode ids the agent offers."),
130
+ }).passthrough().optional().describe("Present only when deep is true. Everything past ok and error is absent when ok is false."),
131
+ };
132
+
133
+ // Exported as a shape for the same reason as delegateOutputShape, and with agent split out
134
+ // because a top-level .strict() does not look inside a nested object — which is exactly where
135
+ // this schema drifted.
136
+ export const doctorOutputShape = {
86
137
  plugin: z.object({ version: z.string() }).passthrough(),
87
138
  client: z.object({
88
139
  name: z.string().nullable(),
89
140
  version: z.string().nullable(),
90
141
  capabilities: z.record(z.unknown()),
91
142
  }).passthrough(),
92
- agent: z.object({ found: z.boolean() }).passthrough(),
143
+ agent: z.object(doctorAgentShape).passthrough(),
93
144
  runtime: z.object({
94
145
  node: z.string(),
95
146
  platform: z.string(),
@@ -98,7 +149,9 @@ const doctorOutputSchema = z.object({
98
149
  transport: z.literal("stdio"),
99
150
  }),
100
151
  env: z.record(z.unknown()),
101
- }).passthrough();
152
+ };
153
+
154
+ const doctorOutputSchema = z.object(doctorOutputShape).passthrough();
102
155
 
103
156
  export const delegateInputSchema = z.object({
104
157
  spec: z.string().trim().min(1, "spec must not be blank").describe("Inline task brief (default): goal, scope, decisions already made (constraints and fixed choices — quote the user's exact values verbatim), acceptance criteria. Point at files to read or mimic rather than pasting code. Optional file path if the user wants a persisted spec."),
@@ -114,10 +167,20 @@ export const delegateInputSchema = z.object({
114
167
  contextFiles: z.array(z.string()).optional().describe("Paths to attach instead of pasting file contents into spec. Text files are passed as references the agent may open; images (png, jpg, gif, webp, under 5MB) are sent inline. Relative paths resolve against workspace, and paths outside it are allowed — attach only files the agent should read. Anything skipped is reported in protocolWarnings, never fatal."),
115
168
  });
116
169
 
117
- export async function runDelegateTool({ args, extra, server, runDelegate, inFlight, seenSessions = new Set() }) {
170
+ /**
171
+ * @param {{
172
+ * args: any, extra?: any,
173
+ * runDelegate: (opts: any) => Promise<any>,
174
+ * inFlight: Map<string, Set<any>>,
175
+ * seenSessions?: Set<string>,
176
+ * }} deps
177
+ * @returns {Promise<import("@modelcontextprotocol/sdk/types.js").CallToolResult>}
178
+ */
179
+ export async function runDelegateTool({ args, extra, runDelegate, inFlight, seenSessions = new Set() }) {
118
180
  const { spec, mode, resumeSessionId, workspace, model, fast, reasoning, context, contextFiles } = args;
119
181
 
120
182
  const progressToken = extra?._meta?.progressToken;
183
+ /** @type {(message: string) => void} */
121
184
  let onProgress = () => {};
122
185
  if (progressToken != null) {
123
186
  let progress = 0;
@@ -149,7 +212,7 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
149
212
  onSessionReady: (sessionId, client) => {
150
213
  capturedSessionId = sessionId;
151
214
  handle = { client, cancelRequested: false };
152
- inFlight.set(sessionId, handle);
215
+ registerInFlight(inFlight, sessionId, handle);
153
216
  rememberSession(seenSessions, sessionId);
154
217
  // Emit the id the moment the session opens, before the turn finishes, so a host that
155
218
  // can call tools concurrently has something to pass to cancel mid-run — otherwise the
@@ -171,10 +234,19 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
171
234
  isError: true,
172
235
  };
173
236
  } finally {
174
- if (capturedSessionId) inFlight.delete(capturedSessionId);
237
+ // Drops only this delegation's own handle; the id stays registered while another turn
238
+ // is still running on it.
239
+ if (capturedSessionId) unregisterInFlight(inFlight, capturedSessionId, handle);
175
240
  }
176
241
  }
177
242
 
243
+ /**
244
+ * @param {{
245
+ * runDelegate?: (opts: any) => Promise<any>,
246
+ * runDoctor?: (opts: any) => Promise<any>,
247
+ * forceGraceMs?: number,
248
+ * }} [opts]
249
+ */
178
250
  export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000 } = {}) {
179
251
  const runDelegate = runDelegateInjected || runDelegateDefault;
180
252
  const runDoctor = runDoctorInjected || runDoctorDefault;
@@ -198,7 +270,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
198
270
  openWorldHint: true,
199
271
  },
200
272
  },
201
- async (args, extra) => runDelegateTool({ args, extra, server, runDelegate, inFlight, seenSessions })
273
+ async (args, extra) => runDelegateTool({ args, extra, runDelegate, inFlight, seenSessions })
202
274
  );
203
275
 
204
276
  server.registerTool(
@@ -220,8 +292,8 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
220
292
  },
221
293
  },
222
294
  async ({ sessionId, force }) => {
223
- const handle = inFlight.get(sessionId);
224
- if (!handle) {
295
+ const handles = inFlight.get(sessionId);
296
+ if (!handles || handles.size === 0) {
225
297
  // A finished session and a garbage id used to look identical (both not-found), which
226
298
  // read as "bad id" for a session that in fact ran and is still resumable. Split them.
227
299
  const known = seenSessions.has(sessionId);
@@ -232,26 +304,29 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
232
304
  structuredContent: { status: known ? "not-running" : "not-found", sessionId },
233
305
  };
234
306
  }
235
- handle.cancelRequested = true;
236
- await handle.client.cancel(sessionId).catch(() => {});
307
+ // Cancel every turn running on the id: the caller named a session, not one of the
308
+ // turns that happen to share it.
309
+ for (const handle of handles) handle.cancelRequested = true;
310
+ await Promise.all([...handles].map((handle) => handle.client.cancel(sessionId).catch(() => {})));
237
311
  if (!force) {
238
- // The handle stays registered: session/cancel is best-effort, so the turn may still
239
- // be running. Dropping it here made the natural escalation — cancel, wait, cancel
240
- // with force — report not-found while the agent was alive. The delegation's own
241
- // finally removes the entry when the turn actually settles.
312
+ // The handles stay registered: session/cancel is best-effort, so the turn may still
313
+ // be running. Dropping them here made the natural escalation — cancel, wait, cancel
314
+ // with force — report not-found while the agent was alive. Each delegation's own
315
+ // finally removes its handle when the turn actually settles.
242
316
  return {
243
317
  content: [{ type: "text", text: `cancelled ${sessionId}` }],
244
318
  structuredContent: { status: "cancelled", sessionId },
245
319
  };
246
320
  }
247
321
  await new Promise((r) => setTimeout(r, forceGraceMs));
248
- if (!inFlight.has(sessionId)) {
322
+ const stillRunning = inFlight.get(sessionId);
323
+ if (!stillRunning || stillRunning.size === 0) {
249
324
  return {
250
325
  content: [{ type: "text", text: `cancelled ${sessionId}` }],
251
326
  structuredContent: { status: "cancelled", sessionId },
252
327
  };
253
328
  }
254
- handle.client.stop();
329
+ for (const handle of stillRunning) handle.client.stop();
255
330
  inFlight.delete(sessionId);
256
331
  return {
257
332
  content: [{ type: "text", text: `killed ${sessionId}` }],
@@ -1,8 +1,4 @@
1
- function makeError(reason, message) {
2
- const err = new Error(message);
3
- err.reason = reason;
4
- return err;
5
- }
1
+ import { makeError } from "./errors.js";
6
2
 
7
3
  export class SessionSupervisor {
8
4
  constructor(client, {
package/src/spawn.js CHANGED
@@ -9,6 +9,11 @@ export function splitArgs(raw) {
9
9
  return args;
10
10
  }
11
11
 
12
+ // shell:true on win32 is what lets a .cmd/.ps1 launcher resolve at all, and it means the
13
+ // command and args are parsed by cmd.exe. Safe only because both come from the environment,
14
+ // which is already as trusted as this process: anything that can set them can run code here
15
+ // anyway. Routing host- or caller-supplied values into either variable would turn this into a
16
+ // command-injection path, so don't.
12
17
  export function resolveAcpSpawn() {
13
18
  const command = process.env.ACP_AGENT_COMMAND || "cursor-agent";
14
19
  const args = process.env.ACP_AGENT_ARGS
@@ -0,0 +1,193 @@
1
+ // Everything that describes the turn in progress, in one object because it has to be wiped as
2
+ // one: session/load replays the previous turn as ordinary update frames, so anything left
3
+ // behind leaks into the next result. This used to be a dozen loose variables cleared by a
4
+ // hand-written block before each prompt, where forgetting a line was a silent stale-data bug
5
+ // on resume — and the list grew every time a field was added. Fields are declared in exactly
6
+ // one place now, freshFields(), which is also what reset() applies.
7
+
8
+ const MAX_OUTPUT = 10 * 1024 * 1024;
9
+ const TRUNCATION_MARKER = "\n\n[output truncated at 10MB]";
10
+
11
+ // Cutting a UTF-16 string at an arbitrary index can split a surrogate pair and leave a lone
12
+ // half-character — ill-formed Unicode that strict JSON consumers reject or mangle. Step back
13
+ // one unit when the boundary would land inside a pair.
14
+ function cutAtCodePoint(s, n) {
15
+ if (n >= s.length) return s;
16
+ const cu = s.charCodeAt(n - 1);
17
+ return s.slice(0, cu >= 0xd800 && cu <= 0xdbff ? n - 1 : n);
18
+ }
19
+
20
+ const isTerminalToolStatus = (status) =>
21
+ status === "completed" || status === "failed" || status === "cancelled";
22
+
23
+ // Each stream reports its newest complete sentence, at most one per throttle window.
24
+ // Capital-letter boundary: cursor-agent thoughts arrive as sentences with no separator.
25
+ const SENTENCE_END = /[.!?](?=\s|[A-Z])|\n/;
26
+ const MARKDOWN_LINE = /^(?:[|#>`~*_=+-]|\d+[.)]\s)/;
27
+ /**
28
+ * @param {string} prefix
29
+ * @param {((message: string) => void) | undefined} onProgress
30
+ * @param {number} throttleMs
31
+ */
32
+ function progressStream(prefix, onProgress, throttleMs) {
33
+ let buf = "", pending = null, lastEmit = 0;
34
+ const flush = (force) => {
35
+ if (pending === null || (!force && Date.now() - lastEmit < throttleMs)) return;
36
+ lastEmit = Date.now();
37
+ try { onProgress?.(prefix + pending); } catch {}
38
+ pending = null;
39
+ };
40
+ const take = (s) => {
41
+ const line = s.replace(/\s+/g, " ").trim().slice(0, 200);
42
+ if (line.length > 3 && !MARKDOWN_LINE.test(line)) pending = line;
43
+ flush(false);
44
+ };
45
+ return {
46
+ push(text) {
47
+ buf += text;
48
+ for (let m; (m = SENTENCE_END.exec(buf)); buf = buf.slice(m.index + 1)) {
49
+ take(buf.slice(0, m.index + 1));
50
+ }
51
+ if (buf.length > 300) { take(buf); buf = ""; }
52
+ },
53
+ end() { take(buf); buf = ""; flush(true); },
54
+ reset() { buf = ""; pending = null; },
55
+ };
56
+ }
57
+
58
+ // The single declaration of what a turn accumulates. Anything added here is reset for free.
59
+ function freshFields() {
60
+ return {
61
+ resultChunks: [],
62
+ resultLength: 0,
63
+ truncated: false,
64
+ // Text superseded by a later tool call is normally a preamble ("Inspecting the
65
+ // implementation.") and returning it would be inventing a summary. But the rule cannot
66
+ // tell a preamble from the whole answer: an agent that replies and then runs one more
67
+ // command has its entire reply discarded, and the caller gets "" with stopReason end_turn
68
+ // and no error. So keep the last discarded segment and hand it back only when nothing
69
+ // survived — labelled, never blended with a real final message.
70
+ discardedResult: "",
71
+ sawToolCall: false,
72
+ collectingPostToolResult: false,
73
+ activeToolCalls: new Set(),
74
+ planEntries: [],
75
+ planOverview: undefined,
76
+ planDetail: undefined,
77
+ // merge:false replaces the list, merge:true upserts by id. Entries always arrive complete,
78
+ // so a keyed set is enough — no field-level merging.
79
+ todos: new Map(),
80
+ sawTodoFrame: false,
81
+ touched: new Set(),
82
+ lastToolLabel: null,
83
+ sessionTitle: undefined,
84
+ };
85
+ }
86
+
87
+ /**
88
+ * @param {{ onProgress?: (message: string) => void, progressThrottleMs?: number }} [opts]
89
+ */
90
+ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
91
+ const state = {
92
+ ...freshFields(),
93
+ thoughts: progressStream("thinking: ", onProgress, progressThrottleMs),
94
+ messages: progressStream("Cursor: ", onProgress, progressThrottleMs),
95
+
96
+ reset() {
97
+ Object.assign(state, freshFields());
98
+ state.thoughts.reset();
99
+ state.messages.reset();
100
+ },
101
+
102
+ // The result text as it stands, truncation marker included.
103
+ text() {
104
+ const joined = state.resultChunks.join("");
105
+ return state.truncated ? joined + TRUNCATION_MARKER : joined;
106
+ },
107
+
108
+ resetResult() {
109
+ if (state.resultLength > 0) state.discardedResult = state.resultChunks.join("");
110
+ state.resultChunks.length = 0;
111
+ state.resultLength = 0;
112
+ state.truncated = false;
113
+ },
114
+
115
+ appendResult(text) {
116
+ if (state.truncated) return;
117
+ const remaining = MAX_OUTPUT - state.resultLength;
118
+ if (text.length <= remaining) {
119
+ state.resultChunks.push(text);
120
+ state.resultLength += text.length;
121
+ } else if (remaining > 0) {
122
+ const cut = cutAtCodePoint(text, remaining);
123
+ state.resultChunks.push(cut);
124
+ state.resultLength += cut.length;
125
+ state.truncated = true;
126
+ } else {
127
+ state.truncated = true;
128
+ }
129
+ },
130
+
131
+ startTool(toolCallId, status) {
132
+ state.sawToolCall = true;
133
+ state.collectingPostToolResult = false;
134
+ state.resetResult();
135
+ if (toolCallId != null && !isTerminalToolStatus(status)) state.activeToolCalls.add(toolCallId);
136
+ if (isTerminalToolStatus(status) && state.activeToolCalls.size === 0) state.collectingPostToolResult = true;
137
+ },
138
+
139
+ updateToolStatus(toolCallId, status) {
140
+ if (!status) return;
141
+ if (!state.sawToolCall) {
142
+ state.sawToolCall = true;
143
+ state.resetResult();
144
+ }
145
+ if (isTerminalToolStatus(status)) {
146
+ if (toolCallId != null) state.activeToolCalls.delete(toolCallId);
147
+ if (state.activeToolCalls.size === 0 && !state.collectingPostToolResult) {
148
+ // Discard any message text emitted while tools were still running.
149
+ // A duplicate or late terminal update must not wipe an already-collected final message.
150
+ state.resetResult();
151
+ state.collectingPostToolResult = true;
152
+ }
153
+ } else {
154
+ state.collectingPostToolResult = false;
155
+ state.resetResult();
156
+ if (toolCallId != null) state.activeToolCalls.add(toolCallId);
157
+ }
158
+ },
159
+
160
+ // True while a message chunk still belongs in the result: before any tool ran, or after
161
+ // the last one finished.
162
+ collectingResult() {
163
+ return !state.sawToolCall || (state.collectingPostToolResult && state.activeToolCalls.size === 0);
164
+ },
165
+
166
+ todoLabel() {
167
+ const entries = [...state.todos.values()].filter((t) => typeof t?.content === "string");
168
+ if (!entries.length) return null;
169
+ const i = entries.findIndex((t) => t.status === "in_progress");
170
+ if (i !== -1) return `todo ${i + 1}/${entries.length}: ${entries[i].content}`;
171
+ const done = entries.filter((t) => t.status === "completed").length;
172
+ return `todos ${done}/${entries.length} complete`;
173
+ },
174
+
175
+ recordTodos({ todos: incoming, merge }) {
176
+ if (!Array.isArray(incoming)) return;
177
+ state.sawTodoFrame = true;
178
+ if (merge === false) state.todos = new Map();
179
+ for (const t of incoming) {
180
+ if (t?.id === undefined || t?.id === null) continue;
181
+ state.todos.set(String(t.id), t);
182
+ }
183
+ const label = state.todoLabel();
184
+ if (label) { try { onProgress?.(label.slice(0, 200)); } catch {} }
185
+ },
186
+
187
+ recordCreatePlan(body) {
188
+ if (body?.overview !== undefined) state.planOverview = body.overview;
189
+ if (body?.plan !== undefined) state.planDetail = body.plan;
190
+ },
191
+ };
192
+ return state;
193
+ }