cursor-delegate-mcp 3.1.0 → 3.2.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 +69 -0
- package/package.json +1 -1
- package/src/acp-client.js +20 -58
- package/src/delegate.js +40 -69
- package/src/doctor.js +16 -45
- package/src/errors.js +4 -3
- package/src/jsonrpc.js +11 -32
- package/src/proc.js +92 -77
- package/src/server.js +22 -153
- package/src/session-supervisor.js +6 -26
- package/src/shutdown.js +27 -0
- package/src/tasks.js +33 -23
package/src/jsonrpc.js
CHANGED
|
@@ -2,17 +2,8 @@ import readline from "node:readline";
|
|
|
2
2
|
import { makeError } from "./errors.js";
|
|
3
3
|
|
|
4
4
|
const FRAME_CAP = 2048;
|
|
5
|
-
const DEFAULT_LOG_SIZE = 2000;
|
|
6
5
|
|
|
7
|
-
|
|
8
|
-
if (raw === undefined) return DEFAULT_LOG_SIZE;
|
|
9
|
-
const n = Number(raw);
|
|
10
|
-
if (!Number.isFinite(n) || n < 0) return DEFAULT_LOG_SIZE;
|
|
11
|
-
return Math.floor(n);
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
// Depth for an unparseable CURSOR_DELEGATE_TRANSCRIPT. Not DEFAULT_LOG_SIZE: that bounds memory,
|
|
15
|
-
// this bounds what lands in the caller's context, so keep it near the old 40-frame dump.
|
|
6
|
+
// Depth for an unparseable CURSOR_DELEGATE_TRANSCRIPT; it bounds what lands in the caller's context.
|
|
16
7
|
const TRANSCRIPT_DEFAULT_FRAMES = 50;
|
|
17
8
|
|
|
18
9
|
// Frames CURSOR_DELEGATE_TRANSCRIPT asks for: unset or blank is none, a number is the count
|
|
@@ -41,10 +32,8 @@ export class JsonRpcPeer {
|
|
|
41
32
|
this.onActivity = onActivity || (() => {});
|
|
42
33
|
this.nextId = 1;
|
|
43
34
|
this.pending = new Map();
|
|
44
|
-
//
|
|
45
|
-
this._logSize =
|
|
46
|
-
// Only the opt-in failure transcript reads these frames, so record only when it is on.
|
|
47
|
-
this._recording = this._logSize > 0 && transcriptFrames() > 0;
|
|
35
|
+
// Only the opt-in failure transcript reads these frames, so only as many as it shows are kept.
|
|
36
|
+
this._logSize = transcriptFrames();
|
|
48
37
|
this._log = [];
|
|
49
38
|
this.rl = readline.createInterface({ input });
|
|
50
39
|
// readline re-emits the stream's error as its own, which acp-client's stdout handler does not
|
|
@@ -53,25 +42,16 @@ export class JsonRpcPeer {
|
|
|
53
42
|
this.rl.on("line", (line) => this._onLine(line));
|
|
54
43
|
}
|
|
55
44
|
|
|
56
|
-
// Overshoots by a quarter and trims in one batch, rather than shifting the array per frame;
|
|
57
|
-
// readers take the last _logSize.
|
|
58
45
|
_record(dir, line) {
|
|
59
|
-
if (!this.
|
|
60
|
-
|
|
61
|
-
this._log.
|
|
62
|
-
if (this._log.length > this._logSize + (this._logSize >> 2)) {
|
|
63
|
-
this._log = this._log.slice(-this._logSize);
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
_entries() {
|
|
68
|
-
return this._log.length > this._logSize ? this._log.slice(-this._logSize) : this._log;
|
|
46
|
+
if (!this._logSize) return;
|
|
47
|
+
this._log.push({ t: Date.now(), dir, line: line.length > FRAME_CAP ? line.slice(0, FRAME_CAP) : line });
|
|
48
|
+
if (this._log.length > this._logSize) this._log.shift();
|
|
69
49
|
}
|
|
70
50
|
|
|
71
|
-
getLog() { return [...this.
|
|
51
|
+
getLog() { return [...this._log]; }
|
|
72
52
|
|
|
73
53
|
formatLog(n) {
|
|
74
|
-
const entries = n !== undefined ? this.
|
|
54
|
+
const entries = n !== undefined ? this._log.slice(-n) : this._log;
|
|
75
55
|
return entries.map((e) => `${new Date(e.t).toISOString()} ${e.dir} ${e.line}`).join("\n");
|
|
76
56
|
}
|
|
77
57
|
|
|
@@ -81,8 +61,7 @@ export class JsonRpcPeer {
|
|
|
81
61
|
let msg;
|
|
82
62
|
try { msg = JSON.parse(line); } catch { return; }
|
|
83
63
|
if (msg === null || typeof msg !== "object" || Array.isArray(msg)) return;
|
|
84
|
-
// Only a parsed frame is activity; a blank line or launcher banner
|
|
85
|
-
// guard open.
|
|
64
|
+
// Only a parsed frame is activity; a blank line or launcher banner is not.
|
|
86
65
|
this.onActivity();
|
|
87
66
|
const hasId = msg.id !== undefined && msg.id !== null;
|
|
88
67
|
if (hasId && (msg.result !== undefined || msg.error !== undefined)) {
|
|
@@ -93,7 +72,7 @@ export class JsonRpcPeer {
|
|
|
93
72
|
this.pending.delete(key);
|
|
94
73
|
// cursor-agent puts the reason in error.data.message; error.message is a bare "Invalid params".
|
|
95
74
|
if (msg.error) {
|
|
96
|
-
p.reject(makeError(undefined, [msg.error.message || "rpc error", msg.error.data?.message].filter(Boolean).join(": "), { code: msg.error.code }));
|
|
75
|
+
p.reject(makeError(undefined, [msg.error.message || "rpc error", msg.error.data?.message].filter(Boolean).join(": "), { code: msg.error.code, method: p.method }));
|
|
97
76
|
}
|
|
98
77
|
else p.resolve(msg.result);
|
|
99
78
|
}
|
|
@@ -113,7 +92,7 @@ export class JsonRpcPeer {
|
|
|
113
92
|
request(method, params) {
|
|
114
93
|
const id = this.nextId++;
|
|
115
94
|
return new Promise((resolve, reject) => {
|
|
116
|
-
this.pending.set(String(id), { resolve, reject });
|
|
95
|
+
this.pending.set(String(id), { resolve, reject, method });
|
|
117
96
|
this._write({ jsonrpc: "2.0", id, method, params });
|
|
118
97
|
});
|
|
119
98
|
}
|
package/src/proc.js
CHANGED
|
@@ -7,108 +7,124 @@ export function isChildAlive(child) {
|
|
|
7
7
|
return child && child.exitCode === null && child.signalCode === null;
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
-
// POSIX only: a process group leader
|
|
11
|
-
// it would
|
|
12
|
-
// in resolveAcpSpawn, so an injected spec gets it too.
|
|
10
|
+
// POSIX only: detached makes the child a process group leader, so treeKill reaches its children.
|
|
11
|
+
// On win32 it would open a separate console, and taskkill /T walks the tree.
|
|
13
12
|
export const DETACHED = process.platform !== "win32";
|
|
14
13
|
|
|
15
|
-
//
|
|
14
|
+
// How long taskkill may run, and then how long a stop waits for the exit.
|
|
15
|
+
export const KILL_WAIT_MS = 5000;
|
|
16
|
+
|
|
17
|
+
// Every process below pid, from one ps snapshot. Empty when ps fails: the group kill still runs.
|
|
18
|
+
function descendantPids(pid) {
|
|
19
|
+
return /** @type {Promise<number[]>} */ (new Promise((resolve) => {
|
|
20
|
+
execFile("ps", ["-A", "-o", "pid=,ppid="], { timeout: 3000 }, (err, stdout) => {
|
|
21
|
+
if (err) return resolve([]);
|
|
22
|
+
/** @type {Map<number, number[]>} */
|
|
23
|
+
const byParent = new Map();
|
|
24
|
+
for (const line of String(stdout).split("\n")) {
|
|
25
|
+
const [p, pp] = line.trim().split(/\s+/).map(Number);
|
|
26
|
+
if (!p || !Number.isFinite(pp)) continue;
|
|
27
|
+
if (!byParent.has(pp)) byParent.set(pp, []);
|
|
28
|
+
byParent.get(pp)?.push(p);
|
|
29
|
+
}
|
|
30
|
+
const out = [];
|
|
31
|
+
const queue = [pid];
|
|
32
|
+
while (queue.length) {
|
|
33
|
+
for (const c of byParent.get(queue.shift()) ?? []) {
|
|
34
|
+
if (!out.includes(c)) { out.push(c); queue.push(c); }
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
resolve(out);
|
|
38
|
+
});
|
|
39
|
+
}));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// On win32 a plain kill reaches only the launcher; taskkill /T takes the tree. False when taskkill
|
|
43
|
+
// failed or stalled. Its 128 is a process that ended before taskkill reached it: the launcher, or a
|
|
44
|
+
// short-lived command during the walk (measured).
|
|
16
45
|
export async function treeKill(pid, { childAlive = true } = {}) {
|
|
17
|
-
if (!pid) return;
|
|
46
|
+
if (!pid) return true;
|
|
18
47
|
if (process.platform === "win32") {
|
|
19
|
-
//
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
execFile("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true }, () => resolve());
|
|
48
|
+
// An exited leader has no tree left for taskkill to walk, and its pid may be reused.
|
|
49
|
+
if (!childAlive) return true;
|
|
50
|
+
return /** @type {Promise<boolean>} */ (new Promise((resolve) => {
|
|
51
|
+
execFile("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true, timeout: KILL_WAIT_MS, killSignal: "SIGKILL" }, (err) => resolve(!err || err.code === 128));
|
|
24
52
|
}));
|
|
25
|
-
return;
|
|
26
53
|
}
|
|
27
|
-
//
|
|
28
|
-
//
|
|
54
|
+
// Commands in a session of their own are outside the group: walked while the child is alive to
|
|
55
|
+
// hold their parent links.
|
|
56
|
+
const descendants = childAlive ? await descendantPids(pid) : [];
|
|
57
|
+
// The group, even after the leader exited: members can outlive it.
|
|
29
58
|
try { process.kill(-pid, "SIGKILL"); } catch {}
|
|
30
|
-
|
|
31
|
-
|
|
59
|
+
for (const d of descendants) {
|
|
60
|
+
try { process.kill(-d, "SIGKILL"); } catch {}
|
|
61
|
+
try { process.kill(d, "SIGKILL"); } catch {}
|
|
62
|
+
}
|
|
63
|
+
// A child that is not a group leader; skipped once reaped, as its pid may be reused.
|
|
32
64
|
if (childAlive) { try { process.kill(pid, "SIGKILL"); } catch {} }
|
|
65
|
+
return true;
|
|
33
66
|
}
|
|
34
67
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
export const KILL_WAIT_MS = 2000;
|
|
68
|
+
/** @type {WeakMap<object, Promise<boolean>>} */
|
|
69
|
+
const stops = new WeakMap();
|
|
38
70
|
|
|
39
|
-
|
|
71
|
+
/**
|
|
72
|
+
* Kills child's tree, its own handle too when the tree kill fails, and waits for the exit within
|
|
73
|
+
* KILL_WAIT_MS. True when the exit was seen and the tree kill succeeded. Once per child: every later
|
|
74
|
+
* call gets the same promise.
|
|
75
|
+
* @param {any} child
|
|
76
|
+
* @returns {Promise<boolean>}
|
|
77
|
+
*/
|
|
78
|
+
export function stopChild(child) {
|
|
79
|
+
let stop = stops.get(child);
|
|
80
|
+
if (!stop) {
|
|
81
|
+
stop = killAndWait(child);
|
|
82
|
+
stops.set(child, stop);
|
|
83
|
+
}
|
|
84
|
+
return stop;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function killAndWait(child) {
|
|
40
88
|
if (!child.pid) return true;
|
|
41
89
|
const alive = isChildAlive(child);
|
|
42
|
-
// Subscribed before the kill, so an
|
|
43
|
-
const exited = alive
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
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;
|
|
90
|
+
// Subscribed before the kill, so an immediate exit is not missed.
|
|
91
|
+
const exited = alive ? new Promise((resolve) => child.once("exit", () => resolve(true))) : Promise.resolve(true);
|
|
92
|
+
const tidy = await treeKill(child.pid, { childAlive: alive }).catch(() => false);
|
|
93
|
+
if (!tidy && isChildAlive(child)) { try { child.kill("SIGKILL"); } catch {} }
|
|
94
|
+
return (await withDeadline(exited, KILL_WAIT_MS, false)) && tidy;
|
|
58
95
|
}
|
|
59
96
|
|
|
60
97
|
/**
|
|
61
|
-
*
|
|
62
|
-
*
|
|
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
|
|
98
|
+
* promise's value, or fallback once ms have passed.
|
|
99
|
+
* @template T @param {Promise<T>} promise @param {number} ms @param {T} fallback @returns {Promise<T>}
|
|
68
100
|
*/
|
|
101
|
+
export function withDeadline(promise, ms, fallback) {
|
|
102
|
+
/** @type {NodeJS.Timeout | undefined} */
|
|
103
|
+
let timer;
|
|
104
|
+
const deadline = new Promise((resolve) => { timer = setTimeout(() => resolve(fallback), ms); });
|
|
105
|
+
return Promise.race([promise, deadline]).finally(() => clearTimeout(timer));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** @typedef {ReturnType<typeof createChildRegistry>} ChildRegistry */
|
|
69
109
|
|
|
70
|
-
// The processes
|
|
71
|
-
// its owner releases it; after that its pid may be reused.
|
|
110
|
+
// The processes shutdown stops. A child leaves when it exits, as its pid may then be reused.
|
|
72
111
|
export function createChildRegistry() {
|
|
73
|
-
/** @type {Set<
|
|
112
|
+
/** @type {Set<any>} */
|
|
74
113
|
const live = new Set();
|
|
75
114
|
let closed = false;
|
|
76
115
|
return {
|
|
77
|
-
/**
|
|
78
|
-
* @param {() => ChildKill} start
|
|
79
|
-
* @returns {TrackedChild}
|
|
80
|
-
*/
|
|
116
|
+
/** @param {() => any} start a spawned child, or null */
|
|
81
117
|
track(start) {
|
|
82
118
|
if (closed) throw makeError("spawn-failed", "the server is shutting down, so no process was started");
|
|
83
|
-
const
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
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;
|
|
119
|
+
const child = start();
|
|
120
|
+
if (!child) return null;
|
|
121
|
+
live.add(child);
|
|
122
|
+
child.once("exit", () => live.delete(child));
|
|
123
|
+
return child;
|
|
107
124
|
},
|
|
108
|
-
// Each stop sends its kill as it starts, so on POSIX every kill is out before this returns.
|
|
109
125
|
stopAll() {
|
|
110
126
|
closed = true;
|
|
111
|
-
return Promise.all([...live].map(
|
|
127
|
+
return Promise.all([...live].map(stopChild)).then(() => undefined);
|
|
112
128
|
},
|
|
113
129
|
};
|
|
114
130
|
}
|
|
@@ -125,7 +141,6 @@ export const children = createChildRegistry();
|
|
|
125
141
|
export function spawnChild(command, args, options, { stdio }, registry = children) {
|
|
126
142
|
return registry.track(() => {
|
|
127
143
|
const argv = spawnArgv(command, args, options);
|
|
128
|
-
|
|
129
|
-
return { child, kill: (timeoutMs) => killAndSeeExit(child, timeoutMs) };
|
|
144
|
+
return spawn(argv.command, argv.args, { ...argv.options, detached: DETACHED, stdio });
|
|
130
145
|
});
|
|
131
146
|
}
|
package/src/server.js
CHANGED
|
@@ -3,13 +3,13 @@ import process from "node:process";
|
|
|
3
3
|
import { realpathSync } from "node:fs";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
5
|
import { McpServer, CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, PROTOCOL_VERSION_META_KEY } from "@modelcontextprotocol/server";
|
|
6
|
-
import { serveStdio } from "@modelcontextprotocol/server/stdio";
|
|
6
|
+
import { serveStdio, StdioServerTransport } from "@modelcontextprotocol/server/stdio";
|
|
7
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 {
|
|
12
|
-
import {
|
|
11
|
+
import { children } from "./proc.js";
|
|
12
|
+
import { installSignalCleanup } from "./shutdown.js";
|
|
13
13
|
import { TASKS_EXTENSION, createTaskStore, listsTasks, registerTaskHandlers, runAsTask } from "./tasks.js";
|
|
14
14
|
|
|
15
15
|
const ICON_BASE = `https://raw.githubusercontent.com/andreilungeanu/cursor-delegate-mcp/v${VERSION}/assets`;
|
|
@@ -44,16 +44,8 @@ function unregisterInFlight(map, sessionId, handle) {
|
|
|
44
44
|
if (handles.size === 0) map.delete(sessionId);
|
|
45
45
|
}
|
|
46
46
|
// Session ids seen by this process, kept after the turn ends so cancel can tell a finished
|
|
47
|
-
// (still resumable) session from an id that never existed.
|
|
47
|
+
// (still resumable) session from an id that never existed.
|
|
48
48
|
const seenSessions = new Set();
|
|
49
|
-
const SEEN_SESSIONS_CAP = 500;
|
|
50
|
-
function rememberSession(set, id) {
|
|
51
|
-
if (id == null) return;
|
|
52
|
-
// Delete-then-add makes the Set an LRU, so a session still being resumed outlives one seen once.
|
|
53
|
-
if (set.has(id)) set.delete(id);
|
|
54
|
-
set.add(id);
|
|
55
|
-
if (set.size > SEEN_SESSIONS_CAP) set.delete(set.values().next().value);
|
|
56
|
-
}
|
|
57
49
|
|
|
58
50
|
// Delegations answered as MCP tasks. Module-level, as inFlight: a task outlives the request that
|
|
59
51
|
// started it, and serveStdio may build more than one server instance.
|
|
@@ -63,100 +55,12 @@ const taskStore = createTaskStore();
|
|
|
63
55
|
// the parameter descriptions.
|
|
64
56
|
export const SERVER_INSTRUCTIONS = `Delegate coding work to Cursor through the delegate tool. Every permission the agent requests is auto-approved, in every mode: agent/plan/ask reach any file the user account can, and mode instructs the agent rather than limiting it. Scope workspace tightly and review the git diff after every run — filesReportedByEditTools carries only what the agent's edit tools reported; the diff is authoritative.`;
|
|
65
57
|
|
|
66
|
-
const planEntrySchema = z.object({
|
|
67
|
-
content: z.string(),
|
|
68
|
-
priority: z.enum(PLAN_PRIORITIES).optional(),
|
|
69
|
-
status: z.enum(PLAN_STATUSES).optional(),
|
|
70
|
-
}).passthrough();
|
|
71
|
-
|
|
72
|
-
// No outputSchema: it requires structuredContent too, and a host that reads both (Codex) puts the
|
|
73
|
-
// payload in context twice. Strict copy in delegate.test.js; field meanings in
|
|
74
|
-
// skills/delegate/reference.md.
|
|
75
|
-
export const delegateOutputShape = {
|
|
76
|
-
result: z.string(),
|
|
77
|
-
resultSource: z.enum(["pre-tool-fallback", "none"]).optional(),
|
|
78
|
-
effectiveModel: z.string().optional(),
|
|
79
|
-
effectiveEffort: z.record(z.string(), z.string()).optional(),
|
|
80
|
-
stopReason: z.string().optional(),
|
|
81
|
-
sessionId: z.string(),
|
|
82
|
-
filesReportedByEditTools: z.array(z.string()).optional(),
|
|
83
|
-
resumed: z.boolean().optional(),
|
|
84
|
-
cancelRequested: z.boolean().optional(),
|
|
85
|
-
protocolWarnings: z.array(z.string()).optional(),
|
|
86
|
-
plan: z.object({
|
|
87
|
-
entries: z.array(planEntrySchema),
|
|
88
|
-
overview: z.string().optional(),
|
|
89
|
-
detail: z.string().optional(),
|
|
90
|
-
}).optional(),
|
|
91
|
-
todos: z.array(z.object({
|
|
92
|
-
id: z.string(),
|
|
93
|
-
content: z.string(),
|
|
94
|
-
status: z.enum(TODO_STATUSES).optional(),
|
|
95
|
-
})).optional(),
|
|
96
|
-
todoProgress: z.object({
|
|
97
|
-
total: z.number(),
|
|
98
|
-
completed: z.number(),
|
|
99
|
-
inProgress: z.number(),
|
|
100
|
-
pending: z.number(),
|
|
101
|
-
cancelled: z.number(),
|
|
102
|
-
}).optional(),
|
|
103
|
-
};
|
|
104
|
-
|
|
105
|
-
// Same contract as delegateOutputShape; strict copy in doctor.test.js. Relayed agent fields stay
|
|
106
|
-
// unknown so an odd protocolVersion is a diagnostic, not a failed call. Handshake is its own
|
|
107
|
-
// shape because .strict() does not look inside a nested object.
|
|
108
|
-
export const doctorHandshakeShape = {
|
|
109
|
-
ok: z.boolean(),
|
|
110
|
-
error: z.string().optional(),
|
|
111
|
-
protocolVersion: z.unknown().optional(),
|
|
112
|
-
agentCapabilities: z.unknown().optional(),
|
|
113
|
-
models: z.array(z.unknown()).optional(),
|
|
114
|
-
currentModel: z.unknown().optional(),
|
|
115
|
-
modes: z.array(z.unknown()).optional(),
|
|
116
|
-
// Built here, not relayed, so it gets a real type.
|
|
117
|
-
currentModelOptions: z.array(z.object({
|
|
118
|
-
id: z.string(),
|
|
119
|
-
name: z.string().optional(),
|
|
120
|
-
category: z.string().optional(),
|
|
121
|
-
values: z.array(z.string()),
|
|
122
|
-
currentValue: z.string().optional(),
|
|
123
|
-
})).optional(),
|
|
124
|
-
};
|
|
125
|
-
|
|
126
|
-
export const doctorAgentShape = {
|
|
127
|
-
found: z.boolean(),
|
|
128
|
-
command: z.string(),
|
|
129
|
-
version: z.string().nullable(),
|
|
130
|
-
error: z.string().optional(),
|
|
131
|
-
handshake: z.object(doctorHandshakeShape).passthrough().optional(),
|
|
132
|
-
};
|
|
133
|
-
|
|
134
|
-
// agent is split out for the same reason as handshake.
|
|
135
|
-
export const doctorOutputShape = {
|
|
136
|
-
plugin: z.object({ version: z.string() }).passthrough(),
|
|
137
|
-
client: z.object({
|
|
138
|
-
name: z.string().nullable(),
|
|
139
|
-
version: z.string().nullable(),
|
|
140
|
-
capabilities: z.record(z.string(), z.unknown()),
|
|
141
|
-
protocolVersion: z.string().optional(),
|
|
142
|
-
}).passthrough(),
|
|
143
|
-
agent: z.object(doctorAgentShape).passthrough(),
|
|
144
|
-
runtime: z.object({
|
|
145
|
-
node: z.string(),
|
|
146
|
-
platform: z.string(),
|
|
147
|
-
arch: z.string(),
|
|
148
|
-
cwd: z.string(),
|
|
149
|
-
transport: z.literal("stdio"),
|
|
150
|
-
}),
|
|
151
|
-
env: z.record(z.string(), z.unknown()),
|
|
152
|
-
};
|
|
153
|
-
|
|
154
58
|
export const delegateInputSchema = z.object({
|
|
155
59
|
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."),
|
|
156
60
|
mode: z.enum(["agent", "plan", "ask"]).default("agent").describe("agent implements; plan and ask are instructions to the agent, not limits."),
|
|
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."),
|
|
61
|
+
resumeSessionId: z.string().trim().optional().describe("Continue an existing ACP session. When delegate ran as an MCP task, its server-side task id works too."),
|
|
158
62
|
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."),
|
|
159
|
-
model: z.string().trim().min(1, "model must be a non-empty string").default(DEFAULT_MODEL).describe(
|
|
63
|
+
model: z.string().trim().min(1, "model must be a non-empty string").default(DEFAULT_MODEL).describe(`Bare ACP family id, version included, such as ${DEFAULT_MODEL}. The ids on offer depend on the account; doctor deep:true lists them.`),
|
|
160
64
|
fast: z.boolean().default(false).describe("Fast tier; higher cost — only when the user asks."),
|
|
161
65
|
// Open string: a model's values are known only once it is selected, then validated live.
|
|
162
66
|
effort: z.string().trim().min(1).optional().describe("Exact Cursor thinking-effort value for the selected model. Values differ per model and some expose no effort option; invalid values fail before the prompt and name the accepted set. Pass only when the user asks for Cursor effort — the host's own reasoning setting is unrelated."),
|
|
@@ -189,14 +93,13 @@ export function progressNotifier(ctx) {
|
|
|
189
93
|
* signal?: AbortSignal,
|
|
190
94
|
* onProgress?: (message: string) => void,
|
|
191
95
|
* onPromptSent?: (sessionId: string, handle: any, resumeNote?: string) => void,
|
|
192
|
-
* onUnseenExit?: (note: string) => void,
|
|
193
96
|
* onTurnEnd?: () => void,
|
|
194
97
|
* }} deps
|
|
195
98
|
* @returns {Promise<import("@modelcontextprotocol/server").CallToolResult>}
|
|
196
99
|
*/
|
|
197
100
|
export async function runDelegateTool({
|
|
198
101
|
args, ctx, runDelegate, inFlight, seenSessions = new Set(),
|
|
199
|
-
signal = ctx?.mcpReq?.signal, onProgress = progressNotifier(ctx), onPromptSent,
|
|
102
|
+
signal = ctx?.mcpReq?.signal, onProgress = progressNotifier(ctx), onPromptSent, onTurnEnd,
|
|
200
103
|
}) {
|
|
201
104
|
const { spec, mode, resumeSessionId, workspace, model, fast, effort, context, contextFiles } = args;
|
|
202
105
|
|
|
@@ -206,7 +109,8 @@ export async function runDelegateTool({
|
|
|
206
109
|
const out = await runDelegate({
|
|
207
110
|
spec,
|
|
208
111
|
mode,
|
|
209
|
-
|
|
112
|
+
// Blank is no resume: hosts fill optional fields with "".
|
|
113
|
+
resumeSessionId: resumeSessionId || undefined,
|
|
210
114
|
workspace,
|
|
211
115
|
model,
|
|
212
116
|
fast,
|
|
@@ -216,12 +120,11 @@ export async function runDelegateTool({
|
|
|
216
120
|
onProgress,
|
|
217
121
|
signal,
|
|
218
122
|
onPromptSent: onPromptSent && ((sessionId, resumeNote) => onPromptSent(sessionId, handle, resumeNote)),
|
|
219
|
-
onUnseenExit,
|
|
220
123
|
onSessionReady: (sessionId, client) => {
|
|
221
124
|
capturedSessionId = sessionId;
|
|
222
125
|
handle = { client, cancelRequested: false };
|
|
223
126
|
registerInFlight(inFlight, sessionId, handle);
|
|
224
|
-
|
|
127
|
+
seenSessions.add(sessionId);
|
|
225
128
|
// Sent now so a host that can call tools concurrently has an id to cancel mid-run.
|
|
226
129
|
onProgress(`session ready: ${sessionId}`);
|
|
227
130
|
},
|
|
@@ -296,7 +199,7 @@ export function buildServer({
|
|
|
296
199
|
},
|
|
297
200
|
async (args, ctx) => {
|
|
298
201
|
// Claude Code tells the model a task's id and never its session id, even after a stop.
|
|
299
|
-
const resumeSessionId = tasks.
|
|
202
|
+
const resumeSessionId = tasks.sessionOf(args.resumeSessionId) ?? args.resumeSessionId;
|
|
300
203
|
/** @param {Record<string, any>} [over] */
|
|
301
204
|
const run = (over) => runDelegateTool({ args: { ...args, resumeSessionId }, ctx, runDelegate, inFlight: flights, seenSessions, ...over });
|
|
302
205
|
if (!servesTasks || !listsTasks(ctx)) return run();
|
|
@@ -308,7 +211,7 @@ export function buildServer({
|
|
|
308
211
|
"cancel",
|
|
309
212
|
{
|
|
310
213
|
description:
|
|
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
|
|
214
|
+
"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 session history).",
|
|
312
215
|
inputSchema: z.object({
|
|
313
216
|
// Blank is a malformed call, not a stale id.
|
|
314
217
|
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."),
|
|
@@ -352,7 +255,7 @@ export function buildServer({
|
|
|
352
255
|
const observed = await Promise.all(
|
|
353
256
|
toKill.map((handle) => Promise.resolve(handle.client.stop()).catch(() => false))
|
|
354
257
|
);
|
|
355
|
-
// "killed" needs an observed exit
|
|
258
|
+
// "killed" needs an observed exit.
|
|
356
259
|
if (!observed.every(Boolean)) return cancelResult("cancelled", sessionId);
|
|
357
260
|
for (const handle of toKill) unregisterInFlight(flights, sessionId, handle);
|
|
358
261
|
return cancelResult("killed", sessionId);
|
|
@@ -408,47 +311,6 @@ if (process.argv[1]) {
|
|
|
408
311
|
}
|
|
409
312
|
}
|
|
410
313
|
|
|
411
|
-
// Kill what is still running, then exit, on any way the host has of going away.
|
|
412
|
-
/** @param {import("./proc.js").ChildRegistry} [registry] */
|
|
413
|
-
export function installSignalCleanup(registry = children, {
|
|
414
|
-
exit = (code) => process.exit(code),
|
|
415
|
-
setExitCode = (code) => { process.exitCode = code; },
|
|
416
|
-
schedule = (fn) => setImmediate(fn),
|
|
417
|
-
stdin = process.stdin,
|
|
418
|
-
} = {}) {
|
|
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;
|
|
423
|
-
const shutdown = (code, fromSignal = false) => {
|
|
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
|
-
}
|
|
431
|
-
shuttingDown = true;
|
|
432
|
-
exitCode = code;
|
|
433
|
-
// Set now: the loop may run dry before the scheduled exit gets a turn.
|
|
434
|
-
setExitCode(code);
|
|
435
|
-
// Waits for the kills: on Windows taskkill is a separate process, and exiting first orphans the
|
|
436
|
-
// launcher and agent below the shell (measured). Each stop bounds itself, so the wait is finite.
|
|
437
|
-
// The exit is scheduled onto a clean loop turn rather than run on the settlement stack.
|
|
438
|
-
const leave = () => schedule(() => exit(exitCode));
|
|
439
|
-
registry.stopAll().then(leave, leave);
|
|
440
|
-
};
|
|
441
|
-
// On POSIX each agent has its own process group, which a signal to this process misses, so the
|
|
442
|
-
// handler kills them first. SIGHUP too: a closed terminal, whose default leaves them running.
|
|
443
|
-
if (DETACHED) {
|
|
444
|
-
const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]]);
|
|
445
|
-
for (const [signal, code] of signals) process.on(signal, () => shutdown(code, true));
|
|
446
|
-
}
|
|
447
|
-
// A stdio host closes stdin before it resorts to a signal. The SDK aborts in-flight requests on
|
|
448
|
-
// EOF; this also stops their agents directly, waits for the kills, and exits.
|
|
449
|
-
stdin.on("end", () => shutdown(0));
|
|
450
|
-
}
|
|
451
|
-
|
|
452
314
|
if (isMain) {
|
|
453
315
|
// Answered before the transport starts, so an install can be checked without a host. Reads the
|
|
454
316
|
// package.json beside this file: the code actually running, not what a manifest pinned.
|
|
@@ -456,9 +318,16 @@ if (isMain) {
|
|
|
456
318
|
if (argv.includes("--version") || argv.includes("-v")) {
|
|
457
319
|
console.log(readPackageVersion());
|
|
458
320
|
} else {
|
|
459
|
-
installSignalCleanup();
|
|
321
|
+
const hostGone = installSignalCleanup(() => children.stopAll());
|
|
322
|
+
const transport = new StdioServerTransport();
|
|
460
323
|
// One factory serves both protocol eras: a 2025-era initialize pins a legacy instance, and only
|
|
461
324
|
// a modern one answers with tasks.
|
|
462
|
-
serveStdio(({ era }) => buildServer({ era }));
|
|
325
|
+
serveStdio(({ era }) => buildServer({ era }), { transport });
|
|
326
|
+
// The transport also closes on a broken stdout, and then pauses stdin, so no 'end' arrives.
|
|
327
|
+
const closeServers = transport.onclose;
|
|
328
|
+
transport.onclose = () => {
|
|
329
|
+
closeServers?.();
|
|
330
|
+
hostGone();
|
|
331
|
+
};
|
|
463
332
|
}
|
|
464
333
|
}
|