cursor-delegate-mcp 2.11.0 → 3.0.1

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 CHANGED
@@ -6,6 +6,47 @@ All notable changes to this project are documented here. The format follows
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [3.0.1] - 2026-11-23
10
+
11
+ ### Fixed
12
+
13
+ - A delegation stopped with TaskStop in Claude Code can be resumed: `resumeSessionId` takes the
14
+ task's server-side id, the only id Claude Code tells the model. `cancel` takes it too and
15
+ reaches only that task's turn.
16
+
17
+ ### Changed
18
+
19
+ - The `aborted` error drops the last tool call, frame age, todos and edited files: no host
20
+ receives a response to a request it cancelled. The skill reference no longer lists `aborted`.
21
+
22
+ ## [3.0.0] - 2026-11-23
23
+
24
+ `delegate` no longer holds your agent while Cursor works. In an interactive Claude Code CLI session
25
+ it runs as an MCP task, and the Antigravity plugin runs it in the background: your agent stays free
26
+ to plan, review or start the next delegation, and Cursor's result arrives when its turn ends. Codex
27
+ and other hosts keep the blocking call. One thing changes on upgrade in Claude Code: the
28
+ `delegate` call returns before Cursor has finished, and its result comes back as a task
29
+ notification.
30
+
31
+ ### Added
32
+
33
+ - The server serves the MCP Tasks extension (`io.modelcontextprotocol/tasks`, 2026-07-28) to a
34
+ request that lists it: `tasks/get`, `tasks/update` and `tasks/cancel`. A finished task's result
35
+ is kept for an hour, up to 100 tasks.
36
+
37
+ ### Changed
38
+
39
+ - **Breaking: in an interactive Claude Code CLI session, `delegate` runs as an MCP task.** The call
40
+ returns once cursor-agent has the prompt, and the same result arrives as a task notification
41
+ when the turn ends. Progress shows as the task's status message in `/tasks`, and stopping the
42
+ task cancels the turn and stops cursor-agent. An argument cursor-agent rejects still fails the
43
+ call before the prompt. A request that does not list the extension, as Codex's and
44
+ Antigravity's do not, is answered with the result, as before.
45
+ `CLAUDE_CODE_DISABLE_MCP_TASK_BACKGROUND=1` makes Claude Code wait for the result in the call.
46
+ - The Antigravity plugin runs `delegate` in the background (`tools.delegate.background: "always"`):
47
+ Antigravity hands the call back to the model at once and wakes it with the result.
48
+ `timeoutSeconds` still bounds the call.
49
+
9
50
  ## [2.11.0] - 2026-11-23
10
51
 
11
52
  ### 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": "2.11.0",
3
+ "version": "3.0.1",
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
  } = {}) {
@@ -268,7 +269,7 @@ export async function runDelegate({
268
269
  // already fired. Throw, not supervisor.abort(): tripping before supervise() installs its reject
269
270
  // settles the supervisor with nothing listening.
270
271
  if (signal?.aborted) {
271
- throw makeError("aborted", "delegation aborted by MCP host");
272
+ throw makeError("aborted", "delegation aborted by MCP host.");
272
273
  }
273
274
  // Before the spawn: validating later costs a process, a handshake and a billed turn.
274
275
  assertWorkspace(workspace);
@@ -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
- return await client.prompt(sessionId, [{ type: "text", text: promptText }, ...blocks]);
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;
@@ -602,7 +606,8 @@ export async function runDelegate({
602
606
  // A handshake timeout gets the forensics but not the long-command advice: no prompt was sent,
603
607
  // so no shell command explains the silence.
604
608
  const isStall = isTimeout || err?.reason === "handshake-timeout";
605
- if (isStall || err?.reason === "aborted" || err?.reason === "agent-exit") {
609
+ // Not on an abort: the SDK sends no response to a request its host cancelled.
610
+ if (isStall || err?.reason === "agent-exit") {
606
611
  const age = fmtDuration(supervisor.msSinceActivity());
607
612
  err.message += `\n\nLast ACP frame ${age} ago${state.lastToolLabel ? `; last tool call: ${state.lastToolLabel}` : ""}.`;
608
613
  if (state.sessionTitle) err.message += ` The agent titled this turn ${JSON.stringify(state.sessionTitle)}.`;
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.`;
@@ -153,7 +158,7 @@ export const doctorOutputShape = {
153
158
  export const delegateInputSchema = z.object({
154
159
  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."),
155
160
  mode: z.enum(["agent", "plan", "ask"]).default("agent").describe("agent implements; plan and ask are instructions to the agent, not limits."),
156
- resumeSessionId: z.string().optional().describe("Continue an existing ACP session."),
161
+ resumeSessionId: z.string().optional().describe("Continue an existing ACP session. When delegate ran as an MCP task, its server-side task id works too."),
157
162
  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."),
158
163
  model: z.string().trim().min(1, "model must be a non-empty string").default(DEFAULT_MODEL).describe("Bare ACP family id, version included: composer-2.5, grok-4.5, claude-opus-5, gpt-5.6-sol. doctor deep:true lists every id."),
159
164
  fast: z.boolean().default(false).describe("Fast tier; higher cost — only when the user asks."),
@@ -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, handle: any) => void,
197
+ * onTurnEnd?: () => void,
173
198
  * }} deps
174
199
  * @returns {Promise<import("@modelcontextprotocol/server").CallToolResult>}
175
200
  */
176
- export async function runDelegateTool({ args, ctx, runDelegate, inFlight, pending = new Set(), seenSessions = new Set() }) {
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: ctx?.mcpReq?.signal,
221
+ signal,
222
+ onPromptSent: onPromptSent && ((sessionId) => onPromptSent(sessionId, handle)),
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: () => { if (handle) handle.ended = true; },
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,36 @@ 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({ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000, pending = pendingDelegations } = {}) {
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
- { instructions: SERVER_INSTRUCTIONS }
279
+ {
280
+ instructions: SERVER_INSTRUCTIONS,
281
+ ...(servesTasks ? { capabilities: { extensions: { [TASKS_EXTENSION]: {} } } } : {}),
282
+ }
256
283
  );
284
+ if (servesTasks) registerTaskHandlers(server, tasks);
285
+ // A task id names its own run, which a later turn on the same session is not; a session id names
286
+ // every turn running on it.
287
+ /** @param {string} id */
288
+ const targetOf = (id) => {
289
+ const task = tasks.get(id);
290
+ if (!task?.sessionId) return { sessionId: id, handles: flights.get(id) };
291
+ const running = task.status === "working" && flights.get(task.sessionId)?.has(task.handle);
292
+ return { sessionId: task.sessionId, handles: new Set(running ? [task.handle] : []) };
293
+ };
257
294
 
258
295
  server.registerTool(
259
296
  "delegate",
@@ -269,7 +306,14 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
269
306
  openWorldHint: true,
270
307
  },
271
308
  },
272
- async (args, ctx) => runDelegateTool({ args, ctx, runDelegate, inFlight, pending, seenSessions })
309
+ async (args, ctx) => {
310
+ // Claude Code tells the model a task's id and never its session id, even after a stop.
311
+ const resumeSessionId = tasks.get(args.resumeSessionId)?.sessionId ?? args.resumeSessionId;
312
+ /** @param {Record<string, any>} [over] */
313
+ const run = (over) => runDelegateTool({ args: { ...args, resumeSessionId }, ctx, runDelegate, inFlight: flights, pending, seenSessions, ...over });
314
+ if (!servesTasks || !listsTasks(ctx)) return run();
315
+ return /** @type {any} */ (runAsTask({ run, signal: ctx?.mcpReq?.signal, notify: progressNotifier(ctx), store: tasks }));
316
+ }
273
317
  );
274
318
 
275
319
  server.registerTool(
@@ -279,7 +323,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
279
323
  "Best-effort cancel of an in-flight delegation by sessionId. session/cancel is advisory — the agent may finish the turn anyway, and the delegate result then carries cancelRequested. Status: cancelled, killed (agent process observed to exit), not-running (turn already ended, still resumable), not-found (id not in this process's recent session history).",
280
324
  inputSchema: z.object({
281
325
  // Blank is a malformed call, not a stale id.
282
- sessionId: z.string().trim().min(1, "sessionId must not be blank"),
326
+ 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."),
283
327
  force: z.boolean().default(false).describe("Kill the agent process if the turn is still running after a short grace period."),
284
328
  }),
285
329
  annotations: {
@@ -290,16 +334,16 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
290
334
  openWorldHint: false,
291
335
  },
292
336
  },
293
- async ({ sessionId, force }) => {
294
- const handles = inFlight.get(sessionId);
337
+ async ({ sessionId: id, force }) => {
338
+ const { sessionId, handles } = targetOf(id);
295
339
  if (!handles || handles.size === 0) {
296
340
  // A finished session is still resumable; only an unknown id is not-found.
297
341
  const known = seenSessions.has(sessionId);
298
342
  return cancelResult(known ? "not-running" : "not-found", sessionId);
299
343
  }
300
- // Every turn on the id (the caller named a session), taken now: a resume that registers during
301
- // the grace or the kill is not swept in. An ended turn stays registered while its agent is
302
- // stopped; its result is decided, so a cancel leaves it alone.
344
+ // Every turn the id names, taken now: a resume that registers during the grace or the kill is
345
+ // not swept in. An ended turn stays registered while its agent is stopped; its result is
346
+ // decided, so a cancel leaves it alone.
303
347
  const targeted = [...handles].filter((handle) => !handle.ended);
304
348
  if (targeted.length === 0) return cancelResult("not-running", sessionId);
305
349
  for (const handle of targeted) handle.cancelRequested = true;
@@ -310,7 +354,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
310
354
  return cancelResult("cancelled", sessionId);
311
355
  }
312
356
  // Polled, not slept through: the turn often settles well inside the grace.
313
- const running = () => targeted.filter((handle) => !handle.ended && inFlight.get(sessionId)?.has(handle));
357
+ const running = () => targeted.filter((handle) => !handle.ended && flights.get(sessionId)?.has(handle));
314
358
  const graceEnds = Date.now() + forceGraceMs;
315
359
  while (Date.now() < graceEnds && running().length) {
316
360
  await new Promise((r) => setTimeout(r, Math.min(50, Math.max(1, graceEnds - Date.now()))));
@@ -322,7 +366,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
322
366
  );
323
367
  // "killed" needs an observed exit; without one the handles stay and force can be retried.
324
368
  if (!observed.every(Boolean)) return cancelResult("cancelled", sessionId);
325
- for (const handle of toKill) unregisterInFlight(inFlight, sessionId, handle);
369
+ for (const handle of toKill) unregisterInFlight(flights, sessionId, handle);
326
370
  return cancelResult("killed", sessionId);
327
371
  }
328
372
  );
@@ -437,7 +481,8 @@ if (isMain) {
437
481
  console.log(readPackageVersion());
438
482
  } else {
439
483
  installSignalCleanup(inFlight, { pending: pendingDelegations });
440
- // One factory serves both protocol eras: a 2025-era initialize pins a legacy instance.
441
- serveStdio(() => buildServer());
484
+ // One factory serves both protocol eras: a 2025-era initialize pins a legacy instance, and only
485
+ // a modern one answers with tasks.
486
+ serveStdio(({ era }) => buildServer({ era }));
442
487
  }
443
488
  }
@@ -90,7 +90,7 @@ export class SessionSupervisor {
90
90
  }
91
91
 
92
92
  abort() {
93
- this._trip("aborted", "delegation aborted by MCP host");
93
+ this._trip("aborted", "delegation aborted by MCP host.");
94
94
  }
95
95
 
96
96
  _trip(reason, message) {
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, handle?: any, 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, handle?: any) => 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, handle) => { task.sessionId = sessionId; task.handle = handle; 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
+ }