cursor-delegate-mcp 3.0.0 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +46 -0
- package/package.json +1 -1
- package/src/acp-client.js +77 -43
- package/src/delegate.js +50 -43
- package/src/doctor.js +21 -28
- package/src/errors.js +9 -6
- package/src/jsonrpc.js +2 -4
- package/src/proc.js +103 -3
- package/src/server.js +48 -61
- package/src/session-supervisor.js +10 -1
- package/src/tasks.js +18 -10
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,52 @@ All notable changes to this project are documented here. The format follows
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [3.1.0] - 2026-11-24
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
|
|
13
|
+
- A stopped task's status message stays `cancelled; resume with resumeSessionId <id>` after the
|
|
14
|
+
run ends, where it became the run's `delegate failed [aborted]` error. It gains a note when the
|
|
15
|
+
run had started a fresh session after a failed resume, or when the stop did not see cursor-agent
|
|
16
|
+
exit.
|
|
17
|
+
- A process the server would start after shutdown began fails with `spawn-failed` instead of
|
|
18
|
+
starting.
|
|
19
|
+
- A stop counts as done once cursor-agent's exit was seen and its tree kill finished. On Windows it
|
|
20
|
+
waits for `taskkill` to finish with the tree.
|
|
21
|
+
- A shutdown signal that arrives after stdin closed sets the exit code and waits for the agents to
|
|
22
|
+
be stopped, where it exited at once. Only a second signal skips that wait.
|
|
23
|
+
- An aborted `doctor` version probe returns once its stop saw the probe exit: up to 4 s, where it
|
|
24
|
+
was 2 s.
|
|
25
|
+
|
|
26
|
+
### Fixed
|
|
27
|
+
|
|
28
|
+
- A shutdown signal during `doctor` with `deep: true` stops the agent doctor starts for its
|
|
29
|
+
handshake, rather than exiting with it running.
|
|
30
|
+
- A delegation that fails, times out or is aborted during setup sends cursor-agent nothing more: a
|
|
31
|
+
reply that arrives afterwards no longer goes on to change the session's model, effort or mode, or
|
|
32
|
+
to send the prompt. In task mode a handshake timeout fails the call, rather than answering it
|
|
33
|
+
with a task id.
|
|
34
|
+
- A cancel before the prompt ends the delegation at once with `stopReason: "cancelled"`, rather
|
|
35
|
+
than waiting on the setup request in flight.
|
|
36
|
+
- A delegation aborted or timed out during setup sends no progress notifications after its call
|
|
37
|
+
returned.
|
|
38
|
+
- Text cursor-agent sends while `contextFiles` are read stays out of `result`.
|
|
39
|
+
- The note that cursor-agent may still be running and the resume hint reach the caller whatever
|
|
40
|
+
cursor-agent's side threw, a frozen error or a value that is not an Error included.
|
|
41
|
+
|
|
42
|
+
## [3.0.1] - 2026-11-23
|
|
43
|
+
|
|
44
|
+
### Fixed
|
|
45
|
+
|
|
46
|
+
- A delegation stopped with TaskStop in Claude Code can be resumed: `resumeSessionId` takes the
|
|
47
|
+
task's server-side id, the only id Claude Code tells the model. `cancel` takes it too and
|
|
48
|
+
reaches only that task's turn.
|
|
49
|
+
|
|
50
|
+
### Changed
|
|
51
|
+
|
|
52
|
+
- The `aborted` error drops the last tool call, frame age, todos and edited files: no host
|
|
53
|
+
receives a response to a request it cancelled. The skill reference no longer lists `aborted`.
|
|
54
|
+
|
|
9
55
|
## [3.0.0] - 2026-11-23
|
|
10
56
|
|
|
11
57
|
`delegate` no longer holds your agent while Cursor works. In an interactive Claude Code CLI session
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cursor-delegate-mcp",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.1.0",
|
|
4
4
|
"mcpName": "io.github.andreilungeanu/cursor-delegate-mcp",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Delegate multi-file coding work from Claude Code, Codex, Copilot, or any MCP client to Cursor's CLI agent — structured results, plan mode, and changed files.",
|
package/src/acp-client.js
CHANGED
|
@@ -1,17 +1,34 @@
|
|
|
1
|
-
import { spawn } from "node:child_process";
|
|
2
1
|
import { EventEmitter } from "node:events";
|
|
3
2
|
import { StringDecoder } from "node:string_decoder";
|
|
4
3
|
import { JsonRpcPeer } from "./jsonrpc.js";
|
|
5
4
|
import { createRequestRouter } from "./request-router.js";
|
|
6
|
-
import { commandExists, resolveAcpSpawn
|
|
7
|
-
import {
|
|
5
|
+
import { commandExists, resolveAcpSpawn } from "./spawn.js";
|
|
6
|
+
import { children, isChildAlive, spawnChild } from "./proc.js";
|
|
8
7
|
import { VERSION } from "./version.js";
|
|
9
8
|
import { makeError } from "./errors.js";
|
|
10
9
|
|
|
11
10
|
const STDERR_CAP = 64 * 1024;
|
|
12
|
-
|
|
13
|
-
//
|
|
14
|
-
|
|
11
|
+
|
|
12
|
+
// Each phase lists the transitions it allows; any other is refused.
|
|
13
|
+
/** @typedef {"setup" | "running" | "cancelled-in-setup" | "cancelled" | "ended" | "exited"} WirePhase */
|
|
14
|
+
/** @typedef {"prompt" | "cancel" | "end" | "exit"} WireTransition */
|
|
15
|
+
/** @type {Record<WirePhase, Partial<Record<WireTransition, WirePhase>>>} */
|
|
16
|
+
const PHASES = {
|
|
17
|
+
setup: { prompt: "running", cancel: "cancelled-in-setup", end: "ended", exit: "exited" },
|
|
18
|
+
running: { cancel: "cancelled", end: "ended", exit: "exited" },
|
|
19
|
+
"cancelled-in-setup": { exit: "exited" },
|
|
20
|
+
cancelled: { exit: "exited" },
|
|
21
|
+
ended: { exit: "exited" },
|
|
22
|
+
exited: {},
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
// What a request the phase refuses throws; after a cancel before the prompt, with the cancel's reason.
|
|
26
|
+
/** @param {WirePhase} phase */
|
|
27
|
+
function wireClosed(phase) {
|
|
28
|
+
return phase === "cancelled-in-setup"
|
|
29
|
+
? makeError("cancelled-in-setup", "cancelled before the prompt was sent")
|
|
30
|
+
: makeError("wire-closed", `no prompt can go out: the wire is ${phase}`);
|
|
31
|
+
}
|
|
15
32
|
|
|
16
33
|
export class AcpClient extends EventEmitter {
|
|
17
34
|
/**
|
|
@@ -20,11 +37,15 @@ export class AcpClient extends EventEmitter {
|
|
|
20
37
|
* mode?: string,
|
|
21
38
|
* onCreatePlan?: (body: any) => void,
|
|
22
39
|
* onTodos?: (body: any) => void,
|
|
40
|
+
* registry?: import("./proc.js").ChildRegistry,
|
|
23
41
|
* }} [opts]
|
|
24
42
|
*/
|
|
25
|
-
constructor({ spawnSpec, mode, onCreatePlan, onTodos } = {}) {
|
|
43
|
+
constructor({ spawnSpec, mode, onCreatePlan, onTodos, registry = children } = {}) {
|
|
26
44
|
super();
|
|
27
45
|
this.spawnSpec = spawnSpec || resolveAcpSpawn();
|
|
46
|
+
this.registry = registry;
|
|
47
|
+
/** @type {import("./proc.js").TrackedChild | null} */
|
|
48
|
+
this._tracked = null;
|
|
28
49
|
this.mode = mode;
|
|
29
50
|
this.onCreatePlan = onCreatePlan;
|
|
30
51
|
this.onTodos = onTodos;
|
|
@@ -32,8 +53,12 @@ export class AcpClient extends EventEmitter {
|
|
|
32
53
|
this._stderrLength = 0;
|
|
33
54
|
/** @type {Promise<boolean> | null} */
|
|
34
55
|
this._stopping = null;
|
|
56
|
+
/** @type {WirePhase} */
|
|
57
|
+
this._phase = "setup";
|
|
35
58
|
}
|
|
36
59
|
|
|
60
|
+
get child() { return this._tracked?.child; }
|
|
61
|
+
|
|
37
62
|
// The stderr tail an exit error quotes. Kept as chunks and joined on read, so a noisy agent costs
|
|
38
63
|
// a push per chunk; a StringDecoder keeps a multi-byte character split across reads intact.
|
|
39
64
|
// stderr is not ACP activity, so it does not feed the supervisor.
|
|
@@ -42,18 +67,16 @@ export class AcpClient extends EventEmitter {
|
|
|
42
67
|
return joined.length > STDERR_CAP ? joined.slice(-STDERR_CAP) : joined;
|
|
43
68
|
}
|
|
44
69
|
|
|
45
|
-
start() {
|
|
70
|
+
async start() {
|
|
46
71
|
const { command, args, options } = this.spawnSpec;
|
|
47
72
|
const opts = /** @type {{ shell?: boolean, env?: NodeJS.ProcessEnv }} */ (options);
|
|
48
73
|
if (opts?.shell && !commandExists(command, opts.env)) {
|
|
49
|
-
|
|
74
|
+
throw makeError("spawn-failed", `Failed to spawn agent (${command}): not found on PATH. Install Cursor CLI and run 'cursor-agent login'.`);
|
|
50
75
|
}
|
|
76
|
+
this._tracked = spawnChild(command, args, opts, { stdio: ["pipe", "pipe", "pipe"] }, this.registry);
|
|
51
77
|
this._stderrChunks = [];
|
|
52
78
|
this._stderrLength = 0;
|
|
53
79
|
const stderrDecoder = new StringDecoder("utf8");
|
|
54
|
-
this._exitEmitted = false;
|
|
55
|
-
const argv = spawnArgv(command, args, opts);
|
|
56
|
-
this.child = spawn(argv.command, argv.args, { ...argv.options, detached: DETACHED, stdio: ["pipe", "pipe", "pipe"] });
|
|
57
80
|
this.child.stderr.on("data", (chunk) => {
|
|
58
81
|
const text = stderrDecoder.write(chunk);
|
|
59
82
|
if (text) {
|
|
@@ -78,9 +101,9 @@ export class AcpClient extends EventEmitter {
|
|
|
78
101
|
// take down the server. readline adds no handler on stdout either.
|
|
79
102
|
this.child.stdin.on("error", () => {});
|
|
80
103
|
this.child.stdout.on("error", () => {});
|
|
104
|
+
// Both 'exit' and 'close' land here; the transition the first one takes refuses the second.
|
|
81
105
|
const emitExit = (code, signal) => {
|
|
82
|
-
if (this.
|
|
83
|
-
this._exitEmitted = true;
|
|
106
|
+
if (!this._advance("exit")) return;
|
|
84
107
|
const stderr = this.stderrBuffer;
|
|
85
108
|
const err = makeError(
|
|
86
109
|
"agent-exit",
|
|
@@ -128,7 +151,7 @@ export class AcpClient extends EventEmitter {
|
|
|
128
151
|
|
|
129
152
|
// Stashed for the unknown-model check and doctor deep, so neither needs a second handshake.
|
|
130
153
|
async initialize() {
|
|
131
|
-
const res = await this.
|
|
154
|
+
const res = await this._setup("initialize", { protocolVersion: 1, clientInfo: { name: "cursor-delegate-mcp", version: VERSION }, clientCapabilities: { _meta: { parameterizedModelPicker: true } } });
|
|
132
155
|
this.protocolVersion = res?.protocolVersion;
|
|
133
156
|
this.agentCapabilities = res?.agentCapabilities;
|
|
134
157
|
return res;
|
|
@@ -139,15 +162,38 @@ export class AcpClient extends EventEmitter {
|
|
|
139
162
|
this.configOptions = res?.configOptions;
|
|
140
163
|
return res;
|
|
141
164
|
}
|
|
142
|
-
async newSession(cwd) { return this._captureSession(await this.
|
|
143
|
-
async loadSession(sessionId, cwd) { return this._captureSession(await this.
|
|
144
|
-
setModel(sessionId, modelId) { return this.
|
|
145
|
-
setConfigOption(sessionId, configId, value) { return this.
|
|
146
|
-
setMode(sessionId, modeId) { return this.
|
|
147
|
-
|
|
165
|
+
async newSession(cwd) { return this._captureSession(await this._setup("session/new", { cwd, mcpServers: [] })); }
|
|
166
|
+
async loadSession(sessionId, cwd) { return this._captureSession(await this._setup("session/load", { sessionId, cwd, mcpServers: [] })); }
|
|
167
|
+
setModel(sessionId, modelId) { return this._setup("session/set_model", { sessionId, modelId }); }
|
|
168
|
+
setConfigOption(sessionId, configId, value) { return this._setup("session/set_config_option", { sessionId, configId, value: String(value) }); } // configId, not optionId; ACP wants a string value
|
|
169
|
+
setMode(sessionId, modeId) { return this._setup("session/set_mode", { sessionId, modeId }); }
|
|
170
|
+
// Every request before the task prompt. A reply that lands once setup ended, at a cancel or a
|
|
171
|
+
// failed delegation, is refused too, so no setup step runs on from it.
|
|
172
|
+
async _setup(method, params) {
|
|
173
|
+
if (this._phase !== "setup") throw wireClosed(this._phase);
|
|
174
|
+
const reply = await this.peer.request(method, params);
|
|
175
|
+
if (this._phase !== "setup") throw wireClosed(this._phase);
|
|
176
|
+
return reply;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** @param {WireTransition} transition @returns {WirePhase | undefined} */
|
|
180
|
+
_advance(transition) {
|
|
181
|
+
const next = PHASES[this._phase][transition];
|
|
182
|
+
if (next) this._phase = next;
|
|
183
|
+
return next;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// The task prompt, and the only way into the running phase.
|
|
187
|
+
prompt(sessionId, blocks) {
|
|
188
|
+
if (!this._advance("prompt")) throw wireClosed(this._phase);
|
|
189
|
+
return this.peer.request("session/prompt", { sessionId, prompt: blocks });
|
|
190
|
+
}
|
|
191
|
+
// The delegation is decided: nothing sent from here on would reach a caller.
|
|
192
|
+
endTurn() { this._advance("end"); }
|
|
193
|
+
// Before the prompt nothing runs that the agent could finish, so the supervisor ends the
|
|
194
|
+
// delegation at once, whatever setup is awaiting.
|
|
148
195
|
cancel(sessionId) {
|
|
149
|
-
|
|
150
|
-
this.cancelRequested = true;
|
|
196
|
+
if (this._advance("cancel") === "cancelled-in-setup") this.emit("cancelled-in-setup");
|
|
151
197
|
this.peer.notify("session/cancel", { sessionId });
|
|
152
198
|
return Promise.resolve();
|
|
153
199
|
}
|
|
@@ -155,8 +201,9 @@ export class AcpClient extends EventEmitter {
|
|
|
155
201
|
getTranscript(n) { return this.peer ? this.peer.formatLog(n) : ""; }
|
|
156
202
|
|
|
157
203
|
// Idempotent while teardown is in flight and after a confirmed exit. A missed exit is not
|
|
158
|
-
// memoized
|
|
159
|
-
|
|
204
|
+
// memoized, so a later stop kills again. A confirmed exit stays so later callers join.
|
|
205
|
+
/** @param {{ timeoutMs?: number }} [opts] */
|
|
206
|
+
stop({ timeoutMs } = {}) {
|
|
160
207
|
if (!this._stopping) {
|
|
161
208
|
this._stopping = this._teardown(timeoutMs).then((observed) => {
|
|
162
209
|
if (!observed) this._stopping = null;
|
|
@@ -170,29 +217,16 @@ export class AcpClient extends EventEmitter {
|
|
|
170
217
|
}
|
|
171
218
|
|
|
172
219
|
async _teardown(timeoutMs) {
|
|
173
|
-
const
|
|
174
|
-
if (!
|
|
220
|
+
const tracked = this._tracked;
|
|
221
|
+
if (!tracked) {
|
|
175
222
|
try { this.peer?.close(); } catch {}
|
|
176
223
|
return true;
|
|
177
224
|
}
|
|
178
|
-
const
|
|
179
|
-
|
|
180
|
-
const exited = alive
|
|
181
|
-
? /** @type {Promise<boolean>} */ (new Promise((resolve) => child.once("exit", () => resolve(true))))
|
|
182
|
-
: Promise.resolve(true);
|
|
183
|
-
// Runs for an exited child too: the agent can be gone while the commands it spawned are still
|
|
184
|
-
// running, and on POSIX they stay in its process group, which is the only handle left on them.
|
|
185
|
-
treeKill(child.pid, { childAlive: alive }).catch(() => {});
|
|
186
|
-
/** @type {NodeJS.Timeout | undefined} */
|
|
187
|
-
let timer;
|
|
188
|
-
const bounded = /** @type {Promise<boolean>} */ (new Promise((resolve) => {
|
|
189
|
-
timer = setTimeout(() => resolve(false), timeoutMs);
|
|
190
|
-
}));
|
|
191
|
-
const observed = await Promise.race([exited, bounded]);
|
|
192
|
-
clearTimeout(timer);
|
|
225
|
+
const { child } = tracked;
|
|
226
|
+
const observed = await tracked.stop({ timeoutMs });
|
|
193
227
|
// On an observed exit, emitExit rejects in-flight RPCs with stderr, and racing it here would
|
|
194
228
|
// drop that. Only a child still alive after the stop has its RPCs settled here.
|
|
195
|
-
if (!observed &&
|
|
229
|
+
if (!observed && this._phase !== "exited" && isChildAlive(child)) {
|
|
196
230
|
try {
|
|
197
231
|
this.peer?.rejectAllPending(makeError("agent-exit", "agent process did not exit after stop"));
|
|
198
232
|
} catch {}
|
package/src/delegate.js
CHANGED
|
@@ -249,9 +249,9 @@ async function applyEffort(client, sessionId, model, value, modelOptions) {
|
|
|
249
249
|
* model?: string, fast?: boolean, effort?: string, context?: string,
|
|
250
250
|
* contextFiles?: string[], clientFactory?: (opts: any) => any,
|
|
251
251
|
* idleMs?: number, handshakeMs?: number, hardCapMs?: number, timeoutMs?: number,
|
|
252
|
-
* onClientReady?: (client: any) => void,
|
|
253
252
|
* onSessionReady?: (sessionId: string, client: any) => void,
|
|
254
|
-
* onPromptSent?: (sessionId: string) => void,
|
|
253
|
+
* onPromptSent?: (sessionId: string, resumeNote?: string) => void,
|
|
254
|
+
* onUnseenExit?: (note: string) => void,
|
|
255
255
|
* onTurnEnd?: () => void,
|
|
256
256
|
* onProgress?: (message: string) => void,
|
|
257
257
|
* progressThrottleMs?: number, heartbeatMs?: number, signal?: AbortSignal,
|
|
@@ -261,7 +261,7 @@ export async function runDelegate({
|
|
|
261
261
|
spec, mode = "agent", resumeSessionId, workspace,
|
|
262
262
|
model = DEFAULT_MODEL, fast = false, effort, context, contextFiles, clientFactory,
|
|
263
263
|
idleMs, handshakeMs, hardCapMs, timeoutMs,
|
|
264
|
-
|
|
264
|
+
onSessionReady, onPromptSent, onUnseenExit, onTurnEnd, onProgress, progressThrottleMs = 2000,
|
|
265
265
|
heartbeatMs = DEFAULT_HEARTBEAT_MS,
|
|
266
266
|
signal,
|
|
267
267
|
} = {}) {
|
|
@@ -269,7 +269,7 @@ export async function runDelegate({
|
|
|
269
269
|
// already fired. Throw, not supervisor.abort(): tripping before supervise() installs its reject
|
|
270
270
|
// settles the supervisor with nothing listening.
|
|
271
271
|
if (signal?.aborted) {
|
|
272
|
-
throw makeError("aborted", "delegation aborted by MCP host");
|
|
272
|
+
throw makeError("aborted", "delegation aborted by MCP host.");
|
|
273
273
|
}
|
|
274
274
|
// Before the spawn: validating later costs a process, a handshake and a billed turn.
|
|
275
275
|
assertWorkspace(workspace);
|
|
@@ -342,9 +342,6 @@ export async function runDelegate({
|
|
|
342
342
|
|
|
343
343
|
const make = clientFactory || ((opts) => new AcpClient(opts));
|
|
344
344
|
const client = make({ mode, onCreatePlan: state.recordCreatePlan, onTodos: state.recordTodos });
|
|
345
|
-
// Before the spawn, so the caller can stop the agent from its first moment; onSessionReady comes
|
|
346
|
-
// ~3.4s later, and a host exiting in between would leave the agent running.
|
|
347
|
-
onClientReady?.(client);
|
|
348
345
|
const supervisor = new SessionSupervisor(client, { idleMs: turnIdleMs, handshakeMs: shakeMs, hardCapMs: capMs });
|
|
349
346
|
const onAbort = () => supervisor.abort();
|
|
350
347
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
@@ -354,7 +351,8 @@ export async function runDelegate({
|
|
|
354
351
|
let promptInFlight = false;
|
|
355
352
|
let heartbeat = null;
|
|
356
353
|
const startHeartbeat = () => {
|
|
357
|
-
|
|
354
|
+
// Setup orphaned by a trip must not arm a timer the teardown has already cleared.
|
|
355
|
+
if (!(heartbeatMs > 0) || supervisor.settled) return;
|
|
358
356
|
const startedAt = Date.now();
|
|
359
357
|
heartbeat = setInterval(() => {
|
|
360
358
|
const parts = [
|
|
@@ -447,6 +445,10 @@ export async function runDelegate({
|
|
|
447
445
|
|
|
448
446
|
let sessionId;
|
|
449
447
|
let resumeError;
|
|
448
|
+
// Otherwise a resume hint reads as continuing work this session never had.
|
|
449
|
+
const resumeNote = () => (resumeError
|
|
450
|
+
? `resuming ${resumeSessionId} had already failed (${resumeError}), so this ran as a fresh session and none of that earlier work was in context.`
|
|
451
|
+
: undefined);
|
|
450
452
|
const unsupportedOptions = [];
|
|
451
453
|
let servedModel;
|
|
452
454
|
let effectiveEffort;
|
|
@@ -454,8 +456,8 @@ export async function runDelegate({
|
|
|
454
456
|
// Set before the teardown in finally, which notes an unseen exit on whichever is going out.
|
|
455
457
|
/** @type {any} */
|
|
456
458
|
let out;
|
|
457
|
-
/** @type {any} */
|
|
458
|
-
let
|
|
459
|
+
/** @type {{ cause: any, reason?: string, notes: string[] } | undefined} */
|
|
460
|
+
let failure;
|
|
459
461
|
try {
|
|
460
462
|
const res = await supervisor.supervise(async () => {
|
|
461
463
|
await client.start();
|
|
@@ -515,14 +517,13 @@ export async function runDelegate({
|
|
|
515
517
|
state.reset();
|
|
516
518
|
supervisor.promptStarted();
|
|
517
519
|
startHeartbeat();
|
|
518
|
-
promptInFlight = true;
|
|
519
520
|
try {
|
|
520
521
|
const blocks = await buildContextBlocks(contextFiles, workspace, client, contextWarnings);
|
|
521
|
-
//
|
|
522
|
-
|
|
522
|
+
// Raised with the prompt, so a frame sent while attachments were read is not folded in.
|
|
523
|
+
promptInFlight = true;
|
|
523
524
|
const turn = client.prompt(sessionId, [{ type: "text", text: promptText }, ...blocks]);
|
|
524
525
|
// Every argument has been accepted by now, so a caller may stop waiting on the result.
|
|
525
|
-
try { onPromptSent?.(sessionId); } catch {}
|
|
526
|
+
try { onPromptSent?.(sessionId, resumeNote()); } catch {}
|
|
526
527
|
return await turn;
|
|
527
528
|
} finally {
|
|
528
529
|
// The result is assembled across later awaits; a frame trailing the turn must not join it.
|
|
@@ -546,7 +547,7 @@ export async function runDelegate({
|
|
|
546
547
|
"the agent ran a tool after its last message and never spoke again, so no final message closed the turn."
|
|
547
548
|
+ " result carries the last message before that tool call — it may be a preamble rather than the answer."
|
|
548
549
|
);
|
|
549
|
-
} else if (!finalMessageAvailable
|
|
550
|
+
} else if (!finalMessageAvailable) {
|
|
550
551
|
protocolWarnings.push("the agent ended the turn without emitting any message; result is empty.");
|
|
551
552
|
}
|
|
552
553
|
let stopReason;
|
|
@@ -597,41 +598,47 @@ export async function runDelegate({
|
|
|
597
598
|
if (protocolWarnings.length) out.protocolWarnings = protocolWarnings;
|
|
598
599
|
return out;
|
|
599
600
|
} catch (err) {
|
|
601
|
+
// A cancel before the prompt is the outcome the caller asked for: there was no turn to fail.
|
|
602
|
+
if (err?.reason === "cancelled-in-setup" && sessionId) {
|
|
603
|
+
out = { result: "", sessionId, resultSource: "none", stopReason: "cancelled" };
|
|
604
|
+
if (resumeSessionId && sessionId === resumeSessionId) out.resumed = true;
|
|
605
|
+
if (resumeError) out.protocolWarnings = [`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`];
|
|
606
|
+
return out;
|
|
607
|
+
}
|
|
600
608
|
// A JSON-RPC code means the agent rejected something rather than the bridge breaking — the
|
|
601
609
|
// distinction a caller needs to tell "fix your arguments" from "retry".
|
|
602
|
-
|
|
610
|
+
const reason = err?.reason || (typeof err?.code === "number" ? "agent-error" : undefined);
|
|
611
|
+
failure = { cause: err, reason, notes: [] };
|
|
612
|
+
const { notes } = failure;
|
|
603
613
|
// A bare duration cannot distinguish a wedged agent from a slow command, so name what was
|
|
604
614
|
// outstanding — it also lets a retry resume the work already done.
|
|
605
|
-
const isTimeout =
|
|
615
|
+
const isTimeout = reason === "hard-cap" || reason === "idle-timeout";
|
|
606
616
|
// A handshake timeout gets the forensics but not the long-command advice: no prompt was sent,
|
|
607
617
|
// so no shell command explains the silence.
|
|
608
|
-
const isStall = isTimeout ||
|
|
609
|
-
|
|
618
|
+
const isStall = isTimeout || reason === "handshake-timeout";
|
|
619
|
+
// Not on an abort: a cancelled request gets no response, and a cancelled task keeps its own
|
|
620
|
+
// status message.
|
|
621
|
+
if (isStall || reason === "agent-exit") {
|
|
610
622
|
const age = fmtDuration(supervisor.msSinceActivity());
|
|
611
|
-
|
|
612
|
-
if (state.sessionTitle)
|
|
623
|
+
notes.push(`\n\nLast ACP frame ${age} ago${state.lastToolLabel ? `; last tool call: ${state.lastToolLabel}` : ""}.`);
|
|
624
|
+
if (state.sessionTitle) notes.push(` The agent titled this turn ${JSON.stringify(state.sessionTitle)}.`);
|
|
613
625
|
if (state.sawTodoFrame) {
|
|
614
626
|
const { todoProgress } = sanitizeTodos([]);
|
|
615
627
|
const current = state.todoLabel();
|
|
616
|
-
|
|
617
|
-
+ `${current ? `; ${current}` : ""}.`;
|
|
628
|
+
notes.push(` ${todoProgress.completed} of ${todoProgress.total} todos completed${current ? `; ${current}` : ""}.`);
|
|
618
629
|
}
|
|
619
630
|
const files = normalizeAgentReportedFiles([...state.touched], workspace);
|
|
620
|
-
if (files.length)
|
|
621
|
-
}
|
|
622
|
-
if (resumeError) {
|
|
623
|
-
// Otherwise the resume hint reads as continuing work this session never had.
|
|
624
|
-
err.message += ` Note: resuming ${resumeSessionId} had already failed (${resumeError}),`
|
|
625
|
-
+ ` so this ran as a fresh session and none of that earlier work was in context.`;
|
|
631
|
+
if (files.length) notes.push(` Files reported edited: ${files.join(", ")}.`);
|
|
626
632
|
}
|
|
633
|
+
if (resumeError) notes.push(` Note: ${resumeNote()}`);
|
|
627
634
|
// Any failure after session/new leaves a resumable session, unknown-model and a rejected
|
|
628
635
|
// config value included, not just the stalls.
|
|
629
|
-
if (sessionId)
|
|
636
|
+
if (sessionId) notes.push(` Resume with resumeSessionId ${sessionId}.`);
|
|
630
637
|
if (isTimeout) {
|
|
631
638
|
// Name the knob that fired: the hard cap does nothing for an idle-timeout.
|
|
632
|
-
const knob =
|
|
633
|
-
|
|
634
|
-
+ ` nothing until it exits. Split the command, run it in the background and poll, or raise ${knob}
|
|
639
|
+
const knob = reason === "idle-timeout" ? "CURSOR_DELEGATE_IDLE_MS" : "CURSOR_DELEGATE_HARD_CAP_MS";
|
|
640
|
+
notes.push(" cursor-agent does not stream shell output over ACP, so a long-running command emits"
|
|
641
|
+
+ ` nothing until it exits. Split the command, run it in the background and poll, or raise ${knob}.`);
|
|
635
642
|
}
|
|
636
643
|
// Opt-in: raw frames add nothing actionable to the caller's context beyond the forensics
|
|
637
644
|
// above; they help only someone debugging the bridge.
|
|
@@ -639,11 +646,9 @@ export async function runDelegate({
|
|
|
639
646
|
if (frames > 0) {
|
|
640
647
|
try {
|
|
641
648
|
const transcript = client.getTranscript?.(frames);
|
|
642
|
-
if (transcript)
|
|
649
|
+
if (transcript) notes.push(`\n\n--- recent ACP transcript (last ${frames} frames) ---\n` + transcript);
|
|
643
650
|
} catch {}
|
|
644
651
|
}
|
|
645
|
-
failed = err;
|
|
646
|
-
throw err;
|
|
647
652
|
} finally {
|
|
648
653
|
// The turn is decided: from here a cancel finds nothing running.
|
|
649
654
|
try { onTurnEnd?.(); } catch {}
|
|
@@ -651,17 +656,19 @@ export async function runDelegate({
|
|
|
651
656
|
signal?.removeEventListener("abort", onAbort);
|
|
652
657
|
try { supervisor.finish(); } catch {}
|
|
653
658
|
// Awaited: a host may close stdin on the result, and on Windows the server's exit does not take
|
|
654
|
-
// a running agent with it (server.smoke.test.js). An exit not seen is noted instead
|
|
655
|
-
//
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
if (exited === false) exited = await stopOnce();
|
|
659
|
+
// a running agent with it (server.smoke.test.js). An exit not seen is noted instead, as is a
|
|
660
|
+
// stop that rejects.
|
|
661
|
+
let exited = false;
|
|
662
|
+
try { exited = await client.stop(); } catch {}
|
|
659
663
|
if (exited === false) {
|
|
660
664
|
const pid = client.child?.pid;
|
|
661
665
|
const note = `the bridge stopped cursor-agent${pid ? ` (pid ${pid})` : ""} but did not see it exit; it may still be running.`;
|
|
662
|
-
|
|
663
|
-
if (failed) { try { failed.message += ` Note: ${note}`; } catch {} }
|
|
666
|
+
if (failure) failure.notes.push(` Note: ${note}`);
|
|
664
667
|
else if (out) (out.protocolWarnings ??= []).push(note);
|
|
668
|
+
try { onUnseenExit?.(note); } catch {}
|
|
665
669
|
}
|
|
666
670
|
}
|
|
671
|
+
// After teardown, so the exit note it adds is in the message.
|
|
672
|
+
const { cause, reason, notes } = /** @type {NonNullable<typeof failure>} */ (failure);
|
|
673
|
+
throw makeError(reason, (cause?.message || String(cause)) + notes.join(""), { code: cause?.code, cause });
|
|
667
674
|
}
|
package/src/doctor.js
CHANGED
|
@@ -1,17 +1,14 @@
|
|
|
1
1
|
import process from "node:process";
|
|
2
|
-
import { spawn } from "node:child_process";
|
|
3
2
|
import { existsSync } from "node:fs";
|
|
4
3
|
import { AcpClient } from "./acp-client.js";
|
|
5
|
-
import { commandExists, resolveAcpSpawn
|
|
6
|
-
import {
|
|
4
|
+
import { commandExists, resolveAcpSpawn } from "./spawn.js";
|
|
5
|
+
import { children, spawnChild } from "./proc.js";
|
|
7
6
|
import { readPackageVersion } from "./version.js";
|
|
8
7
|
import { describeOptions } from "./model-options.js";
|
|
9
8
|
|
|
10
9
|
const HANDSHAKE_TIMEOUT_MS = 15_000;
|
|
11
10
|
const VERSION_PROBE_TIMEOUT_MS = 10_000;
|
|
12
11
|
const PROBE_STDOUT_CAP = 64 * 1024;
|
|
13
|
-
// How long an aborted probe waits for its kill and close, as stop() bounds an agent's.
|
|
14
|
-
const PROBE_KILL_WAIT_MS = 2000;
|
|
15
12
|
const DEFAULT_LOG_SIZE = "2000";
|
|
16
13
|
|
|
17
14
|
function formatArg(value) {
|
|
@@ -39,9 +36,9 @@ function envReport(name, fallback = null) {
|
|
|
39
36
|
/**
|
|
40
37
|
* @param {{ command: string, args: string[], options?: any }} spawnSpec
|
|
41
38
|
* @param {number} [timeoutMs]
|
|
42
|
-
* @param {{ signal?: AbortSignal,
|
|
39
|
+
* @param {{ signal?: AbortSignal, registry?: import("./proc.js").ChildRegistry }} [opts]
|
|
43
40
|
*/
|
|
44
|
-
export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_MS, { signal,
|
|
41
|
+
export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_MS, { signal, registry = children } = {}) {
|
|
45
42
|
const { command, args, options } = spawnSpec;
|
|
46
43
|
const launcher = String(command || "").replace(/^["']|["']$/g, "");
|
|
47
44
|
const isJsScript = isJsLauncher(launcher);
|
|
@@ -54,10 +51,16 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
|
|
|
54
51
|
// Through a shell, a missing launcher still spawns (the shell does) and would read as found.
|
|
55
52
|
if (options?.shell && !isJsScript && !commandExists(launcher, options.env)) return Promise.resolve({ found: false, version: null });
|
|
56
53
|
const aborted = { version: null, error: "version probe aborted by MCP host" };
|
|
57
|
-
// Interrupted already: nothing is spawned, and found comes from the lookup alone.
|
|
58
|
-
|
|
59
|
-
|
|
54
|
+
// Interrupted already, or shutting down: nothing is spawned, and found comes from the lookup alone.
|
|
55
|
+
const notRun = (error) => Promise.resolve({ found: isJsScript ? existsSync(launcher) : commandExists(launcher, options?.env), version: null, error });
|
|
56
|
+
if (signal?.aborted) return notRun(aborted.error);
|
|
57
|
+
let probe;
|
|
58
|
+
try {
|
|
59
|
+
probe = spawnChild(execCommand, execArgs, options, { stdio: ["ignore", "pipe", "pipe"] }, registry);
|
|
60
|
+
} catch (err) {
|
|
61
|
+
return notRun(err.message);
|
|
60
62
|
}
|
|
63
|
+
const { child } = probe;
|
|
61
64
|
return new Promise((resolve) => {
|
|
62
65
|
let settled = false;
|
|
63
66
|
let aborting = false;
|
|
@@ -70,19 +73,12 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
|
|
|
70
73
|
signal?.removeEventListener("abort", onAbort);
|
|
71
74
|
resolve(result);
|
|
72
75
|
};
|
|
73
|
-
|
|
74
|
-
const child = spawn(argv.command, argv.args, { ...argv.options, detached: DETACHED, stdio: ["ignore", "pipe", "pipe"] });
|
|
75
|
-
// treeKill: on win32 a plain kill reaches only the wrapper, not the launcher.
|
|
76
|
-
const stop = () => (child.pid ? treeKill(child.pid, { childAlive: isChildAlive(child) }).catch(() => {}) : Promise.resolve());
|
|
77
|
-
onSpawn?.({ pid: child.pid, stop });
|
|
78
|
-
const closed = new Promise((r) => child.once("close", r));
|
|
79
|
-
// Settles once the probe has closed, so doctor does not return with it running.
|
|
76
|
+
// Settles once the stop saw the probe exit, so doctor does not return with it running.
|
|
80
77
|
const onAbort = () => {
|
|
81
78
|
// Else it fires during the kill and reports a timeout.
|
|
82
79
|
clearTimeout(timer);
|
|
83
80
|
aborting = true;
|
|
84
|
-
|
|
85
|
-
Promise.race([Promise.all([stop(), closed]), bound]).then(() => finish({ found: true, ...aborted }));
|
|
81
|
+
probe.stop().then(() => finish({ found: true, ...aborted }));
|
|
86
82
|
};
|
|
87
83
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
88
84
|
// Capped: a version is one line, and a launcher that streams is not kept whole.
|
|
@@ -94,6 +90,8 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
|
|
|
94
90
|
child.stderr?.on("error", () => {});
|
|
95
91
|
child.on("error", () => finish({ found: false, version: null }));
|
|
96
92
|
child.on("close", (code) => {
|
|
93
|
+
// Closed: its pid may be reused, so no later stop may kill it.
|
|
94
|
+
probe.release();
|
|
97
95
|
// An aborted probe reports the abort, not the exit its kill caused.
|
|
98
96
|
if (aborting) return;
|
|
99
97
|
const version = code === 0 ? stdout.trim() || null : null;
|
|
@@ -104,7 +102,8 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
|
|
|
104
102
|
});
|
|
105
103
|
});
|
|
106
104
|
timer = setTimeout(() => {
|
|
107
|
-
stop
|
|
105
|
+
// Not awaited, so the timeout returns on time; the probe stays tracked until its stop settles.
|
|
106
|
+
probe.stop();
|
|
108
107
|
// It spawned, so it is found; it just never answered.
|
|
109
108
|
finish({ found: true, version: null, error: `version probe timed out after ${timeoutMs}ms` });
|
|
110
109
|
}, timeoutMs);
|
|
@@ -112,11 +111,9 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
|
|
|
112
111
|
});
|
|
113
112
|
}
|
|
114
113
|
|
|
115
|
-
async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs, signal
|
|
114
|
+
async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs, signal }) {
|
|
116
115
|
if (signal?.aborted) return { ok: false, error: "Handshake aborted by MCP host" };
|
|
117
116
|
const client = clientFactory({ spawnSpec });
|
|
118
|
-
// Handed out before the spawn, so a server shutdown can stop it.
|
|
119
|
-
onClientReady?.(client);
|
|
120
117
|
const workspaceDir = workspace || process.cwd();
|
|
121
118
|
let timer;
|
|
122
119
|
let onAbort;
|
|
@@ -163,7 +160,6 @@ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs
|
|
|
163
160
|
}
|
|
164
161
|
|
|
165
162
|
/**
|
|
166
|
-
* onClientReady gets each process doctor starts, probe then agent, so a shutdown can stop it.
|
|
167
163
|
* @param {{
|
|
168
164
|
* getClientInfo?: () => { capabilities?: any, version?: any, protocolVersion?: string },
|
|
169
165
|
* deep?: boolean,
|
|
@@ -174,7 +170,6 @@ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs
|
|
|
174
170
|
* versionTimeoutMs?: number,
|
|
175
171
|
* readVersion?: () => string,
|
|
176
172
|
* signal?: AbortSignal,
|
|
177
|
-
* onClientReady?: (client: { stop: () => any }) => void,
|
|
178
173
|
* }} [opts]
|
|
179
174
|
*/
|
|
180
175
|
export async function runDoctor({
|
|
@@ -187,10 +182,9 @@ export async function runDoctor({
|
|
|
187
182
|
versionTimeoutMs = VERSION_PROBE_TIMEOUT_MS,
|
|
188
183
|
readVersion = readPackageVersion,
|
|
189
184
|
signal,
|
|
190
|
-
onClientReady,
|
|
191
185
|
} = {}) {
|
|
192
186
|
const { capabilities, version, protocolVersion } = getClientInfo();
|
|
193
|
-
const agentProbe = await probeAgentVersion(spawnSpec, versionTimeoutMs, { signal
|
|
187
|
+
const agentProbe = await probeAgentVersion(spawnSpec, versionTimeoutMs, { signal });
|
|
194
188
|
|
|
195
189
|
/** @type {{ plugin: any, client: any, agent: any & { handshake?: any }, runtime: any, env: any }} */
|
|
196
190
|
const out = {
|
|
@@ -233,7 +227,6 @@ export async function runDoctor({
|
|
|
233
227
|
workspace,
|
|
234
228
|
timeoutMs: handshakeTimeoutMs,
|
|
235
229
|
signal,
|
|
236
|
-
onClientReady,
|
|
237
230
|
});
|
|
238
231
|
}
|
|
239
232
|
|
package/src/errors.js
CHANGED
|
@@ -1,18 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Every failure carries a `reason`, so a caller can tell "fix your arguments" from "retry"
|
|
3
|
-
* without parsing prose. Errors off the wire also carry the agent's JSON-RPC `code`.
|
|
3
|
+
* without parsing prose. Errors off the wire also carry the agent's JSON-RPC `code`. A note goes on
|
|
4
|
+
* a new error with the old one as its `cause`: a caught error may be frozen or a primitive.
|
|
4
5
|
*
|
|
5
6
|
* @typedef {Error & { reason?: string, code?: number }} DelegateError
|
|
6
7
|
*/
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
|
-
* @param {string} reason
|
|
10
|
+
* @param {string | undefined} reason
|
|
10
11
|
* @param {string} message
|
|
11
|
-
* @
|
|
12
|
+
* @param {{ code?: number, cause?: unknown }} [extra]
|
|
13
|
+
* @returns {Readonly<DelegateError>}
|
|
12
14
|
*/
|
|
13
|
-
export function makeError(reason, message) {
|
|
15
|
+
export function makeError(reason, message, { code, cause } = {}) {
|
|
14
16
|
/** @type {DelegateError} */
|
|
15
|
-
const err = new Error(message);
|
|
16
|
-
err.reason = reason;
|
|
17
|
+
const err = new Error(message, cause === undefined ? undefined : { cause });
|
|
18
|
+
if (reason !== undefined) err.reason = reason;
|
|
19
|
+
if (code !== undefined) err.code = code;
|
|
17
20
|
return err;
|
|
18
21
|
}
|
package/src/jsonrpc.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import readline from "node:readline";
|
|
2
|
+
import { makeError } from "./errors.js";
|
|
2
3
|
|
|
3
4
|
const FRAME_CAP = 2048;
|
|
4
5
|
const DEFAULT_LOG_SIZE = 2000;
|
|
@@ -92,10 +93,7 @@ export class JsonRpcPeer {
|
|
|
92
93
|
this.pending.delete(key);
|
|
93
94
|
// cursor-agent puts the reason in error.data.message; error.message is a bare "Invalid params".
|
|
94
95
|
if (msg.error) {
|
|
95
|
-
|
|
96
|
-
const err = new Error([msg.error.message || "rpc error", msg.error.data?.message].filter(Boolean).join(": "));
|
|
97
|
-
err.code = msg.error.code;
|
|
98
|
-
p.reject(err);
|
|
96
|
+
p.reject(makeError(undefined, [msg.error.message || "rpc error", msg.error.data?.message].filter(Boolean).join(": "), { code: msg.error.code }));
|
|
99
97
|
}
|
|
100
98
|
else p.resolve(msg.result);
|
|
101
99
|
}
|
package/src/proc.js
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import process from "node:process";
|
|
2
|
-
import { execFile } from "node:child_process";
|
|
2
|
+
import { execFile, spawn } from "node:child_process";
|
|
3
|
+
import { spawnArgv } from "./spawn.js";
|
|
4
|
+
import { makeError } from "./errors.js";
|
|
3
5
|
|
|
4
6
|
export function isChildAlive(child) {
|
|
5
7
|
return child && child.exitCode === null && child.signalCode === null;
|
|
6
8
|
}
|
|
7
9
|
|
|
8
10
|
// POSIX only: a process group leader (setsid) lets treeKill reach the agent's children. On win32
|
|
9
|
-
// it would mean a new console, and taskkill /T walks the tree anyway. Applied
|
|
10
|
-
//
|
|
11
|
+
// it would mean a new console, and taskkill /T walks the tree anyway. Applied in spawnChild, not
|
|
12
|
+
// in resolveAcpSpawn, so an injected spec gets it too.
|
|
11
13
|
export const DETACHED = process.platform !== "win32";
|
|
12
14
|
|
|
13
15
|
// On win32 child.kill() reaches only the wrapper; taskkill /T takes the whole tree.
|
|
@@ -29,3 +31,101 @@ export async function treeKill(pid, { childAlive = true } = {}) {
|
|
|
29
31
|
// the child is gone, since a reaped pid can already belong to something else.
|
|
30
32
|
if (childAlive) { try { process.kill(pid, "SIGKILL"); } catch {} }
|
|
31
33
|
}
|
|
34
|
+
|
|
35
|
+
// How long one kill attempt waits for the exit and the tree kill. SIGKILL and taskkill /F land in
|
|
36
|
+
// milliseconds, so this elapses only when the kill failed.
|
|
37
|
+
export const KILL_WAIT_MS = 2000;
|
|
38
|
+
|
|
39
|
+
async function killAndSeeExit(child, timeoutMs) {
|
|
40
|
+
if (!child.pid) return true;
|
|
41
|
+
const alive = isChildAlive(child);
|
|
42
|
+
// Subscribed before the kill, so an instant exit is not missed.
|
|
43
|
+
const exited = alive
|
|
44
|
+
? /** @type {Promise<boolean>} */ (new Promise((resolve) => child.once("exit", () => resolve(true))))
|
|
45
|
+
: Promise.resolve(true);
|
|
46
|
+
// Runs for an exited child too: on POSIX the commands it spawned stay in its process group.
|
|
47
|
+
const killed = treeKill(child.pid, { childAlive: alive }).catch(() => {});
|
|
48
|
+
/** @type {NodeJS.Timeout | undefined} */
|
|
49
|
+
let timer;
|
|
50
|
+
const bounded = /** @type {Promise<boolean>} */ (new Promise((resolve) => {
|
|
51
|
+
timer = setTimeout(() => resolve(false), timeoutMs);
|
|
52
|
+
}));
|
|
53
|
+
const observed = await Promise.race([exited, bounded]);
|
|
54
|
+
// On win32 taskkill can still be at work on the tree once the launcher's exit is seen.
|
|
55
|
+
const treeKilled = await Promise.race([killed.then(() => true), bounded]);
|
|
56
|
+
clearTimeout(timer);
|
|
57
|
+
return observed && treeKilled;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* @typedef {{
|
|
62
|
+
* child: any,
|
|
63
|
+
* stop: (opts?: { timeoutMs?: number }) => Promise<boolean>,
|
|
64
|
+
* release: () => void,
|
|
65
|
+
* }} TrackedChild
|
|
66
|
+
* @typedef {{ child?: any, kill: (timeoutMs: number) => Promise<boolean> }} ChildKill
|
|
67
|
+
* @typedef {ReturnType<typeof createChildRegistry>} ChildRegistry
|
|
68
|
+
*/
|
|
69
|
+
|
|
70
|
+
// The processes still to stop. An entry leaves once a stop saw its exit and its tree kill ended, or
|
|
71
|
+
// its owner releases it; after that its pid may be reused.
|
|
72
|
+
export function createChildRegistry() {
|
|
73
|
+
/** @type {Set<TrackedChild>} */
|
|
74
|
+
const live = new Set();
|
|
75
|
+
let closed = false;
|
|
76
|
+
return {
|
|
77
|
+
/**
|
|
78
|
+
* @param {() => ChildKill} start
|
|
79
|
+
* @returns {TrackedChild}
|
|
80
|
+
*/
|
|
81
|
+
track(start) {
|
|
82
|
+
if (closed) throw makeError("spawn-failed", "the server is shutting down, so no process was started");
|
|
83
|
+
const kill = start();
|
|
84
|
+
/** @type {Promise<boolean> | null} */
|
|
85
|
+
let stopping = null;
|
|
86
|
+
const attempt = (timeoutMs) => {
|
|
87
|
+
try { return Promise.resolve(kill.kill(timeoutMs)).catch(() => false); } catch { return Promise.resolve(false); }
|
|
88
|
+
};
|
|
89
|
+
/** @type {TrackedChild} */
|
|
90
|
+
const entry = {
|
|
91
|
+
child: kill.child,
|
|
92
|
+
// An attempt that missed the exit is retried once; a later stop kills again.
|
|
93
|
+
stop: ({ timeoutMs = KILL_WAIT_MS } = {}) => {
|
|
94
|
+
if (!live.has(entry)) return Promise.resolve(true);
|
|
95
|
+
stopping ??= attempt(timeoutMs).then((seen) => seen || attempt(timeoutMs)).then((seen) => {
|
|
96
|
+
stopping = null;
|
|
97
|
+
if (seen) live.delete(entry);
|
|
98
|
+
return seen;
|
|
99
|
+
});
|
|
100
|
+
return stopping;
|
|
101
|
+
},
|
|
102
|
+
// For a child that closed by itself.
|
|
103
|
+
release: () => { if (!stopping) live.delete(entry); },
|
|
104
|
+
};
|
|
105
|
+
live.add(entry);
|
|
106
|
+
return entry;
|
|
107
|
+
},
|
|
108
|
+
// Each stop sends its kill as it starts, so on POSIX every kill is out before this returns.
|
|
109
|
+
stopAll() {
|
|
110
|
+
closed = true;
|
|
111
|
+
return Promise.all([...live].map((entry) => entry.stop())).then(() => undefined);
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export const children = createChildRegistry();
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* The one place a process starts, so shutdown reaches every one. Throws spawn-failed once shutdown
|
|
120
|
+
* began, before spawning.
|
|
121
|
+
* @param {string} command @param {string[]} args @param {any} options
|
|
122
|
+
* @param {{ stdio: any }} where
|
|
123
|
+
* @param {ChildRegistry} [registry]
|
|
124
|
+
*/
|
|
125
|
+
export function spawnChild(command, args, options, { stdio }, registry = children) {
|
|
126
|
+
return registry.track(() => {
|
|
127
|
+
const argv = spawnArgv(command, args, options);
|
|
128
|
+
const child = spawn(argv.command, argv.args, { ...argv.options, detached: DETACHED, stdio });
|
|
129
|
+
return { child, kill: (timeoutMs) => killAndSeeExit(child, timeoutMs) };
|
|
130
|
+
});
|
|
131
|
+
}
|
package/src/server.js
CHANGED
|
@@ -8,7 +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, readPackageVersion } from "./version.js";
|
|
11
|
-
import { DETACHED } from "./proc.js";
|
|
11
|
+
import { DETACHED, children } from "./proc.js";
|
|
12
12
|
import { PLAN_PRIORITIES, PLAN_STATUSES, TODO_STATUSES } from "./acp-enums.js";
|
|
13
13
|
import { TASKS_EXTENSION, createTaskStore, listsTasks, registerTaskHandlers, runAsTask } from "./tasks.js";
|
|
14
14
|
|
|
@@ -43,10 +43,6 @@ function unregisterInFlight(map, sessionId, handle) {
|
|
|
43
43
|
handles.delete(handle);
|
|
44
44
|
if (handles.size === 0) map.delete(sessionId);
|
|
45
45
|
}
|
|
46
|
-
// Delegations whose session has not opened yet: the agent runs ~3.4s before inFlight can key it.
|
|
47
|
-
// Shutdown walks this; cancel cannot, since the caller has no id for these yet.
|
|
48
|
-
const pendingDelegations = new Set();
|
|
49
|
-
|
|
50
46
|
// Session ids seen by this process, kept after the turn ends so cancel can tell a finished
|
|
51
47
|
// (still resumable) session from an id that never existed. Bounded.
|
|
52
48
|
const seenSessions = new Set();
|
|
@@ -158,7 +154,7 @@ export const doctorOutputShape = {
|
|
|
158
154
|
export const delegateInputSchema = z.object({
|
|
159
155
|
spec: z.string().trim().min(1, "spec must not be blank").describe("Task brief: goal, scope, fixed decisions quoted exactly, acceptance criteria. Sent as written. Point at files to read rather than pasting code, or attach them with contextFiles."),
|
|
160
156
|
mode: z.enum(["agent", "plan", "ask"]).default("agent").describe("agent implements; plan and ask are instructions to the agent, not limits."),
|
|
161
|
-
resumeSessionId: z.string().optional().describe("Continue an existing ACP session."),
|
|
157
|
+
resumeSessionId: z.string().optional().describe("Continue an existing ACP session. When delegate ran as an MCP task, its server-side task id works too."),
|
|
162
158
|
workspace: z.string().trim().min(1, "workspace must not be blank").describe("The agent's working directory, not a limit. Smallest directory holding the task's files; with no such directory the project root is the floor. Must already exist; never create one for the call."),
|
|
163
159
|
model: z.string().trim().min(1, "model must be a non-empty string").default(DEFAULT_MODEL).describe("Bare ACP family id, version included: composer-2.5, grok-4.5, claude-opus-5, gpt-5.6-sol. doctor deep:true lists every id."),
|
|
164
160
|
fast: z.boolean().default(false).describe("Fast tier; higher cost — only when the user asks."),
|
|
@@ -189,18 +185,18 @@ export function progressNotifier(ctx) {
|
|
|
189
185
|
* args: any, ctx?: any,
|
|
190
186
|
* runDelegate: (opts: any) => Promise<any>,
|
|
191
187
|
* inFlight: Map<string, Set<any>>,
|
|
192
|
-
* pending?: Set<any>,
|
|
193
188
|
* seenSessions?: Set<string>,
|
|
194
189
|
* signal?: AbortSignal,
|
|
195
190
|
* onProgress?: (message: string) => void,
|
|
196
|
-
* onPromptSent?: (sessionId: string) => void,
|
|
191
|
+
* onPromptSent?: (sessionId: string, handle: any, resumeNote?: string) => void,
|
|
192
|
+
* onUnseenExit?: (note: string) => void,
|
|
197
193
|
* onTurnEnd?: () => void,
|
|
198
194
|
* }} deps
|
|
199
195
|
* @returns {Promise<import("@modelcontextprotocol/server").CallToolResult>}
|
|
200
196
|
*/
|
|
201
197
|
export async function runDelegateTool({
|
|
202
|
-
args, ctx, runDelegate, inFlight,
|
|
203
|
-
signal = ctx?.mcpReq?.signal, onProgress = progressNotifier(ctx), onPromptSent, onTurnEnd,
|
|
198
|
+
args, ctx, runDelegate, inFlight, seenSessions = new Set(),
|
|
199
|
+
signal = ctx?.mcpReq?.signal, onProgress = progressNotifier(ctx), onPromptSent, onUnseenExit, onTurnEnd,
|
|
204
200
|
}) {
|
|
205
201
|
const { spec, mode, resumeSessionId, workspace, model, fast, effort, context, contextFiles } = args;
|
|
206
202
|
|
|
@@ -219,16 +215,11 @@ export async function runDelegateTool({
|
|
|
219
215
|
contextFiles,
|
|
220
216
|
onProgress,
|
|
221
217
|
signal,
|
|
222
|
-
onPromptSent,
|
|
223
|
-
|
|
224
|
-
handle = { client, cancelRequested: false };
|
|
225
|
-
pending.add(handle);
|
|
226
|
-
},
|
|
218
|
+
onPromptSent: onPromptSent && ((sessionId, resumeNote) => onPromptSent(sessionId, handle, resumeNote)),
|
|
219
|
+
onUnseenExit,
|
|
227
220
|
onSessionReady: (sessionId, client) => {
|
|
228
221
|
capturedSessionId = sessionId;
|
|
229
|
-
|
|
230
|
-
handle ??= { client, cancelRequested: false };
|
|
231
|
-
pending.delete(handle);
|
|
222
|
+
handle = { client, cancelRequested: false };
|
|
232
223
|
registerInFlight(inFlight, sessionId, handle);
|
|
233
224
|
rememberSession(seenSessions, sessionId);
|
|
234
225
|
// Sent now so a host that can call tools concurrently has an id to cancel mid-run.
|
|
@@ -248,9 +239,7 @@ export async function runDelegateTool({
|
|
|
248
239
|
isError: true,
|
|
249
240
|
};
|
|
250
241
|
} finally {
|
|
251
|
-
// Drops only this delegation's handle
|
|
252
|
-
// stays registered while another turn runs on it.
|
|
253
|
-
if (handle) pending.delete(handle);
|
|
242
|
+
// Drops only this delegation's handle; the id stays registered while another turn runs on it.
|
|
254
243
|
if (capturedSessionId) unregisterInFlight(inFlight, capturedSessionId, handle);
|
|
255
244
|
}
|
|
256
245
|
}
|
|
@@ -260,14 +249,13 @@ export async function runDelegateTool({
|
|
|
260
249
|
* runDelegate?: (opts: any) => Promise<any>,
|
|
261
250
|
* runDoctor?: (opts: any) => Promise<any>,
|
|
262
251
|
* forceGraceMs?: number,
|
|
263
|
-
* pending?: Set<any>,
|
|
264
252
|
* inFlight?: Map<string, Set<any>>,
|
|
265
253
|
* era?: "legacy" | "modern",
|
|
266
254
|
* tasks?: ReturnType<typeof createTaskStore>,
|
|
267
255
|
* }} [opts]
|
|
268
256
|
*/
|
|
269
257
|
export function buildServer({
|
|
270
|
-
runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000,
|
|
258
|
+
runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000,
|
|
271
259
|
inFlight: flights = inFlight, era, tasks = taskStore,
|
|
272
260
|
} = {}) {
|
|
273
261
|
const runDelegate = runDelegateInjected || runDelegateDefault;
|
|
@@ -282,6 +270,15 @@ export function buildServer({
|
|
|
282
270
|
}
|
|
283
271
|
);
|
|
284
272
|
if (servesTasks) registerTaskHandlers(server, tasks);
|
|
273
|
+
// A task id names its own run, which a later turn on the same session is not; a session id names
|
|
274
|
+
// every turn running on it.
|
|
275
|
+
/** @param {string} id */
|
|
276
|
+
const targetOf = (id) => {
|
|
277
|
+
const task = tasks.get(id);
|
|
278
|
+
if (!task?.sessionId) return { sessionId: id, handles: flights.get(id) };
|
|
279
|
+
const running = task.status === "working" && flights.get(task.sessionId)?.has(task.handle);
|
|
280
|
+
return { sessionId: task.sessionId, handles: new Set(running ? [task.handle] : []) };
|
|
281
|
+
};
|
|
285
282
|
|
|
286
283
|
server.registerTool(
|
|
287
284
|
"delegate",
|
|
@@ -298,8 +295,10 @@ export function buildServer({
|
|
|
298
295
|
},
|
|
299
296
|
},
|
|
300
297
|
async (args, ctx) => {
|
|
298
|
+
// Claude Code tells the model a task's id and never its session id, even after a stop.
|
|
299
|
+
const resumeSessionId = tasks.get(args.resumeSessionId)?.sessionId ?? args.resumeSessionId;
|
|
301
300
|
/** @param {Record<string, any>} [over] */
|
|
302
|
-
const run = (over) => runDelegateTool({ args, ctx, runDelegate, inFlight: flights,
|
|
301
|
+
const run = (over) => runDelegateTool({ args: { ...args, resumeSessionId }, ctx, runDelegate, inFlight: flights, seenSessions, ...over });
|
|
303
302
|
if (!servesTasks || !listsTasks(ctx)) return run();
|
|
304
303
|
return /** @type {any} */ (runAsTask({ run, signal: ctx?.mcpReq?.signal, notify: progressNotifier(ctx), store: tasks }));
|
|
305
304
|
}
|
|
@@ -312,7 +311,7 @@ export function buildServer({
|
|
|
312
311
|
"Best-effort cancel of an in-flight delegation by sessionId. session/cancel is advisory — the agent may finish the turn anyway, and the delegate result then carries cancelRequested. Status: cancelled, killed (agent process observed to exit), not-running (turn already ended, still resumable), not-found (id not in this process's recent session history).",
|
|
313
312
|
inputSchema: z.object({
|
|
314
313
|
// Blank is a malformed call, not a stale id.
|
|
315
|
-
sessionId: z.string().trim().min(1, "sessionId must not be blank"),
|
|
314
|
+
sessionId: z.string().trim().min(1, "sessionId must not be blank").describe("When delegate runs as an MCP task, its server-side task id works too."),
|
|
316
315
|
force: z.boolean().default(false).describe("Kill the agent process if the turn is still running after a short grace period."),
|
|
317
316
|
}),
|
|
318
317
|
annotations: {
|
|
@@ -323,16 +322,16 @@ export function buildServer({
|
|
|
323
322
|
openWorldHint: false,
|
|
324
323
|
},
|
|
325
324
|
},
|
|
326
|
-
async ({ sessionId, force }) => {
|
|
327
|
-
const handles =
|
|
325
|
+
async ({ sessionId: id, force }) => {
|
|
326
|
+
const { sessionId, handles } = targetOf(id);
|
|
328
327
|
if (!handles || handles.size === 0) {
|
|
329
328
|
// A finished session is still resumable; only an unknown id is not-found.
|
|
330
329
|
const known = seenSessions.has(sessionId);
|
|
331
330
|
return cancelResult(known ? "not-running" : "not-found", sessionId);
|
|
332
331
|
}
|
|
333
|
-
// Every turn
|
|
334
|
-
//
|
|
335
|
-
//
|
|
332
|
+
// Every turn the id names, taken now: a resume that registers during the grace or the kill is
|
|
333
|
+
// not swept in. An ended turn stays registered while its agent is stopped; its result is
|
|
334
|
+
// decided, so a cancel leaves it alone.
|
|
336
335
|
const targeted = [...handles].filter((handle) => !handle.ended);
|
|
337
336
|
if (targeted.length === 0) return cancelResult("not-running", sessionId);
|
|
338
337
|
for (const handle of targeted) handle.cancelRequested = true;
|
|
@@ -380,19 +379,8 @@ export function buildServer({
|
|
|
380
379
|
},
|
|
381
380
|
},
|
|
382
381
|
async ({ deep }, ctx) => {
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
try {
|
|
386
|
-
const out = await runDoctor({
|
|
387
|
-
deep,
|
|
388
|
-
signal: ctx?.mcpReq?.signal,
|
|
389
|
-
onClientReady: (client) => { const handle = { client }; handles.push(handle); pending.add(handle); },
|
|
390
|
-
getClientInfo: () => clientInfoOf(server, ctx),
|
|
391
|
-
});
|
|
392
|
-
return { content: [{ type: "text", text: JSON.stringify(out) }] };
|
|
393
|
-
} finally {
|
|
394
|
-
for (const handle of handles) pending.delete(handle);
|
|
395
|
-
}
|
|
382
|
+
const out = await runDoctor({ deep, signal: ctx?.mcpReq?.signal, getClientInfo: () => clientInfoOf(server, ctx) });
|
|
383
|
+
return { content: [{ type: "text", text: JSON.stringify(out) }] };
|
|
396
384
|
}
|
|
397
385
|
);
|
|
398
386
|
|
|
@@ -421,35 +409,34 @@ if (process.argv[1]) {
|
|
|
421
409
|
}
|
|
422
410
|
|
|
423
411
|
// Kill what is still running, then exit, on any way the host has of going away.
|
|
424
|
-
|
|
425
|
-
|
|
412
|
+
/** @param {import("./proc.js").ChildRegistry} [registry] */
|
|
413
|
+
export function installSignalCleanup(registry = children, {
|
|
426
414
|
exit = (code) => process.exit(code),
|
|
427
415
|
setExitCode = (code) => { process.exitCode = code; },
|
|
428
416
|
schedule = (fn) => setImmediate(fn),
|
|
429
417
|
stdin = process.stdin,
|
|
430
418
|
} = {}) {
|
|
431
419
|
let shuttingDown = false;
|
|
420
|
+
let signalsSeen = 0;
|
|
421
|
+
// The code shutdown exits with: a signal's, even when it follows the stdin EOF.
|
|
422
|
+
let exitCode = 0;
|
|
432
423
|
const shutdown = (code, fromSignal = false) => {
|
|
433
|
-
//
|
|
434
|
-
// hangup closes stdin
|
|
435
|
-
if (
|
|
424
|
+
// Only a second signal skips the wait for the kills, which the first pass already sent: a
|
|
425
|
+
// hangup closes stdin and sends SIGHUP, in either order.
|
|
426
|
+
if (fromSignal) signalsSeen++;
|
|
427
|
+
if (shuttingDown) {
|
|
428
|
+
if (fromSignal && signalsSeen === 1) { exitCode = code; setExitCode(code); }
|
|
429
|
+
return signalsSeen < 2 ? undefined : exit(code);
|
|
430
|
+
}
|
|
436
431
|
shuttingDown = true;
|
|
432
|
+
exitCode = code;
|
|
437
433
|
// Set now: the loop may run dry before the scheduled exit gets a turn.
|
|
438
434
|
setExitCode(code);
|
|
439
|
-
const stops = [];
|
|
440
|
-
// An unseen exit is not memoized, so a second stop dispatches a fresh kill before the exit.
|
|
441
|
-
const stopOnce = (handle) => Promise.resolve(handle.client.stop()).catch(() => false);
|
|
442
|
-
const dispatch = (handle) => {
|
|
443
|
-
try { stops.push(stopOnce(handle).then((exited) => (exited === false ? stopOnce(handle) : exited))); } catch {}
|
|
444
|
-
};
|
|
445
|
-
for (const handles of map.values()) for (const handle of handles) dispatch(handle);
|
|
446
|
-
// Delegations still in their handshake: their agent runs, and only pending reaches it.
|
|
447
|
-
for (const handle of pending) dispatch(handle);
|
|
448
435
|
// Waits for the kills: on Windows taskkill is a separate process, and exiting first orphans the
|
|
449
|
-
// launcher and agent below the shell (measured). stop
|
|
436
|
+
// launcher and agent below the shell (measured). Each stop bounds itself, so the wait is finite.
|
|
450
437
|
// The exit is scheduled onto a clean loop turn rather than run on the settlement stack.
|
|
451
|
-
const leave = () => schedule(() => exit(
|
|
452
|
-
|
|
438
|
+
const leave = () => schedule(() => exit(exitCode));
|
|
439
|
+
registry.stopAll().then(leave, leave);
|
|
453
440
|
};
|
|
454
441
|
// On POSIX each agent has its own process group, which a signal to this process misses, so the
|
|
455
442
|
// handler kills them first. SIGHUP too: a closed terminal, whose default leaves them running.
|
|
@@ -469,7 +456,7 @@ if (isMain) {
|
|
|
469
456
|
if (argv.includes("--version") || argv.includes("-v")) {
|
|
470
457
|
console.log(readPackageVersion());
|
|
471
458
|
} else {
|
|
472
|
-
installSignalCleanup(
|
|
459
|
+
installSignalCleanup();
|
|
473
460
|
// One factory serves both protocol eras: a 2025-era initialize pins a legacy instance, and only
|
|
474
461
|
// a modern one answers with tasks.
|
|
475
462
|
serveStdio(({ era }) => buildServer({ era }));
|
|
@@ -27,6 +27,7 @@ export class SessionSupervisor {
|
|
|
27
27
|
this.lastActivityAt = Date.now();
|
|
28
28
|
this._resetIdle();
|
|
29
29
|
};
|
|
30
|
+
this._onSetupCancel = () => this._trip("cancelled-in-setup", "cancelled before the prompt was sent");
|
|
30
31
|
this._onExit = (info) => {
|
|
31
32
|
this._trip(
|
|
32
33
|
"agent-exit",
|
|
@@ -40,6 +41,10 @@ export class SessionSupervisor {
|
|
|
40
41
|
this.sessionId = sessionId;
|
|
41
42
|
}
|
|
42
43
|
|
|
44
|
+
get settled() {
|
|
45
|
+
return this._settled;
|
|
46
|
+
}
|
|
47
|
+
|
|
43
48
|
msSinceActivity() {
|
|
44
49
|
return Date.now() - this.lastActivityAt;
|
|
45
50
|
}
|
|
@@ -49,6 +54,7 @@ export class SessionSupervisor {
|
|
|
49
54
|
this._armed = true;
|
|
50
55
|
this.client.on("activity", this._onActivity);
|
|
51
56
|
this.client.on("exit", this._onExit);
|
|
57
|
+
this.client.on("cancelled-in-setup", this._onSetupCancel);
|
|
52
58
|
this._hardCapTimer = setTimeout(() => {
|
|
53
59
|
this._trip("hard-cap", `Session hard-cap exceeded after ${this.hardCapMs}ms`);
|
|
54
60
|
}, this.hardCapMs);
|
|
@@ -72,6 +78,7 @@ export class SessionSupervisor {
|
|
|
72
78
|
this._armed = false;
|
|
73
79
|
this.client.off("activity", this._onActivity);
|
|
74
80
|
this.client.off("exit", this._onExit);
|
|
81
|
+
this.client.off("cancelled-in-setup", this._onSetupCancel);
|
|
75
82
|
clearTimeout(this._idleTimer);
|
|
76
83
|
clearTimeout(this._handshakeTimer);
|
|
77
84
|
clearTimeout(this._hardCapTimer);
|
|
@@ -90,7 +97,7 @@ export class SessionSupervisor {
|
|
|
90
97
|
}
|
|
91
98
|
|
|
92
99
|
abort() {
|
|
93
|
-
this._trip("aborted", "delegation aborted by MCP host");
|
|
100
|
+
this._trip("aborted", "delegation aborted by MCP host.");
|
|
94
101
|
}
|
|
95
102
|
|
|
96
103
|
_trip(reason, message) {
|
|
@@ -101,6 +108,8 @@ export class SessionSupervisor {
|
|
|
101
108
|
if (reason === "idle-timeout" || reason === "handshake-timeout" || reason === "hard-cap" || reason === "aborted") {
|
|
102
109
|
if (this.sessionId) { try { this.client.cancel(this.sessionId); } catch {} }
|
|
103
110
|
}
|
|
111
|
+
// Ended whether or not a session opened, so setup orphaned by this trip sends nothing more.
|
|
112
|
+
try { this.client.endTurn?.(); } catch {}
|
|
104
113
|
this._guardReject?.(err);
|
|
105
114
|
}
|
|
106
115
|
|
package/src/tasks.js
CHANGED
|
@@ -20,7 +20,7 @@ export function listsTasks(ctx) {
|
|
|
20
20
|
* @typedef {{
|
|
21
21
|
* taskId: string, status: "working" | "completed" | "failed" | "cancelled",
|
|
22
22
|
* createdAt: number, lastUpdatedAt: number, endedAt?: number, statusMessage?: string,
|
|
23
|
-
* sessionId?: string, turnEnded: boolean, ac: AbortController,
|
|
23
|
+
* sessionId?: string, handle?: any, resumeNote?: string, turnEnded: boolean, ac: AbortController,
|
|
24
24
|
* result?: any, error?: { code: number, message: string },
|
|
25
25
|
* }} Task
|
|
26
26
|
*/
|
|
@@ -38,8 +38,17 @@ export function createTaskStore({ now = Date.now, retainMs = RETAIN_MS, maxFinis
|
|
|
38
38
|
.sort((a, b) => /** @type {number} */ (a.endedAt) - /** @type {number} */ (b.endedAt));
|
|
39
39
|
for (const task of kept.slice(0, Math.max(0, kept.length - maxFinished))) tasks.delete(task.taskId);
|
|
40
40
|
};
|
|
41
|
+
// A fact that changes what to do after a cancel, such as an agent the stop did not see exit.
|
|
42
|
+
/** @param {Task} task @param {string} text */
|
|
43
|
+
const note = (task, text) => {
|
|
44
|
+
if (task.status !== "cancelled") return;
|
|
45
|
+
const base = task.statusMessage ?? "cancelled";
|
|
46
|
+
task.statusMessage = `${base}${base.endsWith(".") ? "" : "."} Note: ${text}`;
|
|
47
|
+
task.lastUpdatedAt = now();
|
|
48
|
+
};
|
|
41
49
|
return {
|
|
42
50
|
now,
|
|
51
|
+
note,
|
|
43
52
|
/** @returns {Task} */
|
|
44
53
|
create() {
|
|
45
54
|
const t = now();
|
|
@@ -49,10 +58,12 @@ export function createTaskStore({ now = Date.now, retainMs = RETAIN_MS, maxFinis
|
|
|
49
58
|
add(task) { prune(); tasks.set(task.taskId, task); },
|
|
50
59
|
/** @param {string} taskId */
|
|
51
60
|
get(taskId) { prune(); return tasks.get(taskId); },
|
|
61
|
+
// A cancelled task keeps its own status message: the run's error names the abort, a reason no
|
|
62
|
+
// blocking call returns.
|
|
52
63
|
/** @param {Task} task @param {{ result?: any, error?: any }} outcome */
|
|
53
64
|
finish(task, outcome) {
|
|
54
65
|
if (task.status === "working") {
|
|
55
|
-
task.endedAt = now();
|
|
66
|
+
task.endedAt = task.lastUpdatedAt = now();
|
|
56
67
|
if ("error" in outcome) {
|
|
57
68
|
task.status = "failed";
|
|
58
69
|
task.error = { code: ProtocolErrorCode.InternalError, message: String(outcome.error?.message ?? outcome.error) };
|
|
@@ -60,11 +71,7 @@ export function createTaskStore({ now = Date.now, retainMs = RETAIN_MS, maxFinis
|
|
|
60
71
|
task.status = "completed";
|
|
61
72
|
task.result = outcome.result;
|
|
62
73
|
}
|
|
63
|
-
} else if (outcome.result?.isError) {
|
|
64
|
-
// A cancelled run's own error names its resume id and an agent the stop did not see exit.
|
|
65
|
-
task.statusMessage = outcome.result.content?.[0]?.text ?? task.statusMessage;
|
|
66
74
|
}
|
|
67
|
-
task.lastUpdatedAt = now();
|
|
68
75
|
prune();
|
|
69
76
|
},
|
|
70
77
|
// A turn that has ended has its result decided, so a cancel leaves it, as the cancel tool does.
|
|
@@ -73,6 +80,7 @@ export function createTaskStore({ now = Date.now, retainMs = RETAIN_MS, maxFinis
|
|
|
73
80
|
if (task.status !== "working" || task.turnEnded) return;
|
|
74
81
|
task.status = "cancelled";
|
|
75
82
|
task.statusMessage = task.sessionId ? `cancelled; resume with resumeSessionId ${task.sessionId}` : "cancelled";
|
|
83
|
+
if (task.resumeNote) note(task, task.resumeNote);
|
|
76
84
|
task.endedAt = task.lastUpdatedAt = now();
|
|
77
85
|
task.ac.abort();
|
|
78
86
|
},
|
|
@@ -100,7 +108,7 @@ export function createTaskStore({ now = Date.now, retainMs = RETAIN_MS, maxFinis
|
|
|
100
108
|
* Runs a delegation that answers its request with a task once the prompt is sent. A run that
|
|
101
109
|
* settles before then, setup failures included, answers with its result as a blocking call does.
|
|
102
110
|
* @param {{
|
|
103
|
-
* run: (over: { signal: AbortSignal, onProgress: (m: string) => void, onPromptSent: (id: string) => void, onTurnEnd: () => void }) => Promise<any>,
|
|
111
|
+
* run: (over: { signal: AbortSignal, onProgress: (m: string) => void, onPromptSent: (id: string, handle?: any, resumeNote?: string) => void, onUnseenExit: (note: string) => void, onTurnEnd: () => void }) => Promise<any>,
|
|
104
112
|
* signal?: AbortSignal, notify?: (message: string) => void, store: ReturnType<typeof createTaskStore>,
|
|
105
113
|
* }} opts
|
|
106
114
|
*/
|
|
@@ -124,13 +132,13 @@ export async function runAsTask({ run, signal, notify = () => {}, store }) {
|
|
|
124
132
|
// Once the task is the answer, progress belongs to the task, not the request.
|
|
125
133
|
if (!answered) notify(message);
|
|
126
134
|
},
|
|
127
|
-
onPromptSent: (sessionId) => { task.sessionId = sessionId; markSent(); },
|
|
135
|
+
onPromptSent: (sessionId, handle, resumeNote) => { task.sessionId = sessionId; task.handle = handle; task.resumeNote = resumeNote; markSent(); },
|
|
136
|
+
onUnseenExit: (note) => store.note(task, note),
|
|
128
137
|
onTurnEnd: () => { task.turnEnded = true; },
|
|
129
138
|
}).then((result) => ({ result }), (error) => ({ error }));
|
|
130
139
|
const first = await Promise.race([sent, outcome]);
|
|
131
140
|
signal?.removeEventListener("abort", forward);
|
|
132
|
-
//
|
|
133
|
-
// prompt; the request is gone by then and nobody would receive the task id.
|
|
141
|
+
// A request cancelled as its prompt goes out is gone, so nobody would receive the task id.
|
|
134
142
|
const settled = first ?? (task.ac.signal.aborted ? await outcome : undefined);
|
|
135
143
|
if (settled) {
|
|
136
144
|
if ("error" in settled) throw settled.error;
|