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 loadCursorSdk: () => ({
98 Agent: {
99 create: cursorSdkMock.create,
100 resume: cursorSdkMock.resume,
101 listRuns: cursorSdkMock.listRuns,
102 cancelRun: cursorSdkMock.cancelRun,
103 messages: {
104 list: vi.fn(async () => []),
105 },
106 },
107 createAgentPlatform: vi.fn(),
108 }),
109 loadCursorSqlite: () => ({ SqliteLocalAgentStore: { open: vi.fn() } }),
110}));
111
112const layerTest = CursorAgentSdk.layer.pipe(
113 Layer.provide(
114 Layer.succeed(ProviderEventLoggers.ProviderEventLoggers, {
115 native: {
116 filePath: "cursor-agent-sdk-test.log",
117 write: (event: unknown) =>
118 Effect.sync(() => {
119 if (
120 typeof event === "object" &&
121 event !== null &&
122 Reflect.get(Reflect.get(event, "event"), "payload")?.type === "agent.close"
123 ) {
124 cursorSdkMock.closeExecutionOrder.push("protocol:agent.close");
125 }
126 }),
127 close: () => Effect.void,
128 },
129 canonical: undefined,
130 }),
131 ),
132 Layer.provide(CursorSdk.layer),
133 Layer.provide(NodeServices.layer),
134);
135
136describe("CursorAgentSdkRunner", () => {
137 it.effect("leaves a resumed agent alone when its next send succeeds", () =>
138 Effect.gen(function* () {
139 cursorSdkMock.runOperations.length = 0;
140 cursorSdkMock.setStaleRunActive(false);
141
142 const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;
143 const session = yield* runner.open({
144 operation: "resume",
145 agentId: "agent-cursor-agent-sdk-test",
146 options: { model: { id: "default" }, mode: "agent", local: { cwd: process.cwd() } },
147 threadId: ThreadId.make("thread-cursor-agent-sdk-normal-resume-test"),
148 providerSessionId: ProviderSessionId.make(
149 "provider-session-cursor-agent-sdk-normal-resume-test",
150 ),
151 });
152 const run = yield* session.send({ message: "continue" });
153 yield* run.wait;
154
155 assert.deepStrictEqual(cursorSdkMock.runOperations, ["run.start"]);
156 }).pipe(Effect.provide(layerTest)),
157 );
158
159 it.effect("retries a resumed send after cancelling its abandoned local run", () =>
160 Effect.gen(function* () {
161 cursorSdkMock.runOperations.length = 0;
162 cursorSdkMock.listRuns.mockClear();
163 cursorSdkMock.cancelRun.mockClear();
164 cursorSdkMock.setStaleRunActive(true);
165
166 const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;
167 const session = yield* runner.open({
168 operation: "resume",
169 agentId: "agent-cursor-agent-sdk-test",
170 options: { model: { id: "default" }, mode: "agent", local: { cwd: process.cwd() } },
171 threadId: ThreadId.make("thread-cursor-agent-sdk-stale-run-test"),
172 providerSessionId: ProviderSessionId.make(
173 "provider-session-cursor-agent-sdk-stale-run-test",
174 ),
175 });
176 assert.deepStrictEqual(cursorSdkMock.runOperations, []);
177 const run = yield* session.send({ message: "continue" });
178 yield* run.wait;
179
180 assert.deepStrictEqual(cursorSdkMock.runOperations, [
181 "run.start",
182 "agent.listRuns",
183 "agent.cancelRun",
184 "run.start",
185 ]);
186 assert.deepStrictEqual(cursorSdkMock.listRuns.mock.calls[0], [
187 "agent-cursor-agent-sdk-test",
188 { runtime: "local", cwd: process.cwd(), limit: 1 },
189 ]);
190 assert.deepStrictEqual(cursorSdkMock.cancelRun.mock.calls[0], [
191 "run-stale",
192 {
193 runtime: "local",
194 cwd: process.cwd(),
195 },
196 ]);
197 }).pipe(Effect.provide(layerTest)),
198 );
199
200 it.effect("logs agent.close before invoking the Cursor SDK", () =>
201 Effect.gen(function* () {
202 cursorSdkMock.agentClose.mockClear();
203 cursorSdkMock.closeExecutionOrder.length = 0;
204 cursorSdkMock.setAgentCloseFailure(undefined);
205
206 const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;
207 const session = yield* runner.open({
208 operation: "create",
209 options: {
210 model: { id: "default" },
211 mode: "agent",
212 local: {
213 cwd: process.cwd(),
214 },
215 },
216 threadId: ThreadId.make("thread-cursor-agent-sdk-close-order-test"),
217 providerSessionId: ProviderSessionId.make(
218 "provider-session-cursor-agent-sdk-close-order-test",
219 ),
220 });
221
222 cursorSdkMock.closeExecutionOrder.length = 0;
223 yield* session.close;
224
225 assert.deepStrictEqual(cursorSdkMock.closeExecutionOrder, [
226 "protocol:agent.close",
227 "sdk:agent.close",
228 ]);
229 assert.equal(cursorSdkMock.agentClose.mock.calls.length, 1);
230 }).pipe(Effect.provide(layerTest)),
231 );
232
233 it.effect("logs agent.close even when the Cursor SDK close fails", () =>
234 Effect.gen(function* () {
235 cursorSdkMock.agentClose.mockClear();
236 cursorSdkMock.closeExecutionOrder.length = 0;
237 const closeFailure = new Error("agent close failed");
238 cursorSdkMock.setAgentCloseFailure(closeFailure);
239
240 const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;
241 const session = yield* runner.open({
242 operation: "create",
243 options: {
244 model: { id: "default" },
245 mode: "agent",
246 local: {
247 cwd: process.cwd(),
248 },
249 },
250 threadId: ThreadId.make("thread-cursor-agent-sdk-close-failure-test"),
251 providerSessionId: ProviderSessionId.make(
252 "provider-session-cursor-agent-sdk-close-failure-test",
253 ),
254 });
255
256 cursorSdkMock.closeExecutionOrder.length = 0;
257 const error = yield* Effect.flip(session.close);
258
259 assert.instanceOf(error, CursorAgentSdk.CursorAgentSdkRunnerError);
260 assert.equal(error.method, "agent.close");
261 assert.strictEqual(error.cause, closeFailure);
262 assert.deepStrictEqual(cursorSdkMock.closeExecutionOrder, [
263 "protocol:agent.close",
264 "sdk:agent.close",
265 ]);
266 assert.equal(cursorSdkMock.agentClose.mock.calls.length, 1);
267 cursorSdkMock.setAgentCloseFailure(undefined);
268 }).pipe(Effect.provide(layerTest)),
269 );
270
271 it.effect("surfaces interaction callback failures through run.wait", () =>
272 Effect.gen(function* () {
273 cursorSdkMock.create.mockClear();
274 cursorSdkMock.runWait.mockClear();
275 cursorSdkMock.send.mockClear();
276
277 const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;
278 const session = yield* runner.open({
279 operation: "create",
280 options: {
281 model: { id: "default" },
282 mode: "agent",
283 local: {
284 cwd: process.cwd(),
285 autoReview: false,
286 sandboxOptions: { enabled: false },
287 enableAgentRetries: true,
288 },
289 },
290 threadId: ThreadId.make("thread-cursor-agent-sdk-test"),
291 providerSessionId: ProviderSessionId.make("provider-session-cursor-agent-sdk-test"),
292 });
293
294 const callbackFailure = new Error("delta callback failed");
295 const run = yield* session.send({
296 message: "hello",
297 onDelta: () => Effect.fail(callbackFailure),
298 });
299
300 const error = yield* Effect.flip(run.wait);
301
302 assert.instanceOf(error, CursorAgentSdk.CursorAgentSdkRunnerError);
303 assert.equal(error.method, "run.wait");
304 assert.strictEqual(error.cause, callbackFailure);
305 assert.equal(cursorSdkMock.create.mock.calls.length, 1);
306 assert.equal(cursorSdkMock.send.mock.calls.length, 1);
307 assert.equal(cursorSdkMock.runWait.mock.calls.length, 1);
308 }).pipe(Effect.provide(layerTest)),
309 );
310
311 it("names the SDK's reason, code and HTTP status in a runner failure's text", () => {
312 const failed = (cause: unknown) =>
313 CursorAgentSdk.cursorSdkFailureMessage(
314 new CursorAgentSdk.CursorAgentSdkRunnerError({ method: "agent.create", cause }),
315 );
316 assert.equal(
317 new CursorAgentSdk.CursorAgentSdkRunnerError({
318 method: "agent.create",
319 cause: new Error("Too many requests"),
320 }).message,
321 "Cursor Agent SDK agent.create failed.",
322 );
323 assert.equal(
324 failed(Object.assign(new Error("Too many requests"), { code: "rate_limited", status: 429 })),
325 "Cursor Agent SDK agent.create failed: Too many requests (rate_limited, HTTP 429)",
326 );
327 // Cursor's messages often start with the code already.
328 assert.equal(
329 failed(
330 Object.assign(new Error("[resource_exhausted] Error"), { code: "resource_exhausted" }),
331 ),
332 "Cursor Agent SDK agent.create failed: [resource_exhausted] Error",
333 );
334 assert.equal(
335 failed(Object.assign(new Error("Invalid User API Key"), { code: "error", status: 401 })),
336 "Cursor Agent SDK agent.create failed: Invalid User API Key (HTTP 401)",
337 );
338 assert.equal(failed(undefined), "Cursor Agent SDK agent.create failed.");
339 });
340});