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

GrokTextGeneration.ts

254 lines8.0 KB

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