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 { Agent, SqliteLocalAgentStore } = 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 // sandbox.json expands writable paths independently of settingSources; the public API cannot override it.
87 if (yield* fs.exists(`${yield* HostProcess.HomeDirectory}/.cursor/sandbox.json`)) {
88 return yield* new TextGenerationError({
89 operation,
90 detail:
91 "Cursor text generation cannot enforce workspace isolation with a custom ~/.cursor/sandbox.json. Use another text-generation provider.",
92 });
93 }
94 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-text-" });
95 // Only store disposal releases SDK SQLite handles; keep state outside the empty workspace.
96 const stateRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-text-state-" });
97 const store = yield* Effect.acquireRelease(
98 Effect.tryPromise(() => SqliteLocalAgentStore.open({ workspaceRef: cwd, stateRoot })),
99 (store) => Effect.tryPromise(() => store.dispose()).pipe(Effect.ignore({ log: true })),
100 );
101 const agentOptions = {
102 apiKey,
103 mode: "plan",
104 model: cursorSdkModelSelection(modelSelection),
105 local: {
106 cwd,
107 store,
108 autoReview: false,
109 sandboxOptions: { enabled: true },
110 settingSources: [],
111 enableAgentRetries: true,
112 },
113 } satisfies AgentOptions;
114 const createCursorAgent = (sandboxEnabled: boolean) =>
115 Effect.tryPromise((signal) =>
116 Agent.create(
117 sandboxEnabled
118 ? agentOptions
119 : {
120 ...agentOptions,
121 local: {
122 ...agentOptions.local,
123 sandboxOptions: { enabled: false },
124 },
125 },
126 ).then((agent) => {
127 if (signal.aborted) agent.close();
128 return agent;
129 }),
130 );
131
132 const request = Effect.gen(function* () {
133 // Empty cwd and setting sources isolate the run from user projects even if sandboxing fails.
134 const agent = yield* Effect.acquireRelease(
135 createCursorAgent(true).pipe(
136 Effect.catchIf(cursorSandboxUnsupported, () => createCursorAgent(false)),
137 ),
138 (agent) =>
139 Effect.tryPromise(() => agent[Symbol.asyncDispose]()).pipe(
140 Effect.timeout("5 seconds"),
141 Effect.ignore({ log: true }),
142 ),
143 { interruptible: true },
144 );
145 const run = yield* Effect.tryPromise((signal) =>
146 agent.send(prompt).then((run) => {
147 if (signal.aborted) void run.cancel().catch(() => undefined);
148 return run;
149 }),
150 );
151 yield* Effect.addFinalizer(() =>
152 run.status === "running"
153 ? Effect.tryPromise(() => run.cancel()).pipe(
154 Effect.timeout("5 seconds"),
155 Effect.ignore({ log: true }),
156 )
157 : Effect.void,
158 );
159 return yield* Effect.tryPromise(() => run.wait());
160 }).pipe(Effect.scoped);
161 const promptResult = yield* request.pipe(
162 Effect.timeoutOption(CURSOR_TIMEOUT_MS),
163 Effect.flatMap(
164 Option.match({
165 onNone: () =>
166 Effect.fail(
167 new TextGenerationError({
168 operation,
169 detail: "Cursor SDK request timed out.",
170 }),
171 ),
172 onSome: (value) => Effect.succeed(value),
173 }),
174 ),
175 );
176
177 const rawResult = promptResult.result?.trim() ?? "";
178 if (promptResult.status !== "finished" || !rawResult) {
179 return yield* new TextGenerationError({
180 operation,
181 detail: cursorSdkResultDetail(promptResult),
182 });
183 }
184
185 return yield* TextGenerationOperations.decodeJsonReply(input, "Cursor SDK", rawResult);
186 },
187 (effect, input) => {
188 const { operation } = input;
189 return effect.pipe(
190 Effect.scoped,
191 (effect) => (withAccess ? withAccess(effect) : effect),
192 Effect.scoped,
193 Effect.mapError((cause) =>
194 isTextGenerationError(cause)
195 ? cause
196 : new TextGenerationError({
197 operation,
198 detail: "Cursor SDK text generation failed.",
199 cause,
200 }),
201 ),
202 );
203 },
204 );
205
206 return TextGenerationOperations.fromRunner(
207 "CursorTextGeneration",
208 TextGenerationOperations.withoutInvestigation("Cursor", runCursorJson),
209 );
210});