Open History to see the last commit
1import type { ListRunsOptions } from "@cursor/sdk";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, describe, it } from "@effect/vitest";
4import { ProviderSessionId, ThreadId } from "@t3tools/contracts";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Exit from "effect/Exit";
10import * as Cause from "effect/Cause";
11import { vi } from "vite-plus/test";
12
13import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
14import * as CursorAgentSdk from "./CursorAgentSdk.ts";
15import * as CursorSdk from "./CursorSdk.ts";
16
17const cursorSdkMock = vi.hoisted(() => {
18 const closeExecutionOrder: Array<string> = [];
19 const runOperations: Array<string> = [];
20 let agentCloseFailure: unknown;
21 // The local store lists runs oldest first, like the real SDK.
22 let storedRuns: Array<{ readonly id: string; readonly status: string }> = [];
23 const runWait = vi.fn(async () => ({
24 id: "run-cursor-agent-sdk-test",
25 requestId: "request-cursor-agent-sdk-test",
26 status: "finished",
27 result: "ok",
28 model: { id: "default" },
29 durationMs: 1,
30 }));
31 const runCancel = vi.fn(async () => {});
32 const runSteer = vi.fn(async () => "complete_delivered" as const);
33 const agentClose = vi.fn(() => {
34 closeExecutionOrder.push("sdk:agent.close");
35 if (agentCloseFailure !== undefined) {
36 throw agentCloseFailure;
37 }
38 });
39 const send = vi.fn(
40 async (
41 _message: unknown,
42 options: { readonly onDelta?: (input: { readonly update: unknown }) => Promise<void> },
43 ) => {
44 runOperations.push("run.start");
45 if (storedRuns.some((run) => run.status === "running")) {
46 throw new Error("Agent agent-cursor-agent-sdk-test already has active run");
47 }
48 await options.onDelta?.({
49 update: {
50 type: "assistant-message-chunk",
51 text: "hello",
52 },
53 });
54 return {
55 id: "run-cursor-agent-sdk-test",
56 agentId: "agent-cursor-agent-sdk-test",
57 wait: runWait,
58 cancel: runCancel,
59 steer: runSteer as typeof runSteer | undefined,
60 };
61 },
62 );
63 const create = vi.fn(async (_options?: unknown) => ({
64 agentId: "agent-cursor-agent-sdk-test",
65 send,
66 close: agentClose,
67 }));
68 const resume = vi.fn(async () => ({
69 agentId: "agent-cursor-agent-sdk-test",
70 send,
71 close: agentClose,
72 }));
73 const listRuns = vi.fn(async (_agentId: string, options?: ListRunsOptions) => {
74 runOperations.push("agent.listRuns");
75 // Mirrors the SDK's opaque cursor pagination with its default page size of 50.
76 const offset = options?.cursor === undefined ? 0 : Number(options.cursor);
77 const end = offset + (options?.limit ?? 50);
78 return {
79 items: storedRuns.slice(offset, end),
80 ...(end < storedRuns.length ? { nextCursor: String(end) } : {}),
81 };
82 });
83 const cancelRun = vi.fn(async (runId: string) => {
84 runOperations.push("agent.cancelRun");
85 storedRuns = storedRuns.map((run) =>
86 run.id === runId ? { ...run, status: "cancelled" } : run,
87 );
88 });
89
90 const sqliteOpen = vi.fn<() => Promise<unknown>>(async () => undefined);
91
92 return {
93 agentClose,
94 cancelRun,
95 closeExecutionOrder,
96 create,
97 listRuns,
98 resume,
99 runOperations,
100 runCancel,
101 runSteer,
102 runWait,
103 send,
104 sqliteOpen,
105 setAgentCloseFailure: (failure: unknown) => {
106 agentCloseFailure = failure;
107 },
108 setStoredRuns: (runs: Array<{ readonly id: string; readonly status: string }>) => {
109 storedRuns = runs;
110 },
111 };
112});
113
114vi.mock("./sdk.ts", () => ({
115 loadCursorSdk: () => ({
116 Agent: {
117 create: cursorSdkMock.create,
118 resume: cursorSdkMock.resume,
119 listRuns: cursorSdkMock.listRuns,
120 cancelRun: cursorSdkMock.cancelRun,
121 messages: {
122 list: vi.fn(async () => []),
123 },
124 },
125 createAgentPlatform: vi.fn(),
126 }),
127 loadCursorSqlite: () => ({ SqliteLocalAgentStore: { open: cursorSdkMock.sqliteOpen } }),
128}));
129
130const layerTest = CursorAgentSdk.layer.pipe(
131 Layer.provide(
132 Layer.succeed(ProviderEventLoggers.ProviderEventLoggers, {
133 native: {
134 filePath: "cursor-agent-sdk-test.log",
135 write: (event: unknown) =>
136 Effect.sync(() => {
137 if (
138 typeof event === "object" &&
139 event !== null &&
140 Reflect.get(Reflect.get(event, "event"), "payload")?.type === "agent.close"
141 ) {
142 cursorSdkMock.closeExecutionOrder.push("protocol:agent.close");
143 }
144 }),
145 close: () => Effect.void,
146 },
147 canonical: undefined,
148 }),
149 ),
150 Layer.provide(CursorSdk.layer),
151 Layer.provide(NodeServices.layer),
152);
153
154describe("CursorAgentSdkRunner", () => {
155 it.effect("resumes from the original store after the working directory changes", () =>
156 Effect.gen(function* () {
157 const fileSystem = yield* FileSystem.FileSystem;
158 const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-resume-" });
159 const loaders = yield* Effect.promise(() =>
160 vi.importActual<typeof import("./sdk.ts")>("./sdk.ts"),
161 );
162 const sdk = loaders.loadCursorSdk();
163 const store = new sdk.JsonlLocalAgentStore(workspace);
164 const storeCwd = `${workspace}/checkout`;
165 const cwd = `${workspace}/worktree`;
166 const platform = yield* Effect.promise(() =>
167 sdk.createAgentPlatform({ localStore: store, workspaceRef: storeCwd }),
168 );
169 const { agent, run } = yield* Effect.promise(() =>
170 platform.store.createAgent({ agentId: "agent-moved", workspaceRef: storeCwd }),
171 );
172 const runner = yield* CursorAgentSdk.makeCursorAgentSdkRunner(() => undefined).pipe(
173 Effect.provideService(CursorSdk.CursorSdk, {
174 load: loaders.loadCursorSdk,
175 loadSqlite: loaders.loadCursorSqlite,
176 }),
177 );
178 const session = yield* runner.open({
179 operation: "resume",
180 agentId: agent.agentId,
181 storeCwd,
182 options: { apiKey: "synthetic-cursor-key", local: { cwd, store } },
183 threadId: ThreadId.make("moved-workspace"),
184 providerSessionId: ProviderSessionId.make("moved-workspace"),
185 });
186 assert.equal(session.agentId, agent.agentId);
187 assert.deepStrictEqual(yield* session.listMessages, []);
188 assert.strictEqual(yield* session.readContextUsage!, undefined);
189
190 // Cursor's conversation holds a run's request only once that run saved its own checkpoint.
191 assert.isFalse(yield* session.runCheckpointed!());
192 yield* Effect.promise(() =>
193 platform.store.patchCheckpoint(agent.agentId, run.runId, {
194 blobId: "checkpoint-1",
195 storeKind: "local",
196 }),
197 );
198 assert.isTrue(yield* session.runCheckpointed!());
199 yield* Effect.promise(() =>
200 platform.store.markRunTerminal(agent.agentId, run.runId, { status: "CANCELLED" }),
201 );
202 const followUp = yield* Effect.promise(() =>
203 platform.store.createFollowUpRun(agent.agentId, {}),
204 );
205 assert.isFalse(yield* session.runCheckpointed!(), "the follow-up has no checkpoint yet");
206 assert.isTrue(yield* session.runCheckpointed!(run.runId));
207 assert.isFalse(yield* session.runCheckpointed!(followUp.runId));
208 yield* session.close;
209 }).pipe(Effect.provide(NodeServices.layer)),
210 );
211
212 it.effect("rewinds the agent to the state its first unwound run started from", () =>
213 Effect.gen(function* () {
214 const fileSystem = yield* FileSystem.FileSystem;
215 const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-rewind-" });
216 const loaders = yield* Effect.promise(() =>
217 vi.importActual<typeof import("./sdk.ts")>("./sdk.ts"),
218 );
219 const sdk = loaders.loadCursorSdk();
220 const store = new sdk.JsonlLocalAgentStore(workspace);
221 const platform = yield* Effect.promise(() =>
222 sdk.createAgentPlatform({ localStore: store, workspaceRef: workspace }),
223 );
224 const { agent, run: first } = yield* Effect.promise(() =>
225 platform.store.createAgent({ agentId: "agent-rewind", workspaceRef: workspace }),
226 );
227 const finishRun = (runId: string, state: string) =>
228 Effect.promise(async () => {
229 const checkpoint = await platform.checkpointStore.saveCheckpoint(agent.agentId, {
230 toBinary: () => new TextEncoder().encode(state),
231 });
232 await platform.store.patchCheckpoint(agent.agentId, runId, checkpoint);
233 await platform.store.markRunTerminal(agent.agentId, runId, { status: "FINISHED" });
234 return checkpoint.blobId;
235 });
236 const followUp = Effect.promise(() => platform.store.createFollowUpRun(agent.agentId, {}));
237 const head = Effect.promise(
238 async () => (await platform.store.getAgent(agent.agentId))?.latestCheckpointRef?.blobId,
239 );
240
241 const afterFirst = yield* finishRun(first.runId, "after first");
242 const second = yield* followUp;
243 yield* finishRun(second.runId, "after second");
244 const third = yield* followUp;
245 const afterThird = yield* finishRun(third.runId, "after third");
246
247 const runner = yield* CursorAgentSdk.makeCursorAgentSdkRunner(() => undefined).pipe(
248 Effect.provideService(CursorSdk.CursorSdk, {
249 load: loaders.loadCursorSdk,
250 loadSqlite: loaders.loadCursorSqlite,
251 }),
252 );
253 const session = yield* runner.open({
254 operation: "resume",
255 agentId: agent.agentId,
256 storeCwd: workspace,
257 options: { apiKey: "synthetic-cursor-key", local: { cwd: workspace, store } },
258 threadId: ThreadId.make("rewind"),
259 providerSessionId: ProviderSessionId.make("rewind"),
260 });
261
262 yield* session.rewindAfterRun!(third.runId);
263 assert.strictEqual(yield* head, afterThird, "nothing ran after the kept run");
264 yield* session.rewindAfterRun!(first.runId);
265 assert.strictEqual(yield* head, afterFirst);
266 yield* session.close;
267 }).pipe(Effect.provide(NodeServices.layer)),
268 );
269
270 it.effect("constructs without loading and reports first-use load failures as runner errors", () =>
271 Effect.gen(function* () {
272 const failure = new Error("missing SDK chunk");
273 const load = vi.fn(() => {
274 throw failure;
275 });
276 const runner = yield* CursorAgentSdk.makeCursorAgentSdkRunner(() => undefined).pipe(
277 Effect.provideService(CursorSdk.CursorSdk, {
278 load,
279 loadSqlite: () => {
280 throw new Error("unused SQLite");
281 },
282 }),
283 );
284 assert.strictEqual(load.mock.calls.length, 0);
285 const result = yield* runner
286 .open({
287 operation: "create",
288 options: {},
289 threadId: ThreadId.make("lazy-load"),
290 providerSessionId: ProviderSessionId.make("lazy-load"),
291 })
292 .pipe(Effect.exit);
293 assert(Exit.isFailure(result));
294 assert.deepStrictEqual(
295 Cause.squash(result.cause),
296 new CursorAgentSdk.CursorAgentSdkRunnerError({
297 method: "agent.create",
298 cause: failure,
299 }),
300 );
301 assert.strictEqual(load.mock.calls.length, 1);
302 }),
303 );
304
305 it.effect("retries a resumed send after cancelling its abandoned local run", () =>
306 Effect.gen(function* () {
307 cursorSdkMock.runOperations.length = 0;
308 cursorSdkMock.listRuns.mockClear();
309 cursorSdkMock.cancelRun.mockClear();
310 cursorSdkMock.setStoredRuns([
311 ...Array.from({ length: 50 }, (_, index) => ({
312 id: `run-terminal-${index}`,
313 status: index === 0 ? "cancelled" : "finished",
314 })),
315 { id: "run-stale", status: "running" },
316 ]);
317
318 const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;
319 const session = yield* runner.open({
320 operation: "resume",
321 agentId: "agent-cursor-agent-sdk-test",
322 options: { model: { id: "default" }, mode: "agent", local: { cwd: process.cwd() } },
323 threadId: ThreadId.make("thread-cursor-agent-sdk-stale-run-test"),
324 providerSessionId: ProviderSessionId.make(
325 "provider-session-cursor-agent-sdk-stale-run-test",
326 ),
327 });
328 assert.deepStrictEqual(cursorSdkMock.runOperations, []);
329 const run = yield* session.send({ message: "continue" });
330 yield* run.wait;
331
332 assert.deepStrictEqual(cursorSdkMock.runOperations, [
333 "run.start",
334 "agent.listRuns",
335 "agent.listRuns",
336 "agent.cancelRun",
337 "run.start",
338 ]);
339 assert.deepStrictEqual(cursorSdkMock.listRuns.mock.calls[0], [
340 "agent-cursor-agent-sdk-test",
341 { runtime: "local", cwd: process.cwd() },
342 ]);
343 assert.strictEqual(cursorSdkMock.listRuns.mock.calls.length, 2);
344 assert.deepStrictEqual(cursorSdkMock.listRuns.mock.calls[1], [
345 "agent-cursor-agent-sdk-test",
346 { runtime: "local", cwd: process.cwd(), cursor: "50" },
347 ]);
348 assert.deepStrictEqual(cursorSdkMock.cancelRun.mock.calls[0], [
349 "run-stale",
350 {
351 runtime: "local",
352 cwd: process.cwd(),
353 },
354 ]);
355 }).pipe(Effect.provide(layerTest)),
356 );
357
358 it.effect("reports the SDK's startup phases only to the send that is starting", () =>
359 Effect.gen(function* () {
360 const publish = (phase: string) =>
361 (Reflect.get(globalThis, Symbol.for("@cursor/sdk.startupPhase")) as Function)(phase);
362 const startSend = cursorSdkMock.send.getMockImplementation()!;
363 cursorSdkMock.send.mockImplementationOnce(async (message, options) => {
364 await Promise.resolve();
365 publish("plugins");
366 return startSend(message, options);
367 });
368 const phases: Array<string> = [];
369 const reported = yield* Deferred.make<void>();
370 const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;
371 const session = yield* runner.open({
372 operation: "create",
373 options: {},
374 threadId: ThreadId.make("thread-cursor-agent-sdk-phase"),
375 providerSessionId: ProviderSessionId.make("provider-session-cursor-agent-sdk-phase"),
376 });
377 const run = yield* session.send({
378 message: "start",
379 onStartupPhase: (phase) =>
380 Effect.sync(() => phases.push(phase)).pipe(
381 Effect.andThen(Deferred.succeed(reported, undefined)),
382 ),
383 });
384 yield* Deferred.await(reported);
385 publish("mcp");
386 yield* run.wait;
387
388 assert.deepStrictEqual(phases, ["plugins"]);
389 }).pipe(Effect.provide(layerTest)),
390 );
391
392 it.effect("keeps an agent's background shells and reports each start and end in order", () =>
393 Effect.gen(function* () {
394 const start = (conversationId: string, id: number) => {
395 let complete: (completion: object) => void = () => {};
396 const abort = vi.fn();
397 const kept: unknown = (
398 Reflect.get(globalThis, Symbol.for("@cursor/sdk.backgroundShell")) as Function
399 )({
400 conversationId,
401 command: "sleep 60",
402 shell: {
403 id,
404 pid: id + 1,
405 abort,
406 onComplete: (listener: typeof complete) => (complete = listener),
407 },
408 });
409 return { kept, abort, complete: (completion: object) => complete(completion) };
410 };
411 const events: Array<object> = [];
412 const stops: Array<() => void> = [];
413 const reported = yield* Deferred.make<void>();
414 const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;
415 const session = yield* runner.open({
416 operation: "create",
417 options: {},
418 threadId: ThreadId.make("thread-cursor-agent-sdk-background"),
419 providerSessionId: ProviderSessionId.make("provider-session-cursor-agent-sdk-background"),
420 });
421 const run = yield* session.send({
422 message: "watch it",
423 onBackgroundShell: (event) =>
424 Effect.gen(function* () {
425 if (event.type === "started") {
426 const { stop, ...started } = event;
427 stops.push(stop);
428 events.push(started);
429 return;
430 }
431 events.push(event);
432 if (!event.stopped) yield* Deferred.succeed(reported, undefined);
433 }),
434 });
435 yield* run.wait;
436
437 const killed = start("agent-cursor-agent-sdk-test", 10);
438 const finished = start("agent-cursor-agent-sdk-test", 20);
439 const foreign = start("agent-someone-else", 30);
440 killed.complete({ code: null, aborted: true });
441 finished.complete({ code: 3, aborted: false, outputPath: "/terminals/20.txt" });
442 yield* Deferred.await(reported);
443 stops[0]!();
444
445 assert.deepStrictEqual([killed.kept, finished.kept, foreign.kept], [true, true, false]);
446 assert.strictEqual(killed.abort.mock.calls.length, 1);
447 const shell = (id: string, pid: number) => ({ id, pid, command: "sleep 60" });
448 assert.deepStrictEqual(events, [
449 { ...shell("10", 11), type: "started" },
450 { ...shell("20", 21), type: "started" },
451 {
452 ...shell("10", 11),
453 type: "ended",
454 stopped: true,
455 exitCode: undefined,
456 outputPath: undefined,
457 },
458 {
459 ...shell("20", 21),
460 type: "ended",
461 stopped: false,
462 exitCode: 3,
463 outputPath: "/terminals/20.txt",
464 },
465 ]);
466 }).pipe(Effect.provide(layerTest)),
467 );
468
469 it.effect("forwards Run.steer and reports a missing method as a follow-up", () =>
470 Effect.gen(function* () {
471 cursorSdkMock.runSteer.mockClear();
472 const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;
473 const session = yield* runner.open({
474 operation: "create",
475 options: {},
476 threadId: ThreadId.make("thread-cursor-agent-sdk-steer"),
477 providerSessionId: ProviderSessionId.make("provider-session-cursor-agent-sdk-steer"),
478 });
479 const run = yield* session.send({ message: "continue" });
480 assert.equal(yield* run.steer!("keep going"), "complete_delivered");
481 assert.deepStrictEqual(cursorSdkMock.runSteer.mock.calls, [["keep going"]]);
482
483 cursorSdkMock.runSteer.mockImplementationOnce(async () => {
484 throw new Error("steer transport failed");
485 });
486 const failed = yield* run.steer!("again").pipe(Effect.exit);
487 assert(Exit.isFailure(failed));
488
489 cursorSdkMock.send.mockImplementationOnce(async () => ({
490 id: "run-without-steer",
491 agentId: "agent-cursor-agent-sdk-test",
492 wait: cursorSdkMock.runWait,
493 cancel: cursorSdkMock.runCancel,
494 steer: undefined,
495 }));
496 const plain = yield* session.send({ message: "plain" });
497 assert.equal(yield* plain.steer!("later"), "revert_to_followup");
498 }).pipe(Effect.provide(layerTest)),
499 );
500
501 it.effect(
502 "ref-counts one disposable SqliteLocalAgentStore with run-event persistence disabled per workspace",
503 () =>
504 Effect.gen(function* () {
505 const dispose = vi.fn(async () => {});
506 const fakeStore = {
507 persistRunEvents: true,
508 agents: { get: vi.fn() },
509 runs: { list: vi.fn() },
510 checkpoints: { save: vi.fn() },
511 runEvents: { append: vi.fn(), list: vi.fn(), delete: vi.fn() },
512 retainAgent: vi.fn(),
513 dispose,
514 };
515 cursorSdkMock.sqliteOpen.mockClear();
516 cursorSdkMock.sqliteOpen.mockResolvedValueOnce(fakeStore);
517 cursorSdkMock.create.mockClear();
518
519 const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;
520 const session = yield* runner.open({
521 operation: "create",
522 options: { local: { cwd: "/workspace/cursor-store-test" } },
523 threadId: ThreadId.make("thread-cursor-agent-sdk-store"),
524 providerSessionId: ProviderSessionId.make("provider-session-cursor-agent-sdk-store"),
525 });
526 const peer = yield* runner.open({
527 operation: "create",
528 options: { local: { cwd: "/workspace/cursor-store-test" } },
529 threadId: ThreadId.make("thread-cursor-agent-sdk-store-peer"),
530 providerSessionId: ProviderSessionId.make("provider-session-cursor-agent-sdk-store-peer"),
531 });
532
533 assert.deepStrictEqual(cursorSdkMock.sqliteOpen.mock.calls, [
534 [{ workspaceRef: "/workspace/cursor-store-test" }],
535 ]);
536 const passedOptions = cursorSdkMock.create.mock.calls[0]?.[0] as
537 | { readonly local?: { readonly store?: { readonly persistRunEvents?: boolean } } }
538 | undefined;
539 const peerOptions = cursorSdkMock.create.mock.calls[1]?.[0] as typeof passedOptions;
540 const passedStore = passedOptions?.local?.store;
541 assert.strictEqual(passedStore, fakeStore);
542 assert.strictEqual(peerOptions?.local?.store, passedStore);
543 assert.strictEqual(passedStore?.persistRunEvents, false);
544 assert.equal(dispose.mock.calls.length, 0);
545
546 // Closing one session keeps the shared workspace store alive; repeated close does not double-release.
547 yield* session.close;
548 yield* session.close;
549 assert.equal(dispose.mock.calls.length, 0);
550
551 yield* peer.close;
552 assert.equal(dispose.mock.calls.length, 1);
553
554 // Failed open disposes the newly opened store instead of leaking SQLite FDs.
555 const failingDispose = vi.fn(async () => {});
556 cursorSdkMock.sqliteOpen.mockResolvedValueOnce({ ...fakeStore, dispose: failingDispose });
557 cursorSdkMock.create.mockRejectedValueOnce(new Error("boom"));
558 const failed = yield* runner
559 .open({
560 operation: "create",
561 options: { local: { cwd: "/workspace/cursor-store-fail" } },
562 threadId: ThreadId.make("thread-cursor-agent-sdk-store-fail"),
563 providerSessionId: ProviderSessionId.make(
564 "provider-session-cursor-agent-sdk-store-fail",
565 ),
566 })
567 .pipe(Effect.exit);
568 assert(Exit.isFailure(failed));
569 assert.equal(failingDispose.mock.calls.length, 1);
570 }).pipe(Effect.provide(layerTest)),
571 );
572});