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