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