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