Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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";
Expand All @@ -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) => {
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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 });
Expand Down Expand Up @@ -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<CursorWorkerMessage> = [];
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<string, SDKCustomTool> } };
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", () => {
Expand Down Expand Up @@ -392,6 +489,59 @@ 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 openError = yield* Effect.flip(
runner.open({
...openInput,
options: {
...openInput.options,
local: { customTools: { ask_user: { execute: () => "" } } },
},
}),
);
assert.equal(openError.method, "agent.open");
const calls: Array<unknown> = [];
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* () {
Expand Down
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -29,6 +35,7 @@ import {
deserializeRunResult,
deserializeWorkerError,
encodeWorkerFrame,
serializeWorkerError,
} from "./CursorAgentSdkWorkerProtocol.ts";

const WORKER_CLOSE_TIMEOUT = Duration.seconds(3);
Expand Down Expand Up @@ -56,6 +63,7 @@ interface ActiveWorkerRun {
readonly queue: Queue.Queue<RunQueueItem>;
readonly waitDeferred: Deferred.Deferred<RunResult, CursorAgentSdk.CursorAgentSdkRunnerError>;
readonly onStartupPhase: ((phase: string) => Effect.Effect<void>) | undefined;
readonly customTools: Record<string, SDKCustomTool> | undefined;
doneEnqueued: boolean;
}

Expand Down Expand Up @@ -109,6 +117,7 @@ interface SpawnedCursorWorker {
sessionId: number,
sendId: number,
onStartupPhase: ActiveWorkerRun["onStartupPhase"],
customTools: ActiveWorkerRun["customTools"],
) => Effect.Effect<ActiveWorkerRun>;
readonly unregisterRun: (sendId: number) => Effect.Effect<void>;
readonly failSessionRuns: (sessionId: number) => Effect.Effect<void>;
Expand Down Expand Up @@ -365,6 +374,37 @@ 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 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);
},
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) {
Expand Down Expand Up @@ -610,6 +650,7 @@ export const makeCursorAgentSdkProcessRunner = Effect.fn("makeCursorAgentSdkProc
sessionId: number,
sendId: number,
onStartupPhase: ActiveWorkerRun["onStartupPhase"],
customTools: ActiveWorkerRun["customTools"],
) {
const queue = yield* Queue.unbounded<RunQueueItem>();
const waitDeferred = yield* Deferred.make<
Expand All @@ -621,6 +662,7 @@ export const makeCursorAgentSdkProcessRunner = Effect.fn("makeCursorAgentSdkProc
queue,
waitDeferred,
onStartupPhase,
customTools,
doneEnqueued: false,
};
activeRuns.set(sendId, state);
Expand Down Expand Up @@ -773,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();
Expand Down Expand Up @@ -884,6 +934,7 @@ export const makeCursorAgentSdkProcessRunner = Effect.fn("makeCursorAgentSdkProc
sessionId,
sendId,
sendInput.onStartupPhase,
sendInput.options?.local?.customTools,
);
let transmitted = false;
let acknowledged = false;
Expand Down
12 changes: 11 additions & 1 deletion packages/provider-cursor/src/server/CursorAgentSdkWorker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
type SerializedRunnerFailure,
decodeWorkerFrame,
encodeWorkerFrame,
makeCustomToolBridge,
serializeRunResult,
serializeWorkerError,
} from "./CursorAgentSdkWorkerProtocol.ts";
Expand Down Expand Up @@ -84,6 +85,7 @@ const runCursorSdkWorkerWithStdio = Effect.fn("CursorAgentSdkWorker.run")(functi
const pendingCancelledSendIds = new Set<number>();
const sessionIdByOptions = new WeakMap<object, number>();
let shuttingDown = false;
const customTools = makeCustomToolBridge(writeMessage);

const runner = yield* CursorAgentSdk.makeCursorAgentSdkRunner((input) => {
const boundSessionId = sessionIdByOptions.get(input.options);
Expand Down Expand Up @@ -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) =>
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading