Open History to see the last commit
1import * as FileSystem from "effect/FileSystem";
2
3import type { AgentOptions, RunResult } from "@cursor/sdk";
4import * as Effect from "effect/Effect";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7
8import {
9 type ProviderSetupError,
10 type ServerProviderModel,
11 TextGenerationError,
12} from "@t3tools/contracts";
13import type { CursorSettings } from "../settings.ts";
14
15import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations";
16import { cursorSdkModelSelection } from "./sdkModel.ts";
17import type { CursorAuth } from "./auth.ts";
18import * as CursorAgentSdk from "./CursorAgentSdk.ts";
19import * as CursorSdk from "./CursorSdk.ts";
20import * as HostProcess from "@t3tools/shared/HostProcess";
21
22const CURSOR_TIMEOUT_MS = 180_000;
23
24const isTextGenerationError = Schema.is(TextGenerationError);
25
26function cursorSdkResultDetail(result: RunResult): string {
27 switch (result.status) {
28 case "cancelled":
29 return "Cursor SDK request was cancelled.";
30 case "error":
31 return CursorAgentSdk.isCursorUsageLimitError(result.error)
32 ? "Cursor usage limit reached. Try again later or choose another text-generation provider."
33 : "Cursor SDK request finished with an error.";
34 case "finished":
35 return "Cursor SDK returned empty output.";
36 }
37}
38
39// Sandboxing fails without cursorsandbox or after a process-wide unsupported result.
40function cursorSandboxUnsupported(cause: unknown): boolean {
41 const seen = new Set<object>();
42 let current = cause;
43 while (typeof current === "object" && current !== null && !seen.has(current)) {
44 seen.add(current);
45 if (current instanceof Error && current.message.includes("sandboxing is not supported")) {
46 return true;
47 }
48 current = Reflect.get(current, "cause");
49 }
50 return false;
51}
52
53export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(function* (
54 cursorSettings: CursorSettings,
55 environment?: NodeJS.ProcessEnv,
56 resolveApiKey?: Effect.Effect<string, ProviderSetupError>,
57 withAccess?: CursorAuth["withAccess"],
58 getModels?: () => ReadonlyArray<ServerProviderModel>,
59) {
60 const fs = yield* FileSystem.FileSystem;
61 const sdk = yield* CursorSdk.CursorSdk;
62 const resolvedEnvironment = environment ?? process.env;
63
64 const resolveCursorApiKey = Effect.fn("CursorTextGeneration.resolveCursorApiKey")(function* (
65 operation: TextGenerationOperations.Operation,
66 ) {
67 if (!cursorSettings.enabled) {
68 return yield* new TextGenerationError({
69 operation,
70 detail: "Cursor is disabled in T3 Code settings.",
71 });
72 }
73
74 const apiKey = resolveApiKey
75 ? yield* resolveApiKey
76 : resolvedEnvironment.CURSOR_API_KEY?.trim();
77 if (!apiKey) {
78 return yield* new TextGenerationError({
79 operation,
80 detail: "Sign in with Cursor or add CURSOR_API_KEY in provider settings.",
81 });
82 }
83
84 return apiKey;
85 });
86
87 const runCursorJson: TextGenerationOperations.Runner = Effect.fn(
88 "CursorTextGeneration.runCursorJson",
89 )(
90 function* (input) {
91 const { operation, prompt, modelSelection } = input;
92
93 const apiKey = yield* resolveCursorApiKey(operation);
94 const sdkFailure = (detail: string) => (cause: unknown) =>
95 new TextGenerationError({ operation, detail, cause });
96 const { Agent } = yield* Effect.try({
97 try: sdk.load,
98 catch: sdkFailure("Cursor SDK could not be loaded."),
99 });
100 // sandbox.json expands writable paths independently of settingSources; the public API cannot override it.
101 if (yield* fs.exists(`${yield* HostProcess.HomeDirectory}/.cursor/sandbox.json`)) {
102 return yield* new TextGenerationError({
103 operation,
104 detail:
105 "Cursor text generation cannot enforce workspace isolation with a custom ~/.cursor/sandbox.json. Use another text-generation provider.",
106 });
107 }
108 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-text-" });
109 // Only store disposal releases SDK SQLite handles; keep state outside the empty workspace.
110 const stateRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-text-state-" });
111 const store = yield* Effect.acquireRelease(
112 Effect.tryPromise({
113 try: () => sdk.loadSqlite().SqliteLocalAgentStore.open({ workspaceRef: cwd, stateRoot }),
114 catch: sdkFailure("Cursor SDK agent store could not be opened."),
115 }),
116 (store) =>
117 Effect.tryPromise({
118 try: () => store.dispose(),
119 catch: sdkFailure("Cursor SDK agent store could not be disposed."),
120 }).pipe(Effect.ignore({ log: true })),
121 );
122 const agentOptions = {
123 apiKey,
124 mode: "plan",
125 model: cursorSdkModelSelection(modelSelection, getModels?.() ?? []),
126 local: {
127 cwd,
128 store,
129 autoReview: false,
130 sandboxOptions: { enabled: true },
131 settingSources: [],
132 enableAgentRetries: true,
133 },
134 } satisfies AgentOptions;
135 const createCursorAgent = (sandboxEnabled: boolean) =>
136 Effect.tryPromise({
137 try: (signal) =>
138 Agent.create(
139 sandboxEnabled
140 ? agentOptions
141 : {
142 ...agentOptions,
143 local: {
144 ...agentOptions.local,
145 sandboxOptions: { enabled: false },
146 },
147 },
148 ).then((agent) => {
149 if (signal.aborted) agent.close();
150 return agent;
151 }),
152 catch: sdkFailure("Cursor SDK agent could not be created."),
153 });
154
155 const runPrompt = Effect.fn("CursorTextGeneration.runPrompt")(function* (
156 sandboxEnabled: boolean,
157 ) {
158 const agent = yield* Effect.acquireRelease(
159 createCursorAgent(sandboxEnabled),
160 (agent) =>
161 Effect.tryPromise({
162 try: () => agent[Symbol.asyncDispose](),
163 catch: sdkFailure("Cursor SDK agent could not be disposed."),
164 }).pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true })),
165 { interruptible: true },
166 );
167 const run = yield* Effect.tryPromise({
168 try: (signal) =>
169 agent.send(prompt).then((run) => {
170 if (signal.aborted) void run.cancel().catch(() => undefined);
171 return run;
172 }),
173 catch: sdkFailure("Cursor SDK request could not be sent."),
174 });
175 yield* Effect.addFinalizer(() =>
176 run.status === "running"
177 ? Effect.tryPromise({
178 try: () => run.cancel(),
179 catch: sdkFailure("Cursor SDK run could not be cancelled."),
180 }).pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true }))
181 : Effect.void,
182 );
183 return yield* Effect.tryPromise({
184 try: () => run.wait(),
185 catch: sdkFailure("Cursor SDK run failed."),
186 });
187 }, Effect.scoped);
188 // The SDK may reject sandboxing in create or lazily in send. Empty cwd and setting
189 // sources isolate the unsandboxed retry from user projects.
190 const request = runPrompt(true).pipe(
191 Effect.catchIf(cursorSandboxUnsupported, () => runPrompt(false)),
192 );
193 const promptResult = yield* request.pipe(
194 Effect.timeoutOption(CURSOR_TIMEOUT_MS),
195 Effect.flatMap(
196 Option.match({
197 onNone: () =>
198 Effect.fail(
199 new TextGenerationError({
200 operation,
201 detail: "Cursor SDK request timed out.",
202 }),
203 ),
204 onSome: (value) => Effect.succeed(value),
205 }),
206 ),
207 );
208
209 const rawResult = promptResult.result?.trim() ?? "";
210 if (promptResult.status !== "finished" || !rawResult) {
211 return yield* new TextGenerationError({
212 operation,
213 detail: cursorSdkResultDetail(promptResult),
214 ...(promptResult.error ? { cause: promptResult.error } : {}),
215 });
216 }
217
218 return yield* TextGenerationOperations.decodeJsonReply(input, "Cursor SDK", rawResult);
219 },
220 (effect, input) => {
221 const { operation } = input;
222 return effect.pipe(
223 Effect.scoped,
224 (effect) => (withAccess ? withAccess(effect) : effect),
225 Effect.scoped,
226 Effect.mapError((cause) =>
227 isTextGenerationError(cause)
228 ? cause
229 : new TextGenerationError({
230 operation,
231 detail: "Cursor SDK text generation failed.",
232 cause,
233 }),
234 ),
235 );
236 },
237 );
238
239 return TextGenerationOperations.fromRunner(
240 "CursorTextGeneration",
241 TextGenerationOperations.withoutInvestigation("Cursor", runCursorJson),
242 );
243});