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