Open History to see the last commit
1import { Agent, type AgentOptions, type RunResult } from "@cursor/sdk";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import * as Schema from "effect/Schema";
5
6import { type CursorSettings, type ModelSelection } from "@t3tools/contracts";
7import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
8import { extractJsonObject } from "@t3tools/shared/schemaJson";
9
10import { TextGenerationError } from "@t3tools/contracts";
11import * as TextGeneration from "./TextGeneration.ts";
12import {
13 buildBranchNamePrompt,
14 buildCommitMessagePrompt,
15 buildPrContentPrompt,
16 buildThreadTitlePrompt,
17} from "./TextGenerationPrompts.ts";
18import {
19 sanitizeCommitSubject,
20 sanitizePrTitle,
21 sanitizeThreadTitle,
22} from "./TextGenerationUtils.ts";
23import { cursorSdkModelSelection } from "../provider/cursorSdkModel.ts";
24
25const CURSOR_TIMEOUT_MS = 180_000;
26
27const isTextGenerationError = Schema.is(TextGenerationError);
28type CursorTextGenerationOperation =
29 | "generateCommitMessage"
30 | "generatePrContent"
31 | "generateBranchName"
32 | "generateThreadTitle";
33
34function emptyCursorSdkResultDetail(result: RunResult): string {
35 switch (result.status) {
36 case "cancelled":
37 return "Cursor SDK request was cancelled.";
38 case "error":
39 return "Cursor SDK request finished with an error and no output.";
40 case "finished":
41 return "Cursor SDK returned empty output.";
42 }
43}
44
45/**
46 * Build a Cursor text-generation closure bound to a specific `CursorSettings`
47 * payload. See `makeCodexAdapter` for the overall per-instance rationale.
48 */
49export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")((
50 cursorSettings: CursorSettings,
51 environment?: NodeJS.ProcessEnv,
52) => {
53 const resolvedEnvironment = environment ?? process.env;
54
55 const resolveCursorApiKey = (operation: CursorTextGenerationOperation) =>
56 Effect.gen(function* () {
57 if (!cursorSettings.enabled) {
58 return yield* new TextGenerationError({
59 operation,
60 detail: "Cursor is disabled in T3 Code settings.",
61 });
62 }
63
64 const apiKey = resolvedEnvironment.CURSOR_API_KEY?.trim();
65 if (!apiKey) {
66 return yield* new TextGenerationError({
67 operation,
68 detail: "Cursor API key is required. Add CURSOR_API_KEY in provider settings.",
69 });
70 }
71
72 return apiKey;
73 });
74
75 const runCursorJson = <S extends Schema.Top>({
76 operation,
77 cwd,
78 prompt,
79 outputSchemaJson,
80 modelSelection,
81 }: {
82 operation: CursorTextGenerationOperation;
83 cwd: string;
84 prompt: string;
85 outputSchemaJson: S;
86 modelSelection: ModelSelection;
87 }): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
88 Effect.gen(function* () {
89 const apiKey = yield* resolveCursorApiKey(operation);
90 const agentOptions = {
91 apiKey,
92 mode: "agent",
93 model: cursorSdkModelSelection(modelSelection),
94 local: {
95 cwd,
96 autoReview: false,
97 sandboxOptions: { enabled: false },
98 enableAgentRetries: true,
99 },
100 } satisfies AgentOptions;
101
102 const promptResult = yield* Effect.tryPromise({
103 try: () => Agent.prompt(prompt, agentOptions),
104 catch: (cause) =>
105 new TextGenerationError({
106 operation,
107 detail: "Cursor SDK request failed.",
108 cause,
109 }),
110 }).pipe(
111 Effect.timeoutOption(CURSOR_TIMEOUT_MS),
112 Effect.flatMap(
113 Option.match({
114 onNone: () =>
115 Effect.fail(
116 new TextGenerationError({
117 operation,
118 detail: "Cursor SDK request timed out.",
119 }),
120 ),
121 onSome: (value) => Effect.succeed(value),
122 }),
123 ),
124 );
125
126 const rawResult = promptResult.result?.trim() ?? "";
127 if (!rawResult) {
128 return yield* new TextGenerationError({
129 operation,
130 detail: emptyCursorSdkResultDetail(promptResult),
131 });
132 }
133
134 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
135 return yield* decodeOutput(extractJsonObject(rawResult)).pipe(
136 Effect.catchTags({
137 SchemaError: (cause) =>
138 Effect.fail(
139 new TextGenerationError({
140 operation,
141 detail: "Cursor SDK returned invalid structured output.",
142 cause,
143 }),
144 ),
145 }),
146 );
147 }).pipe(
148 Effect.mapError((cause) =>
149 isTextGenerationError(cause)
150 ? cause
151 : new TextGenerationError({
152 operation,
153 detail: "Cursor SDK text generation failed.",
154 cause,
155 }),
156 ),
157 );
158
159 const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
160 Effect.fn("CursorTextGeneration.generateCommitMessage")(function* (input) {
161 const { prompt, outputSchema } = buildCommitMessagePrompt({
162 branch: input.branch,
163 stagedSummary: input.stagedSummary,
164 stagedPatch: input.stagedPatch,
165 includeBranch: input.includeBranch === true,
166 });
167
168 const generated = yield* runCursorJson({
169 operation: "generateCommitMessage",
170 cwd: input.cwd,
171 prompt,
172 outputSchemaJson: outputSchema,
173 modelSelection: input.modelSelection,
174 });
175
176 return {
177 subject: sanitizeCommitSubject(generated.subject),
178 body: generated.body.trim(),
179 ...("branch" in generated && typeof generated.branch === "string"
180 ? { branch: sanitizeFeatureBranchName(generated.branch) }
181 : {}),
182 };
183 });
184
185 const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
186 Effect.fn("CursorTextGeneration.generatePrContent")(function* (input) {
187 const { prompt, outputSchema } = buildPrContentPrompt({
188 baseBranch: input.baseBranch,
189 headBranch: input.headBranch,
190 commitSummary: input.commitSummary,
191 diffSummary: input.diffSummary,
192 diffPatch: input.diffPatch,
193 });
194
195 const generated = yield* runCursorJson({
196 operation: "generatePrContent",
197 cwd: input.cwd,
198 prompt,
199 outputSchemaJson: outputSchema,
200 modelSelection: input.modelSelection,
201 });
202
203 return {
204 title: sanitizePrTitle(generated.title),
205 body: generated.body.trim(),
206 };
207 });
208
209 const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
210 Effect.fn("CursorTextGeneration.generateBranchName")(function* (input) {
211 const { prompt, outputSchema } = buildBranchNamePrompt({
212 message: input.message,
213 attachments: input.attachments,
214 });
215
216 const generated = yield* runCursorJson({
217 operation: "generateBranchName",
218 cwd: input.cwd,
219 prompt,
220 outputSchemaJson: outputSchema,
221 modelSelection: input.modelSelection,
222 });
223
224 return {
225 branch: sanitizeBranchFragment(generated.branch),
226 };
227 });
228
229 const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
230 Effect.fn("CursorTextGeneration.generateThreadTitle")(function* (input) {
231 const { prompt, outputSchema } = buildThreadTitlePrompt({
232 message: input.message,
233 attachments: input.attachments,
234 });
235
236 const generated = yield* runCursorJson({
237 operation: "generateThreadTitle",
238 cwd: input.cwd,
239 prompt,
240 outputSchemaJson: outputSchema,
241 modelSelection: input.modelSelection,
242 });
243
244 return {
245 title: sanitizeThreadTitle(generated.title),
246 } satisfies TextGeneration.ThreadTitleGenerationResult;
247 });
248
249 return Effect.succeed({
250 generateCommitMessage,
251 generatePrContent,
252 generateBranchName,
253 generateThreadTitle,
254 } satisfies TextGeneration.TextGeneration["Service"]);
255});