From 423af9ae663a0b04ca195f72f33d94f3b5eb3de6 Mon Sep 17 00:00:00 2001 From: nach <10445733+nachogames@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:20:14 -0500 Subject: [PATCH 1/2] fix(cursor): ask_user works again with the out-of-process Cursor SDK Cursor now runs in a worker process, and send options reach it as JSON. The ask_user tool's execute function was dropped on the way, so every call failed with "i.execute is not a function". The worker now gives each custom tool an execute that sends a customToolCall frame to the server. The server runs the real tool and replies with customToolResult. Co-Authored-By: Claude Opus 5.5 --- .../CursorAgentSdkProcessRunner.test.ts | 140 ++++++++++++++++++ .../src/server/CursorAgentSdkProcessRunner.ts | 43 +++++- .../src/server/CursorAgentSdkWorker.ts | 12 +- .../server/CursorAgentSdkWorkerProtocol.ts | 73 +++++++++ 4 files changed, 266 insertions(+), 2 deletions(-) diff --git a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts index f52a11fb25a87..1fddf3623abb0 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts @@ -1,3 +1,4 @@ +import type { SDKCustomTool } from "@cursor/sdk"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { ProviderSessionId, ThreadId } from "@t3tools/contracts"; @@ -13,8 +14,10 @@ import * as Path from "effect/Path"; import * as CursorAgentSdk from "./CursorAgentSdk.ts"; import * as CursorAgentSdkProcessRunner from "./CursorAgentSdkProcessRunner.ts"; import { + type CursorWorkerMessage, deserializeRunResult, deserializeWorkerError, + makeCustomToolBridge, serializeRunResult, serializeWorkerError, } from "./CursorAgentSdkWorkerProtocol.ts"; @@ -26,6 +29,8 @@ const readline = require("node:readline"); const rawWrite = process.stdout.write.bind(process.stdout); const send = (msg) => rawWrite(JSON.stringify(msg) + "\\n"); const mode = process.env.FAKE_WORKER_MODE || "ok"; +let toolSendId; +const toolResults = []; const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); rl.on("line", (line) => { @@ -57,6 +62,13 @@ rl.on("line", (line) => { send({ type: "protocolLog", providerSessionId: "provider-session-worker-test", event: { direction: "incoming", stage: "decoded", payload: { type: "run.started", runId: "pending", agentId: "agent-worker-1" } } }); return; } + if (mode === "custom-tool") { + toolSendId = req.id; + send({ type: "response", id: req.id, ok: true, result: { runId: "run-tool", agentId: "agent-worker-1" } }); + send({ type: "customToolCall", sendId: req.id, callId: 7, toolName: "ask_user", args: { question: "Pick one?" }, context: { toolCallId: "tc-7" } }); + send({ type: "customToolCall", sendId: req.id, callId: 8, toolName: "missing", args: {}, context: {} }); + return; + } if (mode === "crash-mid-run") { send({ type: "response", id: req.id, ok: true, result: { runId: "run-crash", agentId: "agent-worker-1" } }); process.stderr.write("fatal worker boom\\n"); @@ -93,6 +105,26 @@ rl.on("line", (line) => { } return; } + if (req.type === "customToolResult") { + send({ type: "response", id: req.id, ok: true, result: null }); + toolResults.push(req); + if (toolResults.length < 2) return; + toolResults.sort((a, b) => a.callId - b.callId); + send({ + type: "runDone", + sendId: toolSendId, + ok: true, + result: { + id: "run-tool", + requestId: "req-tool", + status: "finished", + result: JSON.stringify(toolResults.map(({ callId, ok, result, error }) => ({ callId, ok, result, error: error && error.message }))), + model: { id: "default" }, + durationMs: 1, + }, + }); + return; + } if (req.type === "stopBackgroundShell") { send({ type: "backgroundShell", sessionId: req.sessionId, event: { type: "ended", id: req.shellId, pid: 4101, command: "sleep 60", stopped: true, exitCode: undefined, outputPath: undefined } }); send({ type: "response", id: req.id, ok: true, result: null }); @@ -242,6 +274,71 @@ describe("CursorAgentSdkWorkerProtocol", () => { const restoredNullProto = deserializeWorkerError(serializeWorkerError(nullProto)); assert.equal(restoredNullProto.message, "[Unserializable error]"); }); + + it.effect( + "forwards a custom tool call from the worker and settles it with the server's answer", + () => + Effect.gen(function* () { + const written: Array = []; + const bridge = makeCustomToolBridge((message) => written.push(message)); + // The tool as it arrives in the worker: its `execute` was lost in the JSON frame. + const received = JSON.parse( + JSON.stringify({ + local: { customTools: { ask_user: { description: "Ask", execute: () => "never" } } }, + }), + ) as { local: { customTools: Record } }; + const tool = bridge.bridgeSendOptions(42, received).local!.customTools!.ask_user!; + + const answered = Effect.promise(async () => + tool.execute({ question: "Pick?" }, { toolCallId: "tc-1" }), + ); + const failed = Effect.promise(() => + Promise.resolve(tool.execute({ question: "Again?" }, {})).then( + () => "resolved", + (error: Error) => error.message, + ), + ); + const [first, second] = yield* Effect.all( + [ + answered, + failed, + Effect.sync(() => { + assert.deepEqual( + written.map((message) => + message.type === "customToolCall" ? [message.sendId, message.callId] : null, + ), + [ + [42, 1], + [42, 2], + ], + ); + assert.deepInclude(written[0], { + toolName: "ask_user", + args: { question: "Pick?" }, + context: { toolCallId: "tc-1" }, + }); + bridge.settle({ + id: 1, + type: "customToolResult", + callId: 1, + ok: true, + result: "blue", + }); + bridge.settle({ + id: 2, + type: "customToolResult", + callId: 2, + ok: false, + error: { name: "Error", message: "dismissed" }, + }); + }), + ], + { concurrency: "unbounded" }, + ); + assert.equal(first, "blue"); + assert.equal(second, "dismissed"); + }), + ); }); describe("CursorAgentSdkProcessRunner", () => { @@ -392,6 +489,49 @@ describe("CursorAgentSdkProcessRunner", () => { ).pipe(Effect.provide(NodeServices.layer)), ); + it.live("runs the server's custom tool when the worker calls it and returns the answer", () => + Effect.scoped( + Effect.gen(function* () { + const scriptPath = yield* writeFakeWorker; + const executable = yield* HostProcess.ExecutablePath; + const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({ + resolveLaunch: Effect.succeed({ + command: executable, + args: [scriptPath], + env: { FAKE_WORKER_MODE: "custom-tool" }, + }), + protocolLoggerFor: () => undefined, + }); + const calls: Array = []; + const session = yield* runner.open(openInput); + const run = yield* session.send({ + message: "ask me", + options: { + local: { + customTools: { + ask_user: { + execute: (args, context) => { + calls.push({ args, context }); + return "blue"; + }, + }, + }, + }, + }, + }); + const result = yield* run.wait; + assert.deepEqual(calls, [ + { args: { question: "Pick one?" }, context: { toolCallId: "tc-7" } }, + ]); + assert.deepEqual(JSON.parse(result.result ?? ""), [ + { callId: 7, ok: true, result: "blue" }, + { callId: 8, ok: false, error: "Unknown custom tool: missing" }, + ]); + yield* session.close; + }), + ).pipe(Effect.provide(NodeServices.layer)), + ); + it.live("fails run.wait with exit code and stderr when the worker crashes mid-run", () => Effect.scoped( Effect.gen(function* () { diff --git a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts index ec40415dd932a..271763e8ade2c 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts @@ -1,4 +1,10 @@ -import type { AgentMessage, InteractionUpdate, RunResult, SteerAckOutcome } from "@cursor/sdk"; +import type { + AgentMessage, + InteractionUpdate, + RunResult, + SDKCustomTool, + SteerAckOutcome, +} from "@cursor/sdk"; import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; import { AgentScope } from "@t3tools/shared/AgentScope"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -29,6 +35,7 @@ import { deserializeRunResult, deserializeWorkerError, encodeWorkerFrame, + serializeWorkerError, } from "./CursorAgentSdkWorkerProtocol.ts"; const WORKER_CLOSE_TIMEOUT = Duration.seconds(3); @@ -56,6 +63,7 @@ interface ActiveWorkerRun { readonly queue: Queue.Queue; readonly waitDeferred: Deferred.Deferred; readonly onStartupPhase: ((phase: string) => Effect.Effect) | undefined; + readonly customTools: Record | undefined; doneEnqueued: boolean; } @@ -109,6 +117,7 @@ interface SpawnedCursorWorker { sessionId: number, sendId: number, onStartupPhase: ActiveWorkerRun["onStartupPhase"], + customTools: ActiveWorkerRun["customTools"], ) => Effect.Effect; readonly unregisterRun: (sendId: number) => Effect.Effect; readonly failSessionRuns: (sessionId: number) => Effect.Effect; @@ -365,6 +374,35 @@ export const makeCursorAgentSdkProcessRunner = Effect.fn("makeCursorAgentSdkProc } case "startupPhase": return activeRuns.get(parsed.sendId)?.onStartupPhase?.(parsed.phase) ?? Effect.void; + case "customToolCall": { + const { callId, toolName, args, context } = parsed; + const tool = activeRuns.get(parsed.sendId)?.customTools?.[toolName]; + // Forked: a tool such as ask_user waits on the user while frames keep flowing. + return Effect.tryPromise({ + try: async () => { + if (tool === undefined) throw new Error(`Unknown custom tool: ${toolName}`); + return await tool.execute(args, context); + }, + catch: (cause) => toRunnerError("customTool.execute", cause), + }).pipe( + Effect.match({ + onSuccess: (result) => ({ ok: true as const, result }), + onFailure: (error) => ({ + ok: false as const, + error: serializeWorkerError(error.cause), + }), + }), + Effect.flatMap((outcome) => + request( + (id) => ({ id, type: "customToolResult", callId, ...outcome }), + "customTool.result", + ), + ), + Effect.ignore, + Effect.forkIn(workerScope), + Effect.asVoid, + ); + } case "runDone": { const run = activeRuns.get(parsed.sendId); if (run !== undefined && !run.doneEnqueued) { @@ -610,6 +648,7 @@ export const makeCursorAgentSdkProcessRunner = Effect.fn("makeCursorAgentSdkProc sessionId: number, sendId: number, onStartupPhase: ActiveWorkerRun["onStartupPhase"], + customTools: ActiveWorkerRun["customTools"], ) { const queue = yield* Queue.unbounded(); const waitDeferred = yield* Deferred.make< @@ -621,6 +660,7 @@ export const makeCursorAgentSdkProcessRunner = Effect.fn("makeCursorAgentSdkProc queue, waitDeferred, onStartupPhase, + customTools, doneEnqueued: false, }; activeRuns.set(sendId, state); @@ -884,6 +924,7 @@ export const makeCursorAgentSdkProcessRunner = Effect.fn("makeCursorAgentSdkProc sessionId, sendId, sendInput.onStartupPhase, + sendInput.options?.local?.customTools, ); let transmitted = false; let acknowledged = false; diff --git a/packages/provider-cursor/src/server/CursorAgentSdkWorker.ts b/packages/provider-cursor/src/server/CursorAgentSdkWorker.ts index cdd0fb0136806..4338fd6620ba1 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdkWorker.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdkWorker.ts @@ -19,6 +19,7 @@ import { type SerializedRunnerFailure, decodeWorkerFrame, encodeWorkerFrame, + makeCustomToolBridge, serializeRunResult, serializeWorkerError, } from "./CursorAgentSdkWorkerProtocol.ts"; @@ -84,6 +85,7 @@ const runCursorSdkWorkerWithStdio = Effect.fn("CursorAgentSdkWorker.run")(functi const pendingCancelledSendIds = new Set(); const sessionIdByOptions = new WeakMap(); let shuttingDown = false; + const customTools = makeCustomToolBridge(writeMessage); const runner = yield* CursorAgentSdk.makeCursorAgentSdkRunner((input) => { const boundSessionId = sessionIdByOptions.get(input.options); @@ -216,7 +218,9 @@ const runCursorSdkWorkerWithStdio = Effect.fn("CursorAgentSdkWorker.run")(functi const exit = yield* Effect.exit( session.send({ message: req.message, - ...(req.options === undefined ? {} : { options: req.options }), + ...(req.options === undefined + ? {} + : { options: customTools.bridgeSendOptions(req.id, req.options) }), ...(req.summarize === undefined ? {} : { summarize: req.summarize }), ...(req.resume === undefined ? {} : { resume: req.resume }), onDelta: (update) => @@ -327,6 +331,12 @@ const runCursorSdkWorkerWithStdio = Effect.fn("CursorAgentSdkWorker.run")(functi return; } + case "customToolResult": { + customTools.settle(req); + writeMessage({ type: "response", id: req.id, ok: true, result: null }); + return; + } + case "stopBackgroundShell": { const key = `${req.sessionId}:${req.shellId}`; const stop = backgroundShellStops.get(key); diff --git a/packages/provider-cursor/src/server/CursorAgentSdkWorkerProtocol.ts b/packages/provider-cursor/src/server/CursorAgentSdkWorkerProtocol.ts index 7f33fde74d0ee..309ada45806cf 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdkWorkerProtocol.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdkWorkerProtocol.ts @@ -3,6 +3,10 @@ import type { AgentOptions, InteractionUpdate, RunResult, + SDKCustomTool, + SDKCustomToolContext, + SDKCustomToolResult, + SDKJsonValue, SDKUserMessage, SendOptions, SteerAckOutcome, @@ -123,6 +127,14 @@ export type CursorWorkerRequest = readonly type: "cancelTextGenerate"; readonly textGenerateId: number; } + | ({ + readonly id: number; + readonly type: "customToolResult"; + readonly callId: number; + } & ( + | { readonly ok: true; readonly result: SDKCustomToolResult } + | { readonly ok: false; readonly error: SerializedWorkerError } + )) | { /** Closes every session and exits the worker. */ readonly id: number; @@ -188,6 +200,15 @@ export type CursorWorkerMessage = readonly type: "backgroundShell"; readonly sessionId: number; readonly event: SerializedBackgroundShellEvent; + } + | { + /** Custom tool callbacks stay in the server; the worker asks it to run one. */ + readonly type: "customToolCall"; + readonly sendId: number; + readonly callId: number; + readonly toolName: string; + readonly args: Record; + readonly context: SDKCustomToolContext; }; const MAX_ERROR_CAUSE_DEPTH = 8; @@ -307,3 +328,55 @@ export function encodeWorkerFrame(frame: CursorWorkerRequest | CursorWorkerMessa export function decodeWorkerFrame(line: string): unknown { return JSON.parse(line); } + +type CustomToolResultRequest = Extract; +type WorkerSendOptions = NonNullable["options"]>; + +/** + * Worker half of custom tools. `execute` does not survive the JSON frame, so each bridged tool + * posts a `customToolCall` and waits for the server's `customToolResult`. + */ +export function makeCustomToolBridge(writeMessage: (message: CursorWorkerMessage) => void) { + const pending = new Map< + number, + { + readonly resolve: (result: SDKCustomToolResult) => void; + readonly reject: (error: Error) => void; + } + >(); + let nextCallId = 0; + + const bridgeTools = ( + sendId: number, + tools: Record, + ): Record => + Object.fromEntries( + Object.entries(tools).map(([toolName, tool]) => [ + toolName, + { + ...tool, + execute: (args, context) => + new Promise((resolve, reject) => { + const callId = ++nextCallId; + pending.set(callId, { resolve, reject }); + writeMessage({ type: "customToolCall", sendId, callId, toolName, args, context }); + }), + } satisfies SDKCustomTool, + ]), + ); + + return { + bridgeSendOptions: (sendId: number, options: WorkerSendOptions): WorkerSendOptions => { + const tools = options.local?.customTools; + if (tools === undefined) return options; + return { ...options, local: { ...options.local, customTools: bridgeTools(sendId, tools) } }; + }, + settle: (req: CustomToolResultRequest): void => { + const call = pending.get(req.callId); + pending.delete(req.callId); + if (call === undefined) return; + if (req.ok) call.resolve(req.result); + else call.reject(deserializeWorkerError(req.error)); + }, + }; +} From b0e104fb1dea40347249c6a05c56edf2dfba1199 Mon Sep 17 00:00:00 2001 From: nach <10445733+nachogames@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:37:57 -0500 Subject: [PATCH 2/2] fix(cursor): refuse open-time custom tools and name ended runs Custom tools passed when opening a Cursor agent would reach the worker without execute, the same silent failure as ask_user. The process runner now refuses them with a clear error. A tool call that arrives after its run has finished now says the run ended instead of calling the tool unknown. Co-Authored-By: Claude Opus 5.5 --- .../src/server/CursorAgentSdkProcessRunner.test.ts | 10 ++++++++++ .../src/server/CursorAgentSdkProcessRunner.ts | 12 +++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts index 1fddf3623abb0..793aba9cc884f 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts @@ -502,6 +502,16 @@ describe("CursorAgentSdkProcessRunner", () => { }), protocolLoggerFor: () => undefined, }); + const openError = yield* Effect.flip( + runner.open({ + ...openInput, + options: { + ...openInput.options, + local: { customTools: { ask_user: { execute: () => "" } } }, + }, + }), + ); + assert.equal(openError.method, "agent.open"); const calls: Array = []; const session = yield* runner.open(openInput); const run = yield* session.send({ diff --git a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts index 271763e8ade2c..ee95889311b63 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts @@ -376,10 +376,12 @@ export const makeCursorAgentSdkProcessRunner = Effect.fn("makeCursorAgentSdkProc return activeRuns.get(parsed.sendId)?.onStartupPhase?.(parsed.phase) ?? Effect.void; case "customToolCall": { const { callId, toolName, args, context } = parsed; - const tool = activeRuns.get(parsed.sendId)?.customTools?.[toolName]; + const run = activeRuns.get(parsed.sendId); + const tool = run?.customTools?.[toolName]; // Forked: a tool such as ask_user waits on the user while frames keep flowing. return Effect.tryPromise({ try: async () => { + if (run === undefined) throw new Error(`The run calling ${toolName} has ended.`); if (tool === undefined) throw new Error(`Unknown custom tool: ${toolName}`); return await tool.execute(args, context); }, @@ -813,6 +815,14 @@ export const makeCursorAgentSdkProcessRunner = Effect.fn("makeCursorAgentSdkProc }, }); + // Only send-time tools are forwarded back to the server; open-time ones would lose `execute`. + if (input.options.local?.customTools !== undefined) { + return yield* toRunnerError( + "agent.open", + new Error("Pass Cursor custom tools when sending, not when opening the agent."), + ); + } + const lease = yield* acquireWorker; const { worker } = lease; const sessionId = worker.nextId();