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