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

CodexTextGeneration.ts

408 lines12.5 KB

1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Option from "effect/Option";
4import * as Path from "effect/Path";
5import * as Schema from "effect/Schema";
6import * as Scope from "effect/Scope";
7import * as Stream from "effect/Stream";
8import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
9​
10import { type CodexSettings, type ModelSelection } from "@t3tools/contracts";
11import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
12​
13import { resolveAttachmentPath } from "../attachmentStore.ts";
14import { ServerConfig } from "../config.ts";
15import { expandHomePath } from "../pathExpansion.ts";
16import { TextGenerationError } from "@t3tools/contracts";
17import {
18 type BranchNameGenerationInput,
19 type ThreadTitleGenerationResult,
20 type TextGenerationShape,
21} from "./TextGeneration.ts";
22import {
23 buildBranchNamePrompt,
24 buildCommitMessagePrompt,
25 buildPrContentPrompt,
26 buildThreadTitlePrompt,
27} from "./TextGenerationPrompts.ts";
28import {
29 normalizeCliError,
30 sanitizeCommitSubject,
31 sanitizePrTitle,
32 sanitizeThreadTitle,
33 toJsonSchemaObject,
34} from "./TextGenerationUtils.ts";
35import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
36import { getCodexServiceTierOptionValue } from "../codexModelOptions.ts";
37​
38const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
39const CODEX_TIMEOUT_MS = 180_000;
40const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString);
41/**
42 * Build a Codex text-generation closure bound to a specific `CodexSettings`
43 * payload. See `makeCodexAdapter` for the overall per-instance rationale.
44 */
45export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(function* (
46 codexConfig: CodexSettings,
47 environment: NodeJS.ProcessEnv = process.env,
48) {
49 const fileSystem = yield* FileSystem.FileSystem;
50 const path = yield* Path.Path;
51 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
52 const serverConfig = yield* Effect.service(ServerConfig);
53​
54 type MaterializedImageAttachments = {
55 readonly imagePaths: ReadonlyArray<string>;
56 };
57​
58 const readStreamAsString = <E>(
59 operation: string,
60 stream: Stream.Stream<Uint8Array, E>,
61 ): Effect.Effect<string, TextGenerationError> =>
62 stream.pipe(
63 Stream.decodeText(),
64 Stream.runFold(
65 () => "",
66 (acc, chunk) => acc + chunk,
67 ),
68 Effect.mapError((cause) =>
69 normalizeCliError("codex", operation, cause, "Failed to collect process output"),
70 ),
71 );
72​
73 const writeTempFile = (
74 operation: string,
75 prefix: string,
76 content: string,
77 ): Effect.Effect<string, TextGenerationError, Scope.Scope> =>
78 fileSystem
79 .makeTempFileScoped({
80 prefix: `t3code-${prefix}-${process.pid}-`,
81 })
82 .pipe(
83 Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)),
84 Effect.mapError(
85 (cause) =>
86 new TextGenerationError({
87 operation,
88 detail: `Failed to write temp file`,
89 cause,
90 }),
91 ),
92 );
93​
94 const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
95 fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
96​
97 const encodeJsonForOperation = (
98 operation:
99 | "generateCommitMessage"
100 | "generatePrContent"
101 | "generateBranchName"
102 | "generateThreadTitle",
103 value: unknown,
104 ): Effect.Effect<string, TextGenerationError> =>
105 encodeJsonString(value).pipe(
106 Effect.mapError(
107 (cause) =>
108 new TextGenerationError({
109 operation,
110 detail: "Failed to encode structured output schema.",
111 cause,
112 }),
113 ),
114 );
115​
116 const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
117 _operation:
118 | "generateCommitMessage"
119 | "generatePrContent"
120 | "generateBranchName"
121 | "generateThreadTitle",
122 attachments: BranchNameGenerationInput["attachments"],
123 ): Effect.fn.Return<MaterializedImageAttachments, TextGenerationError> {
124 if (!attachments || attachments.length === 0) {
125 return { imagePaths: [] };
126 }
127​
128 const imagePaths: string[] = [];
129 for (const attachment of attachments) {
130 if (attachment.type !== "image") {
131 continue;
132 }
133​
134 const resolvedPath = resolveAttachmentPath({
135 attachmentsDir: serverConfig.attachmentsDir,
136 attachment,
137 });
138 if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
139 continue;
140 }
141 const fileInfo = yield* fileSystem.stat(resolvedPath).pipe(Effect.orElseSucceed(() => null));
142 if (!fileInfo || fileInfo.type !== "File") {
143 continue;
144 }
145 imagePaths.push(resolvedPath);
146 }
147 return { imagePaths };
148 });
149​
150 const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
151 operation,
152 cwd,
153 prompt,
154 outputSchemaJson,
155 imagePaths = [],
156 cleanupPaths = [],
157 modelSelection,
158 }: {
159 operation:
160 | "generateCommitMessage"
161 | "generatePrContent"
162 | "generateBranchName"
163 | "generateThreadTitle";
164 cwd: string;
165 prompt: string;
166 outputSchemaJson: S;
167 imagePaths?: ReadonlyArray<string>;
168 cleanupPaths?: ReadonlyArray<string>;
169 modelSelection: ModelSelection;
170 }): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
171 const schemaJson = yield* encodeJsonForOperation(
172 operation,
173 toJsonSchemaObject(outputSchemaJson),
174 );
175 const schemaPath = yield* writeTempFile(operation, "codex-schema", schemaJson);
176 const outputPath = yield* writeTempFile(operation, "codex-output", "");
177​
178 const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
179 const reasoningEffort =
180 getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
181 CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
182 const serviceTier = getCodexServiceTierOptionValue(modelSelection);
183 const command = ChildProcess.make(
184 codexConfig.binaryPath || "codex",
185 [
186 "exec",
187 "--ephemeral",
188 "--skip-git-repo-check",
189 "-s",
190 "read-only",
191 "--model",
192 modelSelection.model,
193 "--config",
194 `model_reasoning_effort="${reasoningEffort}"`,
195 ...(serviceTier ? ["--config", `service_tier="${serviceTier}"`] : []),
196 "--output-schema",
197 schemaPath,
198 "--output-last-message",
199 outputPath,
200 ...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
201 "-",
202 ],
203 {
204 env: {
205 ...environment,
206 ...(codexConfig.homePath ? { CODEX_HOME: expandHomePath(codexConfig.homePath) } : {}),
207 },
208 cwd,
209 shell: process.platform === "win32",
210 stdin: {
211 stream: Stream.encodeText(Stream.make(prompt)),
212 },
213 },
214 );
215​
216 const child = yield* commandSpawner
217 .spawn(command)
218 .pipe(
219 Effect.mapError((cause) =>
220 normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
221 ),
222 );
223​
224 const [stdout, stderr, exitCode] = yield* Effect.all(
225 [
226 readStreamAsString(operation, child.stdout),
227 readStreamAsString(operation, child.stderr),
228 child.exitCode.pipe(
229 Effect.mapError((cause) =>
230 normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
231 ),
232 ),
233 ],
234 { concurrency: "unbounded" },
235 );
236​
237 if (exitCode !== 0) {
238 const stderrDetail = stderr.trim();
239 const stdoutDetail = stdout.trim();
240 const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
241 return yield* new TextGenerationError({
242 operation,
243 detail:
244 detail.length > 0
245 ? `Codex CLI command failed: ${detail}`
246 : `Codex CLI command failed with code ${exitCode}.`,
247 });
248 }
249 });
250​
251 const cleanup = Effect.all(
252 [schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
253 {
254 concurrency: "unbounded",
255 },
256 ).pipe(Effect.asVoid);
257​
258 return yield* Effect.gen(function* () {
259 yield* runCodexCommand().pipe(
260 Effect.scoped,
261 Effect.timeoutOption(CODEX_TIMEOUT_MS),
262 Effect.flatMap(
263 Option.match({
264 onNone: () =>
265 Effect.fail(
266 new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
267 ),
268 onSome: () => Effect.void,
269 }),
270 ),
271 );
272​
273 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
274​
275 return yield* fileSystem.readFileString(outputPath).pipe(
276 Effect.mapError(
277 (cause) =>
278 new TextGenerationError({
279 operation,
280 detail: "Failed to read Codex output file.",
281 cause,
282 }),
283 ),
284 Effect.flatMap(decodeOutput),
285 Effect.catchTag("SchemaError", (cause) =>
286 Effect.fail(
287 new TextGenerationError({
288 operation,
289 detail: "Codex returned invalid structured output.",
290 cause,
291 }),
292 ),
293 ),
294 );
295 }).pipe(Effect.ensuring(cleanup));
296 });
297​
298 const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
299 "CodexTextGeneration.generateCommitMessage",
300 )(function* (input) {
301 const { prompt, outputSchema } = buildCommitMessagePrompt({
302 branch: input.branch,
303 stagedSummary: input.stagedSummary,
304 stagedPatch: input.stagedPatch,
305 includeBranch: input.includeBranch === true,
306 });
307​
308 const generated = yield* runCodexJson({
309 operation: "generateCommitMessage",
310 cwd: input.cwd,
311 prompt,
312 outputSchemaJson: outputSchema,
313 modelSelection: input.modelSelection,
314 });
315​
316 return {
317 subject: sanitizeCommitSubject(generated.subject),
318 body: generated.body.trim(),
319 ...("branch" in generated && typeof generated.branch === "string"
320 ? { branch: sanitizeFeatureBranchName(generated.branch) }
321 : {}),
322 };
323 });
324​
325 const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
326 "CodexTextGeneration.generatePrContent",
327 )(function* (input) {
328 const { prompt, outputSchema } = buildPrContentPrompt({
329 baseBranch: input.baseBranch,
330 headBranch: input.headBranch,
331 commitSummary: input.commitSummary,
332 diffSummary: input.diffSummary,
333 diffPatch: input.diffPatch,
334 });
335​
336 const generated = yield* runCodexJson({
337 operation: "generatePrContent",
338 cwd: input.cwd,
339 prompt,
340 outputSchemaJson: outputSchema,
341 modelSelection: input.modelSelection,
342 });
343​
344 return {
345 title: sanitizePrTitle(generated.title),
346 body: generated.body.trim(),
347 };
348 });
349​
350 const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
351 "CodexTextGeneration.generateBranchName",
352 )(function* (input) {
353 const { imagePaths } = yield* materializeImageAttachments(
354 "generateBranchName",
355 input.attachments,
356 );
357 const { prompt, outputSchema } = buildBranchNamePrompt({
358 message: input.message,
359 attachments: input.attachments,
360 });
361​
362 const generated = yield* runCodexJson({
363 operation: "generateBranchName",
364 cwd: input.cwd,
365 prompt,
366 outputSchemaJson: outputSchema,
367 imagePaths,
368 modelSelection: input.modelSelection,
369 });
370​
371 return {
372 branch: sanitizeBranchFragment(generated.branch),
373 };
374 });
375​
376 const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
377 "CodexTextGeneration.generateThreadTitle",
378 )(function* (input) {
379 const { imagePaths } = yield* materializeImageAttachments(
380 "generateThreadTitle",
381 input.attachments,
382 );
383 const { prompt, outputSchema } = buildThreadTitlePrompt({
384 message: input.message,
385 attachments: input.attachments,
386 });
387​
388 const generated = yield* runCodexJson({
389 operation: "generateThreadTitle",
390 cwd: input.cwd,
391 prompt,
392 outputSchemaJson: outputSchema,
393 imagePaths,
394 modelSelection: input.modelSelection,
395 });
396​
397 return {
398 title: sanitizeThreadTitle(generated.title),
399 } satisfies ThreadTitleGenerationResult;
400 });
401​
402 return {
403 generateCommitMessage,
404 generatePrContent,
405 generateBranchName,
406 generateThreadTitle,
407 } satisfies TextGenerationShape;
408});