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

GrokTextGeneration.ts

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