Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import { ProviderSessionId, ThreadId } from "@t3tools/contracts";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import { vi } from "vite-plus/test";
7
8import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
9import * as CursorAgentSdk from "./CursorAgentSdk.ts";
10import * as CursorSdk from "./CursorSdk.ts";
11
12const cursorSdkMock = vi.hoisted(() => {
13 const closeExecutionOrder: Array<string> = [];
14 const runOperations: Array<string> = [];
15 let agentCloseFailure: unknown;
16 let staleRunActive = false;
17 const runWait = vi.fn(async () => ({
18 id: "run-cursor-agent-sdk-test",
19 requestId: "request-cursor-agent-sdk-test",
20 status: "finished",
21 result: "ok",
22 model: { id: "default" },
23 durationMs: 1,
24 }));
25 const runCancel = vi.fn(async () => {});
26 const agentClose = vi.fn(() => {
27 closeExecutionOrder.push("sdk:agent.close");
28 if (agentCloseFailure !== undefined) {
29 throw agentCloseFailure;
30 }
31 });
32 const send = vi.fn(
33 async (
34 _message: unknown,
35 options: { readonly onDelta?: (input: { readonly update: unknown }) => Promise<void> },
36 ) => {
37 runOperations.push("run.start");
38 if (staleRunActive) {
39 throw new Error("Agent agent-cursor-agent-sdk-test already has active run");
40 }
41 await options.onDelta?.({
42 update: {
43 type: "assistant-message-chunk",
44 text: "hello",
45 },
46 });
47 return {
48 id: "run-cursor-agent-sdk-test",
49 agentId: "agent-cursor-agent-sdk-test",
50 wait: runWait,
51 cancel: runCancel,
52 };
53 },
54 );
55 const create = vi.fn(async () => ({
56 agentId: "agent-cursor-agent-sdk-test",
57 send,
58 close: agentClose,
59 }));
60 const resume = vi.fn(async () => ({
61 agentId: "agent-cursor-agent-sdk-test",
62 send,
63 close: agentClose,
64 }));
65 const listRuns = vi.fn(async () => {
66 runOperations.push("agent.listRuns");
67 return {
68 items: staleRunActive ? [{ id: "run-stale", status: "running" }] : [],
69 };
70 });
71 const cancelRun = vi.fn(async () => {
72 runOperations.push("agent.cancelRun");
73 staleRunActive = false;
74 });
75
76 return {
77 agentClose,
78 cancelRun,
79 closeExecutionOrder,
80 create,
81 listRuns,
82 resume,
83 runOperations,
84 runCancel,
85 runWait,
86 send,
87 setAgentCloseFailure: (failure: unknown) => {
88 agentCloseFailure = failure;
89 },
90 setStaleRunActive: (active: boolean) => {
91 staleRunActive = active;
92 },
93 };
94});
95
96vi.mock("./sdk.ts", () => ({
97 Agent: {
98 create: cursorSdkMock.create,
99 resume: cursorSdkMock.resume,
100 listRuns: cursorSdkMock.listRuns,
101 cancelRun: cursorSdkMock.cancelRun,
102 messages: {
103 list: vi.fn(async () => []),
104 },
105 },
106 createAgentPlatform: vi.fn(),
107}));
108
109const layerTest = CursorAgentSdk.layer.pipe(
110 Layer.provide(
111 Layer.succeed(ProviderEventLoggers.ProviderEventLoggers, {
112 native: {
113 filePath: "cursor-agent-sdk-test.log",
114 write: (event: unknown) =>
115 Effect.sync(() => {
116 if (
117 typeof event === "object" &&
118 event !== null &&
119 Reflect.get(Reflect.get(event, "event"), "payload")?.type === "agent.close"
120 ) {
121 cursorSdkMock.closeExecutionOrder.push("protocol:agent.close");
122 }
123 }),
124 close: () => Effect.void,
125 },
126 canonical: undefined,
127 }),
128 ),
129 Layer.provide(CursorSdk.layer),
130 Layer.provide(NodeServices.layer),
131);
132
133describe("CursorAgentSdkRunner", () => {
134 it.effect("leaves a resumed agent alone when its next send succeeds", () =>
135 Effect.gen(function* () {
136 cursorSdkMock.runOperations.length = 0;
137 cursorSdkMock.setStaleRunActive(false);
138
139 const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;
140 const session = yield* runner.open({
141 operation: "resume",
142 agentId: "agent-cursor-agent-sdk-test",
143 options: { model: { id: "default" }, mode: "agent", local: { cwd: process.cwd() } },
144 threadId: ThreadId.make("thread-cursor-agent-sdk-normal-resume-test"),
145 providerSessionId: ProviderSessionId.make(
146 "provider-session-cursor-agent-sdk-normal-resume-test",
147 ),
148 });
149 const run = yield* session.send({ message: "continue" });
150 yield* run.wait;
151
152 assert.deepStrictEqual(cursorSdkMock.runOperations, ["run.start"]);
153 }).pipe(Effect.provide(layerTest)),
154 );
155
156 it.effect("retries a resumed send after cancelling its abandoned local run", () =>
157 Effect.gen(function* () {
158 cursorSdkMock.runOperations.length = 0;
159 cursorSdkMock.listRuns.mockClear();
160 cursorSdkMock.cancelRun.mockClear();
161 cursorSdkMock.setStaleRunActive(true);
162
163 const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;
164 const session = yield* runner.open({
165 operation: "resume",
166 agentId: "agent-cursor-agent-sdk-test",
167 options: { model: { id: "default" }, mode: "agent", local: { cwd: process.cwd() } },
168 threadId: ThreadId.make("thread-cursor-agent-sdk-stale-run-test"),
169 providerSessionId: ProviderSessionId.make(
170 "provider-session-cursor-agent-sdk-stale-run-test",
171 ),
172 });
173 assert.deepStrictEqual(cursorSdkMock.runOperations, []);
174 const run = yield* session.send({ message: "continue" });
175 yield* run.wait;
176
177 assert.deepStrictEqual(cursorSdkMock.runOperations, [
178 "run.start",
179 "agent.listRuns",
180 "agent.cancelRun",
181 "run.start",
182 ]);
183 assert.deepStrictEqual(cursorSdkMock.listRuns.mock.calls[0], [
184 "agent-cursor-agent-sdk-test",
185 { runtime: "local", cwd: process.cwd(), limit: 1 },
186 ]);
187 assert.deepStrictEqual(cursorSdkMock.cancelRun.mock.calls[0], [
188 "run-stale",
189 {
190 runtime: "local",
191 cwd: process.cwd(),
192 },
193 ]);
194 }).pipe(Effect.provide(layerTest)),
195 );
196
197 it.effect("logs agent.close before invoking the Cursor SDK", () =>
198 Effect.gen(function* () {
199 cursorSdkMock.agentClose.mockClear();
200 cursorSdkMock.closeExecutionOrder.length = 0;
201 cursorSdkMock.setAgentCloseFailure(undefined);
202
203 const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;
204 const session = yield* runner.open({
205 operation: "create",
206 options: {
207 model: { id: "default" },
208 mode: "agent",
209 local: {
210 cwd: process.cwd(),
211 },
212 },
213 threadId: ThreadId.make("thread-cursor-agent-sdk-close-order-test"),
214 providerSessionId: ProviderSessionId.make(
215 "provider-session-cursor-agent-sdk-close-order-test",
216 ),
217 });
218
219 cursorSdkMock.closeExecutionOrder.length = 0;
220 yield* session.close;
221
222 assert.deepStrictEqual(cursorSdkMock.closeExecutionOrder, [
223 "protocol:agent.close",
224 "sdk:agent.close",
225 ]);
226 assert.equal(cursorSdkMock.agentClose.mock.calls.length, 1);
227 }).pipe(Effect.provide(layerTest)),
228 );
229
230 it.effect("logs agent.close even when the Cursor SDK close fails", () =>
231 Effect.gen(function* () {
232 cursorSdkMock.agentClose.mockClear();
233 cursorSdkMock.closeExecutionOrder.length = 0;
234 const closeFailure = new Error("agent close failed");
235 cursorSdkMock.setAgentCloseFailure(closeFailure);
236
237 const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;
238 const session = yield* runner.open({
239 operation: "create",
240 options: {
241 model: { id: "default" },
242 mode: "agent",
243 local: {
244 cwd: process.cwd(),
245 },
246 },
247 threadId: ThreadId.make("thread-cursor-agent-sdk-close-failure-test"),
248 providerSessionId: ProviderSessionId.make(
249 "provider-session-cursor-agent-sdk-close-failure-test",
250 ),
251 });
252
253 cursorSdkMock.closeExecutionOrder.length = 0;
254 const error = yield* Effect.flip(session.close);
255
256 assert.instanceOf(error, CursorAgentSdk.CursorAgentSdkRunnerError);
257 assert.equal(error.method, "agent.close");
258 assert.strictEqual(error.cause, closeFailure);
259 assert.deepStrictEqual(cursorSdkMock.closeExecutionOrder, [
260 "protocol:agent.close",
261 "sdk:agent.close",
262 ]);
263 assert.equal(cursorSdkMock.agentClose.mock.calls.length, 1);
264 cursorSdkMock.setAgentCloseFailure(undefined);
265 }).pipe(Effect.provide(layerTest)),
266 );
267
268 it.effect("surfaces interaction callback failures through run.wait", () =>
269 Effect.gen(function* () {
270 cursorSdkMock.create.mockClear();
271 cursorSdkMock.runWait.mockClear();
272 cursorSdkMock.send.mockClear();
273
274 const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;
275 const session = yield* runner.open({
276 operation: "create",
277 options: {
278 model: { id: "default" },
279 mode: "agent",
280 local: {
281 cwd: process.cwd(),
282 autoReview: false,
283 sandboxOptions: { enabled: false },
284 enableAgentRetries: true,
285 },
286 },
287 threadId: ThreadId.make("thread-cursor-agent-sdk-test"),
288 providerSessionId: ProviderSessionId.make("provider-session-cursor-agent-sdk-test"),
289 });
290
291 const callbackFailure = new Error("delta callback failed");
292 const run = yield* session.send({
293 message: "hello",
294 onDelta: () => Effect.fail(callbackFailure),
295 });
296
297 const error = yield* Effect.flip(run.wait);
298
299 assert.instanceOf(error, CursorAgentSdk.CursorAgentSdkRunnerError);
300 assert.equal(error.method, "run.wait");
301 assert.strictEqual(error.cause, callbackFailure);
302 assert.equal(cursorSdkMock.create.mock.calls.length, 1);
303 assert.equal(cursorSdkMock.send.mock.calls.length, 1);
304 assert.equal(cursorSdkMock.runWait.mock.calls.length, 1);
305 }).pipe(Effect.provide(layerTest)),
306 );
307
308 it("names the SDK's reason, code and HTTP status in a runner failure's text", () => {
309 const failed = (cause: unknown) =>
310 CursorAgentSdk.cursorSdkFailureMessage(
311 new CursorAgentSdk.CursorAgentSdkRunnerError({ method: "agent.create", cause }),
312 );
313 assert.equal(
314 new CursorAgentSdk.CursorAgentSdkRunnerError({
315 method: "agent.create",
316 cause: new Error("Too many requests"),
317 }).message,
318 "Cursor Agent SDK agent.create failed.",
319 );
320 assert.equal(
321 failed(Object.assign(new Error("Too many requests"), { code: "rate_limited", status: 429 })),
322 "Cursor Agent SDK agent.create failed: Too many requests (rate_limited, HTTP 429)",
323 );
324 // Cursor's messages often start with the code already.
325 assert.equal(
326 failed(
327 Object.assign(new Error("[resource_exhausted] Error"), { code: "resource_exhausted" }),
328 ),
329 "Cursor Agent SDK agent.create failed: [resource_exhausted] Error",
330 );
331 assert.equal(
332 failed(Object.assign(new Error("Invalid User API Key"), { code: "error", status: 401 })),
333 "Cursor Agent SDK agent.create failed: Invalid User API Key (HTTP 401)",
334 );
335 assert.equal(failed(undefined), "Cursor Agent SDK agent.create failed.");
336 });
337});