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