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

adapter.test.ts

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