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