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