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