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 { ConfigurationError } 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, { city: "Berlin" });
834 }
835 const fileSearchItems = events.flatMap((event) =>
836 event.type === "turn_item.updated" &&
837 event.turnItem.type === "file_search" &&
838 event.turnItem.status !== "running"
839 ? [event.turnItem]
840 : [],
841 );
842 const readItems = events.flatMap((event) =>
843 event.type === "turn_item.updated" &&
844 event.turnItem.type === "dynamic_tool" &&
845 event.turnItem.toolName === "Read" &&
846 event.turnItem.status === "completed"
847 ? [event.turnItem]
848 : [],
849 );
850 assert.deepEqual(
851 readItems.map((item) => ({ title: item.title, input: item.input })),
852 [{ title: "Read src/env.ts", input: { path: "src/env.ts" } }],
853 );
854 assert.deepEqual(
855 fileSearchItems.map((item) => ({
856 pattern: item.pattern,
857 status: item.status,
858 results: item.results,
859 })),
860 [
861 {
862 pattern: workspace,
863 status: "completed",
864 results: [
865 { fileName: path.join(workspace, "README.md") },
866 { fileName: path.join(workspace, "src", "index.ts") },
867 { fileName: path.join(workspace, "src", "nested", "util.ts") },
868 ],
869 },
870 {
871 pattern: path.join(workspace, "empty"),
872 status: "completed",
873 results: undefined,
874 },
875 {
876 pattern: path.join(workspace, "missing"),
877 status: "failed",
878 results: [{ fileName: path.join(workspace, "missing"), preview: "ENOENT" }],
879 },
880 {
881 pattern: "TODO",
882 status: "failed",
883 results: [{ fileName: "src", preview: "search failed" }],
884 },
885 {
886 pattern: "*.ts",
887 status: "failed",
888 results: [{ fileName: ".", preview: "search failed" }],
889 },
890 {
891 pattern: "src/a.ts, src/b.ts",
892 status: "completed",
893 results: [
894 { fileName: "src/a.ts", line: 1, column: 5, preview: "Unused variable" },
895 { fileName: "src/a.ts", line: 12, preview: "Cannot find name" },
896 { fileName: "src/b.ts", preview: "File-level diagnostic" },
897 ],
898 },
899 {
900 pattern: "src/clean.ts",
901 status: "completed",
902 results: undefined,
903 },
904 {
905 pattern: "src/a.ts",
906 status: "failed",
907 results: [{ fileName: "src/a.ts", preview: "lint failed" }],
908 },
909 ],
910 );
911 }).pipe(
912 Effect.scoped,
913 Effect.provide(
914 Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),
915 ),
916 ),
917 );
918
919 it.effect("names a custom model Cursor's account catalog rejects", () =>
920 Effect.gen(function* () {
921 const fileSystem = yield* FileSystem.FileSystem;
922 const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-model-" });
923 const instanceId = ProviderInstanceId.make("cursor");
924 const threadId = ThreadId.make("cursor-custom-model-thread");
925 const catalogModel = { instanceId, model: "composer-2.5" };
926 const customModel = { instanceId, model: "deepseek/deepseek-v4.1-flash" };
927 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
928 runtimeMode: "full-access",
929 interactionMode: "default",
930 cwd: workspace,
931 });
932 // The SDK checks every create, resume, and send model against the account catalog.
933 const checkModel = (method: string, model: { readonly id: string } | undefined) =>
934 model === undefined || model.id === "composer-2.5"
935 ? Effect.void
936 : Effect.fail(
937 new CursorAgentSdk.CursorAgentSdkRunnerError({
938 method,
939 cause: new ConfigurationError(
940 `Cannot use this model: ${model.id}. Available models: default, composer-2.5. Use Cursor.models.list() to discover valid selections.`,
941 { isRetryable: false },
942 ),
943 }),
944 );
945 const adapter = yield* makeCursorAdapterV2({
946 instanceId,
947 settings: yield* decodeCursorSettings({}),
948 environment: { HOME: workspace },
949 }).pipe(
950 Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
951 assertComplete: Effect.void,
952 open: (input) =>
953 checkModel(`agent.${input.operation}`, input.options.model).pipe(
954 Effect.as({
955 agentId: "native-cursor-custom-model",
956 listMessages: Effect.succeed([]),
957 close: Effect.void,
958 send: (sendInput) =>
959 checkModel("run.start", sendInput.options?.model).pipe(
960 Effect.andThen(Effect.die("unexpected Cursor run")),
961 ),
962 }),
963 ),
964 }),
965 Effect.provide(TestProviderHost.layer({ cwd: workspace })),
966 );
967 const runtime = yield* adapter.openSession({
968 threadId,
969 providerSessionId: ProviderSessionId.make("cursor-custom-model-session"),
970 modelSelection: catalogModel,
971 runtimePolicy,
972 });
973 const expected =
974 '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.';
975
976 // A new thread created with the custom model.
977 const createFailure = yield* runtime
978 .ensureThread({ threadId, modelSelection: customModel, runtimePolicy })
979 .pipe(Effect.flip);
980 assert.equal(makeProviderFailure({ cause: createFailure }).message, expected);
981
982 // An existing thread switched to the custom model.
983 const providerThread = yield* runtime.ensureThread({
984 threadId,
985 modelSelection: catalogModel,
986 runtimePolicy,
987 });
988 const now = yield* DateTime.now;
989 const sendFailure = yield* runtime
990 .startTurn({
991 threadId,
992 providerThread,
993 modelSelection: customModel,
994 runtimePolicy,
995 runId: RunId.make("cursor-custom-model-run"),
996 runOrdinal: 1,
997 providerTurnOrdinal: 1,
998 attemptId: RunAttemptId.make("cursor-custom-model-attempt"),
999 rootNodeId: NodeId.make("cursor-custom-model-root"),
1000 appThread: {
1001 id: threadId,
1002 projectId: ProjectId.make("cursor-custom-model-project"),
1003 createdBy: "user",
1004 creationSource: "web",
1005 title: "Cursor custom model",
1006 providerInstanceId: instanceId,
1007 modelSelection: customModel,
1008 runtimeMode: "full-access",
1009 interactionMode: "default",
1010 branch: null,
1011 worktreePath: null,
1012 activeProviderThreadId: providerThread.id,
1013 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
1014 forkedFrom: null,
1015 createdAt: now,
1016 updatedAt: now,
1017 archivedAt: null,
1018 settledOverride: null,
1019 settledAt: null,
1020 lastVisitedAt: null,
1021 deletedAt: null,
1022 },
1023 message: {
1024 messageId: MessageId.make("cursor-custom-model-message"),
1025 createdBy: "user",
1026 creationSource: "web",
1027 text: "Hello.",
1028 attachments: [],
1029 },
1030 })
1031 .pipe(Effect.flip);
1032 assert.equal(makeProviderFailure({ cause: sendFailure }).message, expected);
1033 }).pipe(
1034 Effect.scoped,
1035 Effect.provide(
1036 Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),
1037 ),
1038 ),
1039 );
1040
1041 it("maps Cursor auto and model parameters to SDK selections", () => {
1042 assert.deepEqual(
1043 cursorSdkModelSelection({
1044 instanceId: ProviderInstanceId.make("cursor"),
1045 model: "auto",
1046 options: [
1047 { id: "thinking", value: "high" },
1048 { id: "contextWindow", value: "1m" },
1049 { id: "fastMode", value: true },
1050 ],
1051 }),
1052 {
1053 id: "default",
1054 params: [
1055 { id: "thinking", value: "high" },
1056 { id: "context", value: "1m" },
1057 { id: "fast", value: "true" },
1058 ],
1059 },
1060 );
1061 });
1062
1063 it("maps runtime modes to the SDK sandbox and auto-review controls", () => {
1064 const base = {
1065 interactionMode: "default" as const,
1066 cwd: "/tmp/cursor-adapter",
1067 };
1068 assert.deepEqual(
1069 cursorRuntimeAgentPolicy({
1070 ...base,
1071 runtimeMode: "full-access",
1072 }),
1073 {
1074 autoReview: false,
1075 sandboxEnabled: false,
1076 },
1077 );
1078 assert.deepEqual(
1079 cursorRuntimeAgentPolicy({
1080 ...base,
1081 runtimeMode: "auto-accept-edits",
1082 }),
1083 {
1084 autoReview: false,
1085 sandboxEnabled: true,
1086 },
1087 );
1088 assert.deepEqual(
1089 cursorRuntimeAgentPolicy({
1090 ...base,
1091 runtimeMode: "auto",
1092 }),
1093 {
1094 autoReview: true,
1095 sandboxEnabled: true,
1096 },
1097 );
1098 assert.deepEqual(
1099 cursorRuntimeAgentPolicy({
1100 ...base,
1101 runtimeMode: "approval-required",
1102 }),
1103 {
1104 autoReview: true,
1105 sandboxEnabled: true,
1106 },
1107 );
1108 assert.deepEqual(
1109 cursorRuntimeAgentPolicy({
1110 ...base,
1111 runtimeMode: "full-access",
1112 approvalPolicy: "never",
1113 sandboxPolicy: { type: "readOnly" },
1114 }),
1115 {
1116 autoReview: false,
1117 sandboxEnabled: true,
1118 },
1119 );
1120 assert.deepEqual(
1121 cursorRuntimeAgentPolicy({
1122 ...base,
1123 runtimeMode: "approval-required",
1124 approvalPolicy: "never",
1125 sandboxPolicy: { type: "dangerFullAccess" },
1126 }),
1127 {
1128 autoReview: false,
1129 sandboxEnabled: false,
1130 },
1131 );
1132 });
1133
1134 it("loads the user's Cursor settings layers in every runtime mode", () => {
1135 for (const runtimeMode of ["full-access", "auto-accept-edits", "approval-required"] as const) {
1136 const options = makeCursorAgentOptions({
1137 modelSelection: {
1138 instanceId: ProviderInstanceId.make("cursor"),
1139 model: "composer-2.5",
1140 },
1141 runtimePolicy: { runtimeMode, interactionMode: "default", cwd: "/workspace" },
1142 threadId: ThreadId.make("thread-cursor-setting-sources"),
1143 mcpSession: undefined,
1144 });
1145 assert.deepEqual(options.local?.settingSources, [
1146 "project",
1147 "user",
1148 "team",
1149 "mdm",
1150 "plugins",
1151 ]);
1152 }
1153 });
1154
1155 it("injects thread-scoped MCP credentials without logging them", () => {
1156 const threadId = ThreadId.make("thread-cursor-mcp");
1157 const mcpSession = {
1158 environmentId: EnvironmentId.make("environment-cursor-mcp"),
1159 threadId,
1160 providerSessionId: "mcp-session-cursor",
1161 providerInstanceId: ProviderInstanceId.make("cursor"),
1162 endpoint: "http://127.0.0.1:43123/mcp",
1163 authorizationHeader: "Bearer secret-cursor-mcp-token",
1164 browserToolsAvailable: true,
1165 };
1166
1167 assert.deepEqual(cursorMcpServers(mcpSession), {
1168 "t3-code": {
1169 type: "http",
1170 url: "http://127.0.0.1:43123/mcp",
1171 headers: {
1172 Authorization: "Bearer secret-cursor-mcp-token",
1173 },
1174 },
1175 });
1176
1177 const options = makeCursorAgentOptions({
1178 apiKey: "secret-cursor-api-key",
1179 modelSelection: {
1180 instanceId: ProviderInstanceId.make("cursor"),
1181 model: "composer-2.5",
1182 },
1183 runtimePolicy: {
1184 runtimeMode: "full-access",
1185 interactionMode: "default",
1186 cwd: "/workspace",
1187 },
1188 threadId,
1189 mcpSession,
1190 });
1191 assert.deepEqual(options.mcpServers, cursorMcpServers(mcpSession));
1192
1193 const logged = JSON.stringify(CursorAgentSdk.loggedCursorAgentOptions(options));
1194 assert.notInclude(logged, "secret-cursor-api-key");
1195 assert.notInclude(logged, "secret-cursor-mcp-token");
1196 });
1197
1198 it("recognizes direct and SDK-wrapped abort failures as cancellation", () => {
1199 assert.isTrue(CursorAgentSdk.isCursorCancellationError({ name: "AbortError" }));
1200 assert.isTrue(
1201 CursorAgentSdk.isCursorCancellationError({
1202 name: "ConnectError",
1203 cause: {
1204 name: "ConnectError",
1205 cause: { name: "AbortError" },
1206 },
1207 }),
1208 );
1209 assert.isFalse(CursorAgentSdk.isCursorCancellationError(new Error("request failed")));
1210 assert.isFalse(CursorAgentSdk.isCursorCancellationError(null));
1211 });
1212
1213 it("preserves failed nested read calls when Cursor omits their path", () => {
1214 assert.deepEqual(
1215 nestedToolCallFromEnvelope({
1216 toolCallId: "tool:failed-read",
1217 readToolCall: {
1218 args: {},
1219 result: { error: "File path was not provided." },
1220 },
1221 }),
1222 {
1223 callId: "tool:failed-read",
1224 toolCall: {
1225 type: "read",
1226 args: { path: "<unknown path>" },
1227 result: {
1228 status: "error",
1229 error: "File path was not provided.",
1230 },
1231 },
1232 },
1233 );
1234 });
1235});