Open History to see the last commit
1import * as NodeOS from "node:os";
2import * as FileSystem from "effect/FileSystem";
3
4import type { AgentOptions, RunResult } from "@cursor/sdk";
5import { Agent } from "../provider/cursorSdk.ts";
6import * as Effect from "effect/Effect";
7import * as Option from "effect/Option";
8import * as Schema from "effect/Schema";
9
10import {
11 type CursorSettings,
12 type ModelSelection,
13 type ProviderSetupError,
14} from "@t3tools/contracts";
15import { formatGeneratedBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
16import { extractJsonObject } from "@t3tools/shared/schemaJson";
17
18import { TextGenerationError } from "@t3tools/contracts";
19import * as TextGeneration from "./TextGeneration.ts";
20import {
21 buildBranchNamePrompt,
22 buildCommitMessagePrompt,
23 buildPrContentPrompt,
24 buildThreadTitlePrompt,
25} from "./TextGenerationPrompts.ts";
26import {
27 sanitizeCommitSubject,
28 sanitizePrTitle,
29 sanitizeThreadTitle,
30} from "./TextGenerationUtils.ts";
31import { cursorSdkModelSelection } from "../provider/cursorSdkModel.ts";
32import type { CursorAuth } from "../provider/CursorAuth.ts";
33
34const CURSOR_TIMEOUT_MS = 180_000;
35
36const isTextGenerationError = Schema.is(TextGenerationError);
37type CursorTextGenerationOperation =
38 | "generateCommitMessage"
39 | "generatePrContent"
40 | "generateBranchName"
41 | "generateThreadTitle";
42
43function cursorSdkResultDetail(result: RunResult): string {
44 switch (result.status) {
45 case "cancelled":
46 return "Cursor SDK request was cancelled.";
47 case "error":
48 return "Cursor SDK request finished with an error.";
49 case "finished":
50 return "Cursor SDK returned empty output.";
51 }
52}
53
54/**
55 * The SDK throws this when `sandboxOptions.enabled` is set and local sandboxing
56 * is unavailable. That happens on hosts that cannot launch `cursorsandbox`, and
57 * also after an unsandboxed run caches "unsupported" for the process.
58 */
59function cursorSandboxUnsupported(cause: unknown): boolean {
60 const seen = new Set<object>();
61 let current = cause;
62 while (typeof current === "object" && current !== null && !seen.has(current)) {
63 seen.add(current);
64 if (current instanceof Error && current.message.includes("sandboxing is not supported")) {
65 return true;
66 }
67 current = Reflect.get(current, "cause");
68 }
69 return false;
70}
71
72/**
73 * Build a Cursor text-generation closure bound to a specific `CursorSettings`
74 * payload. See `makeCodexAdapter` for the overall per-instance rationale.
75 */
76export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(function* (
77 cursorSettings: CursorSettings,
78 environment?: NodeJS.ProcessEnv,
79 resolveApiKey?: Effect.Effect<string, ProviderSetupError>,
80 withAccess?: CursorAuth["withAccess"],
81) {
82 const fs = yield* FileSystem.FileSystem;
83 const resolvedEnvironment = environment ?? process.env;
84
85 const resolveCursorApiKey = (operation: CursorTextGenerationOperation) =>
86 Effect.gen(function* () {
87 if (!cursorSettings.enabled) {
88 return yield* new TextGenerationError({
89 operation,
90 detail: "Cursor is disabled in T3 Code settings.",
91 });
92 }
93
94 const apiKey = resolveApiKey
95 ? yield* resolveApiKey
96 : resolvedEnvironment.CURSOR_API_KEY?.trim();
97 if (!apiKey) {
98 return yield* new TextGenerationError({
99 operation,
100 detail: "Sign in with Cursor or add CURSOR_API_KEY in provider settings.",
101 });
102 }
103
104 return apiKey;
105 });
106
107 const runCursorJson = <S extends Schema.Top>({
108 operation,
109 prompt,
110 outputSchemaJson,
111 modelSelection,
112 }: {
113 operation: CursorTextGenerationOperation;
114 prompt: string;
115 outputSchemaJson: S;
116 modelSelection: ModelSelection;
117 }): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
118 Effect.gen(function* () {
119 const apiKey = yield* resolveCursorApiKey(operation);
120 // The SDK loads sandbox.json independently of settingSources and lets it
121 // expand the writable paths. Its public API cannot override that policy.
122 if (yield* fs.exists(`${NodeOS.homedir()}/.cursor/sandbox.json`)) {
123 return yield* new TextGenerationError({
124 operation,
125 detail:
126 "Cursor text generation cannot enforce workspace isolation with a custom ~/.cursor/sandbox.json. Use another text-generation provider.",
127 });
128 }
129 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-text-" });
130 const agentOptions = {
131 apiKey,
132 mode: "plan",
133 model: cursorSdkModelSelection(modelSelection),
134 local: {
135 cwd,
136 autoReview: false,
137 sandboxOptions: { enabled: true },
138 settingSources: [],
139 enableAgentRetries: true,
140 },
141 } satisfies AgentOptions;
142 const createCursorAgent = (sandboxEnabled: boolean) =>
143 Effect.tryPromise((signal) =>
144 Agent.create(
145 sandboxEnabled
146 ? agentOptions
147 : {
148 ...agentOptions,
149 local: {
150 ...agentOptions.local,
151 sandboxOptions: { enabled: false },
152 },
153 },
154 ).then((agent) => {
155 if (signal.aborted) agent.close();
156 return agent;
157 }),
158 );
159
160 const request = Effect.gen(function* () {
161 // Prefer the sandbox. When the SDK refuses it, the empty temp directory
162 // and empty setting sources still keep this run off the user's project.
163 const agent = yield* Effect.acquireRelease(
164 createCursorAgent(true).pipe(
165 Effect.catchIf(cursorSandboxUnsupported, () => createCursorAgent(false)),
166 ),
167 (agent) =>
168 Effect.tryPromise(() => agent[Symbol.asyncDispose]()).pipe(
169 Effect.timeout("5 seconds"),
170 Effect.ignore({ log: true }),
171 ),
172 { interruptible: true },
173 );
174 const run = yield* Effect.tryPromise((signal) =>
175 agent.send(prompt).then((run) => {
176 if (signal.aborted) void run.cancel().catch(() => undefined);
177 return run;
178 }),
179 );
180 yield* Effect.addFinalizer(() =>
181 run.status === "running"
182 ? Effect.tryPromise(() => run.cancel()).pipe(
183 Effect.timeout("5 seconds"),
184 Effect.ignore({ log: true }),
185 )
186 : Effect.void,
187 );
188 return yield* Effect.tryPromise(() => run.wait());
189 }).pipe(Effect.scoped);
190 const promptResult = yield* request.pipe(
191 Effect.timeoutOption(CURSOR_TIMEOUT_MS),
192 Effect.flatMap(
193 Option.match({
194 onNone: () =>
195 Effect.fail(
196 new TextGenerationError({
197 operation,
198 detail: "Cursor SDK request timed out.",
199 }),
200 ),
201 onSome: (value) => Effect.succeed(value),
202 }),
203 ),
204 );
205
206 const rawResult = promptResult.result?.trim() ?? "";
207 if (promptResult.status !== "finished" || !rawResult) {
208 return yield* new TextGenerationError({
209 operation,
210 detail: cursorSdkResultDetail(promptResult),
211 });
212 }
213
214 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
215 return yield* decodeOutput(extractJsonObject(rawResult)).pipe(
216 Effect.catchTags({
217 SchemaError: (cause) =>
218 Effect.fail(
219 new TextGenerationError({
220 operation,
221 detail: "Cursor SDK returned invalid structured output.",
222 cause,
223 }),
224 ),
225 }),
226 );
227 }).pipe(
228 (effect) => (withAccess ? withAccess(effect) : effect),
229 Effect.scoped,
230 Effect.mapError((cause) =>
231 isTextGenerationError(cause)
232 ? cause
233 : new TextGenerationError({
234 operation,
235 detail: "Cursor SDK text generation failed.",
236 cause,
237 }),
238 ),
239 );
240
241 const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
242 Effect.fn("CursorTextGeneration.generateCommitMessage")(function* (input) {
243 const { prompt, outputSchema } = buildCommitMessagePrompt({
244 branch: input.branch,
245 stagedSummary: input.stagedSummary,
246 stagedPatch: input.stagedPatch,
247 includeBranch: input.includeBranch === true,
248 policy: input.policy,
249 });
250
251 const generated = yield* runCursorJson({
252 operation: "generateCommitMessage",
253 prompt,
254 outputSchemaJson: outputSchema,
255 modelSelection: input.modelSelection,
256 });
257
258 return {
259 subject: sanitizeCommitSubject(generated.subject),
260 body: generated.body.trim(),
261 ...("branch" in generated && typeof generated.branch === "string"
262 ? { branch: sanitizeFeatureBranchName(generated.branch) }
263 : {}),
264 };
265 });
266
267 const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
268 Effect.fn("CursorTextGeneration.generatePrContent")(function* (input) {
269 const { prompt, outputSchema } = buildPrContentPrompt({
270 baseBranch: input.baseBranch,
271 headBranch: input.headBranch,
272 commitSummary: input.commitSummary,
273 diffSummary: input.diffSummary,
274 diffPatch: input.diffPatch,
275 policy: input.policy,
276 changeRequestTemplate: input.changeRequestTemplate,
277 });
278
279 const generated = yield* runCursorJson({
280 operation: "generatePrContent",
281 prompt,
282 outputSchemaJson: outputSchema,
283 modelSelection: input.modelSelection,
284 });
285
286 return {
287 title: sanitizePrTitle(generated.title),
288 body: generated.body.trim(),
289 };
290 });
291
292 const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
293 Effect.fn("CursorTextGeneration.generateBranchName")(function* (input) {
294 const { prompt, outputSchema } = buildBranchNamePrompt({
295 message: input.message,
296 attachments: input.attachments,
297 naming: input.naming,
298 });
299
300 const generated = yield* runCursorJson({
301 operation: "generateBranchName",
302 prompt,
303 outputSchemaJson: outputSchema,
304 modelSelection: input.modelSelection,
305 });
306
307 return {
308 branch: formatGeneratedBranchName(generated.branch, input.naming),
309 };
310 });
311
312 const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
313 Effect.fn("CursorTextGeneration.generateThreadTitle")(function* (input) {
314 const { prompt, outputSchema } = buildThreadTitlePrompt({
315 message: input.message,
316 previousTitle: input.previousTitle,
317 linkedContext: input.linkedContext,
318 attachments: input.attachments,
319 });
320
321 const generated = yield* runCursorJson({
322 operation: "generateThreadTitle",
323 prompt,
324 outputSchemaJson: outputSchema,
325 modelSelection: input.modelSelection,
326 });
327
328 return {
329 title: sanitizeThreadTitle(generated.title),
330 ...(generated.needsRefinement ? { needsRefinement: true } : {}),
331 } satisfies TextGeneration.ThreadTitleGenerationResult;
332 });
333
334 return {
335 generateCommitMessage,
336 generatePrContent,
337 generateBranchName,
338 generateThreadTitle,
339 } satisfies TextGeneration.TextGeneration["Service"];
340});