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

CodexTextGeneration.ts

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