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

GrokTextGeneration.ts

271 lines8.9 KB

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 outputRef = yield* Ref.make("");
65 const runtime = yield* makeGrokAcpRuntime({
66 grokSettings,
67 environment,
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 const resolvedModel = resolveGrokAcpBaseModelId(modelSelection.model);
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 return yield* runtime.prompt({
108 prompt: [{ type: "text", text: prompt }],
109 });
110 }).pipe(
111 Effect.timeoutOption(GROK_TIMEOUT_MS),
112 Effect.flatMap(
113 Option.match({
114 onNone: () =>
115 Effect.fail(
116 new TextGenerationError({ operation, detail: "Grok ACP request timed out." }),
117 ),
118 onSome: (value) => Effect.succeed(value),
119 }),
120 ),
121 Effect.mapError((cause: EffectAcpErrors.AcpError | TextGenerationError) =>
122 isTextGenerationError(cause)
123 ? cause
124 : new TextGenerationError({
125 operation,
126 detail: "Grok ACP request failed.",
127 cause,
128 }),
129 ),
130 );
131​
132 const trimmed = (yield* Ref.get(outputRef)).trim();
133 if (!trimmed) {
134 return yield* new TextGenerationError({
135 operation,
136 detail:
137 promptResult.stopReason === "cancelled"
138 ? "Grok ACP request was cancelled."
139 : "Grok Agent returned empty output.",
140 });
141 }
142​
143 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
144 return yield* decodeOutput(extractJsonObject(trimmed)).pipe(
145 Effect.catchTags({
146 SchemaError: (cause) =>
147 Effect.fail(
148 new TextGenerationError({
149 operation,
150 detail: "Grok Agent returned invalid structured output.",
151 cause,
152 }),
153 ),
154 }),
155 );
156 }).pipe(
157 Effect.mapError((cause) =>
158 isTextGenerationError(cause)
159 ? cause
160 : new TextGenerationError({
161 operation,
162 detail: "Grok ACP text generation failed.",
163 cause,
164 }),
165 ),
166 Effect.scoped,
167 );
168​
169 const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
170 Effect.fn("GrokTextGeneration.generateCommitMessage")(function* (input) {
171 const { prompt, outputSchema } = buildCommitMessagePrompt({
172 branch: input.branch,
173 stagedSummary: input.stagedSummary,
174 stagedPatch: input.stagedPatch,
175 includeBranch: input.includeBranch === true,
176 policy: input.policy,
177 });
178​
179 const generated = yield* runGrokJson({
180 operation: "generateCommitMessage",
181 cwd: input.cwd,
182 prompt,
183 outputSchemaJson: outputSchema,
184 modelSelection: input.modelSelection,
185 });
186​
187 return {
188 subject: sanitizeCommitSubject(generated.subject),
189 body: generated.body.trim(),
190 ...("branch" in generated && typeof generated.branch === "string"
191 ? { branch: sanitizeFeatureBranchName(generated.branch) }
192 : {}),
193 };
194 });
195​
196 const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
197 Effect.fn("GrokTextGeneration.generatePrContent")(function* (input) {
198 const { prompt, outputSchema } = buildPrContentPrompt({
199 baseBranch: input.baseBranch,
200 headBranch: input.headBranch,
201 commitSummary: input.commitSummary,
202 diffSummary: input.diffSummary,
203 diffPatch: input.diffPatch,
204 policy: input.policy,
205 changeRequestTemplate: input.changeRequestTemplate,
206 });
207​
208 const generated = yield* runGrokJson({
209 operation: "generatePrContent",
210 cwd: input.cwd,
211 prompt,
212 outputSchemaJson: outputSchema,
213 modelSelection: input.modelSelection,
214 });
215​
216 return {
217 title: sanitizePrTitle(generated.title),
218 body: generated.body.trim(),
219 };
220 });
221​
222 const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
223 Effect.fn("GrokTextGeneration.generateBranchName")(function* (input) {
224 const { prompt, outputSchema } = buildBranchNamePrompt({
225 message: input.message,
226 attachments: input.attachments,
227 });
228​
229 const generated = yield* runGrokJson({
230 operation: "generateBranchName",
231 cwd: input.cwd,
232 prompt,
233 outputSchemaJson: outputSchema,
234 modelSelection: input.modelSelection,
235 });
236​
237 return {
238 branch: sanitizeBranchFragment(generated.branch),
239 };
240 });
241​
242 const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
243 Effect.fn("GrokTextGeneration.generateThreadTitle")(function* (input) {
244 const { prompt, outputSchema } = buildThreadTitlePrompt({
245 message: input.message,
246 previousTitle: input.previousTitle,
247 linkedContext: input.linkedContext,
248 attachments: input.attachments,
249 });
250​
251 const generated = yield* runGrokJson({
252 operation: "generateThreadTitle",
253 cwd: input.cwd,
254 prompt,
255 outputSchemaJson: outputSchema,
256 modelSelection: input.modelSelection,
257 });
258​
259 return {
260 title: sanitizeThreadTitle(generated.title),
261 ...(generated.needsRefinement ? { needsRefinement: true } : {}),
262 } satisfies TextGeneration.ThreadTitleGenerationResult;
263 });
264​
265 return {
266 generateCommitMessage,
267 generatePrContent,
268 generateBranchName,
269 generateThreadTitle,
270 } satisfies TextGeneration.TextGeneration["Service"];
271});