Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

adapter.test.ts

1,265 lines42.3 KB

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