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