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/package.json +7 -2
- package/src/acp-client.js +44 -9
- package/src/acp-enums.js +15 -0
- package/src/delegate.js +84 -229
- package/src/doctor.js +34 -2
- package/src/errors.js +20 -0
- package/src/jsonrpc.js +38 -9
- package/src/proc.js +2 -2
- package/src/request-router.js +15 -1
- package/src/server.js +97 -22
- package/src/session-supervisor.js +1 -5
- package/src/spawn.js +5 -0
- package/src/turn-state.js +193 -0
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 {
|
|
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
|
|
29
|
+
return Number.isFinite(n) && n > 0 ? n : fallback;
|
|
19
30
|
}
|
|
20
31
|
|
|
21
32
|
function fmtDuration(ms) {
|
|
@@ -23,15 +34,6 @@ function fmtDuration(ms) {
|
|
|
23
34
|
return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s`;
|
|
24
35
|
}
|
|
25
36
|
|
|
26
|
-
// Cutting a UTF-16 string at an arbitrary index can split a surrogate pair and leave a lone
|
|
27
|
-
// half-character — ill-formed Unicode that strict JSON consumers reject or mangle. Step back
|
|
28
|
-
// one unit when the boundary would land inside a pair.
|
|
29
|
-
function cutAtCodePoint(s, n) {
|
|
30
|
-
if (n >= s.length) return s;
|
|
31
|
-
const cu = s.charCodeAt(n - 1);
|
|
32
|
-
return s.slice(0, cu >= 0xd800 && cu <= 0xdbff ? n - 1 : n);
|
|
33
|
-
}
|
|
34
|
-
|
|
35
37
|
// Two different questions, and conflating them is what made a typo'd brief cost a live turn.
|
|
36
38
|
// "Could this be a path?" is deliberately loose — a one-line brief ending in .md is worth a
|
|
37
39
|
// stat. "Was a path clearly intended?" has to be strict, because an ordinary inline spec
|
|
@@ -43,14 +45,12 @@ function looksLikeSpecPath(spec) {
|
|
|
43
45
|
}
|
|
44
46
|
const isBareSpecPath = (spec) => !/\s/.test(spec.trim());
|
|
45
47
|
|
|
46
|
-
function resolveSpec(spec) {
|
|
48
|
+
async function resolveSpec(spec) {
|
|
47
49
|
if (typeof spec !== "string") return spec;
|
|
48
50
|
// A blank spec spins up a live session that only replies "No prompt content provided" —
|
|
49
51
|
// a billed turn for nothing. Reject it here, before the spawn, like the other bad specs.
|
|
50
52
|
if (spec.trim() === "") {
|
|
51
|
-
|
|
52
|
-
err.reason = "invalid-spec";
|
|
53
|
-
throw err;
|
|
53
|
+
throw makeError("invalid-spec", "spec is empty. Provide a task brief inline, or a path to one.");
|
|
54
54
|
}
|
|
55
55
|
if (!looksLikeSpecPath(spec)) return spec;
|
|
56
56
|
let stat;
|
|
@@ -60,15 +60,11 @@ function resolveSpec(spec) {
|
|
|
60
60
|
// Only a bare path was unambiguously meant as one. Anything else is prose that happens
|
|
61
61
|
// to name a file, and prose is the common case.
|
|
62
62
|
if (!isBareSpecPath(spec)) return spec;
|
|
63
|
-
|
|
64
|
-
err.reason = "invalid-spec";
|
|
65
|
-
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.`);
|
|
66
64
|
}
|
|
67
|
-
if (stat.isFile()) return
|
|
65
|
+
if (stat.isFile()) return readFile(spec, "utf8");
|
|
68
66
|
if (isBareSpecPath(spec)) {
|
|
69
|
-
|
|
70
|
-
err.reason = "invalid-spec";
|
|
71
|
-
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.`);
|
|
72
68
|
}
|
|
73
69
|
return spec;
|
|
74
70
|
}
|
|
@@ -82,14 +78,10 @@ function assertWorkspace(workspace) {
|
|
|
82
78
|
try {
|
|
83
79
|
stat = statSync(workspace);
|
|
84
80
|
} catch {
|
|
85
|
-
|
|
86
|
-
err.reason = "invalid-workspace";
|
|
87
|
-
throw err;
|
|
81
|
+
throw makeError("invalid-workspace", `workspace ${workspace} does not exist. Create it first, or point at an existing directory.`);
|
|
88
82
|
}
|
|
89
83
|
if (!stat.isDirectory()) {
|
|
90
|
-
|
|
91
|
-
err.reason = "invalid-workspace";
|
|
92
|
-
throw err;
|
|
84
|
+
throw makeError("invalid-workspace", `workspace ${workspace} is not a directory.`);
|
|
93
85
|
}
|
|
94
86
|
}
|
|
95
87
|
|
|
@@ -108,7 +100,7 @@ const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
|
|
|
108
100
|
// not support without any error (embeddedContext:false raises nothing), so an ungated
|
|
109
101
|
// image would silently vanish;
|
|
110
102
|
// - report anything skipped, since a dropped attachment is otherwise invisible.
|
|
111
|
-
function buildContextBlocks(contextFiles, workspace, client, warnings) {
|
|
103
|
+
async function buildContextBlocks(contextFiles, workspace, client, warnings) {
|
|
112
104
|
const blocks = [];
|
|
113
105
|
// A glob plus an explicit path (or the same file named a few ways) resolves to one file;
|
|
114
106
|
// sending it several times just wastes prompt space. Collapse by resolved absolute path.
|
|
@@ -139,7 +131,7 @@ function buildContextBlocks(contextFiles, workspace, client, warnings) {
|
|
|
139
131
|
warnings.push(`contextFile ${entry} skipped: ${Math.round(stat.size / 1024)}KB exceeds the ${MAX_IMAGE_BYTES / 1024 / 1024}MB image limit`);
|
|
140
132
|
continue;
|
|
141
133
|
}
|
|
142
|
-
blocks.push({ type: "image", mimeType, data:
|
|
134
|
+
blocks.push({ type: "image", mimeType, data: (await readFile(abs)).toString("base64") });
|
|
143
135
|
continue;
|
|
144
136
|
}
|
|
145
137
|
blocks.push({ type: "resource_link", uri: pathToFileURL(abs).href, name: path.basename(abs) });
|
|
@@ -168,9 +160,7 @@ function assertKnownModel(client, model) {
|
|
|
168
160
|
if (!Array.isArray(available) || available.length === 0) return;
|
|
169
161
|
const ids = available.map((m) => m?.modelId).filter((id) => typeof id === "string");
|
|
170
162
|
if (ids.length === 0 || ids.includes(model)) return;
|
|
171
|
-
|
|
172
|
-
err.reason = "unknown-model";
|
|
173
|
-
throw err;
|
|
163
|
+
throw makeError("unknown-model", `Unknown model ${JSON.stringify(model)}. This agent offers: ${ids.join(", ")}.`);
|
|
174
164
|
}
|
|
175
165
|
|
|
176
166
|
// Which config options a model carries is not discoverable up front: session/new reports
|
|
@@ -201,6 +191,17 @@ function servedModelFrom(res) {
|
|
|
201
191
|
return typeof m?.currentValue === "string" ? m.currentValue : undefined;
|
|
202
192
|
}
|
|
203
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
|
+
*/
|
|
204
205
|
export async function runDelegate({
|
|
205
206
|
spec, mode = "agent", resumeSessionId, workspace,
|
|
206
207
|
model = DEFAULT_MODEL, fast = false, reasoning, context, contextFiles, clientFactory,
|
|
@@ -210,59 +211,23 @@ export async function runDelegate({
|
|
|
210
211
|
signal,
|
|
211
212
|
} = {}) {
|
|
212
213
|
if (signal?.aborted) {
|
|
213
|
-
|
|
214
|
-
err.reason = "aborted";
|
|
215
|
-
throw err;
|
|
214
|
+
throw makeError("aborted", "delegation aborted by MCP host");
|
|
216
215
|
}
|
|
217
216
|
// Before the spawn: a bad path is the caller's to fix, and finding out costs a process,
|
|
218
217
|
// a handshake and a billed turn if it waits until the prompt is assembled.
|
|
219
218
|
assertWorkspace(workspace);
|
|
220
|
-
const promptText = resolveSpec(spec);
|
|
219
|
+
const promptText = await resolveSpec(spec);
|
|
221
220
|
const capMs = hardCapMs ?? timeoutMs ?? envMs("CURSOR_DELEGATE_HARD_CAP_MS", 3600000);
|
|
222
221
|
const shakeMs = handshakeMs ?? envMs("CURSOR_DELEGATE_HANDSHAKE_MS", DEFAULT_HANDSHAKE_MS);
|
|
223
222
|
const turnIdleMs = idleMs ?? envMs("CURSOR_DELEGATE_IDLE_MS", 0);
|
|
224
|
-
const
|
|
225
|
-
const TRUNCATION_MARKER = "\n\n[output truncated at 10MB]";
|
|
226
|
-
// merge:false replaces the list, merge:true upserts by id. Entries always arrive complete,
|
|
227
|
-
// so a keyed set is enough — no field-level merging.
|
|
228
|
-
let todos = new Map();
|
|
229
|
-
let sawTodoFrame = false;
|
|
230
|
-
const todoLabel = () => {
|
|
231
|
-
const entries = [...todos.values()].filter((t) => typeof t?.content === "string");
|
|
232
|
-
if (!entries.length) return null;
|
|
233
|
-
const i = entries.findIndex((t) => t.status === "in_progress");
|
|
234
|
-
if (i !== -1) return `todo ${i + 1}/${entries.length}: ${entries[i].content}`;
|
|
235
|
-
const done = entries.filter((t) => t.status === "completed").length;
|
|
236
|
-
return `todos ${done}/${entries.length} complete`;
|
|
237
|
-
};
|
|
238
|
-
const recordTodos = ({ todos: incoming, merge }) => {
|
|
239
|
-
if (!Array.isArray(incoming)) return;
|
|
240
|
-
sawTodoFrame = true;
|
|
241
|
-
if (merge === false) todos = new Map();
|
|
242
|
-
for (const t of incoming) {
|
|
243
|
-
if (t?.id === undefined || t?.id === null) continue;
|
|
244
|
-
todos.set(String(t.id), t);
|
|
245
|
-
}
|
|
246
|
-
const label = todoLabel();
|
|
247
|
-
if (label) { try { onProgress?.(label.slice(0, 200)); } catch {} }
|
|
248
|
-
};
|
|
249
|
-
|
|
250
|
-
let planEntries = [];
|
|
251
|
-
let planOverview;
|
|
252
|
-
let planDetail;
|
|
253
|
-
const recordCreatePlan = (body) => {
|
|
254
|
-
if (body?.overview !== undefined) planOverview = body.overview;
|
|
255
|
-
if (body?.plan !== undefined) planDetail = body.plan;
|
|
256
|
-
};
|
|
223
|
+
const state = makeTurnState({ onProgress, progressThrottleMs });
|
|
257
224
|
|
|
258
225
|
// ACP requires plan entry content to be a string and bounds priority/status to
|
|
259
226
|
// known values. Frames that violate that must not fail the MCP call after the
|
|
260
227
|
// work is done — drop the bad data and report it as a protocol diagnostic.
|
|
261
|
-
const PLAN_PRIORITIES = ["high", "medium", "low"];
|
|
262
|
-
const PLAN_STATUSES = ["pending", "in_progress", "completed"];
|
|
263
228
|
const sanitizePlan = (warnings) => {
|
|
264
229
|
const entries = [];
|
|
265
|
-
planEntries.forEach((raw, i) => {
|
|
230
|
+
state.planEntries.forEach((raw, i) => {
|
|
266
231
|
if (typeof raw?.content !== "string") {
|
|
267
232
|
warnings.push(`plan entry ${i} dropped: ACP requires string content, got ${raw === null ? "null" : typeof raw?.content}`);
|
|
268
233
|
return;
|
|
@@ -279,22 +244,21 @@ export async function runDelegate({
|
|
|
279
244
|
entries.push(entry);
|
|
280
245
|
});
|
|
281
246
|
const plan = { entries };
|
|
282
|
-
if (planOverview !== undefined) {
|
|
283
|
-
if (typeof planOverview === "string") plan.overview = planOverview;
|
|
247
|
+
if (state.planOverview !== undefined) {
|
|
248
|
+
if (typeof state.planOverview === "string") plan.overview = state.planOverview;
|
|
284
249
|
else warnings.push("plan overview dropped: expected string");
|
|
285
250
|
}
|
|
286
|
-
if (planDetail !== undefined) {
|
|
287
|
-
if (typeof planDetail === "string") plan.detail = planDetail;
|
|
251
|
+
if (state.planDetail !== undefined) {
|
|
252
|
+
if (typeof state.planDetail === "string") plan.detail = state.planDetail;
|
|
288
253
|
else warnings.push("plan detail dropped: expected string");
|
|
289
254
|
}
|
|
290
255
|
return plan;
|
|
291
256
|
};
|
|
292
257
|
|
|
293
|
-
const TODO_STATUSES = ["pending", "in_progress", "completed"];
|
|
294
258
|
const sanitizeTodos = (warnings) => {
|
|
295
259
|
const entries = [];
|
|
296
260
|
let i = -1;
|
|
297
|
-
for (const raw of todos.values()) {
|
|
261
|
+
for (const raw of state.todos.values()) {
|
|
298
262
|
i++;
|
|
299
263
|
if (typeof raw?.content !== "string") {
|
|
300
264
|
warnings.push(`todo ${i} dropped: expected string content, got ${raw === null ? "null" : typeof raw?.content}`);
|
|
@@ -319,113 +283,13 @@ export async function runDelegate({
|
|
|
319
283
|
};
|
|
320
284
|
|
|
321
285
|
const make = clientFactory || ((opts) => new AcpClient(opts));
|
|
322
|
-
const client = make({ mode, onCreatePlan: recordCreatePlan, onTodos: recordTodos });
|
|
286
|
+
const client = make({ mode, onCreatePlan: state.recordCreatePlan, onTodos: state.recordTodos });
|
|
323
287
|
const supervisor = new SessionSupervisor(client, { idleMs: turnIdleMs, handshakeMs: shakeMs, hardCapMs: capMs });
|
|
324
288
|
const onAbort = () => supervisor.abort();
|
|
325
289
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
326
290
|
|
|
327
|
-
const resultChunks = [];
|
|
328
|
-
let resultLength = 0;
|
|
329
|
-
let truncated = false;
|
|
330
|
-
let sawToolCall = false;
|
|
331
|
-
let collectingPostToolResult = false;
|
|
332
|
-
const activeToolCalls = new Set();
|
|
333
|
-
const touched = new Set();
|
|
334
|
-
|
|
335
|
-
// Text superseded by a later tool call is normally a preamble ("Inspecting the
|
|
336
|
-
// implementation.") and returning it would be inventing a summary. But the rule cannot
|
|
337
|
-
// tell a preamble from the whole answer: an agent that replies and then runs one more
|
|
338
|
-
// command has its entire reply discarded, and the caller gets "" with stopReason end_turn
|
|
339
|
-
// and no error. So keep the last discarded segment and hand it back only when nothing
|
|
340
|
-
// survived — labelled, never blended with a real final message.
|
|
341
|
-
let discardedResult = "";
|
|
342
|
-
const resetResult = () => {
|
|
343
|
-
if (resultLength > 0) discardedResult = resultChunks.join("");
|
|
344
|
-
resultChunks.length = 0;
|
|
345
|
-
resultLength = 0;
|
|
346
|
-
truncated = false;
|
|
347
|
-
};
|
|
348
|
-
const appendResult = (text) => {
|
|
349
|
-
if (truncated) return;
|
|
350
|
-
const remaining = MAX_OUTPUT - resultLength;
|
|
351
|
-
if (text.length <= remaining) {
|
|
352
|
-
resultChunks.push(text);
|
|
353
|
-
resultLength += text.length;
|
|
354
|
-
} else if (remaining > 0) {
|
|
355
|
-
const cut = cutAtCodePoint(text, remaining);
|
|
356
|
-
resultChunks.push(cut);
|
|
357
|
-
resultLength += cut.length;
|
|
358
|
-
truncated = true;
|
|
359
|
-
} else {
|
|
360
|
-
truncated = true;
|
|
361
|
-
}
|
|
362
|
-
};
|
|
363
|
-
const isTerminalToolStatus = (status) =>
|
|
364
|
-
status === "completed" || status === "failed" || status === "cancelled";
|
|
365
|
-
const startTool = (toolCallId, status) => {
|
|
366
|
-
sawToolCall = true;
|
|
367
|
-
collectingPostToolResult = false;
|
|
368
|
-
resetResult();
|
|
369
|
-
if (toolCallId != null && !isTerminalToolStatus(status)) activeToolCalls.add(toolCallId);
|
|
370
|
-
if (isTerminalToolStatus(status) && activeToolCalls.size === 0) collectingPostToolResult = true;
|
|
371
|
-
};
|
|
372
|
-
const updateToolStatus = (toolCallId, status) => {
|
|
373
|
-
if (!status) return;
|
|
374
|
-
if (!sawToolCall) {
|
|
375
|
-
sawToolCall = true;
|
|
376
|
-
resetResult();
|
|
377
|
-
}
|
|
378
|
-
if (isTerminalToolStatus(status)) {
|
|
379
|
-
if (toolCallId != null) activeToolCalls.delete(toolCallId);
|
|
380
|
-
if (activeToolCalls.size === 0 && !collectingPostToolResult) {
|
|
381
|
-
// Discard any message text emitted while tools were still running.
|
|
382
|
-
// A duplicate or late terminal update must not wipe an already-collected final message.
|
|
383
|
-
resetResult();
|
|
384
|
-
collectingPostToolResult = true;
|
|
385
|
-
}
|
|
386
|
-
} else {
|
|
387
|
-
collectingPostToolResult = false;
|
|
388
|
-
resetResult();
|
|
389
|
-
if (toolCallId != null) activeToolCalls.add(toolCallId);
|
|
390
|
-
}
|
|
391
|
-
};
|
|
392
|
-
|
|
393
|
-
// Each stream reports its newest complete sentence, at most one per throttle window.
|
|
394
|
-
// Capital-letter boundary: cursor-agent thoughts arrive as sentences with no separator.
|
|
395
|
-
const SENTENCE_END = /[.!?](?=\s|[A-Z])|\n/;
|
|
396
|
-
const MARKDOWN_LINE = /^(?:[|#>`~*_=+-]|\d+[.)]\s)/;
|
|
397
|
-
const progressStream = (prefix) => {
|
|
398
|
-
let buf = "", pending = null, lastEmit = 0;
|
|
399
|
-
const flush = (force) => {
|
|
400
|
-
if (pending === null || (!force && Date.now() - lastEmit < progressThrottleMs)) return;
|
|
401
|
-
lastEmit = Date.now();
|
|
402
|
-
try { onProgress?.(prefix + pending); } catch {}
|
|
403
|
-
pending = null;
|
|
404
|
-
};
|
|
405
|
-
const take = (s) => {
|
|
406
|
-
const line = s.replace(/\s+/g, " ").trim().slice(0, 200);
|
|
407
|
-
if (line.length > 3 && !MARKDOWN_LINE.test(line)) pending = line;
|
|
408
|
-
flush(false);
|
|
409
|
-
};
|
|
410
|
-
return {
|
|
411
|
-
push(text) {
|
|
412
|
-
buf += text;
|
|
413
|
-
for (let m; (m = SENTENCE_END.exec(buf)); buf = buf.slice(m.index + 1)) {
|
|
414
|
-
take(buf.slice(0, m.index + 1));
|
|
415
|
-
}
|
|
416
|
-
if (buf.length > 300) { take(buf); buf = ""; }
|
|
417
|
-
},
|
|
418
|
-
end() { take(buf); buf = ""; flush(true); },
|
|
419
|
-
reset() { buf = ""; pending = null; },
|
|
420
|
-
};
|
|
421
|
-
};
|
|
422
|
-
const thoughtProgress = progressStream("thinking: ");
|
|
423
|
-
const messageProgress = progressStream("Cursor: ");
|
|
424
|
-
|
|
425
291
|
// The bridge cannot see inside a running shell command, so a long silence is reported
|
|
426
292
|
// rather than acted on: the caller gets elapsed time and frame age and can decide.
|
|
427
|
-
let lastToolLabel = null;
|
|
428
|
-
let sessionTitle;
|
|
429
293
|
let promptInFlight = false;
|
|
430
294
|
let heartbeat = null;
|
|
431
295
|
const startHeartbeat = () => {
|
|
@@ -436,9 +300,9 @@ export async function runDelegate({
|
|
|
436
300
|
`still working — ${fmtDuration(Date.now() - startedAt)} elapsed`,
|
|
437
301
|
`last agent frame ${fmtDuration(supervisor.msSinceActivity())} ago`,
|
|
438
302
|
];
|
|
439
|
-
const todo = todoLabel();
|
|
303
|
+
const todo = state.todoLabel();
|
|
440
304
|
if (todo) parts.push(todo);
|
|
441
|
-
if (lastToolLabel) parts.push(`running: ${lastToolLabel}`);
|
|
305
|
+
if (state.lastToolLabel) parts.push(`running: ${state.lastToolLabel}`);
|
|
442
306
|
try { onProgress?.(parts.join(", ").slice(0, 200)); } catch {}
|
|
443
307
|
}, heartbeatMs);
|
|
444
308
|
heartbeat.unref?.();
|
|
@@ -452,36 +316,36 @@ export async function runDelegate({
|
|
|
452
316
|
if (!promptInFlight) return;
|
|
453
317
|
const up = u?.update || {};
|
|
454
318
|
if (up.sessionUpdate === "plan") {
|
|
455
|
-
planEntries = up.entries || [];
|
|
319
|
+
state.planEntries = up.entries || [];
|
|
456
320
|
}
|
|
457
321
|
// The agent names the turn a beat after the prompt lands ("File Creator"). Useful as an
|
|
458
322
|
// ephemeral label while several delegations run, and in timeout forensics — but not in
|
|
459
323
|
// the result, where it arrives after there is nothing left to tell apart and has been
|
|
460
324
|
// measured contradicting the answer ("No Image Detected" on a turn describing an image).
|
|
461
325
|
if (up.sessionUpdate === "session_info_update" && typeof up.title === "string" && up.title) {
|
|
462
|
-
if (up.title !== sessionTitle) { try { onProgress?.(`turn titled: ${up.title}`.slice(0, 200)); } catch {} }
|
|
463
|
-
sessionTitle = up.title;
|
|
326
|
+
if (up.title !== state.sessionTitle) { try { onProgress?.(`turn titled: ${up.title}`.slice(0, 200)); } catch {} }
|
|
327
|
+
state.sessionTitle = up.title;
|
|
464
328
|
}
|
|
465
329
|
if (up.sessionUpdate === "agent_thought_chunk" && up.content?.text) {
|
|
466
|
-
|
|
330
|
+
state.thoughts.push(up.content.text);
|
|
467
331
|
}
|
|
468
332
|
if (up.sessionUpdate === "tool_call") {
|
|
469
|
-
startTool(up.toolCallId, up.status);
|
|
333
|
+
state.startTool(up.toolCallId, up.status);
|
|
470
334
|
const label = up.title || up.kind || "tool";
|
|
471
335
|
const path = up.locations?.[0]?.path;
|
|
472
|
-
lastToolLabel = String(label) + (path ? " — " + path : "");
|
|
473
|
-
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 {}
|
|
474
338
|
}
|
|
475
339
|
if (up.sessionUpdate === "agent_message_chunk" && up.content?.text) {
|
|
476
340
|
const text = up.content.text;
|
|
477
|
-
if (
|
|
478
|
-
|
|
341
|
+
if (state.collectingResult()) state.appendResult(text);
|
|
342
|
+
state.messages.push(text);
|
|
479
343
|
}
|
|
480
344
|
if (up.sessionUpdate === "tool_call_update") {
|
|
481
|
-
updateToolStatus(up.toolCallId, up.status);
|
|
345
|
+
state.updateToolStatus(up.toolCallId, up.status);
|
|
482
346
|
for (const c of up.content || []) {
|
|
483
347
|
if (c.type === "diff" && c.path) {
|
|
484
|
-
touched.add(c.path);
|
|
348
|
+
state.touched.add(c.path);
|
|
485
349
|
try { onProgress?.("editing " + c.path); } catch {}
|
|
486
350
|
}
|
|
487
351
|
}
|
|
@@ -517,36 +381,27 @@ export async function runDelegate({
|
|
|
517
381
|
else servedModel = servedModelFrom(r.res) ?? servedModel;
|
|
518
382
|
}
|
|
519
383
|
await client.setMode(sessionId, mode);
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
collectingPostToolResult = false;
|
|
523
|
-
activeToolCalls.clear();
|
|
524
|
-
thoughtProgress.reset();
|
|
525
|
-
messageProgress.reset();
|
|
526
|
-
planEntries = [];
|
|
527
|
-
planOverview = undefined;
|
|
528
|
-
planDetail = undefined;
|
|
529
|
-
todos = new Map();
|
|
530
|
-
sawTodoFrame = false;
|
|
531
|
-
discardedResult = "";
|
|
532
|
-
touched.clear();
|
|
533
|
-
lastToolLabel = null;
|
|
534
|
-
sessionTitle = undefined;
|
|
384
|
+
// Everything a session/load replay may have written belongs to the previous turn.
|
|
385
|
+
state.reset();
|
|
535
386
|
supervisor.promptStarted();
|
|
536
387
|
startHeartbeat();
|
|
537
388
|
promptInFlight = true;
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
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
|
+
}
|
|
542
398
|
});
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
let result =
|
|
546
|
-
if (truncated) result += TRUNCATION_MARKER;
|
|
399
|
+
state.thoughts.end();
|
|
400
|
+
state.messages.end();
|
|
401
|
+
let result = state.text();
|
|
547
402
|
const finalMessageAvailable = result.length > 0;
|
|
548
403
|
let resultSource = finalMessageAvailable
|
|
549
|
-
? (sawToolCall ? "post-tool" : "tool-free-stream")
|
|
404
|
+
? (state.sawToolCall ? "post-tool" : "tool-free-stream")
|
|
550
405
|
: "none";
|
|
551
406
|
const protocolWarnings = [];
|
|
552
407
|
// plan.detail is the model restating — into chat's sibling channel — a plan it also filed via
|
|
@@ -555,9 +410,9 @@ export async function runDelegate({
|
|
|
555
410
|
// from result + plan.entries. So in plan/ask drop the detail and let result be the agent's own
|
|
556
411
|
// message verbatim — no bridge-side guess at whether that message "is really the plan". In
|
|
557
412
|
// agent mode the plan was accepted and result is the implementation report — both stay.
|
|
558
|
-
const dropPlanDetail = typeof planDetail === "string" && (mode === "plan" || mode === "ask");
|
|
559
|
-
if (!finalMessageAvailable && discardedResult) {
|
|
560
|
-
result = discardedResult;
|
|
413
|
+
const dropPlanDetail = typeof state.planDetail === "string" && (mode === "plan" || mode === "ask");
|
|
414
|
+
if (!finalMessageAvailable && state.discardedResult) {
|
|
415
|
+
result = state.discardedResult;
|
|
561
416
|
resultSource = "pre-tool-fallback";
|
|
562
417
|
protocolWarnings.push(
|
|
563
418
|
"the agent ran a tool after its last message and never spoke again, so no final message closed the turn."
|
|
@@ -584,7 +439,7 @@ export async function runDelegate({
|
|
|
584
439
|
// Like every other collection here, absence means "nothing reported": an empty list on
|
|
585
440
|
// every read-only turn read as a claim that nothing changed, which this field cannot make
|
|
586
441
|
// (shell-driven edits leave no diff event).
|
|
587
|
-
const filesReported = normalizeAgentReportedFiles([...touched], workspace);
|
|
442
|
+
const filesReported = normalizeAgentReportedFiles([...state.touched], workspace);
|
|
588
443
|
if (filesReported.length) out.filesReportedByEditTools = filesReported;
|
|
589
444
|
// resultSource is a caveat, not a fact worth stating on every turn: on the happy path
|
|
590
445
|
// (post-tool / tool-free-stream) result is simply the answer, so say nothing. Surface it only
|
|
@@ -602,7 +457,7 @@ export async function runDelegate({
|
|
|
602
457
|
if (resumeError) protocolWarnings.push(`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`);
|
|
603
458
|
for (const id of unsupportedOptions) protocolWarnings.push(`model ${model} has no ${id} option; the requested value was ignored`);
|
|
604
459
|
protocolWarnings.push(...contextWarnings);
|
|
605
|
-
if (planEntries.length > 0 || planOverview !== undefined || planDetail !== undefined) {
|
|
460
|
+
if (state.planEntries.length > 0 || state.planOverview !== undefined || state.planDetail !== undefined) {
|
|
606
461
|
out.plan = sanitizePlan(protocolWarnings);
|
|
607
462
|
// In plan/ask result already carries the agent's own plan message, so the detail here is a
|
|
608
463
|
// duplicate — drop it. entries and overview are structured and unique, and always stay.
|
|
@@ -612,7 +467,7 @@ export async function runDelegate({
|
|
|
612
467
|
// done" rather than "not tracked". Report only what the agent actually sent — and of
|
|
613
468
|
// that, the full list only when it says something todoProgress cannot: which items
|
|
614
469
|
// remain. On a fully-completed turn the list restates the counts entry by entry.
|
|
615
|
-
if (sawTodoFrame) {
|
|
470
|
+
if (state.sawTodoFrame) {
|
|
616
471
|
const { todos: todoList, todoProgress } = sanitizeTodos(protocolWarnings);
|
|
617
472
|
out.todoProgress = todoProgress;
|
|
618
473
|
if (todoProgress.completed < todoProgress.total) out.todos = todoList;
|
|
@@ -634,15 +489,15 @@ export async function runDelegate({
|
|
|
634
489
|
const isStall = isTimeout || err?.reason === "handshake-timeout";
|
|
635
490
|
if (isStall || err?.reason === "aborted" || err?.reason === "agent-exit") {
|
|
636
491
|
const age = fmtDuration(supervisor.msSinceActivity());
|
|
637
|
-
err.message += `\n\nLast ACP frame ${age} ago${lastToolLabel ? `; last tool call: ${lastToolLabel}` : ""}.`;
|
|
638
|
-
if (sessionTitle) err.message += ` The agent titled this turn ${JSON.stringify(sessionTitle)}.`;
|
|
639
|
-
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) {
|
|
640
495
|
const { todoProgress } = sanitizeTodos([]);
|
|
641
|
-
const current = todoLabel();
|
|
496
|
+
const current = state.todoLabel();
|
|
642
497
|
err.message += ` ${todoProgress.completed} of ${todoProgress.total} todos completed`
|
|
643
498
|
+ `${current ? `; ${current}` : ""}.`;
|
|
644
499
|
}
|
|
645
|
-
const files = normalizeAgentReportedFiles([...touched], workspace);
|
|
500
|
+
const files = normalizeAgentReportedFiles([...state.touched], workspace);
|
|
646
501
|
if (files.length) err.message += ` Files reported edited: ${files.join(", ")}.`;
|
|
647
502
|
// Without this the resume hint below reads as "carry on from where you were", when the
|
|
648
503
|
// requested session was never loaded and this turn started from nothing.
|
package/src/doctor.js
CHANGED
|
@@ -2,16 +2,22 @@ import process from "node:process";
|
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
3
|
import { AcpClient } from "./acp-client.js";
|
|
4
4
|
import { resolveAcpSpawn } from "./spawn.js";
|
|
5
|
+
import { treeKill } from "./proc.js";
|
|
5
6
|
import { readPackageVersion } from "./version.js";
|
|
6
7
|
|
|
7
8
|
const HANDSHAKE_TIMEOUT_MS = 15_000;
|
|
9
|
+
const VERSION_PROBE_TIMEOUT_MS = 10_000;
|
|
8
10
|
const DEFAULT_LOG_SIZE = "2000";
|
|
9
11
|
|
|
10
12
|
function formatCommand({ command, args }) {
|
|
11
13
|
return args?.length ? `${command} ${args.join(" ")}` : command;
|
|
12
14
|
}
|
|
13
15
|
|
|
14
|
-
|
|
16
|
+
// A launcher that accepts --version and then never answers used to hang doctor forever — and
|
|
17
|
+
// doctor is the tool you run when delegation is already broken, so a wedged agent is exactly
|
|
18
|
+
// the case it has to survive. Deep handshakes have always been time-boxed; this is that guard
|
|
19
|
+
// applied to the shallow probe that runs on every call.
|
|
20
|
+
export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_MS) {
|
|
15
21
|
const { command, options } = spawnSpec;
|
|
16
22
|
const isJsScript = /\.js$/i.test(command);
|
|
17
23
|
const execCommand = isJsScript ? process.execPath : command;
|
|
@@ -19,9 +25,11 @@ export function probeAgentVersion(spawnSpec) {
|
|
|
19
25
|
return new Promise((resolve) => {
|
|
20
26
|
let settled = false;
|
|
21
27
|
let stdout = "";
|
|
28
|
+
let timer;
|
|
22
29
|
const finish = (result) => {
|
|
23
30
|
if (settled) return;
|
|
24
31
|
settled = true;
|
|
32
|
+
clearTimeout(timer);
|
|
25
33
|
resolve(result);
|
|
26
34
|
};
|
|
27
35
|
const child = spawn(execCommand, execArgs, { ...options, stdio: ["ignore", "pipe", "pipe"] });
|
|
@@ -33,6 +41,15 @@ export function probeAgentVersion(spawnSpec) {
|
|
|
33
41
|
version: code === 0 ? stdout.trim() || null : null,
|
|
34
42
|
});
|
|
35
43
|
});
|
|
44
|
+
timer = setTimeout(() => {
|
|
45
|
+
// treeKill, not child.kill: the spawn spec carries shell:true on win32, where a plain
|
|
46
|
+
// kill only reaches the wrapper and leaves the launcher running.
|
|
47
|
+
if (child.pid) treeKill(child.pid).catch(() => {});
|
|
48
|
+
// The launcher exists — it spawned — it just never answered, which is a different
|
|
49
|
+
// diagnosis from "not installed" and has to read that way.
|
|
50
|
+
finish({ found: true, version: null, error: `version probe timed out after ${timeoutMs}ms` });
|
|
51
|
+
}, timeoutMs);
|
|
52
|
+
timer.unref?.();
|
|
36
53
|
});
|
|
37
54
|
}
|
|
38
55
|
|
|
@@ -68,6 +85,18 @@ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs
|
|
|
68
85
|
}
|
|
69
86
|
}
|
|
70
87
|
|
|
88
|
+
/**
|
|
89
|
+
* @param {{
|
|
90
|
+
* getClientInfo?: () => { capabilities?: any, version?: any },
|
|
91
|
+
* deep?: boolean,
|
|
92
|
+
* spawnSpec?: { command: string, args: string[], options?: object },
|
|
93
|
+
* clientFactory?: (opts: any) => any,
|
|
94
|
+
* workspace?: string,
|
|
95
|
+
* handshakeTimeoutMs?: number,
|
|
96
|
+
* versionTimeoutMs?: number,
|
|
97
|
+
* readVersion?: () => string,
|
|
98
|
+
* }} [opts]
|
|
99
|
+
*/
|
|
71
100
|
export async function runDoctor({
|
|
72
101
|
getClientInfo = () => ({ capabilities: {}, version: {} }),
|
|
73
102
|
deep = false,
|
|
@@ -75,11 +104,13 @@ export async function runDoctor({
|
|
|
75
104
|
clientFactory = (opts) => new AcpClient(opts),
|
|
76
105
|
workspace,
|
|
77
106
|
handshakeTimeoutMs = HANDSHAKE_TIMEOUT_MS,
|
|
107
|
+
versionTimeoutMs = VERSION_PROBE_TIMEOUT_MS,
|
|
78
108
|
readVersion = readPackageVersion,
|
|
79
109
|
} = {}) {
|
|
80
110
|
const { capabilities, version } = getClientInfo();
|
|
81
|
-
const agentProbe = await probeAgentVersion(spawnSpec);
|
|
111
|
+
const agentProbe = await probeAgentVersion(spawnSpec, versionTimeoutMs);
|
|
82
112
|
|
|
113
|
+
/** @type {{ plugin: any, client: any, agent: any & { handshake?: any }, runtime: any, env: any }} */
|
|
83
114
|
const out = {
|
|
84
115
|
plugin: { version: readVersion() },
|
|
85
116
|
client: {
|
|
@@ -91,6 +122,7 @@ export async function runDoctor({
|
|
|
91
122
|
found: agentProbe.found,
|
|
92
123
|
command: formatCommand(spawnSpec),
|
|
93
124
|
version: agentProbe.version,
|
|
125
|
+
...(agentProbe.error ? { error: agentProbe.error } : {}),
|
|
94
126
|
},
|
|
95
127
|
runtime: {
|
|
96
128
|
node: process.versions.node,
|
package/src/errors.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every failure this bridge raises carries a `reason`, which is what lets a caller tell
|
|
3
|
+
* "fix your arguments" from "retry" without parsing prose. Errors that came off the wire also
|
|
4
|
+
* carry the agent's JSON-RPC `code`. One shape, one constructor, so the tag is never forgotten
|
|
5
|
+
* and the type checker has something to check against.
|
|
6
|
+
*
|
|
7
|
+
* @typedef {Error & { reason?: string, code?: number }} DelegateError
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @param {string} reason
|
|
12
|
+
* @param {string} message
|
|
13
|
+
* @returns {DelegateError}
|
|
14
|
+
*/
|
|
15
|
+
export function makeError(reason, message) {
|
|
16
|
+
/** @type {DelegateError} */
|
|
17
|
+
const err = new Error(message);
|
|
18
|
+
err.reason = reason;
|
|
19
|
+
return err;
|
|
20
|
+
}
|