cursor-delegate-mcp 1.12.0 → 1.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +7 -2
- package/src/acp-client.js +45 -12
- package/src/acp-enums.js +15 -0
- package/src/delegate.js +128 -341
- package/src/doctor.js +34 -3
- package/src/errors.js +20 -0
- package/src/jsonrpc.js +38 -9
- package/src/proc.js +2 -2
- package/src/request-router.js +16 -11
- package/src/server.js +108 -113
- package/src/session-supervisor.js +1 -5
- package/src/spawn.js +5 -0
- package/src/turn-state.js +193 -0
package/src/doctor.js
CHANGED
|
@@ -2,16 +2,22 @@ import process from "node:process";
|
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
3
|
import { AcpClient } from "./acp-client.js";
|
|
4
4
|
import { resolveAcpSpawn } from "./spawn.js";
|
|
5
|
+
import { treeKill } from "./proc.js";
|
|
5
6
|
import { readPackageVersion } from "./version.js";
|
|
6
7
|
|
|
7
8
|
const HANDSHAKE_TIMEOUT_MS = 15_000;
|
|
9
|
+
const VERSION_PROBE_TIMEOUT_MS = 10_000;
|
|
8
10
|
const DEFAULT_LOG_SIZE = "2000";
|
|
9
11
|
|
|
10
12
|
function formatCommand({ command, args }) {
|
|
11
13
|
return args?.length ? `${command} ${args.join(" ")}` : command;
|
|
12
14
|
}
|
|
13
15
|
|
|
14
|
-
|
|
16
|
+
// A launcher that accepts --version and then never answers used to hang doctor forever — and
|
|
17
|
+
// doctor is the tool you run when delegation is already broken, so a wedged agent is exactly
|
|
18
|
+
// the case it has to survive. Deep handshakes have always been time-boxed; this is that guard
|
|
19
|
+
// applied to the shallow probe that runs on every call.
|
|
20
|
+
export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_MS) {
|
|
15
21
|
const { command, options } = spawnSpec;
|
|
16
22
|
const isJsScript = /\.js$/i.test(command);
|
|
17
23
|
const execCommand = isJsScript ? process.execPath : command;
|
|
@@ -19,9 +25,11 @@ export function probeAgentVersion(spawnSpec) {
|
|
|
19
25
|
return new Promise((resolve) => {
|
|
20
26
|
let settled = false;
|
|
21
27
|
let stdout = "";
|
|
28
|
+
let timer;
|
|
22
29
|
const finish = (result) => {
|
|
23
30
|
if (settled) return;
|
|
24
31
|
settled = true;
|
|
32
|
+
clearTimeout(timer);
|
|
25
33
|
resolve(result);
|
|
26
34
|
};
|
|
27
35
|
const child = spawn(execCommand, execArgs, { ...options, stdio: ["ignore", "pipe", "pipe"] });
|
|
@@ -33,6 +41,15 @@ export function probeAgentVersion(spawnSpec) {
|
|
|
33
41
|
version: code === 0 ? stdout.trim() || null : null,
|
|
34
42
|
});
|
|
35
43
|
});
|
|
44
|
+
timer = setTimeout(() => {
|
|
45
|
+
// treeKill, not child.kill: the spawn spec carries shell:true on win32, where a plain
|
|
46
|
+
// kill only reaches the wrapper and leaves the launcher running.
|
|
47
|
+
if (child.pid) treeKill(child.pid).catch(() => {});
|
|
48
|
+
// The launcher exists — it spawned — it just never answered, which is a different
|
|
49
|
+
// diagnosis from "not installed" and has to read that way.
|
|
50
|
+
finish({ found: true, version: null, error: `version probe timed out after ${timeoutMs}ms` });
|
|
51
|
+
}, timeoutMs);
|
|
52
|
+
timer.unref?.();
|
|
36
53
|
});
|
|
37
54
|
}
|
|
38
55
|
|
|
@@ -68,6 +85,18 @@ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs
|
|
|
68
85
|
}
|
|
69
86
|
}
|
|
70
87
|
|
|
88
|
+
/**
|
|
89
|
+
* @param {{
|
|
90
|
+
* getClientInfo?: () => { capabilities?: any, version?: any },
|
|
91
|
+
* deep?: boolean,
|
|
92
|
+
* spawnSpec?: { command: string, args: string[], options?: object },
|
|
93
|
+
* clientFactory?: (opts: any) => any,
|
|
94
|
+
* workspace?: string,
|
|
95
|
+
* handshakeTimeoutMs?: number,
|
|
96
|
+
* versionTimeoutMs?: number,
|
|
97
|
+
* readVersion?: () => string,
|
|
98
|
+
* }} [opts]
|
|
99
|
+
*/
|
|
71
100
|
export async function runDoctor({
|
|
72
101
|
getClientInfo = () => ({ capabilities: {}, version: {} }),
|
|
73
102
|
deep = false,
|
|
@@ -75,23 +104,25 @@ export async function runDoctor({
|
|
|
75
104
|
clientFactory = (opts) => new AcpClient(opts),
|
|
76
105
|
workspace,
|
|
77
106
|
handshakeTimeoutMs = HANDSHAKE_TIMEOUT_MS,
|
|
107
|
+
versionTimeoutMs = VERSION_PROBE_TIMEOUT_MS,
|
|
78
108
|
readVersion = readPackageVersion,
|
|
79
109
|
} = {}) {
|
|
80
110
|
const { capabilities, version } = getClientInfo();
|
|
81
|
-
const agentProbe = await probeAgentVersion(spawnSpec);
|
|
111
|
+
const agentProbe = await probeAgentVersion(spawnSpec, versionTimeoutMs);
|
|
82
112
|
|
|
113
|
+
/** @type {{ plugin: any, client: any, agent: any & { handshake?: any }, runtime: any, env: any }} */
|
|
83
114
|
const out = {
|
|
84
115
|
plugin: { version: readVersion() },
|
|
85
116
|
client: {
|
|
86
117
|
name: version?.name ?? null,
|
|
87
118
|
version: version?.version ?? null,
|
|
88
119
|
capabilities: capabilities ?? {},
|
|
89
|
-
supportsElicitation: !!capabilities?.elicitation,
|
|
90
120
|
},
|
|
91
121
|
agent: {
|
|
92
122
|
found: agentProbe.found,
|
|
93
123
|
command: formatCommand(spawnSpec),
|
|
94
124
|
version: agentProbe.version,
|
|
125
|
+
...(agentProbe.error ? { error: agentProbe.error } : {}),
|
|
95
126
|
},
|
|
96
127
|
runtime: {
|
|
97
128
|
node: process.versions.node,
|
package/src/errors.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every failure this bridge raises carries a `reason`, which is what lets a caller tell
|
|
3
|
+
* "fix your arguments" from "retry" without parsing prose. Errors that came off the wire also
|
|
4
|
+
* carry the agent's JSON-RPC `code`. One shape, one constructor, so the tag is never forgotten
|
|
5
|
+
* and the type checker has something to check against.
|
|
6
|
+
*
|
|
7
|
+
* @typedef {Error & { reason?: string, code?: number }} DelegateError
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @param {string} reason
|
|
12
|
+
* @param {string} message
|
|
13
|
+
* @returns {DelegateError}
|
|
14
|
+
*/
|
|
15
|
+
export function makeError(reason, message) {
|
|
16
|
+
/** @type {DelegateError} */
|
|
17
|
+
const err = new Error(message);
|
|
18
|
+
err.reason = reason;
|
|
19
|
+
return err;
|
|
20
|
+
}
|
package/src/jsonrpc.js
CHANGED
|
@@ -1,8 +1,25 @@
|
|
|
1
1
|
import readline from "node:readline";
|
|
2
2
|
|
|
3
3
|
const FRAME_CAP = 2048;
|
|
4
|
+
const DEFAULT_LOG_SIZE = 2000;
|
|
5
|
+
|
|
6
|
+
function readLogSize(raw) {
|
|
7
|
+
if (raw === undefined) return DEFAULT_LOG_SIZE;
|
|
8
|
+
const n = Number(raw);
|
|
9
|
+
if (!Number.isFinite(n) || n < 0) return DEFAULT_LOG_SIZE;
|
|
10
|
+
return Math.floor(n);
|
|
11
|
+
}
|
|
4
12
|
|
|
5
13
|
export class JsonRpcPeer {
|
|
14
|
+
/**
|
|
15
|
+
* @param {import("node:stream").Readable} input
|
|
16
|
+
* @param {import("node:stream").Writable} output
|
|
17
|
+
* @param {{
|
|
18
|
+
* onNotification?: (method: string, params: any) => void,
|
|
19
|
+
* onRequest?: (id: any, method: string, params: any) => void,
|
|
20
|
+
* onActivity?: () => void,
|
|
21
|
+
* }} handlers
|
|
22
|
+
*/
|
|
6
23
|
constructor(input, output, { onNotification, onRequest, onActivity } = {}) {
|
|
7
24
|
this.output = output;
|
|
8
25
|
this.onNotification = onNotification || (() => {});
|
|
@@ -10,26 +27,34 @@ export class JsonRpcPeer {
|
|
|
10
27
|
this.onActivity = onActivity || (() => {});
|
|
11
28
|
this.nextId = 1;
|
|
12
29
|
this.pending = new Map();
|
|
13
|
-
|
|
14
|
-
|
|
30
|
+
// 0 disables recording and is documented; anything unparseable is a typo, and silently
|
|
31
|
+
// disabling the transcript on a typo is the opposite of what the setter wanted.
|
|
32
|
+
this._logSize = readLogSize(process.env.ACP_LOG_SIZE);
|
|
15
33
|
this._log = [];
|
|
16
34
|
this.rl = readline.createInterface({ input });
|
|
17
35
|
this.rl.on("line", (line) => this._onLine(line));
|
|
18
36
|
}
|
|
19
37
|
|
|
38
|
+
// Trimming to the cap on every frame meant shifting a 2000-entry array per frame, which on a
|
|
39
|
+
// chatty turn cost more than parsing the frames. Let the array overshoot by a quarter and trim
|
|
40
|
+
// in one batch; readers below take the last _logSize, so what the log reports is unchanged.
|
|
20
41
|
_record(dir, line) {
|
|
21
42
|
if (this._logSize <= 0) return;
|
|
22
43
|
const truncated = line.length > FRAME_CAP ? line.slice(0, FRAME_CAP) : line;
|
|
23
44
|
this._log.push({ t: Date.now(), dir, line: truncated });
|
|
24
|
-
if (this._log.length > this._logSize) {
|
|
25
|
-
this._log
|
|
45
|
+
if (this._log.length > this._logSize + (this._logSize >> 2)) {
|
|
46
|
+
this._log = this._log.slice(-this._logSize);
|
|
26
47
|
}
|
|
27
48
|
}
|
|
28
49
|
|
|
29
|
-
|
|
50
|
+
_entries() {
|
|
51
|
+
return this._log.length > this._logSize ? this._log.slice(-this._logSize) : this._log;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
getLog() { return [...this._entries()]; }
|
|
30
55
|
|
|
31
56
|
formatLog(n) {
|
|
32
|
-
const entries = n !== undefined ? this.
|
|
57
|
+
const entries = n !== undefined ? this._entries().slice(-n) : this._entries();
|
|
33
58
|
return entries.map((e) => `${new Date(e.t).toISOString()} ${e.dir} ${e.line}`).join("\n");
|
|
34
59
|
}
|
|
35
60
|
|
|
@@ -41,12 +66,16 @@ export class JsonRpcPeer {
|
|
|
41
66
|
try { msg = JSON.parse(line); } catch { return; }
|
|
42
67
|
const hasId = msg.id !== undefined && msg.id !== null;
|
|
43
68
|
if (hasId && (msg.result !== undefined || msg.error !== undefined)) {
|
|
44
|
-
|
|
69
|
+
// Keyed by string: a peer that echoes "1" for the id 1 is still answering that request,
|
|
70
|
+
// and matching by identity left it pending until a timeout fired an hour later.
|
|
71
|
+
const key = String(msg.id);
|
|
72
|
+
const p = this.pending.get(key);
|
|
45
73
|
if (p) {
|
|
46
|
-
this.pending.delete(
|
|
74
|
+
this.pending.delete(key);
|
|
47
75
|
// cursor-agent puts the actual reason in error.data.message; error.message alone
|
|
48
76
|
// is a bare "Invalid params".
|
|
49
77
|
if (msg.error) {
|
|
78
|
+
/** @type {import("./errors.js").DelegateError} */
|
|
50
79
|
const err = new Error([msg.error.message || "rpc error", msg.error.data?.message].filter(Boolean).join(": "));
|
|
51
80
|
err.code = msg.error.code;
|
|
52
81
|
p.reject(err);
|
|
@@ -69,7 +98,7 @@ export class JsonRpcPeer {
|
|
|
69
98
|
request(method, params) {
|
|
70
99
|
const id = this.nextId++;
|
|
71
100
|
return new Promise((resolve, reject) => {
|
|
72
|
-
this.pending.set(id, { resolve, reject });
|
|
101
|
+
this.pending.set(String(id), { resolve, reject });
|
|
73
102
|
this._write({ jsonrpc: "2.0", id, method, params });
|
|
74
103
|
});
|
|
75
104
|
}
|
package/src/proc.js
CHANGED
|
@@ -9,9 +9,9 @@ export function isChildAlive(child) {
|
|
|
9
9
|
// taskkill /T takes the whole tree so the agent itself dies too.
|
|
10
10
|
export async function treeKill(pid) {
|
|
11
11
|
if (process.platform === "win32") {
|
|
12
|
-
await new Promise((resolve) => {
|
|
12
|
+
await /** @type {Promise<void>} */ (new Promise((resolve) => {
|
|
13
13
|
execFile("taskkill", ["/PID", String(pid), "/T", "/F"], () => resolve());
|
|
14
|
-
});
|
|
14
|
+
}));
|
|
15
15
|
return;
|
|
16
16
|
}
|
|
17
17
|
try { process.kill(pid, "SIGKILL"); } catch {}
|
package/src/request-router.js
CHANGED
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
const ACK_METHODS = new Set(["cursor/task", "cursor/generate_image"]);
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
/**
|
|
4
|
+
* @param {{
|
|
5
|
+
* respond: (id: any, result: any) => void,
|
|
6
|
+
* respondError: (id: any, code: number, message: string) => void,
|
|
7
|
+
* onCreatePlan?: (body: any) => void,
|
|
8
|
+
* onTodos?: (body: any) => void,
|
|
9
|
+
* mode?: string,
|
|
10
|
+
* log?: (entry: any) => void,
|
|
11
|
+
* }} deps
|
|
12
|
+
*/
|
|
13
|
+
export function createRequestRouter({ respond, respondError, onCreatePlan, onTodos, mode = "agent", log = () => {} }) {
|
|
4
14
|
return async function handle(id, method, params) {
|
|
5
15
|
try {
|
|
6
16
|
if (method === "session/request_permission") {
|
|
@@ -9,16 +19,11 @@ export function createRequestRouter({ respond, respondError, onElicit, onCreateP
|
|
|
9
19
|
opts.find((o) => o.kind === "allow_always") ||
|
|
10
20
|
opts.find((o) => o.kind === "allow_once") ||
|
|
11
21
|
opts[0];
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
: null;
|
|
18
|
-
if (ans?.answers?.length) {
|
|
19
|
-
return respond(id, { outcome: { outcome: "answered", answers: ans.answers } });
|
|
20
|
-
}
|
|
21
|
-
return respond(id, { outcome: { outcome: "cancelled" } });
|
|
22
|
+
// Selecting nothing is not a selection: an options-less request answered with
|
|
23
|
+
// optionId undefined is a malformed ACP response. Say cancelled and let the agent
|
|
24
|
+
// decide what to do about it.
|
|
25
|
+
if (!pick?.optionId) return respond(id, { outcome: { outcome: "cancelled" } });
|
|
26
|
+
return respond(id, { outcome: { outcome: "selected", optionId: pick.optionId } });
|
|
22
27
|
}
|
|
23
28
|
if (method === "cursor/create_plan") {
|
|
24
29
|
onCreatePlan?.({
|
package/src/server.js
CHANGED
|
@@ -8,6 +8,7 @@ import { z } from "zod";
|
|
|
8
8
|
import { DEFAULT_MODEL, runDelegate as runDelegateDefault } from "./delegate.js";
|
|
9
9
|
import { runDoctor as runDoctorDefault } from "./doctor.js";
|
|
10
10
|
import { VERSION } from "./version.js";
|
|
11
|
+
import { PLAN_PRIORITIES, PLAN_STATUSES, TODO_STATUSES } from "./acp-enums.js";
|
|
11
12
|
|
|
12
13
|
const nodeMajor = Number(process.versions.node.split(".")[0]);
|
|
13
14
|
if (nodeMajor < 22) {
|
|
@@ -15,7 +16,22 @@ if (nodeMajor < 22) {
|
|
|
15
16
|
process.exit(1);
|
|
16
17
|
}
|
|
17
18
|
|
|
19
|
+
// sessionId -> the set of delegations currently running on it. A set, not a single handle,
|
|
20
|
+
// because a resume can race the turn it resumes: both are live, both are cancellable, and
|
|
21
|
+
// keying one handle per id let whichever finished first deregister the other — after which
|
|
22
|
+
// cancel reported a running session as already ended.
|
|
18
23
|
const inFlight = new Map();
|
|
24
|
+
function registerInFlight(map, sessionId, handle) {
|
|
25
|
+
const handles = map.get(sessionId);
|
|
26
|
+
if (handles) handles.add(handle);
|
|
27
|
+
else map.set(sessionId, new Set([handle]));
|
|
28
|
+
}
|
|
29
|
+
function unregisterInFlight(map, sessionId, handle) {
|
|
30
|
+
const handles = map.get(sessionId);
|
|
31
|
+
if (!handles) return;
|
|
32
|
+
handles.delete(handle);
|
|
33
|
+
if (handles.size === 0) map.delete(sessionId);
|
|
34
|
+
}
|
|
19
35
|
// Session ids seen this process, kept after the turn ends so cancel can tell a finished
|
|
20
36
|
// session (resumable, only the turn is over) from an id that never existed. Bounded so a
|
|
21
37
|
// long-lived server does not grow without limit.
|
|
@@ -34,14 +50,21 @@ export const SERVER_INSTRUCTIONS = `Delegate coding work to Cursor through the d
|
|
|
34
50
|
|
|
35
51
|
const planEntrySchema = z.object({
|
|
36
52
|
content: z.string(),
|
|
37
|
-
priority: z.enum(
|
|
38
|
-
status: z.enum(
|
|
53
|
+
priority: z.enum(PLAN_PRIORITIES).optional(),
|
|
54
|
+
status: z.enum(PLAN_STATUSES).optional(),
|
|
39
55
|
}).passthrough();
|
|
40
56
|
|
|
41
|
-
|
|
57
|
+
// Exported as a plain shape so tests can build a .strict() copy of it. Production stays
|
|
58
|
+
// passthrough — a field the agent adds must not fail a finished call — but that same
|
|
59
|
+
// tolerance means a field added in delegate.js and forgotten here would never be advertised
|
|
60
|
+
// to hosts, and nothing would complain. The strict copy is what complains.
|
|
61
|
+
export const delegateOutputShape = {
|
|
42
62
|
result: z.string(),
|
|
43
|
-
resultSource: z.enum(["pre-tool-fallback", "
|
|
44
|
-
"Present only as a caveat on result; absent on the happy path, where result is simply the agent's answer. pre-tool-fallback: no final message closed the turn and result is the last message before the agent's final tool call — read protocolWarnings before trusting it.
|
|
63
|
+
resultSource: z.enum(["pre-tool-fallback", "none"]).optional().describe(
|
|
64
|
+
"Present only as a caveat on result; absent on the happy path, where result is simply the agent's answer. pre-tool-fallback: no final message closed the turn and result is the last message before the agent's final tool call — read protocolWarnings before trusting it. none: the turn produced no message and result is empty."
|
|
65
|
+
),
|
|
66
|
+
effectiveModel: z.string().optional().describe(
|
|
67
|
+
"The model id the agent reported serving, present only when it differs from the model you requested — e.g. \"default\" resolving to a concrete id, or a cross-model resume. Read from the agent's post-set_model config report; absent when the agent confirmed the requested id or reported no model (some models report none)."
|
|
45
68
|
),
|
|
46
69
|
stopReason: z.string().optional().describe(
|
|
47
70
|
"Present only when it is not the ordinary end_turn — a refusal, a cancel, or an output cap. Absence means the turn ended normally."
|
|
@@ -50,55 +73,74 @@ const delegateOutputSchema = z.object({
|
|
|
50
73
|
filesReportedByEditTools: z.array(z.string()).optional().describe(
|
|
51
74
|
"Files the agent's edit tools reported changing, via native ACP diff events. Absent when they reported none — which is not proof nothing changed: shell-driven edits leave no diff event; the git diff is authoritative."
|
|
52
75
|
),
|
|
53
|
-
questionsAsked: z.array(z.string()).optional().describe(
|
|
54
|
-
"Clarifying questions the agent raised through elicitation. Absent on most turns — the agent usually asks in prose and ends the turn, which this does not capture; read result for that."
|
|
55
|
-
),
|
|
56
76
|
resumed: z.boolean().optional().describe(
|
|
57
77
|
"Present and true only when a requested resume took (the returned session id matched resumeSessionId). Absent for a fresh session, or when a resume failed — a failed resume is reported in protocolWarnings."
|
|
58
78
|
),
|
|
59
|
-
autoAnswered: z.array(z.object({ prompt: z.string(), chosen: z.string() })).optional(),
|
|
60
|
-
fallbackAnswers: z.array(z.object({ prompt: z.string(), given: z.string(), chosen: z.string() })).optional(),
|
|
61
79
|
cancelRequested: z.boolean().optional(),
|
|
62
80
|
protocolWarnings: z.array(z.string()).optional().describe(
|
|
63
|
-
"Non-fatal diagnostics that did not justify failing the call — dropped or sanitized ACP fields, a failed resume, ignored model options, skipped contextFiles
|
|
81
|
+
"Non-fatal diagnostics that did not justify failing the call — dropped or sanitized ACP fields, a failed resume, ignored model options, skipped contextFiles. Read whenever present."
|
|
64
82
|
),
|
|
65
83
|
plan: z.object({
|
|
66
84
|
entries: z.array(planEntrySchema),
|
|
67
85
|
overview: z.string().optional(),
|
|
68
86
|
detail: z.string().optional(),
|
|
69
87
|
}).optional().describe(
|
|
70
|
-
"The agent's plan. entries and overview are the structured plan and always present when a plan exists. detail (a prose rendition the agent also filed) is kept only in agent mode; in plan/ask it is dropped because result already carries the
|
|
88
|
+
"The agent's plan. entries and overview are the structured plan and always present when a plan exists. detail (a prose rendition the agent also filed) is kept only in agent mode; in plan/ask it is dropped because result already carries the agent's own plan message. To act on a plan, resume the sessionId rather than forwarding detail: the plan lives in the agent's session."
|
|
71
89
|
),
|
|
72
90
|
todos: z.array(z.object({
|
|
73
91
|
id: z.string(),
|
|
74
92
|
content: z.string(),
|
|
75
|
-
status: z.enum(
|
|
93
|
+
status: z.enum(TODO_STATUSES).optional(),
|
|
76
94
|
})).optional().describe(
|
|
77
95
|
"Todo items the agent left unfinished, present only when todoProgress shows completed < total — read it to see what remains before resuming. Absent both when the agent tracked no todos (common on short tasks) and when everything tracked was completed; todoProgress tells those apart."
|
|
78
96
|
),
|
|
79
|
-
modeChanged: z.object({ from: z.string(), to: z.string() }).optional().describe(
|
|
80
|
-
"Set when the agent switched itself out of the requested mode mid-session. Absence does not mean the mode was honored — an agent can write while staying in plan."
|
|
81
|
-
),
|
|
82
|
-
writeCapableActivity: z.array(z.object({ kind: z.string(), detail: z.string(), path: z.string().optional() })).optional().describe(
|
|
83
|
-
"Write-capable tool calls (edit/delete/move/execute) the agent ran during a plan or ask turn, which are expected to change nothing. Records what ran, not what changed — kind is what the tool could do, not proof it wrote: an execute entry may be a read-only command like `ls -la`. Read detail for the evidence and the git diff for the truth. Only populated for mode plan and ask."
|
|
84
|
-
),
|
|
85
97
|
todoProgress: z.object({
|
|
86
98
|
total: z.number(),
|
|
87
99
|
completed: z.number(),
|
|
88
100
|
inProgress: z.number(),
|
|
89
101
|
pending: z.number(),
|
|
90
102
|
}).optional(),
|
|
91
|
-
}
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
const delegateOutputSchema = z.object(delegateOutputShape).passthrough();
|
|
92
106
|
|
|
93
|
-
|
|
107
|
+
// What doctor reports about the launcher. Only `found` was advertised before, so `command`,
|
|
108
|
+
// `version`, `error` and the whole deep handshake reached hosts undeclared — the same drift
|
|
109
|
+
// delegateOutputShape exists to prevent, one level further down.
|
|
110
|
+
//
|
|
111
|
+
// Fields this bridge computes are typed; fields relayed verbatim from the agent are left
|
|
112
|
+
// unknown on purpose. The SDK validates structuredContent against this schema and throws when
|
|
113
|
+
// it does not fit, and doctor is what you run when the agent is already misbehaving: a schema
|
|
114
|
+
// tight enough to reject a weird protocolVersion would turn the diagnostic into a crash.
|
|
115
|
+
export const doctorAgentShape = {
|
|
116
|
+
found: z.boolean().describe("Whether the launcher command could be spawned at all."),
|
|
117
|
+
command: z.string().describe("The resolved launcher command line, with ACP_AGENT_COMMAND/ACP_AGENT_ARGS applied."),
|
|
118
|
+
version: z.string().nullable().describe(
|
|
119
|
+
"The launcher's --version output, or null when it could not be read. found:false means it is not installed; found:true with a null version means it exists but did not answer — error says why."
|
|
120
|
+
),
|
|
121
|
+
error: z.string().optional().describe("Why version is null on a launcher that does exist, e.g. the probe timed out."),
|
|
122
|
+
handshake: z.object({
|
|
123
|
+
ok: z.boolean(),
|
|
124
|
+
error: z.string().optional().describe("Present when ok is false: what the handshake failed on, e.g. not logged in, or a timeout."),
|
|
125
|
+
protocolVersion: z.unknown().optional().describe("As reported by the agent; null when it reported none."),
|
|
126
|
+
agentCapabilities: z.unknown().optional(),
|
|
127
|
+
models: z.array(z.unknown()).optional().describe("Model ids the agent offers for a new session."),
|
|
128
|
+
currentModel: z.unknown().optional(),
|
|
129
|
+
modes: z.array(z.unknown()).optional().describe("Session mode ids the agent offers."),
|
|
130
|
+
}).passthrough().optional().describe("Present only when deep is true. Everything past ok and error is absent when ok is false."),
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
// Exported as a shape for the same reason as delegateOutputShape, and with agent split out
|
|
134
|
+
// because a top-level .strict() does not look inside a nested object — which is exactly where
|
|
135
|
+
// this schema drifted.
|
|
136
|
+
export const doctorOutputShape = {
|
|
94
137
|
plugin: z.object({ version: z.string() }).passthrough(),
|
|
95
138
|
client: z.object({
|
|
96
139
|
name: z.string().nullable(),
|
|
97
140
|
version: z.string().nullable(),
|
|
98
141
|
capabilities: z.record(z.unknown()),
|
|
99
|
-
supportsElicitation: z.boolean(),
|
|
100
142
|
}).passthrough(),
|
|
101
|
-
agent: z.object(
|
|
143
|
+
agent: z.object(doctorAgentShape).passthrough(),
|
|
102
144
|
runtime: z.object({
|
|
103
145
|
node: z.string(),
|
|
104
146
|
platform: z.string(),
|
|
@@ -107,11 +149,13 @@ const doctorOutputSchema = z.object({
|
|
|
107
149
|
transport: z.literal("stdio"),
|
|
108
150
|
}),
|
|
109
151
|
env: z.record(z.unknown()),
|
|
110
|
-
}
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
const doctorOutputSchema = z.object(doctorOutputShape).passthrough();
|
|
111
155
|
|
|
112
156
|
export const delegateInputSchema = z.object({
|
|
113
157
|
spec: z.string().trim().min(1, "spec must not be blank").describe("Inline task brief (default): goal, scope, decisions already made (constraints and fixed choices — quote the user's exact values verbatim), acceptance criteria. Point at files to read or mimic rather than pasting code. Optional file path if the user wants a persisted spec."),
|
|
114
|
-
mode: z.enum(["agent", "plan", "ask"]).default("agent").describe("Requested agent mode. plan and ask are passed to the agent as instructions, not enforced by the bridge — the agent may write in any of them
|
|
158
|
+
mode: z.enum(["agent", "plan", "ask"]).default("agent").describe("Requested agent mode. plan and ask are passed to the agent as instructions, not enforced by the bridge — the agent may write in any of them, so review the git diff after every run. ask held on every model tested while plan compliance varies by model, so prefer ask when you need the stricter read-only instruction."),
|
|
115
159
|
resumeSessionId: z.string().optional().describe("Resume an existing ACP session instead of a new one"),
|
|
116
160
|
workspace: z.string().optional().describe("Working directory for the agent (defaults to cwd). Must be an existing directory; the call fails rather than creating it."),
|
|
117
161
|
model: z.string().trim().min(1, "model must be a non-empty string").default(DEFAULT_MODEL),
|
|
@@ -121,28 +165,22 @@ export const delegateInputSchema = z.object({
|
|
|
121
165
|
reasoning: z.string().trim().min(1).optional().describe("Reasoning effort. Not offered by every model; gpt-5.x accepts none, low, medium, high, extra-high."),
|
|
122
166
|
context: z.string().trim().min(1).optional().describe("Context window size. Not offered by every model; gpt-5.x accepts 272k and 1m."),
|
|
123
167
|
contextFiles: z.array(z.string()).optional().describe("Paths to attach instead of pasting file contents into spec. Text files are passed as references the agent may open; images (png, jpg, gif, webp, under 5MB) are sent inline. Relative paths resolve against workspace, and paths outside it are allowed — attach only files the agent should read. Anything skipped is reported in protocolWarnings, never fatal."),
|
|
124
|
-
maxResultChars: z.number().int().positive().optional().describe("Cap the returned result to this many characters. A longer result is truncated with a marker and a protocolWarning, so a runaway agent reply cannot blow up your context; the truncation is never reported as a complete answer."),
|
|
125
168
|
});
|
|
126
169
|
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
}
|
|
139
|
-
return ids;
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
export async function runDelegateTool({ args, extra, server, runDelegate, inFlight, seenSessions = new Set() }) {
|
|
143
|
-
const { spec, mode, resumeSessionId, workspace, model, fast, reasoning, context, contextFiles, maxResultChars } = args;
|
|
170
|
+
/**
|
|
171
|
+
* @param {{
|
|
172
|
+
* args: any, extra?: any,
|
|
173
|
+
* runDelegate: (opts: any) => Promise<any>,
|
|
174
|
+
* inFlight: Map<string, Set<any>>,
|
|
175
|
+
* seenSessions?: Set<string>,
|
|
176
|
+
* }} deps
|
|
177
|
+
* @returns {Promise<import("@modelcontextprotocol/sdk/types.js").CallToolResult>}
|
|
178
|
+
*/
|
|
179
|
+
export async function runDelegateTool({ args, extra, runDelegate, inFlight, seenSessions = new Set() }) {
|
|
180
|
+
const { spec, mode, resumeSessionId, workspace, model, fast, reasoning, context, contextFiles } = args;
|
|
144
181
|
|
|
145
182
|
const progressToken = extra?._meta?.progressToken;
|
|
183
|
+
/** @type {(message: string) => void} */
|
|
146
184
|
let onProgress = () => {};
|
|
147
185
|
if (progressToken != null) {
|
|
148
186
|
let progress = 0;
|
|
@@ -156,57 +194,6 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
|
|
|
156
194
|
};
|
|
157
195
|
}
|
|
158
196
|
|
|
159
|
-
const supportsElicitation = !!server.server.getClientCapabilities?.()?.elicitation;
|
|
160
|
-
const autoAnswered = [];
|
|
161
|
-
const fallbackAnswers = [];
|
|
162
|
-
|
|
163
|
-
const onElicit = async ({ title, questions }) => {
|
|
164
|
-
const answers = [];
|
|
165
|
-
for (const q of questions || []) {
|
|
166
|
-
const opts = q.options || [];
|
|
167
|
-
if (!supportsElicitation) {
|
|
168
|
-
// There is no user to ask, so allowMultiple changes nothing here: selecting every
|
|
169
|
-
// option would consent to more than the caller asked for. Take the first and
|
|
170
|
-
// disclose it. An option-less question answers empty rather than [null].
|
|
171
|
-
const first = opts[0];
|
|
172
|
-
autoAnswered.push({ prompt: String(q.prompt ?? ""), chosen: String(first?.label || first?.id || "") });
|
|
173
|
-
answers.push({ questionId: q.id, selectedOptionIds: first?.id ? [first.id] : [] });
|
|
174
|
-
continue;
|
|
175
|
-
}
|
|
176
|
-
const listing = opts.map((o) => o.label || o.id).join(", ");
|
|
177
|
-
const result = await server.server.elicitInput({
|
|
178
|
-
message: title ? `${title}: ${q.prompt}` : `cursor-agent asks: ${q.prompt}`,
|
|
179
|
-
requestedSchema: {
|
|
180
|
-
type: "object",
|
|
181
|
-
properties: {
|
|
182
|
-
choice: {
|
|
183
|
-
type: "string",
|
|
184
|
-
description: !opts.length
|
|
185
|
-
? "your answer"
|
|
186
|
-
: q.allowMultiple
|
|
187
|
-
? `Options (pick one or more, comma-separated): ${listing}`
|
|
188
|
-
: `Options: ${listing}`,
|
|
189
|
-
},
|
|
190
|
-
},
|
|
191
|
-
required: ["choice"],
|
|
192
|
-
},
|
|
193
|
-
});
|
|
194
|
-
if (result.action !== "accept") return null;
|
|
195
|
-
const choice = result.content?.choice || "";
|
|
196
|
-
const selectedOptionIds = matchOptions(choice, opts, q.allowMultiple);
|
|
197
|
-
if (!selectedOptionIds.length && opts.length) {
|
|
198
|
-
selectedOptionIds.push(opts[0].id);
|
|
199
|
-
fallbackAnswers.push({
|
|
200
|
-
prompt: String(q.prompt ?? ""),
|
|
201
|
-
given: String(choice),
|
|
202
|
-
chosen: String(opts[0].label || opts[0].id || ""),
|
|
203
|
-
});
|
|
204
|
-
}
|
|
205
|
-
answers.push({ questionId: q.id, selectedOptionIds });
|
|
206
|
-
}
|
|
207
|
-
return { answers };
|
|
208
|
-
};
|
|
209
|
-
|
|
210
197
|
let capturedSessionId;
|
|
211
198
|
let handle;
|
|
212
199
|
try {
|
|
@@ -220,14 +207,12 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
|
|
|
220
207
|
reasoning,
|
|
221
208
|
context,
|
|
222
209
|
contextFiles,
|
|
223
|
-
maxResultChars,
|
|
224
|
-
onElicit,
|
|
225
210
|
onProgress,
|
|
226
211
|
signal: extra?.signal,
|
|
227
212
|
onSessionReady: (sessionId, client) => {
|
|
228
213
|
capturedSessionId = sessionId;
|
|
229
214
|
handle = { client, cancelRequested: false };
|
|
230
|
-
inFlight
|
|
215
|
+
registerInFlight(inFlight, sessionId, handle);
|
|
231
216
|
rememberSession(seenSessions, sessionId);
|
|
232
217
|
// Emit the id the moment the session opens, before the turn finishes, so a host that
|
|
233
218
|
// can call tools concurrently has something to pass to cancel mid-run — otherwise the
|
|
@@ -236,8 +221,6 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
|
|
|
236
221
|
onProgress(`session ready: ${sessionId}`);
|
|
237
222
|
},
|
|
238
223
|
});
|
|
239
|
-
if (autoAnswered.length) out.autoAnswered = autoAnswered;
|
|
240
|
-
if (fallbackAnswers.length) out.fallbackAnswers = fallbackAnswers;
|
|
241
224
|
if (handle?.cancelRequested) out.cancelRequested = true;
|
|
242
225
|
return {
|
|
243
226
|
content: [{ type: "text", text: JSON.stringify(out, null, 2) }],
|
|
@@ -251,10 +234,19 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
|
|
|
251
234
|
isError: true,
|
|
252
235
|
};
|
|
253
236
|
} finally {
|
|
254
|
-
|
|
237
|
+
// Drops only this delegation's own handle; the id stays registered while another turn
|
|
238
|
+
// is still running on it.
|
|
239
|
+
if (capturedSessionId) unregisterInFlight(inFlight, capturedSessionId, handle);
|
|
255
240
|
}
|
|
256
241
|
}
|
|
257
242
|
|
|
243
|
+
/**
|
|
244
|
+
* @param {{
|
|
245
|
+
* runDelegate?: (opts: any) => Promise<any>,
|
|
246
|
+
* runDoctor?: (opts: any) => Promise<any>,
|
|
247
|
+
* forceGraceMs?: number,
|
|
248
|
+
* }} [opts]
|
|
249
|
+
*/
|
|
258
250
|
export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000 } = {}) {
|
|
259
251
|
const runDelegate = runDelegateInjected || runDelegateDefault;
|
|
260
252
|
const runDoctor = runDoctorInjected || runDoctorDefault;
|
|
@@ -267,7 +259,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
267
259
|
"delegate",
|
|
268
260
|
{
|
|
269
261
|
description:
|
|
270
|
-
`Delegate a coding task to cursor-agent over ACP. Never shell out to cursor-agent — use this tool only. Pass structured task text inline in spec (default); a file path is optional when the user wants a persisted brief. Defaults: mode=agent, model=${DEFAULT_MODEL}, fast=false. Plan workflow: mode=plan, then resume with mode=agent and resumeSessionId. Auto-approves every permission the agent requests, in any mode and anywhere on disk
|
|
262
|
+
`Delegate a coding task to cursor-agent over ACP. Never shell out to cursor-agent — use this tool only. Pass structured task text inline in spec (default); a file path is optional when the user wants a persisted brief. Defaults: mode=agent, model=${DEFAULT_MODEL}, fast=false. Plan workflow: mode=plan, then resume with mode=agent and resumeSessionId. Auto-approves every permission the agent requests, in any mode and anywhere on disk. Clarifying questions arrive as prose in result — resume with resumeSessionId to answer. Returns the final result, selection source, stop reason, session ID, agent-reported files, and optional plan. See the delegate skill for orchestration.`,
|
|
271
263
|
inputSchema: delegateInputSchema,
|
|
272
264
|
outputSchema: delegateOutputSchema,
|
|
273
265
|
annotations: {
|
|
@@ -278,7 +270,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
278
270
|
openWorldHint: true,
|
|
279
271
|
},
|
|
280
272
|
},
|
|
281
|
-
async (args, extra) => runDelegateTool({ args, extra,
|
|
273
|
+
async (args, extra) => runDelegateTool({ args, extra, runDelegate, inFlight, seenSessions })
|
|
282
274
|
);
|
|
283
275
|
|
|
284
276
|
server.registerTool(
|
|
@@ -300,8 +292,8 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
300
292
|
},
|
|
301
293
|
},
|
|
302
294
|
async ({ sessionId, force }) => {
|
|
303
|
-
const
|
|
304
|
-
if (!
|
|
295
|
+
const handles = inFlight.get(sessionId);
|
|
296
|
+
if (!handles || handles.size === 0) {
|
|
305
297
|
// A finished session and a garbage id used to look identical (both not-found), which
|
|
306
298
|
// read as "bad id" for a session that in fact ran and is still resumable. Split them.
|
|
307
299
|
const known = seenSessions.has(sessionId);
|
|
@@ -312,26 +304,29 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
312
304
|
structuredContent: { status: known ? "not-running" : "not-found", sessionId },
|
|
313
305
|
};
|
|
314
306
|
}
|
|
315
|
-
|
|
316
|
-
|
|
307
|
+
// Cancel every turn running on the id: the caller named a session, not one of the
|
|
308
|
+
// turns that happen to share it.
|
|
309
|
+
for (const handle of handles) handle.cancelRequested = true;
|
|
310
|
+
await Promise.all([...handles].map((handle) => handle.client.cancel(sessionId).catch(() => {})));
|
|
317
311
|
if (!force) {
|
|
318
|
-
// The
|
|
319
|
-
// be running. Dropping
|
|
320
|
-
// with force — report not-found while the agent was alive.
|
|
321
|
-
// finally removes
|
|
312
|
+
// The handles stay registered: session/cancel is best-effort, so the turn may still
|
|
313
|
+
// be running. Dropping them here made the natural escalation — cancel, wait, cancel
|
|
314
|
+
// with force — report not-found while the agent was alive. Each delegation's own
|
|
315
|
+
// finally removes its handle when the turn actually settles.
|
|
322
316
|
return {
|
|
323
317
|
content: [{ type: "text", text: `cancelled ${sessionId}` }],
|
|
324
318
|
structuredContent: { status: "cancelled", sessionId },
|
|
325
319
|
};
|
|
326
320
|
}
|
|
327
321
|
await new Promise((r) => setTimeout(r, forceGraceMs));
|
|
328
|
-
|
|
322
|
+
const stillRunning = inFlight.get(sessionId);
|
|
323
|
+
if (!stillRunning || stillRunning.size === 0) {
|
|
329
324
|
return {
|
|
330
325
|
content: [{ type: "text", text: `cancelled ${sessionId}` }],
|
|
331
326
|
structuredContent: { status: "cancelled", sessionId },
|
|
332
327
|
};
|
|
333
328
|
}
|
|
334
|
-
handle.client.stop();
|
|
329
|
+
for (const handle of stillRunning) handle.client.stop();
|
|
335
330
|
inFlight.delete(sessionId);
|
|
336
331
|
return {
|
|
337
332
|
content: [{ type: "text", text: `killed ${sessionId}` }],
|
|
@@ -344,7 +339,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
344
339
|
"doctor",
|
|
345
340
|
{
|
|
346
341
|
description:
|
|
347
|
-
"Report setup and health diagnostics: plugin version, MCP client capabilities
|
|
342
|
+
"Report setup and health diagnostics: plugin version, MCP client capabilities, cursor-agent launcher resolution, and optional deep ACP handshake. Use when delegation fails or agent.found is false.",
|
|
348
343
|
inputSchema: {
|
|
349
344
|
deep: z
|
|
350
345
|
.boolean()
|