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 ])("fails the turn with $reason", ({ updates = [], wait, failure }) =>
276 Effect.gen(function* () {
277 const fileSystem = yield* FileSystem.FileSystem;
278 const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-failure-" });
279 const instanceId = ProviderInstanceId.make("cursor");
280 const threadId = ThreadId.make("cursor-failure-thread");
281 const modelSelection = { instanceId, model: "claude-fable-5" };
282 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
283 runtimeMode: "full-access",
284 interactionMode: "default",
285 cwd: workspace,
286 });
287 const adapter = yield* makeCursorAdapterV2({
288 instanceId,
289 settings: yield* decodeCursorSettings({}),
290 environment: { HOME: workspace },
291 }).pipe(
292 Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
293 assertComplete: Effect.void,
294 open: () =>
295 Effect.succeed({
296 agentId: "native-cursor-failure",
297 listMessages: Effect.succeed([]),
298 close: Effect.void,
299 send: (input) =>
300 Effect.gen(function* () {
301 for (const update of updates) {
302 yield* input.onDelta!(update).pipe(Effect.orDie);
303 }
304 return {
305 agentId: "native-cursor-failure",
306 runId: "native-cursor-run",
307 wait,
308 cancel: Effect.void,
309 };
310 }),
311 }),
312 }),
313 Effect.provide(TestProviderHost.layer({ cwd: workspace })),
314 );
315 const runtime = yield* adapter.openSession({
316 threadId,
317 providerSessionId: ProviderSessionId.make("cursor-failure-session"),
318 modelSelection,
319 runtimePolicy,
320 });
321 const providerThread = yield* runtime.ensureThread({
322 threadId,
323 modelSelection,
324 runtimePolicy,
325 });
326 const now = yield* DateTime.now;
327 yield* runtime.startTurn({
328 threadId,
329 providerThread,
330 modelSelection,
331 runtimePolicy,
332 runId: RunId.make("cursor-failure-run"),
333 runOrdinal: 1,
334 providerTurnOrdinal: 1,
335 attemptId: RunAttemptId.make("cursor-failure-attempt"),
336 rootNodeId: NodeId.make("cursor-failure-root"),
337 appThread: {
338 id: threadId,
339 projectId: ProjectId.make("cursor-failure-project"),
340 createdBy: "user",
341 creationSource: "web",
342 title: "Cursor failure",
343 providerInstanceId: instanceId,
344 modelSelection,
345 runtimeMode: "full-access",
346 interactionMode: "default",
347 branch: null,
348 worktreePath: null,
349 activeProviderThreadId: providerThread.id,
350 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
351 forkedFrom: null,
352 createdAt: now,
353 updatedAt: now,
354 archivedAt: null,
355 settledOverride: null,
356 settledAt: null,
357 lastVisitedAt: null,
358 deletedAt: null,
359 },
360 message: {
361 messageId: MessageId.make("cursor-failure-message"),
362 createdBy: "user",
363 creationSource: "web",
364 text: "hi",
365 attachments: [],
366 },
367 });
368 const terminal = yield* runtime.events.pipe(
369 Stream.filter((event) => event.type === "turn.terminal"),
370 Stream.runHead,
371 );
372 assert.isTrue(Option.isSome(terminal));
373 if (Option.isSome(terminal)) {
374 assert.equal(terminal.value.status, "failed");
375 assert.equal(terminal.value.failure?.class, failure.class);
376 assert.equal(terminal.value.failure?.message, failure.message);
377 }
378 }).pipe(
379 Effect.scoped,
380 Effect.provide(
381 Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),
382 ),
383 ),
384 );
385
386 it.effect("fails standalone SDK transport diagnostics and sends compaction as /compress", () =>
387 Effect.gen(function* () {
388 const fileSystem = yield* FileSystem.FileSystem;
389 const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-errors-" });
390 const sentMessages: Array<string> = [];
391 let sendCalls = 0;
392 const instanceId = ProviderInstanceId.make("cursor");
393 const threadId = ThreadId.make("cursor-transport-error-thread");
394 const modelSelection = { instanceId, model: "composer-2.5" };
395 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
396 runtimeMode: "full-access",
397 interactionMode: "default",
398 cwd: workspace,
399 });
400 const adapter = yield* makeCursorAdapterV2({
401 instanceId,
402 settings: yield* decodeCursorSettings({}),
403 environment: { HOME: workspace },
404 }).pipe(
405 Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
406 assertComplete: Effect.void,
407 open: () =>
408 Effect.succeed({
409 agentId: "native-cursor-error",
410 listMessages: Effect.succeed([]),
411 close: Effect.void,
412 send: (input) =>
413 Effect.sync(() => {
414 sendCalls += 1;
415 sentMessages.push(
416 typeof input.message === "string" ? input.message : input.message.text,
417 );
418 const runId = `native-cursor-run-${sendCalls}`;
419 return {
420 agentId: "native-cursor-error",
421 runId,
422 wait: Effect.succeed({
423 id: runId,
424 requestId: `native-request-${sendCalls}`,
425 status: "finished" as const,
426 model: { id: "composer-2.5" },
427 durationMs: 1,
428 ...(sendCalls === 1
429 ? { result: "Error: RetriableError: WritableIterable is closed" }
430 : {}),
431 }),
432 cancel: Effect.void,
433 };
434 }),
435 }),
436 }),
437 Effect.provide(TestProviderHost.layer({ cwd: workspace })),
438 );
439 const runtime = yield* adapter.openSession({
440 threadId,
441 providerSessionId: ProviderSessionId.make("cursor-error-session"),
442 modelSelection,
443 runtimePolicy,
444 });
445 const providerThread = yield* runtime.ensureThread({
446 threadId,
447 modelSelection,
448 runtimePolicy,
449 });
450 const now = yield* DateTime.now;
451 const appThread = {
452 id: threadId,
453 projectId: ProjectId.make("cursor-error-project"),
454 createdBy: "user" as const,
455 creationSource: "web" as const,
456 title: "Cursor transport failure",
457 providerInstanceId: instanceId,
458 modelSelection,
459 runtimeMode: "full-access" as const,
460 interactionMode: "default" as const,
461 branch: null,
462 worktreePath: null,
463 activeProviderThreadId: providerThread.id,
464 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
465 forkedFrom: null,
466 createdAt: now,
467 updatedAt: now,
468 archivedAt: null,
469 settledOverride: null,
470 settledAt: null,
471 lastVisitedAt: null,
472 deletedAt: null,
473 };
474 yield* runtime.startTurn({
475 threadId,
476 providerThread,
477 modelSelection,
478 runtimePolicy,
479 runId: RunId.make("cursor-error-run"),
480 runOrdinal: 1,
481 providerTurnOrdinal: 1,
482 attemptId: RunAttemptId.make("cursor-error-attempt"),
483 rootNodeId: NodeId.make("cursor-error-root"),
484 appThread,
485 message: {
486 messageId: MessageId.make("cursor-error-message"),
487 createdBy: "user",
488 creationSource: "web",
489 text: "continue",
490 attachments: [],
491 },
492 });
493 const first = yield* runtime.events.pipe(
494 Stream.filter((event) => event.type === "turn.terminal"),
495 Stream.runHead,
496 );
497 assert.isTrue(Option.isSome(first));
498 if (Option.isSome(first)) {
499 assert.equal(first.value.status, "failed");
500 assert.equal(first.value.failure?.class, "transport_error");
501 }
502
503 assert.isDefined(runtime.compactThread);
504 yield* runtime.compactThread!({
505 threadId,
506 providerThread,
507 modelSelection,
508 runtimePolicy,
509 runId: RunId.make("cursor-compact-run"),
510 runOrdinal: 2,
511 providerTurnOrdinal: 2,
512 attemptId: RunAttemptId.make("cursor-compact-attempt"),
513 rootNodeId: NodeId.make("cursor-compact-root"),
514 appThread,
515 message: {
516 messageId: MessageId.make("cursor-compact-message"),
517 createdBy: "user",
518 creationSource: "web",
519 text: "ignored by compactThread",
520 attachments: [],
521 },
522 });
523 yield* runtime.events.pipe(
524 Stream.filter((event) => event.type === "turn.terminal"),
525 Stream.runHead,
526 );
527 assert.equal(sentMessages[1], "/compress");
528 }).pipe(
529 Effect.scoped,
530 Effect.provide(
531 Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),
532 ),
533 ),
534 );
535
536 it.effect("projects Cursor directory trees and lint diagnostics as file search results", () =>
537 Effect.gen(function* () {
538 const fileSystem = yield* FileSystem.FileSystem;
539 const path = yield* Path.Path;
540 const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-search-" });
541 const instanceId = ProviderInstanceId.make("cursor");
542 const threadId = ThreadId.make("cursor-search-thread");
543 const modelSelection = { instanceId, model: "composer-2.5" };
544 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
545 runtimeMode: "full-access",
546 interactionMode: "default",
547 cwd: workspace,
548 });
549 const emptyLsNode = {
550 childrenDirs: [],
551 childrenFiles: [],
552 childrenWereProcessed: true,
553 fullSubtreeExtensionCounts: {},
554 numFiles: 0,
555 };
556 const updates: ReadonlyArray<InteractionUpdate> = [
557 ...(["tool-call-started", "tool-call-completed"] as const).map((type) => ({
558 type,
559 modelCallId: "native-model-call",
560 callId: "mcp-weather",
561 toolCall: {
562 type: "mcp" as const,
563 args: {
564 providerIdentifier: "weather",
565 toolName: "get_weather",
566 args: { city: "Berlin" },
567 },
568 ...(type === "tool-call-completed"
569 ? { result: { status: "success" as const, value: { content: [], isError: false } } }
570 : {}),
571 },
572 })),
573 {
574 type: "tool-call-completed",
575 modelCallId: "native-model-call",
576 callId: "read-file",
577 toolCall: {
578 type: "read",
579 args: { path: "src/env.ts" },
580 result: {
581 status: "success",
582 value: { fileSize: 12, content: "---\nfile body", totalLines: 2 },
583 },
584 },
585 },
586 {
587 type: "tool-call-completed",
588 modelCallId: "native-model-call",
589 callId: "ls-nested",
590 toolCall: {
591 type: "ls",
592 args: { path: workspace },
593 result: {
594 status: "success",
595 value: {
596 directoryTreeRoot: {
597 ...emptyLsNode,
598 absPath: workspace,
599 childrenFiles: [{ name: "README.md" }],
600 childrenDirs: [
601 {
602 ...emptyLsNode,
603 absPath: path.join(workspace, "src"),
604 childrenFiles: [{ name: "index.ts" }],
605 childrenDirs: [
606 {
607 ...emptyLsNode,
608 absPath: path.join(workspace, "src", "nested"),
609 childrenFiles: [{ name: "util.ts" }],
610 },
611 ],
612 },
613 ],
614 },
615 },
616 },
617 },
618 },
619 {
620 type: "tool-call-completed",
621 modelCallId: "native-model-call",
622 callId: "ls-empty",
623 toolCall: {
624 type: "ls",
625 args: { path: path.join(workspace, "empty") },
626 result: {
627 status: "success",
628 value: {
629 directoryTreeRoot: { ...emptyLsNode, absPath: path.join(workspace, "empty") },
630 },
631 },
632 },
633 },
634 {
635 type: "tool-call-completed",
636 modelCallId: "native-model-call",
637 callId: "ls-failed",
638 toolCall: {
639 type: "ls",
640 args: { path: path.join(workspace, "missing") },
641 result: { status: "error", error: "ENOENT" },
642 },
643 },
644 {
645 type: "tool-call-completed",
646 modelCallId: "native-model-call",
647 callId: "grep-failed",
648 toolCall: {
649 type: "grep",
650 args: { pattern: "TODO", path: "src" },
651 result: { status: "error", error: "search failed" },
652 },
653 },
654 {
655 type: "tool-call-completed",
656 modelCallId: "native-model-call",
657 callId: "glob-failed",
658 toolCall: {
659 type: "glob",
660 args: { globPattern: "*.ts" },
661 result: { status: "error", error: "search failed" },
662 },
663 },
664 {
665 type: "tool-call-completed",
666 modelCallId: "native-model-call",
667 callId: "lints",
668 toolCall: {
669 type: "readLints",
670 args: { paths: ["src/a.ts", "src/b.ts"] },
671 result: {
672 status: "success",
673 value: {
674 totalFiles: 2,
675 totalDiagnostics: 3,
676 fileDiagnostics: [
677 {
678 path: "src/a.ts",
679 diagnosticsCount: 2,
680 diagnostics: [
681 {
682 message: "Unused variable",
683 code: "TS6133",
684 source: "ts",
685 severity: "warning",
686 range: { start: { line: 0, character: 4 } },
687 },
688 {
689 message: "Cannot find name",
690 code: "TS2304",
691 source: "ts",
692 severity: "error",
693 range: { start: { line: 11 } },
694 },
695 ],
696 },
697 {
698 path: "src/b.ts",
699 diagnosticsCount: 1,
700 diagnostics: [
701 {
702 message: "File-level diagnostic",
703 code: "TS0",
704 source: "ts",
705 severity: "information",
706 },
707 ],
708 },
709 ],
710 },
711 },
712 },
713 },
714 {
715 type: "tool-call-completed",
716 modelCallId: "native-model-call",
717 callId: "lints-empty",
718 toolCall: {
719 type: "readLints",
720 args: { paths: ["src/clean.ts"] },
721 result: {
722 status: "success",
723 value: {
724 totalFiles: 1,
725 totalDiagnostics: 0,
726 fileDiagnostics: [{ path: "src/clean.ts", diagnosticsCount: 0, diagnostics: [] }],
727 },
728 },
729 },
730 },
731 {
732 type: "tool-call-completed",
733 modelCallId: "native-model-call",
734 callId: "lints-failed",
735 toolCall: {
736 type: "readLints",
737 args: { paths: ["src/a.ts"] },
738 result: { status: "error", error: "lint failed" },
739 },
740 },
741 ];
742 const adapter = yield* makeCursorAdapterV2({
743 instanceId,
744 settings: yield* decodeCursorSettings({}),
745 environment: { HOME: workspace },
746 }).pipe(
747 Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
748 assertComplete: Effect.void,
749 open: () =>
750 Effect.succeed({
751 agentId: "native-cursor-search",
752 listMessages: Effect.succeed([]),
753 close: Effect.void,
754 send: (input) =>
755 Effect.gen(function* () {
756 for (const update of updates) {
757 if (input.onDelta !== undefined) {
758 yield* input.onDelta(update).pipe(Effect.orDie);
759 }
760 }
761 return {
762 agentId: "native-cursor-search",
763 runId: "native-cursor-run",
764 wait: Effect.succeed({
765 id: "native-cursor-run",
766 requestId: "native-request",
767 status: "finished" as const,
768 model: { id: "composer-2.5" },
769 durationMs: 1,
770 }),
771 cancel: Effect.void,
772 };
773 }),
774 }),
775 }),
776 Effect.provide(TestProviderHost.layer({ cwd: workspace })),
777 );
778 const runtime = yield* adapter.openSession({
779 threadId,
780 providerSessionId: ProviderSessionId.make("cursor-search-session"),
781 modelSelection,
782 runtimePolicy,
783 });
784 const providerThread = yield* runtime.ensureThread({
785 threadId,
786 modelSelection,
787 runtimePolicy,
788 });
789 const now = yield* DateTime.now;
790 yield* runtime.startTurn({
791 threadId,
792 providerThread,
793 modelSelection,
794 runtimePolicy,
795 runId: RunId.make("cursor-search-run"),
796 runOrdinal: 1,
797 providerTurnOrdinal: 1,
798 attemptId: RunAttemptId.make("cursor-search-attempt"),
799 rootNodeId: NodeId.make("cursor-search-root"),
800 appThread: {
801 id: threadId,
802 projectId: ProjectId.make("cursor-search-project"),
803 createdBy: "user",
804 creationSource: "web",
805 title: "Cursor search results",
806 providerInstanceId: instanceId,
807 modelSelection,
808 runtimeMode: "full-access",
809 interactionMode: "default",
810 branch: null,
811 worktreePath: null,
812 activeProviderThreadId: providerThread.id,
813 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
814 forkedFrom: null,
815 createdAt: now,
816 updatedAt: now,
817 archivedAt: null,
818 settledOverride: null,
819 settledAt: null,
820 lastVisitedAt: null,
821 deletedAt: null,
822 },
823 message: {
824 messageId: MessageId.make("cursor-search-message"),
825 createdBy: "user",
826 creationSource: "web",
827 text: "inspect the workspace",
828 attachments: [],
829 },
830 });
831 const events = yield* runtime.events.pipe(
832 Stream.takeUntil((event) => event.type === "turn.terminal"),
833 Stream.runCollect,
834 );
835 const mcpItems = events.flatMap((event) =>
836 event.type === "turn_item.updated" &&
837 event.turnItem.type === "dynamic_tool" &&
838 event.turnItem.toolName === "mcp__weather__get_weather"
839 ? [event.turnItem]
840 : [],
841 );
842 assert.deepEqual(
843 mcpItems.map((item) => item.status),
844 ["running", "completed"],
845 );
846 for (const item of mcpItems) {
847 assert.equal(item.title, "get weather");
848 assert.deepEqual(item.toolSource, {
849 key: "mcp:weather",
850 name: "weather",
851 kind: "integration",
852 });
853 assert.deepEqual(item.input, { city: "Berlin" });
854 }
855 const fileSearchItems = events.flatMap((event) =>
856 event.type === "turn_item.updated" &&
857 event.turnItem.type === "file_search" &&
858 event.turnItem.status !== "running"
859 ? [event.turnItem]
860 : [],
861 );
862 const readItems = events.flatMap((event) =>
863 event.type === "turn_item.updated" &&
864 event.turnItem.type === "dynamic_tool" &&
865 event.turnItem.toolName === "Read" &&
866 event.turnItem.status === "completed"
867 ? [event.turnItem]
868 : [],
869 );
870 assert.deepEqual(
871 readItems.map((item) => ({ title: item.title, input: item.input })),
872 [{ title: "Read src/env.ts", input: { path: "src/env.ts" } }],
873 );
874 assert.deepEqual(
875 fileSearchItems.map((item) => ({
876 pattern: item.pattern,
877 status: item.status,
878 results: item.results,
879 })),
880 [
881 {
882 pattern: workspace,
883 status: "completed",
884 results: [
885 { fileName: path.join(workspace, "README.md") },
886 { fileName: path.join(workspace, "src", "index.ts") },
887 { fileName: path.join(workspace, "src", "nested", "util.ts") },
888 ],
889 },
890 {
891 pattern: path.join(workspace, "empty"),
892 status: "completed",
893 results: undefined,
894 },
895 {
896 pattern: path.join(workspace, "missing"),
897 status: "failed",
898 results: [{ fileName: path.join(workspace, "missing"), preview: "ENOENT" }],
899 },
900 {
901 pattern: "TODO",
902 status: "failed",
903 results: [{ fileName: "src", preview: "search failed" }],
904 },
905 {
906 pattern: "*.ts",
907 status: "failed",
908 results: [{ fileName: ".", preview: "search failed" }],
909 },
910 {
911 pattern: "src/a.ts, src/b.ts",
912 status: "completed",
913 results: [
914 { fileName: "src/a.ts", line: 1, column: 5, preview: "Unused variable" },
915 { fileName: "src/a.ts", line: 12, preview: "Cannot find name" },
916 { fileName: "src/b.ts", preview: "File-level diagnostic" },
917 ],
918 },
919 {
920 pattern: "src/clean.ts",
921 status: "completed",
922 results: undefined,
923 },
924 {
925 pattern: "src/a.ts",
926 status: "failed",
927 results: [{ fileName: "src/a.ts", preview: "lint failed" }],
928 },
929 ],
930 );
931 }).pipe(
932 Effect.scoped,
933 Effect.provide(
934 Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),
935 ),
936 ),
937 );
938
939 it.effect("names a custom model Cursor's account catalog rejects", () =>
940 Effect.gen(function* () {
941 const fileSystem = yield* FileSystem.FileSystem;
942 const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-model-" });
943 const instanceId = ProviderInstanceId.make("cursor");
944 const threadId = ThreadId.make("cursor-custom-model-thread");
945 const catalogModel = { instanceId, model: "composer-2.5" };
946 const customModel = { instanceId, model: "deepseek/deepseek-v4.1-flash" };
947 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
948 runtimeMode: "full-access",
949 interactionMode: "default",
950 cwd: workspace,
951 });
952 // The SDK checks every create, resume, and send model against the account catalog.
953 const checkModel = (method: string, model: { readonly id: string } | undefined) =>
954 model === undefined || model.id === "composer-2.5"
955 ? Effect.void
956 : Effect.fail(
957 new CursorAgentSdk.CursorAgentSdkRunnerError({
958 method,
959 cause: new ConfigurationError(
960 `Cannot use this model: ${model.id}. Available models: default, composer-2.5. Use Cursor.models.list() to discover valid selections.`,
961 { isRetryable: false },
962 ),
963 }),
964 );
965 const adapter = yield* makeCursorAdapterV2({
966 instanceId,
967 settings: yield* decodeCursorSettings({}),
968 environment: { HOME: workspace },
969 }).pipe(
970 Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
971 assertComplete: Effect.void,
972 open: (input) =>
973 checkModel(`agent.${input.operation}`, input.options.model).pipe(
974 Effect.as({
975 agentId: "native-cursor-custom-model",
976 listMessages: Effect.succeed([]),
977 close: Effect.void,
978 send: (sendInput) =>
979 checkModel("run.start", sendInput.options?.model).pipe(
980 Effect.andThen(Effect.die("unexpected Cursor run")),
981 ),
982 }),
983 ),
984 }),
985 Effect.provide(TestProviderHost.layer({ cwd: workspace })),
986 );
987 const runtime = yield* adapter.openSession({
988 threadId,
989 providerSessionId: ProviderSessionId.make("cursor-custom-model-session"),
990 modelSelection: catalogModel,
991 runtimePolicy,
992 });
993 const expected =
994 '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.';
995
996 // A new thread created with the custom model.
997 const createFailure = yield* runtime
998 .ensureThread({ threadId, modelSelection: customModel, runtimePolicy })
999 .pipe(Effect.flip);
1000 assert.equal(makeProviderFailure({ cause: createFailure }).message, expected);
1001
1002 // An existing thread switched to the custom model.
1003 const providerThread = yield* runtime.ensureThread({
1004 threadId,
1005 modelSelection: catalogModel,
1006 runtimePolicy,
1007 });
1008 const now = yield* DateTime.now;
1009 const sendFailure = yield* runtime
1010 .startTurn({
1011 threadId,
1012 providerThread,
1013 modelSelection: customModel,
1014 runtimePolicy,
1015 runId: RunId.make("cursor-custom-model-run"),
1016 runOrdinal: 1,
1017 providerTurnOrdinal: 1,
1018 attemptId: RunAttemptId.make("cursor-custom-model-attempt"),
1019 rootNodeId: NodeId.make("cursor-custom-model-root"),
1020 appThread: {
1021 id: threadId,
1022 projectId: ProjectId.make("cursor-custom-model-project"),
1023 createdBy: "user",
1024 creationSource: "web",
1025 title: "Cursor custom model",
1026 providerInstanceId: instanceId,
1027 modelSelection: customModel,
1028 runtimeMode: "full-access",
1029 interactionMode: "default",
1030 branch: null,
1031 worktreePath: null,
1032 activeProviderThreadId: providerThread.id,
1033 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
1034 forkedFrom: null,
1035 createdAt: now,
1036 updatedAt: now,
1037 archivedAt: null,
1038 settledOverride: null,
1039 settledAt: null,
1040 lastVisitedAt: null,
1041 deletedAt: null,
1042 },
1043 message: {
1044 messageId: MessageId.make("cursor-custom-model-message"),
1045 createdBy: "user",
1046 creationSource: "web",
1047 text: "Hello.",
1048 attachments: [],
1049 },
1050 })
1051 .pipe(Effect.flip);
1052 assert.equal(makeProviderFailure({ cause: sendFailure }).message, expected);
1053 }).pipe(
1054 Effect.scoped,
1055 Effect.provide(
1056 Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),
1057 ),
1058 ),
1059 );
1060
1061 it("maps runtime modes to the SDK sandbox and auto-review controls", () => {
1062 const base = {
1063 interactionMode: "default" as const,
1064 cwd: "/tmp/cursor-adapter",
1065 };
1066 assert.deepEqual(
1067 cursorRuntimeAgentPolicy(
1068 {
1069 ...base,
1070 runtimeMode: "full-access",
1071 },
1072 "linux",
1073 ),
1074 {
1075 autoReview: false,
1076 sandboxEnabled: false,
1077 },
1078 );
1079 assert.deepEqual(
1080 cursorRuntimeAgentPolicy(
1081 {
1082 ...base,
1083 runtimeMode: "auto-accept-edits",
1084 },
1085 "linux",
1086 ),
1087 {
1088 autoReview: false,
1089 sandboxEnabled: true,
1090 },
1091 );
1092 assert.deepEqual(
1093 cursorRuntimeAgentPolicy(
1094 {
1095 ...base,
1096 runtimeMode: "auto",
1097 },
1098 "linux",
1099 ),
1100 {
1101 autoReview: true,
1102 sandboxEnabled: true,
1103 },
1104 );
1105 assert.deepEqual(
1106 cursorRuntimeAgentPolicy(
1107 {
1108 ...base,
1109 runtimeMode: "approval-required",
1110 },
1111 "linux",
1112 ),
1113 {
1114 autoReview: true,
1115 sandboxEnabled: true,
1116 },
1117 );
1118 assert.deepEqual(
1119 cursorRuntimeAgentPolicy(
1120 {
1121 ...base,
1122 runtimeMode: "full-access",
1123 approvalPolicy: "never",
1124 sandboxPolicy: { type: "readOnly" },
1125 },
1126 "linux",
1127 ),
1128 {
1129 autoReview: false,
1130 sandboxEnabled: true,
1131 },
1132 );
1133 assert.deepEqual(
1134 cursorRuntimeAgentPolicy(
1135 {
1136 ...base,
1137 runtimeMode: "approval-required",
1138 approvalPolicy: "never",
1139 sandboxPolicy: { type: "dangerFullAccess" },
1140 },
1141 "linux",
1142 ),
1143 {
1144 autoReview: false,
1145 sandboxEnabled: false,
1146 },
1147 );
1148 assert.deepEqual(
1149 cursorRuntimeAgentPolicy(
1150 {
1151 ...base,
1152 runtimeMode: "auto-accept-edits",
1153 },
1154 "win32",
1155 ),
1156 {
1157 autoReview: false,
1158 sandboxEnabled: true,
1159 },
1160 );
1161 assert.deepEqual(
1162 cursorRuntimeAgentPolicy(
1163 {
1164 ...base,
1165 runtimeMode: "auto",
1166 approvalPolicy: "never",
1167 },
1168 "win32",
1169 ),
1170 {
1171 autoReview: false,
1172 sandboxEnabled: true,
1173 },
1174 );
1175 // Auto-review can gate Windows execution without the unsupported SDK sandbox.
1176 assert.deepEqual(
1177 cursorRuntimeAgentPolicy(
1178 {
1179 ...base,
1180 runtimeMode: "auto",
1181 },
1182 "win32",
1183 ),
1184 {
1185 autoReview: true,
1186 sandboxEnabled: false,
1187 },
1188 );
1189 assert.deepEqual(
1190 cursorRuntimeAgentPolicy(
1191 {
1192 ...base,
1193 runtimeMode: "auto",
1194 sandboxPolicy: { type: "workspaceWrite" },
1195 },
1196 "win32",
1197 ),
1198 {
1199 autoReview: true,
1200 sandboxEnabled: true,
1201 },
1202 );
1203 });
1204
1205 it("injects thread-scoped MCP credentials without logging them", () => {
1206 const threadId = ThreadId.make("thread-cursor-mcp");
1207 const mcpSession = {
1208 environmentId: EnvironmentId.make("environment-cursor-mcp"),
1209 threadId,
1210 providerSessionId: "mcp-session-cursor",
1211 providerInstanceId: ProviderInstanceId.make("cursor"),
1212 endpoint: "http://127.0.0.1:43123/mcp",
1213 authorizationHeader: "Bearer secret-cursor-mcp-token",
1214 browserToolsAvailable: true,
1215 };
1216
1217 assert.deepEqual(cursorMcpServers(mcpSession), {
1218 "t3-code": {
1219 type: "http",
1220 url: "http://127.0.0.1:43123/mcp",
1221 headers: {
1222 Authorization: "Bearer secret-cursor-mcp-token",
1223 },
1224 },
1225 });
1226
1227 const options = makeCursorAgentOptions({
1228 apiKey: "secret-cursor-api-key",
1229 modelSelection: {
1230 instanceId: ProviderInstanceId.make("cursor"),
1231 model: "composer-2.5",
1232 },
1233 runtimePolicy: {
1234 runtimeMode: "full-access",
1235 interactionMode: "default",
1236 cwd: "/workspace",
1237 },
1238 threadId,
1239 mcpSession,
1240 platform: "linux",
1241 });
1242 assert.deepEqual(options.mcpServers, cursorMcpServers(mcpSession));
1243
1244 const logged = JSON.stringify(CursorAgentSdk.loggedCursorAgentOptions(options));
1245 assert.notInclude(logged, "secret-cursor-api-key");
1246 assert.notInclude(logged, "secret-cursor-mcp-token");
1247 });
1248
1249 it("recognizes direct and SDK-wrapped abort failures as cancellation", () => {
1250 assert.isTrue(CursorAgentSdk.isCursorCancellationError({ name: "AbortError" }));
1251 assert.isTrue(
1252 CursorAgentSdk.isCursorCancellationError({
1253 name: "ConnectError",
1254 cause: {
1255 name: "ConnectError",
1256 cause: { name: "AbortError" },
1257 },
1258 }),
1259 );
1260 assert.isFalse(CursorAgentSdk.isCursorCancellationError(new Error("request failed")));
1261 assert.isFalse(CursorAgentSdk.isCursorCancellationError(null));
1262 });
1263
1264 it("preserves failed nested read calls when Cursor omits their path", () => {
1265 assert.deepEqual(
1266 nestedToolCallFromEnvelope({
1267 toolCallId: "tool:failed-read",
1268 readToolCall: {
1269 args: {},
1270 result: { error: "File path was not provided." },
1271 },
1272 }),
1273 {
1274 callId: "tool:failed-read",
1275 toolCall: {
1276 type: "read",
1277 args: { path: "<unknown path>" },
1278 result: {
1279 status: "error",
1280 error: "File path was not provided.",
1281 },
1282 },
1283 },
1284 );
1285 });
1286});