Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CursorTextGeneration.ts

262 lines8.3 KB

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