Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import type { InteractionUpdate } from "@cursor/sdk";
4import {
5 EnvironmentId,
6 MessageId,
7 NodeId,
8 ProjectId,
9 ProviderInstanceId,
10 ProviderSessionId,
11 RunAttemptId,
12 RunId,
13 ThreadId,
14} from "@t3tools/contracts";
15import { CursorSettings } from "../settings.ts";
16import * as DateTime from "effect/DateTime";
17import * as Effect from "effect/Effect";
18import * as FileSystem from "effect/FileSystem";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as Path from "effect/Path";
22import * as Schema from "effect/Schema";
23import * as Stream from "effect/Stream";
24
25import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
26import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
27import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
28import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
29import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
30import {
31 cursorMcpServers,
32 cursorRuntimeAgentPolicy,
33 makeCursorAgentOptions,
34 makeCursorAdapterV2,
35 nestedToolCallFromEnvelope,
36} from "./adapter.ts";
37import * as CursorAgentSdk from "./CursorAgentSdk.ts";
38import { ConfigurationError } from "./sdk.ts";
39
40const decodeCursorSettings = Schema.decodeEffect(CursorSettings);
41
42describe("CursorAdapterV2", () => {
43 it.effect.each([
44 { status: "finished", model: undefined, lateModel: undefined },
45 { status: "cancelled", model: "claude-opus-4-6", lateModel: undefined },
46 { status: "error", model: "custom-fable", lateModel: undefined },
47 { status: "finished", model: undefined, lateModel: "gpt-6-sol" },
48 { status: "finished", model: "gpt-6-sol", lateModel: null },
49 ] as const)(
50 "projects Cursor tasks: $status, late model $lateModel",
51 ({ status, model, lateModel }) =>
52 Effect.gen(function* () {
53 const fileSystem = yield* FileSystem.FileSystem;
54 const workspace = yield* fileSystem.makeTempDirectoryScoped({
55 prefix: "cursor-v2-lifecycle-",
56 });
57 const instanceId = ProviderInstanceId.make("cursor");
58 const threadId = ThreadId.make("cursor-lifecycle-thread");
59 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
60 yield* mcpSessions.set({
61 environmentId: EnvironmentId.make("cursor-lifecycle-environment"),
62 threadId,
63 providerSessionId: "cursor-lifecycle-session",
64 providerInstanceId: instanceId,
65 endpoint: "http://127.0.0.1:43123/mcp",
66 authorizationHeader: "Bearer synthetic-cursor-token",
67 browserToolsAvailable: true,
68 });
69 let sentWithMcpOverride = true;
70 const modelSelection = { instanceId, model: "composer-2.5" };
71 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
72 runtimeMode: "full-access",
73 interactionMode: "default",
74 cwd: workspace,
75 });
76 const adapter = yield* makeCursorAdapterV2({
77 instanceId,
78 settings: yield* decodeCursorSettings({}),
79 environment: { HOME: workspace },
80 }).pipe(
81 Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
82 assertComplete: Effect.void,
83 open: () =>
84 Effect.succeed({
85 agentId: "native-cursor-lifecycle",
86 listMessages: Effect.succeed([]),
87 close: Effect.void,
88 send: (input) =>
89 Effect.gen(function* () {
90 sentWithMcpOverride = Object.hasOwn(input.options ?? {}, "mcpServers");
91 // Recorded Cursor task calls (see fixtures/subagent) stream a
92 // partial-tool-call before tool-call-started with the same args.
93 // The run then ends without tool-call-completed, which a live
94 // run cannot produce on demand.
95 const taskToolCall = {
96 type: "task" as const,
97 args: {
98 description: "Review",
99 prompt: "Review the code.",
100 subagentType: { kind: "unspecified" },
101 ...(model === undefined ? {} : { model }),
102 agentId: "cursor-task-agent",
103 mode: "unspecified" as const,
104 },
105 };
106 const updates =
107 lateModel !== undefined
108 ? (["tool-call-started", "tool-call-completed"] as const)
109 : (["partial-tool-call", "tool-call-started"] as const);
110 for (const type of updates) {
111 yield* input.onDelta!({
112 type,
113 modelCallId: "model-call",
114 callId: "task-call",
115 toolCall: {
116 ...taskToolCall,
117 args: {
118 ...taskToolCall.args,
119 ...(type === "tool-call-completed"
120 ? { model: lateModel ?? undefined }
121 : {}),
122 },
123 },
124 }).pipe(Effect.orDie);
125 }
126 return {
127 agentId: "native-cursor-lifecycle",
128 runId: "native-cursor-run",
129 wait: Effect.succeed({
130 id: "native-cursor-run",
131 requestId: "native-request",
132 status,
133 model: { id: "composer-2.5" },
134 durationMs: 1,
135 }),
136 cancel: Effect.void,
137 };
138 }),
139 }),
140 }),
141 Effect.provide(TestProviderHost.layer({ cwd: workspace })),
142 );
143 const runtime = yield* adapter.openSession({
144 threadId,
145 providerSessionId: ProviderSessionId.make("cursor-lifecycle-session"),
146 modelSelection,
147 runtimePolicy,
148 });
149 const providerThread = yield* runtime.ensureThread({
150 threadId,
151 modelSelection,
152 runtimePolicy,
153 });
154 const now = yield* DateTime.now;
155 yield* runtime.startTurn({
156 threadId,
157 providerThread,
158 modelSelection,
159 runtimePolicy,
160 runId: RunId.make("cursor-lifecycle-run"),
161 runOrdinal: 1,
162 providerTurnOrdinal: 1,
163 attemptId: RunAttemptId.make("cursor-lifecycle-attempt"),
164 rootNodeId: NodeId.make("cursor-lifecycle-root"),
165 appThread: {
166 id: threadId,
167 projectId: ProjectId.make("cursor-lifecycle-project"),
168 createdBy: "user",
169 creationSource: "web",
170 title: "Cursor lifecycle",
171 providerInstanceId: instanceId,
172 modelSelection,
173 runtimeMode: "full-access",
174 interactionMode: "default",
175 branch: null,
176 worktreePath: null,
177 activeProviderThreadId: providerThread.id,
178 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
179 forkedFrom: null,
180 createdAt: now,
181 updatedAt: now,
182 archivedAt: null,
183 settledOverride: null,
184 settledAt: null,
185 lastVisitedAt: null,
186 deletedAt: null,
187 },
188 message: {
189 messageId: MessageId.make("cursor-lifecycle-message"),
190 createdBy: "user",
191 creationSource: "web",
192 text: "Review the code.",
193 attachments: [],
194 },
195 });
196 const events = yield* runtime.events.pipe(
197 Stream.takeUntil((event) => event.type === "turn.terminal"),
198 Stream.runCollect,
199 );
200 assert.isFalse(sentWithMcpOverride);
201 const rows = events.filter((event) => event.type === "subagent.updated");
202 assert.equal(rows[0]?.subagent.status, "running");
203 assert.equal(rows[0]?.subagent.model, model ?? null);
204 assert.equal(rows.at(-1)?.subagent.model, lateModel ?? model ?? null);
205 assert.equal(
206 rows.at(-1)?.subagent.status,
207 lateModel !== undefined
208 ? "completed"
209 : status === "finished"
210 ? "idle"
211 : status === "cancelled"
212 ? "cancelled"
213 : "failed",
214 );
215 assert.isNotNull(rows.at(-1)?.subagent.completedAt);
216 }).pipe(
217 Effect.scoped,
218 Effect.provide(
219 Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),
220 ),
221 ),
222 );
223
224 it.effect.each([
225 {
226 reason: "the error Cursor's run ended with",
227 wait: Effect.succeed({
228 id: "native-cursor-run",
229 requestId: "native-request",
230 status: "error" as const,
231 error: {
232 message: "Model Blocked Please ask your admin to enable access to Claude Fable 5.",
233 },
234 model: { id: "claude-fable-5" },
235 durationMs: 1,
236 }),
237 failure: {
238 class: "provider_error",
239 message: "Model Blocked Please ask your admin to enable access to Claude Fable 5.",
240 },
241 },
242 {
243 reason: "the SDK error that broke the run",
244 wait: Effect.fail(
245 new CursorAgentSdk.CursorAgentSdkRunnerError({
246 method: "run.wait",
247 cause: Object.assign(new Error("Too many requests"), {
248 code: "resource_exhausted",
249 status: 429,
250 }),
251 }),
252 ),
253 failure: {
254 class: "transport_error",
255 message:
256 "Cursor Agent SDK run.wait failed: Too many requests (resource_exhausted, HTTP 429)",
257 },
258 },
259 {
260 reason: "a transport dump sent after earlier commentary",
261 updates: [
262 { type: "text-delta", text: "Checking the build first." },
263 { type: "step-completed", stepId: 1, stepDurationMs: 1 },
264 { type: "text-delta", text: "Error: RetriableError: WritableIterable is closed" },
265 ] satisfies ReadonlyArray<InteractionUpdate>,
266 wait: Effect.succeed({
267 id: "native-cursor-run",
268 requestId: "native-request",
269 status: "finished" as const,
270 model: { id: "claude-fable-5" },
271 durationMs: 1,
272 }),
273 failure: { class: "transport_error", message: "Provider turn failed." },
274 },
275 {
276 reason: "no failure when Cursor's resume after the turn ended made no progress",
277 // Cursor's SDK resumed from an older checkpoint after the answer was
278 // delivered, regenerated the closing, then gave up on the run.
279 updates: [
280 { type: "text-delta", text: "The answer." },
281 { type: "turn-ended" },
282 { type: "text-delta", text: "A regenerated closing." },
283 { type: "turn-ended" },
284 ] satisfies ReadonlyArray<InteractionUpdate>,
285 wait: Effect.succeed({
286 id: "native-cursor-run",
287 requestId: "native-request",
288 status: "error" as const,
289 error: { message: "Agent turn stopped after repeated resume attempts made no progress" },
290 model: { id: "claude-fable-5" },
291 durationMs: 1,
292 }),
293 failure: null,
294 },
295 {
296 reason: "the error a continuation after the turn ended stopped with",
297 updates: [
298 { type: "text-delta", text: "The answer." },
299 { type: "turn-ended" },
300 { type: "text-delta", text: "Following up on the stop hook." },
301 ] satisfies ReadonlyArray<InteractionUpdate>,
302 wait: Effect.succeed({
303 id: "native-cursor-run",
304 requestId: "native-request",
305 status: "error" as const,
306 error: { message: "Agent turn stopped after repeated resume attempts made no progress" },
307 model: { id: "claude-fable-5" },
308 durationMs: 1,
309 }),
310 failure: {
311 class: "provider_error",
312 message: "Agent turn stopped after repeated resume attempts made no progress",
313 },
314 },
315 {
316 reason: "no answer from a resume after the turn ended that made no progress",
317 updates: [{ type: "turn-ended" }] satisfies ReadonlyArray<InteractionUpdate>,
318 wait: Effect.succeed({
319 id: "native-cursor-run",
320 requestId: "native-request",
321 status: "error" as const,
322 error: { message: "Agent turn stopped after repeated resume attempts made no progress" },
323 result: "A regenerated closing.",
324 model: { id: "claude-fable-5" },
325 durationMs: 1,
326 }),
327 failure: null,
328 answers: [],
329 },
330 ])("ends the turn with $reason", ({ updates = [], wait, failure, answers }) =>
331 Effect.gen(function* () {
332 const fileSystem = yield* FileSystem.FileSystem;
333 const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-failure-" });
334 const instanceId = ProviderInstanceId.make("cursor");
335 const threadId = ThreadId.make("cursor-failure-thread");
336 const modelSelection = { instanceId, model: "claude-fable-5" };
337 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
338 runtimeMode: "full-access",
339 interactionMode: "default",
340 cwd: workspace,
341 });
342 const adapter = yield* makeCursorAdapterV2({
343 instanceId,
344 settings: yield* decodeCursorSettings({}),
345 environment: { HOME: workspace },
346 }).pipe(
347 Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
348 assertComplete: Effect.void,
349 open: () =>
350 Effect.succeed({
351 agentId: "native-cursor-failure",
352 listMessages: Effect.succeed([]),
353 close: Effect.void,
354 send: (input) =>
355 Effect.gen(function* () {
356 for (const update of updates) {
357 yield* input.onDelta!(update).pipe(Effect.orDie);
358 }
359 return {
360 agentId: "native-cursor-failure",
361 runId: "native-cursor-run",
362 wait,
363 cancel: Effect.void,
364 };
365 }),
366 }),
367 }),
368 Effect.provide(TestProviderHost.layer({ cwd: workspace })),
369 );
370 const runtime = yield* adapter.openSession({
371 threadId,
372 providerSessionId: ProviderSessionId.make("cursor-failure-session"),
373 modelSelection,
374 runtimePolicy,
375 });
376 const providerThread = yield* runtime.ensureThread({
377 threadId,
378 modelSelection,
379 runtimePolicy,
380 });
381 const now = yield* DateTime.now;
382 yield* runtime.startTurn({
383 threadId,
384 providerThread,
385 modelSelection,
386 runtimePolicy,
387 runId: RunId.make("cursor-failure-run"),
388 runOrdinal: 1,
389 providerTurnOrdinal: 1,
390 attemptId: RunAttemptId.make("cursor-failure-attempt"),
391 rootNodeId: NodeId.make("cursor-failure-root"),
392 appThread: {
393 id: threadId,
394 projectId: ProjectId.make("cursor-failure-project"),
395 createdBy: "user",
396 creationSource: "web",
397 title: "Cursor failure",
398 providerInstanceId: instanceId,
399 modelSelection,
400 runtimeMode: "full-access",
401 interactionMode: "default",
402 branch: null,
403 worktreePath: null,
404 activeProviderThreadId: providerThread.id,
405 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
406 forkedFrom: null,
407 createdAt: now,
408 updatedAt: now,
409 archivedAt: null,
410 settledOverride: null,
411 settledAt: null,
412 lastVisitedAt: null,
413 deletedAt: null,
414 },
415 message: {
416 messageId: MessageId.make("cursor-failure-message"),
417 createdBy: "user",
418 creationSource: "web",
419 text: "hi",
420 attachments: [],
421 },
422 });
423 const events = yield* runtime.events.pipe(
424 Stream.takeUntil((event) => event.type === "turn.terminal"),
425 Stream.runCollect,
426 );
427 const terminal = events.find((event) => event.type === "turn.terminal");
428 assert.equal(terminal?.status, failure === null ? "completed" : "failed");
429 assert.equal(terminal?.failure?.class, failure?.class);
430 assert.equal(terminal?.failure?.message, failure?.message);
431 if (answers !== undefined) {
432 assert.deepEqual(
433 events.flatMap((event) =>
434 event.type === "message.updated" && event.message.role === "assistant"
435 ? [event.message.text]
436 : [],
437 ),
438 answers,
439 );
440 }
441 }).pipe(
442 Effect.scoped,
443 Effect.provide(
444 Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),
445 ),
446 ),
447 );
448
449 it.effect("fails standalone SDK transport diagnostics and sends compaction as /compress", () =>
450 Effect.gen(function* () {
451 const fileSystem = yield* FileSystem.FileSystem;
452 const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-errors-" });
453 const sentMessages: Array<string> = [];
454 let sendCalls = 0;
455 const instanceId = ProviderInstanceId.make("cursor");
456 const threadId = ThreadId.make("cursor-transport-error-thread");
457 const modelSelection = { instanceId, model: "composer-2.5" };
458 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
459 runtimeMode: "full-access",
460 interactionMode: "default",
461 cwd: workspace,
462 });
463 const adapter = yield* makeCursorAdapterV2({
464 instanceId,
465 settings: yield* decodeCursorSettings({}),
466 environment: { HOME: workspace },
467 }).pipe(
468 Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
469 assertComplete: Effect.void,
470 open: () =>
471 Effect.succeed({
472 agentId: "native-cursor-error",
473 listMessages: Effect.succeed([]),
474 close: Effect.void,
475 send: (input) =>
476 Effect.sync(() => {
477 sendCalls += 1;
478 sentMessages.push(
479 typeof input.message === "string" ? input.message : input.message.text,
480 );
481 const runId = `native-cursor-run-${sendCalls}`;
482 return {
483 agentId: "native-cursor-error",
484 runId,
485 wait: Effect.succeed({
486 id: runId,
487 requestId: `native-request-${sendCalls}`,
488 status: "finished" as const,
489 model: { id: "composer-2.5" },
490 durationMs: 1,
491 ...(sendCalls === 1
492 ? { result: "Error: RetriableError: WritableIterable is closed" }
493 : {}),
494 }),
495 cancel: Effect.void,
496 };
497 }),
498 }),
499 }),
500 Effect.provide(TestProviderHost.layer({ cwd: workspace })),
501 );
502 const runtime = yield* adapter.openSession({
503 threadId,
504 providerSessionId: ProviderSessionId.make("cursor-error-session"),
505 modelSelection,
506 runtimePolicy,
507 });
508 const providerThread = yield* runtime.ensureThread({
509 threadId,
510 modelSelection,
511 runtimePolicy,
512 });
513 const now = yield* DateTime.now;
514 const appThread = {
515 id: threadId,
516 projectId: ProjectId.make("cursor-error-project"),
517 createdBy: "user" as const,
518 creationSource: "web" as const,
519 title: "Cursor transport failure",
520 providerInstanceId: instanceId,
521 modelSelection,
522 runtimeMode: "full-access" as const,
523 interactionMode: "default" as const,
524 branch: null,
525 worktreePath: null,
526 activeProviderThreadId: providerThread.id,
527 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
528 forkedFrom: null,
529 createdAt: now,
530 updatedAt: now,
531 archivedAt: null,
532 settledOverride: null,
533 settledAt: null,
534 lastVisitedAt: null,
535 deletedAt: null,
536 };
537 yield* runtime.startTurn({
538 threadId,
539 providerThread,
540 modelSelection,
541 runtimePolicy,
542 runId: RunId.make("cursor-error-run"),
543 runOrdinal: 1,
544 providerTurnOrdinal: 1,
545 attemptId: RunAttemptId.make("cursor-error-attempt"),
546 rootNodeId: NodeId.make("cursor-error-root"),
547 appThread,
548 message: {
549 messageId: MessageId.make("cursor-error-message"),
550 createdBy: "user",
551 creationSource: "web",
552 text: "continue",
553 attachments: [],
554 },
555 });
556 const first = yield* runtime.events.pipe(
557 Stream.filter((event) => event.type === "turn.terminal"),
558 Stream.runHead,
559 );
560 assert.isTrue(Option.isSome(first));
561 if (Option.isSome(first)) {
562 assert.equal(first.value.status, "failed");
563 assert.equal(first.value.failure?.class, "transport_error");
564 }
565
566 assert.isDefined(runtime.compactThread);
567 yield* runtime.compactThread!({
568 threadId,
569 providerThread,
570 modelSelection,
571 runtimePolicy,
572 runId: RunId.make("cursor-compact-run"),
573 runOrdinal: 2,
574 providerTurnOrdinal: 2,
575 attemptId: RunAttemptId.make("cursor-compact-attempt"),
576 rootNodeId: NodeId.make("cursor-compact-root"),
577 appThread,
578 message: {
579 messageId: MessageId.make("cursor-compact-message"),
580 createdBy: "user",
581 creationSource: "web",
582 text: "ignored by compactThread",
583 attachments: [],
584 },
585 });
586 yield* runtime.events.pipe(
587 Stream.filter((event) => event.type === "turn.terminal"),
588 Stream.runHead,
589 );
590 assert.equal(sentMessages[1], "/compress");
591 }).pipe(
592 Effect.scoped,
593 Effect.provide(
594 Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),
595 ),
596 ),
597 );
598
599 it.effect("projects Cursor directory trees and lint diagnostics as file search results", () =>
600 Effect.gen(function* () {
601 const fileSystem = yield* FileSystem.FileSystem;
602 const path = yield* Path.Path;
603 const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-search-" });
604 const instanceId = ProviderInstanceId.make("cursor");
605 const threadId = ThreadId.make("cursor-search-thread");
606 const modelSelection = { instanceId, model: "composer-2.5" };
607 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
608 runtimeMode: "full-access",
609 interactionMode: "default",
610 cwd: workspace,
611 });
612 const emptyLsNode = {
613 childrenDirs: [],
614 childrenFiles: [],
615 childrenWereProcessed: true,
616 fullSubtreeExtensionCounts: {},
617 numFiles: 0,
618 };
619 const updates: ReadonlyArray<InteractionUpdate> = [
620 ...(["tool-call-started", "tool-call-completed"] as const).map((type) => ({
621 type,
622 modelCallId: "native-model-call",
623 callId: "mcp-weather",
624 toolCall: {
625 type: "mcp" as const,
626 args: {
627 providerIdentifier: "weather",
628 toolName: "get_weather",
629 args: { city: "Berlin" },
630 },
631 ...(type === "tool-call-completed"
632 ? { result: { status: "success" as const, value: { content: [], isError: false } } }
633 : {}),
634 },
635 })),
636 {
637 type: "tool-call-completed",
638 modelCallId: "native-model-call",
639 callId: "read-file",
640 toolCall: {
641 type: "read",
642 args: { path: "src/env.ts" },
643 result: {
644 status: "success",
645 value: { fileSize: 12, content: "---\nfile body", totalLines: 2 },
646 },
647 },
648 },
649 {
650 type: "tool-call-completed",
651 modelCallId: "native-model-call",
652 callId: "ls-nested",
653 toolCall: {
654 type: "ls",
655 args: { path: workspace },
656 result: {
657 status: "success",
658 value: {
659 directoryTreeRoot: {
660 ...emptyLsNode,
661 absPath: workspace,
662 childrenFiles: [{ name: "README.md" }],
663 childrenDirs: [
664 {
665 ...emptyLsNode,
666 absPath: path.join(workspace, "src"),
667 childrenFiles: [{ name: "index.ts" }],
668 childrenDirs: [
669 {
670 ...emptyLsNode,
671 absPath: path.join(workspace, "src", "nested"),
672 childrenFiles: [{ name: "util.ts" }],
673 },
674 ],
675 },
676 ],
677 },
678 },
679 },
680 },
681 },
682 {
683 type: "tool-call-completed",
684 modelCallId: "native-model-call",
685 callId: "ls-empty",
686 toolCall: {
687 type: "ls",
688 args: { path: path.join(workspace, "empty") },
689 result: {
690 status: "success",
691 value: {
692 directoryTreeRoot: { ...emptyLsNode, absPath: path.join(workspace, "empty") },
693 },
694 },
695 },
696 },
697 {
698 type: "tool-call-completed",
699 modelCallId: "native-model-call",
700 callId: "ls-failed",
701 toolCall: {
702 type: "ls",
703 args: { path: path.join(workspace, "missing") },
704 result: { status: "error", error: "ENOENT" },
705 },
706 },
707 {
708 type: "tool-call-completed",
709 modelCallId: "native-model-call",
710 callId: "grep-failed",
711 toolCall: {
712 type: "grep",
713 args: { pattern: "TODO", path: "src" },
714 result: { status: "error", error: "search failed" },
715 },
716 },
717 {
718 type: "tool-call-completed",
719 modelCallId: "native-model-call",
720 callId: "glob-failed",
721 toolCall: {
722 type: "glob",
723 args: { globPattern: "*.ts" },
724 result: { status: "error", error: "search failed" },
725 },
726 },
727 {
728 type: "tool-call-completed",
729 modelCallId: "native-model-call",
730 callId: "lints",
731 toolCall: {
732 type: "readLints",
733 args: { paths: ["src/a.ts", "src/b.ts"] },
734 result: {
735 status: "success",
736 value: {
737 totalFiles: 2,
738 totalDiagnostics: 3,
739 fileDiagnostics: [
740 {
741 path: "src/a.ts",
742 diagnosticsCount: 2,
743 diagnostics: [
744 {
745 message: "Unused variable",
746 code: "TS6133",
747 source: "ts",
748 severity: "warning",
749 range: { start: { line: 0, character: 4 } },
750 },
751 {
752 message: "Cannot find name",
753 code: "TS2304",
754 source: "ts",
755 severity: "error",
756 range: { start: { line: 11 } },
757 },
758 ],
759 },
760 {
761 path: "src/b.ts",
762 diagnosticsCount: 1,
763 diagnostics: [
764 {
765 message: "File-level diagnostic",
766 code: "TS0",
767 source: "ts",
768 severity: "information",
769 },
770 ],
771 },
772 ],
773 },
774 },
775 },
776 },
777 {
778 type: "tool-call-completed",
779 modelCallId: "native-model-call",
780 callId: "lints-empty",
781 toolCall: {
782 type: "readLints",
783 args: { paths: ["src/clean.ts"] },
784 result: {
785 status: "success",
786 value: {
787 totalFiles: 1,
788 totalDiagnostics: 0,
789 fileDiagnostics: [{ path: "src/clean.ts", diagnosticsCount: 0, diagnostics: [] }],
790 },
791 },
792 },
793 },
794 {
795 type: "tool-call-completed",
796 modelCallId: "native-model-call",
797 callId: "lints-failed",
798 toolCall: {
799 type: "readLints",
800 args: { paths: ["src/a.ts"] },
801 result: { status: "error", error: "lint failed" },
802 },
803 },
804 ];
805 const adapter = yield* makeCursorAdapterV2({
806 instanceId,
807 settings: yield* decodeCursorSettings({}),
808 environment: { HOME: workspace },
809 }).pipe(
810 Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
811 assertComplete: Effect.void,
812 open: () =>
813 Effect.succeed({
814 agentId: "native-cursor-search",
815 listMessages: Effect.succeed([]),
816 close: Effect.void,
817 send: (input) =>
818 Effect.gen(function* () {
819 for (const update of updates) {
820 if (input.onDelta !== undefined) {
821 yield* input.onDelta(update).pipe(Effect.orDie);
822 }
823 }
824 return {
825 agentId: "native-cursor-search",
826 runId: "native-cursor-run",
827 wait: Effect.succeed({
828 id: "native-cursor-run",
829 requestId: "native-request",
830 status: "finished" as const,
831 model: { id: "composer-2.5" },
832 durationMs: 1,
833 }),
834 cancel: Effect.void,
835 };
836 }),
837 }),
838 }),
839 Effect.provide(TestProviderHost.layer({ cwd: workspace })),
840 );
841 const runtime = yield* adapter.openSession({
842 threadId,
843 providerSessionId: ProviderSessionId.make("cursor-search-session"),
844 modelSelection,
845 runtimePolicy,
846 });
847 const providerThread = yield* runtime.ensureThread({
848 threadId,
849 modelSelection,
850 runtimePolicy,
851 });
852 const now = yield* DateTime.now;
853 yield* runtime.startTurn({
854 threadId,
855 providerThread,
856 modelSelection,
857 runtimePolicy,
858 runId: RunId.make("cursor-search-run"),
859 runOrdinal: 1,
860 providerTurnOrdinal: 1,
861 attemptId: RunAttemptId.make("cursor-search-attempt"),
862 rootNodeId: NodeId.make("cursor-search-root"),
863 appThread: {
864 id: threadId,
865 projectId: ProjectId.make("cursor-search-project"),
866 createdBy: "user",
867 creationSource: "web",
868 title: "Cursor search results",
869 providerInstanceId: instanceId,
870 modelSelection,
871 runtimeMode: "full-access",
872 interactionMode: "default",
873 branch: null,
874 worktreePath: null,
875 activeProviderThreadId: providerThread.id,
876 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
877 forkedFrom: null,
878 createdAt: now,
879 updatedAt: now,
880 archivedAt: null,
881 settledOverride: null,
882 settledAt: null,
883 lastVisitedAt: null,
884 deletedAt: null,
885 },
886 message: {
887 messageId: MessageId.make("cursor-search-message"),
888 createdBy: "user",
889 creationSource: "web",
890 text: "inspect the workspace",
891 attachments: [],
892 },
893 });
894 const events = yield* runtime.events.pipe(
895 Stream.takeUntil((event) => event.type === "turn.terminal"),
896 Stream.runCollect,
897 );
898 const mcpItems = events.flatMap((event) =>
899 event.type === "turn_item.updated" &&
900 event.turnItem.type === "dynamic_tool" &&
901 event.turnItem.toolName === "mcp__weather__get_weather"
902 ? [event.turnItem]
903 : [],
904 );
905 assert.deepEqual(
906 mcpItems.map((item) => item.status),
907 ["running", "completed"],
908 );
909 for (const item of mcpItems) {
910 assert.equal(item.title, "get weather");
911 assert.deepEqual(item.toolSource, {
912 key: "mcp:weather",
913 name: "weather",
914 kind: "integration",
915 });
916 assert.deepEqual(item.input, { city: "Berlin" });
917 }
918 const fileSearchItems = events.flatMap((event) =>
919 event.type === "turn_item.updated" &&
920 event.turnItem.type === "file_search" &&
921 event.turnItem.status !== "running"
922 ? [event.turnItem]
923 : [],
924 );
925 const readItems = events.flatMap((event) =>
926 event.type === "turn_item.updated" &&
927 event.turnItem.type === "dynamic_tool" &&
928 event.turnItem.toolName === "Read" &&
929 event.turnItem.status === "completed"
930 ? [event.turnItem]
931 : [],
932 );
933 assert.deepEqual(
934 readItems.map((item) => ({ title: item.title, input: item.input })),
935 [{ title: "Read src/env.ts", input: { path: "src/env.ts" } }],
936 );
937 assert.deepEqual(
938 fileSearchItems.map((item) => ({
939 pattern: item.pattern,
940 status: item.status,
941 results: item.results,
942 })),
943 [
944 {
945 pattern: workspace,
946 status: "completed",
947 results: [
948 { fileName: path.join(workspace, "README.md") },
949 { fileName: path.join(workspace, "src", "index.ts") },
950 { fileName: path.join(workspace, "src", "nested", "util.ts") },
951 ],
952 },
953 {
954 pattern: path.join(workspace, "empty"),
955 status: "completed",
956 results: undefined,
957 },
958 {
959 pattern: path.join(workspace, "missing"),
960 status: "failed",
961 results: [{ fileName: path.join(workspace, "missing"), preview: "ENOENT" }],
962 },
963 {
964 pattern: "TODO",
965 status: "failed",
966 results: [{ fileName: "src", preview: "search failed" }],
967 },
968 {
969 pattern: "*.ts",
970 status: "failed",
971 results: [{ fileName: ".", preview: "search failed" }],
972 },
973 {
974 pattern: "src/a.ts, src/b.ts",
975 status: "completed",
976 results: [
977 { fileName: "src/a.ts", line: 1, column: 5, preview: "Unused variable" },
978 { fileName: "src/a.ts", line: 12, preview: "Cannot find name" },
979 { fileName: "src/b.ts", preview: "File-level diagnostic" },
980 ],
981 },
982 {
983 pattern: "src/clean.ts",
984 status: "completed",
985 results: undefined,
986 },
987 {
988 pattern: "src/a.ts",
989 status: "failed",
990 results: [{ fileName: "src/a.ts", preview: "lint failed" }],
991 },
992 ],
993 );
994 }).pipe(
995 Effect.scoped,
996 Effect.provide(
997 Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),
998 ),
999 ),
1000 );
1001
1002 it.effect("names a custom model Cursor's account catalog rejects", () =>
1003 Effect.gen(function* () {
1004 const fileSystem = yield* FileSystem.FileSystem;
1005 const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-model-" });
1006 const instanceId = ProviderInstanceId.make("cursor");
1007 const threadId = ThreadId.make("cursor-custom-model-thread");
1008 const catalogModel = { instanceId, model: "composer-2.5" };
1009 const customModel = { instanceId, model: "deepseek/deepseek-v4.1-flash" };
1010 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
1011 runtimeMode: "full-access",
1012 interactionMode: "default",
1013 cwd: workspace,
1014 });
1015 // The SDK checks every create, resume, and send model against the account catalog.
1016 const checkModel = (method: string, model: { readonly id: string } | undefined) =>
1017 model === undefined || model.id === "composer-2.5"
1018 ? Effect.void
1019 : Effect.fail(
1020 new CursorAgentSdk.CursorAgentSdkRunnerError({
1021 method,
1022 cause: new ConfigurationError(
1023 `Cannot use this model: ${model.id}. Available models: default, composer-2.5. Use Cursor.models.list() to discover valid selections.`,
1024 { isRetryable: false },
1025 ),
1026 }),
1027 );
1028 const adapter = yield* makeCursorAdapterV2({
1029 instanceId,
1030 settings: yield* decodeCursorSettings({}),
1031 environment: { HOME: workspace },
1032 }).pipe(
1033 Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
1034 assertComplete: Effect.void,
1035 open: (input) =>
1036 checkModel(`agent.${input.operation}`, input.options.model).pipe(
1037 Effect.as({
1038 agentId: "native-cursor-custom-model",
1039 listMessages: Effect.succeed([]),
1040 close: Effect.void,
1041 send: (sendInput) =>
1042 checkModel("run.start", sendInput.options?.model).pipe(
1043 Effect.andThen(Effect.die("unexpected Cursor run")),
1044 ),
1045 }),
1046 ),
1047 }),
1048 Effect.provide(TestProviderHost.layer({ cwd: workspace })),
1049 );
1050 const runtime = yield* adapter.openSession({
1051 threadId,
1052 providerSessionId: ProviderSessionId.make("cursor-custom-model-session"),
1053 modelSelection: catalogModel,
1054 runtimePolicy,
1055 });
1056 const expected =
1057 'Cursor cannot run the model "deepseek/deepseek-v4.1-flash". Cursor only runs models from your Cursor account. Choose one of those, or use OpenCode for OpenRouter and other API-key models.';
1058
1059 // A new thread created with the custom model.
1060 const createFailure = yield* runtime
1061 .ensureThread({ threadId, modelSelection: customModel, runtimePolicy })
1062 .pipe(Effect.flip);
1063 assert.equal(makeProviderFailure({ cause: createFailure }).message, expected);
1064
1065 // An existing thread switched to the custom model.
1066 const providerThread = yield* runtime.ensureThread({
1067 threadId,
1068 modelSelection: catalogModel,
1069 runtimePolicy,
1070 });
1071 const now = yield* DateTime.now;
1072 const sendFailure = yield* runtime
1073 .startTurn({
1074 threadId,
1075 providerThread,
1076 modelSelection: customModel,
1077 runtimePolicy,
1078 runId: RunId.make("cursor-custom-model-run"),
1079 runOrdinal: 1,
1080 providerTurnOrdinal: 1,
1081 attemptId: RunAttemptId.make("cursor-custom-model-attempt"),
1082 rootNodeId: NodeId.make("cursor-custom-model-root"),
1083 appThread: {
1084 id: threadId,
1085 projectId: ProjectId.make("cursor-custom-model-project"),
1086 createdBy: "user",
1087 creationSource: "web",
1088 title: "Cursor custom model",
1089 providerInstanceId: instanceId,
1090 modelSelection: customModel,
1091 runtimeMode: "full-access",
1092 interactionMode: "default",
1093 branch: null,
1094 worktreePath: null,
1095 activeProviderThreadId: providerThread.id,
1096 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
1097 forkedFrom: null,
1098 createdAt: now,
1099 updatedAt: now,
1100 archivedAt: null,
1101 settledOverride: null,
1102 settledAt: null,
1103 lastVisitedAt: null,
1104 deletedAt: null,
1105 },
1106 message: {
1107 messageId: MessageId.make("cursor-custom-model-message"),
1108 createdBy: "user",
1109 creationSource: "web",
1110 text: "Hello.",
1111 attachments: [],
1112 },
1113 })
1114 .pipe(Effect.flip);
1115 assert.equal(makeProviderFailure({ cause: sendFailure }).message, expected);
1116 }).pipe(
1117 Effect.scoped,
1118 Effect.provide(
1119 Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),
1120 ),
1121 ),
1122 );
1123
1124 it("maps runtime modes to the SDK sandbox and auto-review controls", () => {
1125 const base = {
1126 interactionMode: "default" as const,
1127 cwd: "/tmp/cursor-adapter",
1128 };
1129 assert.deepEqual(
1130 cursorRuntimeAgentPolicy(
1131 {
1132 ...base,
1133 runtimeMode: "full-access",
1134 },
1135 "linux",
1136 ),
1137 {
1138 autoReview: false,
1139 sandboxEnabled: false,
1140 },
1141 );
1142 assert.deepEqual(
1143 cursorRuntimeAgentPolicy(
1144 {
1145 ...base,
1146 runtimeMode: "auto-accept-edits",
1147 },
1148 "linux",
1149 ),
1150 {
1151 autoReview: false,
1152 sandboxEnabled: true,
1153 },
1154 );
1155 assert.deepEqual(
1156 cursorRuntimeAgentPolicy(
1157 {
1158 ...base,
1159 runtimeMode: "auto",
1160 },
1161 "linux",
1162 ),
1163 {
1164 autoReview: true,
1165 sandboxEnabled: true,
1166 },
1167 );
1168 assert.deepEqual(
1169 cursorRuntimeAgentPolicy(
1170 {
1171 ...base,
1172 runtimeMode: "approval-required",
1173 },
1174 "linux",
1175 ),
1176 {
1177 autoReview: true,
1178 sandboxEnabled: true,
1179 },
1180 );
1181 assert.deepEqual(
1182 cursorRuntimeAgentPolicy(
1183 {
1184 ...base,
1185 runtimeMode: "full-access",
1186 approvalPolicy: "never",
1187 sandboxPolicy: { type: "readOnly" },
1188 },
1189 "linux",
1190 ),
1191 {
1192 autoReview: false,
1193 sandboxEnabled: true,
1194 },
1195 );
1196 assert.deepEqual(
1197 cursorRuntimeAgentPolicy(
1198 {
1199 ...base,
1200 runtimeMode: "approval-required",
1201 approvalPolicy: "never",
1202 sandboxPolicy: { type: "dangerFullAccess" },
1203 },
1204 "linux",
1205 ),
1206 {
1207 autoReview: false,
1208 sandboxEnabled: false,
1209 },
1210 );
1211 assert.deepEqual(
1212 cursorRuntimeAgentPolicy(
1213 {
1214 ...base,
1215 runtimeMode: "auto-accept-edits",
1216 },
1217 "win32",
1218 ),
1219 {
1220 autoReview: false,
1221 sandboxEnabled: true,
1222 },
1223 );
1224 assert.deepEqual(
1225 cursorRuntimeAgentPolicy(
1226 {
1227 ...base,
1228 runtimeMode: "auto",
1229 approvalPolicy: "never",
1230 },
1231 "win32",
1232 ),
1233 {
1234 autoReview: false,
1235 sandboxEnabled: true,
1236 },
1237 );
1238 // Auto-review can gate Windows execution without the unsupported SDK sandbox.
1239 assert.deepEqual(
1240 cursorRuntimeAgentPolicy(
1241 {
1242 ...base,
1243 runtimeMode: "auto",
1244 },
1245 "win32",
1246 ),
1247 {
1248 autoReview: true,
1249 sandboxEnabled: false,
1250 },
1251 );
1252 assert.deepEqual(
1253 cursorRuntimeAgentPolicy(
1254 {
1255 ...base,
1256 runtimeMode: "auto",
1257 sandboxPolicy: { type: "workspaceWrite" },
1258 },
1259 "win32",
1260 ),
1261 {
1262 autoReview: true,
1263 sandboxEnabled: true,
1264 },
1265 );
1266 });
1267
1268 it("injects thread-scoped MCP credentials without logging them", () => {
1269 const threadId = ThreadId.make("thread-cursor-mcp");
1270 const mcpSession = {
1271 environmentId: EnvironmentId.make("environment-cursor-mcp"),
1272 threadId,
1273 providerSessionId: "mcp-session-cursor",
1274 providerInstanceId: ProviderInstanceId.make("cursor"),
1275 endpoint: "http://127.0.0.1:43123/mcp",
1276 authorizationHeader: "Bearer secret-cursor-mcp-token",
1277 browserToolsAvailable: true,
1278 };
1279
1280 assert.deepEqual(cursorMcpServers(mcpSession), {
1281 "t3-code": {
1282 type: "http",
1283 url: "http://127.0.0.1:43123/mcp",
1284 headers: {
1285 Authorization: "Bearer secret-cursor-mcp-token",
1286 },
1287 },
1288 });
1289
1290 const options = makeCursorAgentOptions({
1291 apiKey: "secret-cursor-api-key",
1292 modelSelection: {
1293 instanceId: ProviderInstanceId.make("cursor"),
1294 model: "composer-2.5",
1295 },
1296 runtimePolicy: {
1297 runtimeMode: "full-access",
1298 interactionMode: "default",
1299 cwd: "/workspace",
1300 },
1301 threadId,
1302 mcpSession,
1303 platform: "linux",
1304 });
1305 assert.deepEqual(options.mcpServers, cursorMcpServers(mcpSession));
1306
1307 const logged = JSON.stringify(CursorAgentSdk.loggedCursorAgentOptions(options));
1308 assert.notInclude(logged, "secret-cursor-api-key");
1309 assert.notInclude(logged, "secret-cursor-mcp-token");
1310 });
1311
1312 it("recognizes direct and SDK-wrapped abort failures as cancellation", () => {
1313 assert.isTrue(CursorAgentSdk.isCursorCancellationError({ name: "AbortError" }));
1314 assert.isTrue(
1315 CursorAgentSdk.isCursorCancellationError({
1316 name: "ConnectError",
1317 cause: {
1318 name: "ConnectError",
1319 cause: { name: "AbortError" },
1320 },
1321 }),
1322 );
1323 assert.isFalse(CursorAgentSdk.isCursorCancellationError(new Error("request failed")));
1324 assert.isFalse(CursorAgentSdk.isCursorCancellationError(null));
1325 });
1326
1327 it("preserves failed nested read calls when Cursor omits their path", () => {
1328 assert.deepEqual(
1329 nestedToolCallFromEnvelope({
1330 toolCallId: "tool:failed-read",
1331 readToolCall: {
1332 args: {},
1333 result: { error: "File path was not provided." },
1334 },
1335 }),
1336 {
1337 callId: "tool:failed-read",
1338 toolCall: {
1339 type: "read",
1340 args: { path: "<unknown path>" },
1341 result: {
1342 status: "error",
1343 error: "File path was not provided.",
1344 },
1345 },
1346 },
1347 );
1348 });
1349});