cursor-delegate-mcp 2.11.0 → 3.0.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 +28 -0
- package/README.md +3 -1
- package/package.json +1 -1
- package/src/delegate.js +6 -2
- package/src/server.js +61 -27
- package/src/tasks.js +167 -0
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,34 @@ All notable changes to this project are documented here. The format follows
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [3.0.0] - 2026-11-23
|
|
10
|
+
|
|
11
|
+
`delegate` no longer holds your agent while Cursor works. In an interactive Claude Code CLI session
|
|
12
|
+
it runs as an MCP task, and the Antigravity plugin runs it in the background: your agent stays free
|
|
13
|
+
to plan, review or start the next delegation, and Cursor's result arrives when its turn ends. Codex
|
|
14
|
+
and other hosts keep the blocking call. One thing changes on upgrade in Claude Code: the
|
|
15
|
+
`delegate` call returns before Cursor has finished, and its result comes back as a task
|
|
16
|
+
notification.
|
|
17
|
+
|
|
18
|
+
### Added
|
|
19
|
+
|
|
20
|
+
- The server serves the MCP Tasks extension (`io.modelcontextprotocol/tasks`, 2026-07-28) to a
|
|
21
|
+
request that lists it: `tasks/get`, `tasks/update` and `tasks/cancel`. A finished task's result
|
|
22
|
+
is kept for an hour, up to 100 tasks.
|
|
23
|
+
|
|
24
|
+
### Changed
|
|
25
|
+
|
|
26
|
+
- **Breaking: in an interactive Claude Code CLI session, `delegate` runs as an MCP task.** The call
|
|
27
|
+
returns once cursor-agent has the prompt, and the same result arrives as a task notification
|
|
28
|
+
when the turn ends. Progress shows as the task's status message in `/tasks`, and stopping the
|
|
29
|
+
task cancels the turn and stops cursor-agent. An argument cursor-agent rejects still fails the
|
|
30
|
+
call before the prompt. A request that does not list the extension, as Codex's and
|
|
31
|
+
Antigravity's do not, is answered with the result, as before.
|
|
32
|
+
`CLAUDE_CODE_DISABLE_MCP_TASK_BACKGROUND=1` makes Claude Code wait for the result in the call.
|
|
33
|
+
- The Antigravity plugin runs `delegate` in the background (`tools.delegate.background: "always"`):
|
|
34
|
+
Antigravity hands the call back to the model at once and wakes it with the result.
|
|
35
|
+
`timeoutSeconds` still bounds the call.
|
|
36
|
+
|
|
9
37
|
## [2.11.0] - 2026-11-23
|
|
10
38
|
|
|
11
39
|
### Added
|
package/README.md
CHANGED
|
@@ -42,6 +42,7 @@ Composer and Grok draw from the **Cursor Models usage pool**, separate from thir
|
|
|
42
42
|
|
|
43
43
|
- 🤝 **Native plugins** — install into Claude Code, ChatGPT/Codex, Google Antigravity, or GitHub Copilot CLI and just say *"delegate this to Cursor"*. The shared skill teaches your agent how to delegate well.
|
|
44
44
|
- 💬 **No stalled runs** — if Cursor needs to clarify, it ends the turn and returns the question as a normal result. Your agent reads it and answers by resuming the same session — nothing blocks on a modal waiting for input.
|
|
45
|
+
- ⏳ **Runs in the background in Claude Code** — in an interactive Claude Code CLI session, `delegate` runs as an MCP task: the call returns once Cursor has the prompt, and the result arrives as a task notification when Cursor finishes.
|
|
45
46
|
- 📦 **Clean, named results** — final answer, changed files, session id, and the plan, returned as one compact JSON payload. Nothing to scrape.
|
|
46
47
|
- 📋 **Plan first** — `plan` mode: Cursor drafts a plan, you review it, then the same session implements it.
|
|
47
48
|
- 🔍 **Ask anything** — `ask` mode: Q&A over your codebase.
|
|
@@ -180,7 +181,8 @@ OpenCode does **not** use `mcpServers`. Local servers go under `mcp`, with `type
|
|
|
180
181
|
"cursor-delegate": {
|
|
181
182
|
"command": "npx",
|
|
182
183
|
"args": ["-y", "cursor-delegate-mcp"],
|
|
183
|
-
"timeoutSeconds": 21660
|
|
184
|
+
"timeoutSeconds": 21660,
|
|
185
|
+
"tools": { "delegate": { "background": "always" } }
|
|
184
186
|
}
|
|
185
187
|
}
|
|
186
188
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cursor-delegate-mcp",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.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/delegate.js
CHANGED
|
@@ -251,6 +251,7 @@ async function applyEffort(client, sessionId, model, value, modelOptions) {
|
|
|
251
251
|
* idleMs?: number, handshakeMs?: number, hardCapMs?: number, timeoutMs?: number,
|
|
252
252
|
* onClientReady?: (client: any) => void,
|
|
253
253
|
* onSessionReady?: (sessionId: string, client: any) => void,
|
|
254
|
+
* onPromptSent?: (sessionId: string) => void,
|
|
254
255
|
* onTurnEnd?: () => void,
|
|
255
256
|
* onProgress?: (message: string) => void,
|
|
256
257
|
* progressThrottleMs?: number, heartbeatMs?: number, signal?: AbortSignal,
|
|
@@ -260,7 +261,7 @@ export async function runDelegate({
|
|
|
260
261
|
spec, mode = "agent", resumeSessionId, workspace,
|
|
261
262
|
model = DEFAULT_MODEL, fast = false, effort, context, contextFiles, clientFactory,
|
|
262
263
|
idleMs, handshakeMs, hardCapMs, timeoutMs,
|
|
263
|
-
onClientReady, onSessionReady, onTurnEnd, onProgress, progressThrottleMs = 2000,
|
|
264
|
+
onClientReady, onSessionReady, onPromptSent, onTurnEnd, onProgress, progressThrottleMs = 2000,
|
|
264
265
|
heartbeatMs = DEFAULT_HEARTBEAT_MS,
|
|
265
266
|
signal,
|
|
266
267
|
} = {}) {
|
|
@@ -519,7 +520,10 @@ export async function runDelegate({
|
|
|
519
520
|
const blocks = await buildContextBlocks(contextFiles, workspace, client, contextWarnings);
|
|
520
521
|
// The caller has the id from session/new on, so a cancel can come before there is a turn.
|
|
521
522
|
if (client.cancelRequested) return { stopReason: "cancelled", cancelledBeforePrompt: true };
|
|
522
|
-
|
|
523
|
+
const turn = client.prompt(sessionId, [{ type: "text", text: promptText }, ...blocks]);
|
|
524
|
+
// Every argument has been accepted by now, so a caller may stop waiting on the result.
|
|
525
|
+
try { onPromptSent?.(sessionId); } catch {}
|
|
526
|
+
return await turn;
|
|
523
527
|
} finally {
|
|
524
528
|
// The result is assembled across later awaits; a frame trailing the turn must not join it.
|
|
525
529
|
promptInFlight = false;
|
package/src/server.js
CHANGED
|
@@ -10,6 +10,7 @@ import { runDoctor as runDoctorDefault } from "./doctor.js";
|
|
|
10
10
|
import { VERSION, readPackageVersion } from "./version.js";
|
|
11
11
|
import { DETACHED } from "./proc.js";
|
|
12
12
|
import { PLAN_PRIORITIES, PLAN_STATUSES, TODO_STATUSES } from "./acp-enums.js";
|
|
13
|
+
import { TASKS_EXTENSION, createTaskStore, listsTasks, registerTaskHandlers, runAsTask } from "./tasks.js";
|
|
13
14
|
|
|
14
15
|
const ICON_BASE = `https://raw.githubusercontent.com/andreilungeanu/cursor-delegate-mcp/v${VERSION}/assets`;
|
|
15
16
|
/** @type {Array<{ src: string, mimeType: string, sizes: string[], theme: "light" | "dark" }>} */
|
|
@@ -58,6 +59,10 @@ function rememberSession(set, id) {
|
|
|
58
59
|
if (set.size > SEEN_SESSIONS_CAP) set.delete(set.values().next().value);
|
|
59
60
|
}
|
|
60
61
|
|
|
62
|
+
// Delegations answered as MCP tasks. Module-level, as inFlight: a task outlives the request that
|
|
63
|
+
// started it, and serveStdio may build more than one server instance.
|
|
64
|
+
const taskStore = createTaskStore();
|
|
65
|
+
|
|
61
66
|
// Read at connect, so only what decides whether to delegate at all. Call-time facts belong on
|
|
62
67
|
// the parameter descriptions.
|
|
63
68
|
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.`;
|
|
@@ -163,6 +168,22 @@ export const delegateInputSchema = z.object({
|
|
|
163
168
|
contextFiles: z.array(z.string()).optional().describe("Paths to attach instead of pasting contents into spec. Text becomes references the agent may open; images (png/jpg/gif/webp, <5MB) are sent inline. Relative paths resolve against workspace but are not limited to it. Skips are reported in protocolWarnings, never fatal."),
|
|
164
169
|
});
|
|
165
170
|
|
|
171
|
+
/** @returns {(message: string) => void} */
|
|
172
|
+
export function progressNotifier(ctx) {
|
|
173
|
+
const progressToken = ctx?.mcpReq?._meta?.progressToken;
|
|
174
|
+
if (progressToken == null) return () => {};
|
|
175
|
+
let progress = 0;
|
|
176
|
+
return (message) => {
|
|
177
|
+
// An unhandled rejection from notify would exit the server; the try catches a sync throw.
|
|
178
|
+
try {
|
|
179
|
+
Promise.resolve(ctx.mcpReq.notify({
|
|
180
|
+
method: "notifications/progress",
|
|
181
|
+
params: { progressToken, progress: ++progress, message },
|
|
182
|
+
})).catch(() => {});
|
|
183
|
+
} catch {}
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
166
187
|
/**
|
|
167
188
|
* @param {{
|
|
168
189
|
* args: any, ctx?: any,
|
|
@@ -170,28 +191,19 @@ export const delegateInputSchema = z.object({
|
|
|
170
191
|
* inFlight: Map<string, Set<any>>,
|
|
171
192
|
* pending?: Set<any>,
|
|
172
193
|
* seenSessions?: Set<string>,
|
|
194
|
+
* signal?: AbortSignal,
|
|
195
|
+
* onProgress?: (message: string) => void,
|
|
196
|
+
* onPromptSent?: (sessionId: string) => void,
|
|
197
|
+
* onTurnEnd?: () => void,
|
|
173
198
|
* }} deps
|
|
174
199
|
* @returns {Promise<import("@modelcontextprotocol/server").CallToolResult>}
|
|
175
200
|
*/
|
|
176
|
-
export async function runDelegateTool({
|
|
201
|
+
export async function runDelegateTool({
|
|
202
|
+
args, ctx, runDelegate, inFlight, pending = new Set(), seenSessions = new Set(),
|
|
203
|
+
signal = ctx?.mcpReq?.signal, onProgress = progressNotifier(ctx), onPromptSent, onTurnEnd,
|
|
204
|
+
}) {
|
|
177
205
|
const { spec, mode, resumeSessionId, workspace, model, fast, effort, context, contextFiles } = args;
|
|
178
206
|
|
|
179
|
-
const progressToken = ctx?.mcpReq?._meta?.progressToken;
|
|
180
|
-
/** @type {(message: string) => void} */
|
|
181
|
-
let onProgress = () => {};
|
|
182
|
-
if (progressToken != null) {
|
|
183
|
-
let progress = 0;
|
|
184
|
-
onProgress = (message) => {
|
|
185
|
-
// An unhandled rejection from notify would exit the server; the try catches a sync throw.
|
|
186
|
-
try {
|
|
187
|
-
Promise.resolve(ctx.mcpReq.notify({
|
|
188
|
-
method: "notifications/progress",
|
|
189
|
-
params: { progressToken, progress: ++progress, message },
|
|
190
|
-
})).catch(() => {});
|
|
191
|
-
} catch {}
|
|
192
|
-
};
|
|
193
|
-
}
|
|
194
|
-
|
|
195
207
|
let capturedSessionId;
|
|
196
208
|
let handle;
|
|
197
209
|
try {
|
|
@@ -206,7 +218,8 @@ export async function runDelegateTool({ args, ctx, runDelegate, inFlight, pendin
|
|
|
206
218
|
context,
|
|
207
219
|
contextFiles,
|
|
208
220
|
onProgress,
|
|
209
|
-
signal
|
|
221
|
+
signal,
|
|
222
|
+
onPromptSent,
|
|
210
223
|
onClientReady: (client) => {
|
|
211
224
|
handle = { client, cancelRequested: false };
|
|
212
225
|
pending.add(handle);
|
|
@@ -221,7 +234,10 @@ export async function runDelegateTool({ args, ctx, runDelegate, inFlight, pendin
|
|
|
221
234
|
// Sent now so a host that can call tools concurrently has an id to cancel mid-run.
|
|
222
235
|
onProgress(`session ready: ${sessionId}`);
|
|
223
236
|
},
|
|
224
|
-
onTurnEnd: () => {
|
|
237
|
+
onTurnEnd: () => {
|
|
238
|
+
if (handle) handle.ended = true;
|
|
239
|
+
onTurnEnd?.();
|
|
240
|
+
},
|
|
225
241
|
});
|
|
226
242
|
if (handle?.cancelRequested) out.cancelRequested = true;
|
|
227
243
|
return { content: [{ type: "text", text: JSON.stringify(out) }] };
|
|
@@ -245,15 +261,27 @@ export async function runDelegateTool({ args, ctx, runDelegate, inFlight, pendin
|
|
|
245
261
|
* runDoctor?: (opts: any) => Promise<any>,
|
|
246
262
|
* forceGraceMs?: number,
|
|
247
263
|
* pending?: Set<any>,
|
|
264
|
+
* inFlight?: Map<string, Set<any>>,
|
|
265
|
+
* era?: "legacy" | "modern",
|
|
266
|
+
* tasks?: ReturnType<typeof createTaskStore>,
|
|
248
267
|
* }} [opts]
|
|
249
268
|
*/
|
|
250
|
-
export function buildServer({
|
|
269
|
+
export function buildServer({
|
|
270
|
+
runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000, pending = pendingDelegations,
|
|
271
|
+
inFlight: flights = inFlight, era, tasks = taskStore,
|
|
272
|
+
} = {}) {
|
|
251
273
|
const runDelegate = runDelegateInjected || runDelegateDefault;
|
|
252
274
|
const runDoctor = runDoctorInjected || runDoctorDefault;
|
|
275
|
+
// Tasks only on a 2026-07-28 instance: the SDK also lifts envelope keys off 2025-era requests.
|
|
276
|
+
const servesTasks = era === "modern";
|
|
253
277
|
const server = new McpServer(
|
|
254
278
|
{ name: "cursor-delegate-mcp", version: VERSION, icons: SERVER_ICONS },
|
|
255
|
-
{
|
|
279
|
+
{
|
|
280
|
+
instructions: SERVER_INSTRUCTIONS,
|
|
281
|
+
...(servesTasks ? { capabilities: { extensions: { [TASKS_EXTENSION]: {} } } } : {}),
|
|
282
|
+
}
|
|
256
283
|
);
|
|
284
|
+
if (servesTasks) registerTaskHandlers(server, tasks);
|
|
257
285
|
|
|
258
286
|
server.registerTool(
|
|
259
287
|
"delegate",
|
|
@@ -269,7 +297,12 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
269
297
|
openWorldHint: true,
|
|
270
298
|
},
|
|
271
299
|
},
|
|
272
|
-
async (args, ctx) =>
|
|
300
|
+
async (args, ctx) => {
|
|
301
|
+
/** @param {Record<string, any>} [over] */
|
|
302
|
+
const run = (over) => runDelegateTool({ args, ctx, runDelegate, inFlight: flights, pending, seenSessions, ...over });
|
|
303
|
+
if (!servesTasks || !listsTasks(ctx)) return run();
|
|
304
|
+
return /** @type {any} */ (runAsTask({ run, signal: ctx?.mcpReq?.signal, notify: progressNotifier(ctx), store: tasks }));
|
|
305
|
+
}
|
|
273
306
|
);
|
|
274
307
|
|
|
275
308
|
server.registerTool(
|
|
@@ -291,7 +324,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
291
324
|
},
|
|
292
325
|
},
|
|
293
326
|
async ({ sessionId, force }) => {
|
|
294
|
-
const handles =
|
|
327
|
+
const handles = flights.get(sessionId);
|
|
295
328
|
if (!handles || handles.size === 0) {
|
|
296
329
|
// A finished session is still resumable; only an unknown id is not-found.
|
|
297
330
|
const known = seenSessions.has(sessionId);
|
|
@@ -310,7 +343,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
310
343
|
return cancelResult("cancelled", sessionId);
|
|
311
344
|
}
|
|
312
345
|
// Polled, not slept through: the turn often settles well inside the grace.
|
|
313
|
-
const running = () => targeted.filter((handle) => !handle.ended &&
|
|
346
|
+
const running = () => targeted.filter((handle) => !handle.ended && flights.get(sessionId)?.has(handle));
|
|
314
347
|
const graceEnds = Date.now() + forceGraceMs;
|
|
315
348
|
while (Date.now() < graceEnds && running().length) {
|
|
316
349
|
await new Promise((r) => setTimeout(r, Math.min(50, Math.max(1, graceEnds - Date.now()))));
|
|
@@ -322,7 +355,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
322
355
|
);
|
|
323
356
|
// "killed" needs an observed exit; without one the handles stay and force can be retried.
|
|
324
357
|
if (!observed.every(Boolean)) return cancelResult("cancelled", sessionId);
|
|
325
|
-
for (const handle of toKill) unregisterInFlight(
|
|
358
|
+
for (const handle of toKill) unregisterInFlight(flights, sessionId, handle);
|
|
326
359
|
return cancelResult("killed", sessionId);
|
|
327
360
|
}
|
|
328
361
|
);
|
|
@@ -437,7 +470,8 @@ if (isMain) {
|
|
|
437
470
|
console.log(readPackageVersion());
|
|
438
471
|
} else {
|
|
439
472
|
installSignalCleanup(inFlight, { pending: pendingDelegations });
|
|
440
|
-
// One factory serves both protocol eras: a 2025-era initialize pins a legacy instance
|
|
441
|
-
|
|
473
|
+
// One factory serves both protocol eras: a 2025-era initialize pins a legacy instance, and only
|
|
474
|
+
// a modern one answers with tasks.
|
|
475
|
+
serveStdio(({ era }) => buildServer({ era }));
|
|
442
476
|
}
|
|
443
477
|
}
|
package/src/tasks.js
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { CLIENT_CAPABILITIES_META_KEY, MissingRequiredClientCapabilityError, ProtocolError, ProtocolErrorCode } from "@modelcontextprotocol/server";
|
|
4
|
+
|
|
5
|
+
// The MCP Tasks extension, 2026-07-28: https://modelcontextprotocol.io/extensions/tasks/overview
|
|
6
|
+
export const TASKS_EXTENSION = "io.modelcontextprotocol/tasks";
|
|
7
|
+
|
|
8
|
+
const RETAIN_MS = 60 * 60 * 1000;
|
|
9
|
+
const MAX_FINISHED = 100;
|
|
10
|
+
const FAST_POLL_MS = 3000;
|
|
11
|
+
const SLOW_POLL_MS = 10000;
|
|
12
|
+
const FAST_POLL_FOR_MS = 60 * 1000;
|
|
13
|
+
|
|
14
|
+
// Claude Code lists the extension only on a call that can become a task: not from a subagent.
|
|
15
|
+
export function listsTasks(ctx) {
|
|
16
|
+
return ctx?.mcpReq?.envelope?.[CLIENT_CAPABILITIES_META_KEY]?.extensions?.[TASKS_EXTENSION] != null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @typedef {{
|
|
21
|
+
* taskId: string, status: "working" | "completed" | "failed" | "cancelled",
|
|
22
|
+
* createdAt: number, lastUpdatedAt: number, endedAt?: number, statusMessage?: string,
|
|
23
|
+
* sessionId?: string, turnEnded: boolean, ac: AbortController,
|
|
24
|
+
* result?: any, error?: { code: number, message: string },
|
|
25
|
+
* }} Task
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/** @param {{ now?: () => number, retainMs?: number, maxFinished?: number }} [opts] */
|
|
29
|
+
export function createTaskStore({ now = Date.now, retainMs = RETAIN_MS, maxFinished = MAX_FINISHED } = {}) {
|
|
30
|
+
/** @type {Map<string, Task>} */
|
|
31
|
+
const tasks = new Map();
|
|
32
|
+
// A running task is never dropped: its id is the host's only handle on the run.
|
|
33
|
+
const prune = () => {
|
|
34
|
+
const t = now();
|
|
35
|
+
const finished = [...tasks.values()].filter((task) => task.endedAt !== undefined);
|
|
36
|
+
for (const task of finished) if (t - /** @type {number} */ (task.endedAt) > retainMs) tasks.delete(task.taskId);
|
|
37
|
+
const kept = finished.filter((task) => tasks.has(task.taskId))
|
|
38
|
+
.sort((a, b) => /** @type {number} */ (a.endedAt) - /** @type {number} */ (b.endedAt));
|
|
39
|
+
for (const task of kept.slice(0, Math.max(0, kept.length - maxFinished))) tasks.delete(task.taskId);
|
|
40
|
+
};
|
|
41
|
+
return {
|
|
42
|
+
now,
|
|
43
|
+
/** @returns {Task} */
|
|
44
|
+
create() {
|
|
45
|
+
const t = now();
|
|
46
|
+
return { taskId: randomUUID(), status: "working", createdAt: t, lastUpdatedAt: t, turnEnded: false, ac: new AbortController() };
|
|
47
|
+
},
|
|
48
|
+
/** @param {Task} task */
|
|
49
|
+
add(task) { prune(); tasks.set(task.taskId, task); },
|
|
50
|
+
/** @param {string} taskId */
|
|
51
|
+
get(taskId) { prune(); return tasks.get(taskId); },
|
|
52
|
+
/** @param {Task} task @param {{ result?: any, error?: any }} outcome */
|
|
53
|
+
finish(task, outcome) {
|
|
54
|
+
if (task.status === "working") {
|
|
55
|
+
task.endedAt = now();
|
|
56
|
+
if ("error" in outcome) {
|
|
57
|
+
task.status = "failed";
|
|
58
|
+
task.error = { code: ProtocolErrorCode.InternalError, message: String(outcome.error?.message ?? outcome.error) };
|
|
59
|
+
} else {
|
|
60
|
+
task.status = "completed";
|
|
61
|
+
task.result = outcome.result;
|
|
62
|
+
}
|
|
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
|
+
}
|
|
67
|
+
task.lastUpdatedAt = now();
|
|
68
|
+
prune();
|
|
69
|
+
},
|
|
70
|
+
// A turn that has ended has its result decided, so a cancel leaves it, as the cancel tool does.
|
|
71
|
+
/** @param {Task} task */
|
|
72
|
+
cancel(task) {
|
|
73
|
+
if (task.status !== "working" || task.turnEnded) return;
|
|
74
|
+
task.status = "cancelled";
|
|
75
|
+
task.statusMessage = task.sessionId ? `cancelled; resume with resumeSessionId ${task.sessionId}` : "cancelled";
|
|
76
|
+
task.endedAt = task.lastUpdatedAt = now();
|
|
77
|
+
task.ac.abort();
|
|
78
|
+
},
|
|
79
|
+
/** @param {Task} task */
|
|
80
|
+
view(task) {
|
|
81
|
+
const t = now();
|
|
82
|
+
/** @type {Record<string, any>} */
|
|
83
|
+
const view = {
|
|
84
|
+
taskId: task.taskId,
|
|
85
|
+
status: task.status,
|
|
86
|
+
createdAt: new Date(task.createdAt).toISOString(),
|
|
87
|
+
lastUpdatedAt: new Date(task.lastUpdatedAt).toISOString(),
|
|
88
|
+
ttlMs: task.endedAt === undefined ? null : task.endedAt - task.createdAt + retainMs,
|
|
89
|
+
pollIntervalMs: t - task.createdAt < FAST_POLL_FOR_MS ? FAST_POLL_MS : SLOW_POLL_MS,
|
|
90
|
+
};
|
|
91
|
+
if (task.statusMessage) view.statusMessage = task.statusMessage;
|
|
92
|
+
if (task.status === "completed") view.result = task.result;
|
|
93
|
+
if (task.status === "failed") view.error = task.error;
|
|
94
|
+
return view;
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Runs a delegation that answers its request with a task once the prompt is sent. A run that
|
|
101
|
+
* settles before then, setup failures included, answers with its result as a blocking call does.
|
|
102
|
+
* @param {{
|
|
103
|
+
* run: (over: { signal: AbortSignal, onProgress: (m: string) => void, onPromptSent: (id: string) => void, onTurnEnd: () => void }) => Promise<any>,
|
|
104
|
+
* signal?: AbortSignal, notify?: (message: string) => void, store: ReturnType<typeof createTaskStore>,
|
|
105
|
+
* }} opts
|
|
106
|
+
*/
|
|
107
|
+
export async function runAsTask({ run, signal, notify = () => {}, store }) {
|
|
108
|
+
const task = store.create();
|
|
109
|
+
let answered = false;
|
|
110
|
+
/** @type {() => void} */
|
|
111
|
+
let markSent = () => {};
|
|
112
|
+
const sent = new Promise((resolve) => { markSent = () => resolve(undefined); });
|
|
113
|
+
// Until the task is answered the request owns the run, so its cancellation stops the agent.
|
|
114
|
+
const forward = () => task.ac.abort();
|
|
115
|
+
if (signal?.aborted) forward();
|
|
116
|
+
else signal?.addEventListener("abort", forward, { once: true });
|
|
117
|
+
const outcome = run({
|
|
118
|
+
signal: task.ac.signal,
|
|
119
|
+
onProgress: (message) => {
|
|
120
|
+
if (task.status === "working") {
|
|
121
|
+
task.statusMessage = message;
|
|
122
|
+
task.lastUpdatedAt = store.now();
|
|
123
|
+
}
|
|
124
|
+
// Once the task is the answer, progress belongs to the task, not the request.
|
|
125
|
+
if (!answered) notify(message);
|
|
126
|
+
},
|
|
127
|
+
onPromptSent: (sessionId) => { task.sessionId = sessionId; markSent(); },
|
|
128
|
+
onTurnEnd: () => { task.turnEnded = true; },
|
|
129
|
+
}).then((result) => ({ result }), (error) => ({ error }));
|
|
130
|
+
const first = await Promise.race([sent, outcome]);
|
|
131
|
+
signal?.removeEventListener("abort", forward);
|
|
132
|
+
// An abort before the agent has a session sends no session/cancel, so setup can still reach the
|
|
133
|
+
// prompt; the request is gone by then and nobody would receive the task id.
|
|
134
|
+
const settled = first ?? (task.ac.signal.aborted ? await outcome : undefined);
|
|
135
|
+
if (settled) {
|
|
136
|
+
if ("error" in settled) throw settled.error;
|
|
137
|
+
return settled.result;
|
|
138
|
+
}
|
|
139
|
+
answered = true;
|
|
140
|
+
// In the store before the answer goes out: the host polls as soon as it reads the id.
|
|
141
|
+
store.add(task);
|
|
142
|
+
outcome.then((o) => store.finish(task, o));
|
|
143
|
+
return { resultType: "task", ...store.view(task) };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const TaskParams = z.object({ taskId: z.string() }).passthrough();
|
|
147
|
+
const AnyResult = z.object({}).passthrough();
|
|
148
|
+
|
|
149
|
+
/** @param {any} server @param {ReturnType<typeof createTaskStore>} store */
|
|
150
|
+
export function registerTaskHandlers(server, store) {
|
|
151
|
+
/** @param {string} taskId @param {any} ctx */
|
|
152
|
+
const find = (taskId, ctx) => {
|
|
153
|
+
if (!listsTasks(ctx)) {
|
|
154
|
+
throw new MissingRequiredClientCapabilityError({ requiredCapabilities: { extensions: { [TASKS_EXTENSION]: {} } } });
|
|
155
|
+
}
|
|
156
|
+
const task = store.get(taskId);
|
|
157
|
+
if (!task) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Unknown task: ${taskId}`);
|
|
158
|
+
return task;
|
|
159
|
+
};
|
|
160
|
+
server.server.setRequestHandler("tasks/get", { params: TaskParams, result: AnyResult },
|
|
161
|
+
async (/** @type {any} */ { taskId }, /** @type {any} */ ctx) => store.view(find(taskId, ctx)));
|
|
162
|
+
// A delegation never enters input_required: its questions come back in the result.
|
|
163
|
+
server.server.setRequestHandler("tasks/update", { params: TaskParams, result: AnyResult },
|
|
164
|
+
async (/** @type {any} */ { taskId }, /** @type {any} */ ctx) => { find(taskId, ctx); return {}; });
|
|
165
|
+
server.server.setRequestHandler("tasks/cancel", { params: TaskParams, result: AnyResult },
|
|
166
|
+
async (/** @type {any} */ { taskId }, /** @type {any} */ ctx) => { store.cancel(find(taskId, ctx)); return {}; });
|
|
167
|
+
}
|