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