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

GrokTextGeneration.ts

256 lines8.2 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 });
168​
169 const generated = yield* runGrokJson({
170 operation: "generateCommitMessage",
171 cwd: input.cwd,
172 prompt,
173 outputSchemaJson: outputSchema,
174 modelSelection: input.modelSelection,
175 });
176​
177 return {
178 subject: sanitizeCommitSubject(generated.subject),
179 body: generated.body.trim(),
180 ...("branch" in generated && typeof generated.branch === "string"
181 ? { branch: sanitizeFeatureBranchName(generated.branch) }
182 : {}),
183 };
184 });
185​
186 const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
187 Effect.fn("GrokTextGeneration.generatePrContent")(function* (input) {
188 const { prompt, outputSchema } = buildPrContentPrompt({
189 baseBranch: input.baseBranch,
190 headBranch: input.headBranch,
191 commitSummary: input.commitSummary,
192 diffSummary: input.diffSummary,
193 diffPatch: input.diffPatch,
194 });
195​
196 const generated = yield* runGrokJson({
197 operation: "generatePrContent",
198 cwd: input.cwd,
199 prompt,
200 outputSchemaJson: outputSchema,
201 modelSelection: input.modelSelection,
202 });
203​
204 return {
205 title: sanitizePrTitle(generated.title),
206 body: generated.body.trim(),
207 };
208 });
209​
210 const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
211 Effect.fn("GrokTextGeneration.generateBranchName")(function* (input) {
212 const { prompt, outputSchema } = buildBranchNamePrompt({
213 message: input.message,
214 attachments: input.attachments,
215 });
216​
217 const generated = yield* runGrokJson({
218 operation: "generateBranchName",
219 cwd: input.cwd,
220 prompt,
221 outputSchemaJson: outputSchema,
222 modelSelection: input.modelSelection,
223 });
224​
225 return {
226 branch: sanitizeBranchFragment(generated.branch),
227 };
228 });
229​
230 const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
231 Effect.fn("GrokTextGeneration.generateThreadTitle")(function* (input) {
232 const { prompt, outputSchema } = buildThreadTitlePrompt({
233 message: input.message,
234 attachments: input.attachments,
235 });
236​
237 const generated = yield* runGrokJson({
238 operation: "generateThreadTitle",
239 cwd: input.cwd,
240 prompt,
241 outputSchemaJson: outputSchema,
242 modelSelection: input.modelSelection,
243 });
244​
245 return {
246 title: sanitizeThreadTitle(generated.title),
247 } satisfies TextGeneration.ThreadTitleGenerationResult;
248 });
249​
250 return {
251 generateCommitMessage,
252 generatePrContent,
253 generateBranchName,
254 generateThreadTitle,
255 } satisfies TextGeneration.TextGeneration["Service"];
256});