Open History to see the last commit
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";
6import type * as EffectAcpErrors from "effect-acp/errors";
7
8import { type GrokSettings, 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 { type ThreadTitleGenerationResult, type TextGenerationShape } 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 applyGrokAcpModelSelection,
27 currentGrokModelIdFromSessionSetup,
28 makeGrokAcpRuntime,
29 resolveGrokAcpBaseModelId,
30} from "../provider/acp/GrokAcpSupport.ts";
31
32const GROK_TIMEOUT_MS = 180_000;
33
34function mapGrokAcpError(
35 operation:
36 | "generateCommitMessage"
37 | "generatePrContent"
38 | "generateBranchName"
39 | "generateThreadTitle",
40 detail: string,
41 cause: unknown,
42): TextGenerationError {
43 return new TextGenerationError({
44 operation,
45 detail,
46 ...(cause !== undefined ? { cause } : {}),
47 });
48}
49
50function isTextGenerationError(error: unknown): error is TextGenerationError {
51 return (
52 typeof error === "object" &&
53 error !== null &&
54 "_tag" in error &&
55 error._tag === "TextGenerationError"
56 );
57}
58
59export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(function* (
60 grokSettings: GrokSettings,
61 environment: NodeJS.ProcessEnv = process.env,
62) {
63 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
64
65 const runGrokJson = <S extends Schema.Top>({
66 operation,
67 cwd,
68 prompt,
69 outputSchemaJson,
70 modelSelection,
71 }: {
72 operation:
73 | "generateCommitMessage"
74 | "generatePrContent"
75 | "generateBranchName"
76 | "generateThreadTitle";
77 cwd: string;
78 prompt: string;
79 outputSchemaJson: S;
80 modelSelection: ModelSelection;
81 }): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
82 Effect.gen(function* () {
83 const resolvedModel = resolveGrokAcpBaseModelId(modelSelection.model);
84 const outputRef = yield* Ref.make("");
85 const runtime = yield* makeGrokAcpRuntime({
86 grokSettings,
87 environment,
88 childProcessSpawner: commandSpawner,
89 cwd,
90 clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
91 });
92
93 yield* runtime.handleSessionUpdate((notification) => {
94 const update = notification.update;
95 if (update.sessionUpdate !== "agent_message_chunk") {
96 return Effect.void;
97 }
98 const content = update.content;
99 if (content.type !== "text") {
100 return Effect.void;
101 }
102 return Ref.update(outputRef, (current) => current + content.text);
103 });
104
105 const promptResult = yield* Effect.gen(function* () {
106 const started = yield* runtime.start();
107 yield* applyGrokAcpModelSelection({
108 runtime,
109 currentModelId: currentGrokModelIdFromSessionSetup(started.sessionSetupResult),
110 requestedModelId: resolvedModel,
111 mapError: (cause) =>
112 mapGrokAcpError(
113 operation,
114 "Failed to set Grok ACP base model for text generation.",
115 cause,
116 ),
117 });
118
119 return yield* runtime.prompt({
120 prompt: [{ type: "text", text: prompt }],
121 });
122 }).pipe(
123 Effect.timeoutOption(GROK_TIMEOUT_MS),
124 Effect.flatMap(
125 Option.match({
126 onNone: () =>
127 Effect.fail(
128 new TextGenerationError({ operation, detail: "Grok ACP request timed out." }),
129 ),
130 onSome: (value) => Effect.succeed(value),
131 }),
132 ),
133 Effect.mapError((cause: EffectAcpErrors.AcpError | TextGenerationError) =>
134 isTextGenerationError(cause)
135 ? cause
136 : mapGrokAcpError(operation, "Grok ACP request failed.", cause),
137 ),
138 );
139
140 const trimmed = (yield* Ref.get(outputRef)).trim();
141 if (!trimmed) {
142 return yield* new TextGenerationError({
143 operation,
144 detail:
145 promptResult.stopReason === "cancelled"
146 ? "Grok ACP request was cancelled."
147 : "Grok Agent returned empty output.",
148 });
149 }
150
151 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
152 return yield* decodeOutput(extractJsonObject(trimmed)).pipe(
153 Effect.catchTag("SchemaError", (cause) =>
154 Effect.fail(
155 new TextGenerationError({
156 operation,
157 detail: "Grok Agent returned invalid structured output.",
158 cause,
159 }),
160 ),
161 ),
162 );
163 }).pipe(
164 Effect.mapError((cause) =>
165 isTextGenerationError(cause)
166 ? cause
167 : mapGrokAcpError(operation, "Grok ACP text generation failed.", cause),
168 ),
169 Effect.scoped,
170 );
171
172 const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
173 "GrokTextGeneration.generateCommitMessage",
174 )(function* (input) {
175 const { prompt, outputSchema } = buildCommitMessagePrompt({
176 branch: input.branch,
177 stagedSummary: input.stagedSummary,
178 stagedPatch: input.stagedPatch,
179 includeBranch: input.includeBranch === true,
180 });
181
182 const generated = yield* runGrokJson({
183 operation: "generateCommitMessage",
184 cwd: input.cwd,
185 prompt,
186 outputSchemaJson: outputSchema,
187 modelSelection: input.modelSelection,
188 });
189
190 return {
191 subject: sanitizeCommitSubject(generated.subject),
192 body: generated.body.trim(),
193 ...("branch" in generated && typeof generated.branch === "string"
194 ? { branch: sanitizeFeatureBranchName(generated.branch) }
195 : {}),
196 };
197 });
198
199 const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
200 "GrokTextGeneration.generatePrContent",
201 )(function* (input) {
202 const { prompt, outputSchema } = buildPrContentPrompt({
203 baseBranch: input.baseBranch,
204 headBranch: input.headBranch,
205 commitSummary: input.commitSummary,
206 diffSummary: input.diffSummary,
207 diffPatch: input.diffPatch,
208 });
209
210 const generated = yield* runGrokJson({
211 operation: "generatePrContent",
212 cwd: input.cwd,
213 prompt,
214 outputSchemaJson: outputSchema,
215 modelSelection: input.modelSelection,
216 });
217
218 return {
219 title: sanitizePrTitle(generated.title),
220 body: generated.body.trim(),
221 };
222 });
223
224 const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
225 "GrokTextGeneration.generateBranchName",
226 )(function* (input) {
227 const { prompt, outputSchema } = buildBranchNamePrompt({
228 message: input.message,
229 attachments: input.attachments,
230 });
231
232 const generated = yield* runGrokJson({
233 operation: "generateBranchName",
234 cwd: input.cwd,
235 prompt,
236 outputSchemaJson: outputSchema,
237 modelSelection: input.modelSelection,
238 });
239
240 return {
241 branch: sanitizeBranchFragment(generated.branch),
242 };
243 });
244
245 const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
246 "GrokTextGeneration.generateThreadTitle",
247 )(function* (input) {
248 const { prompt, outputSchema } = buildThreadTitlePrompt({
249 message: input.message,
250 attachments: input.attachments,
251 });
252
253 const generated = yield* runGrokJson({
254 operation: "generateThreadTitle",
255 cwd: input.cwd,
256 prompt,
257 outputSchemaJson: outputSchema,
258 modelSelection: input.modelSelection,
259 });
260
261 return {
262 title: sanitizeThreadTitle(generated.title),
263 } satisfies ThreadTitleGenerationResult;
264 });
265
266 return {
267 generateCommitMessage,
268 generatePrContent,
269 generateBranchName,
270 generateThreadTitle,
271 } satisfies TextGenerationShape;
272});