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

CodexTextGeneration.ts

393 lines11.7 KB

1import { randomUUID } from "node:crypto";
2​
3import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
4import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
5​
6import { TextGenerationError } from "../Errors.ts";
7import {
8 type CommitMessageGenerationResult,
9 type PrContentGenerationResult,
10 type TextGenerationShape,
11 TextGeneration,
12} from "../Services/TextGeneration.ts";
13​
14const CODEX_MODEL = "gpt-5.3-codex";
15const CODEX_REASONING_EFFORT = "low";
16const CODEX_TIMEOUT_MS = 180_000;
17​
18const COMMIT_OUTPUT_SCHEMA_JSON = {
19 type: "object",
20 properties: {
21 subject: { type: "string" },
22 body: { type: "string" },
23 },
24 required: ["subject", "body"],
25 additionalProperties: false,
26} as const;
27​
28const PR_OUTPUT_SCHEMA_JSON = {
29 type: "object",
30 properties: {
31 title: { type: "string" },
32 body: { type: "string" },
33 },
34 required: ["title", "body"],
35 additionalProperties: false,
36} as const;
37​
38function normalizeCodexError(
39 operation: string,
40 error: unknown,
41 fallback: string,
42): TextGenerationError {
43 if (Schema.is(TextGenerationError)(error)) {
44 return error;
45 }
46​
47 if (error instanceof Error) {
48 const lower = error.message.toLowerCase();
49 if (
50 error.message.includes("Command not found: codex") ||
51 lower.includes("spawn codex") ||
52 lower.includes("enoent")
53 ) {
54 return new TextGenerationError({
55 operation,
56 detail: "Codex CLI (`codex`) is required but not available on PATH.",
57 cause: error,
58 });
59 }
60 return new TextGenerationError({
61 operation,
62 detail: `${fallback}: ${error.message}`,
63 cause: error,
64 });
65 }
66​
67 return new TextGenerationError({
68 operation,
69 detail: fallback,
70 cause: error,
71 });
73​
74function parseCommitOutput(raw: unknown): { subject: string; body: string } {
75 if (!raw || typeof raw !== "object") {
76 throw new Error("Codex returned a non-object commit message payload.");
77 }
78 const record = raw as Record<string, unknown>;
79 const subject = typeof record.subject === "string" ? record.subject.trim() : "";
80 const body = typeof record.body === "string" ? record.body : "";
81 if (subject.length === 0) {
82 throw new Error("Codex returned an empty commit subject.");
83 }
84 return { subject, body };
86​
87function parsePrOutput(raw: unknown): { title: string; body: string } {
88 if (!raw || typeof raw !== "object") {
89 throw new Error("Codex returned a non-object PR payload.");
90 }
91 const record = raw as Record<string, unknown>;
92 const title = typeof record.title === "string" ? record.title.trim() : "";
93 const body = typeof record.body === "string" ? record.body.trim() : "";
94 if (title.length === 0 || body.length === 0) {
95 throw new Error("Codex returned an invalid PR title/body payload.");
96 }
97 return { title, body };
99​
100function limitSection(value: string, maxChars: number): string {
101 if (value.length <= maxChars) return value;
102 const truncated = value.slice(0, maxChars);
103 return `${truncated}\n\n[truncated]`;
105​
106function sanitizeCommitSubject(raw: string): string {
107 const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
108 const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
109 if (withoutTrailingPeriod.length === 0) {
110 return "Update project files";
111 }
112​
113 if (withoutTrailingPeriod.length <= 72) {
114 return withoutTrailingPeriod;
115 }
116 return withoutTrailingPeriod.slice(0, 72).trimEnd();
118​
119function sanitizePrTitle(raw: string): string {
120 const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
121 if (singleLine.length > 0) {
122 return singleLine;
123 }
124 return "Update project changes";
126​
127const makeCodexTextGeneration = Effect.gen(function* () {
128 const fileSystem = yield* FileSystem.FileSystem;
129 const path = yield* Path.Path;
130 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
131​
132 const readStreamAsString = <E>(
133 operation: string,
134 stream: Stream.Stream<Uint8Array, E>,
135 ): Effect.Effect<string, TextGenerationError> =>
136 Effect.gen(function* () {
137 let text = "";
138 yield* Stream.runForEach(stream, (chunk) =>
139 Effect.sync(() => {
140 text += Buffer.from(chunk).toString("utf8");
141 }),
142 ).pipe(
143 Effect.mapError((cause) =>
144 normalizeCodexError(operation, cause, "Failed to collect process output"),
145 ),
146 );
147 return text;
148 });
149​
150 const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
151​
152 const writeTempFile = (
153 operation: string,
154 prefix: string,
155 content: string,
156 ): Effect.Effect<string, TextGenerationError> => {
157 const filePath = path.join(tempDir, `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`);
158 return fileSystem.writeFileString(filePath, content).pipe(
159 Effect.mapError(
160 (cause) =>
161 new TextGenerationError({
162 operation,
163 detail: `Failed to write temp file at ${filePath}.`,
164 cause,
165 }),
166 ),
167 Effect.as(filePath),
168 );
169 };
170​
171 const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
172 fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
173​
174 const runCodexJson = <T>({
175 operation,
176 cwd,
177 prompt,
178 outputSchemaJson,
179 parse,
180 }: {
181 operation: "generateCommitMessage" | "generatePrContent";
182 cwd: string;
183 prompt: string;
184 outputSchemaJson: object;
185 parse: (raw: unknown) => T;
186 }): Effect.Effect<T, TextGenerationError> =>
187 Effect.gen(function* () {
188 const schemaPath = yield* writeTempFile(
189 operation,
190 "codex-schema",
191 JSON.stringify(outputSchemaJson),
192 );
193 const outputPath = yield* writeTempFile(operation, "codex-output", "");
194​
195 const runCodexCommand = Effect.gen(function* () {
196 const command = ChildProcess.make(
197 "codex",
198 [
199 "exec",
200 "--ephemeral",
201 "-s",
202 "read-only",
203 "--model",
204 CODEX_MODEL,
205 "--config",
206 `model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
207 "--output-schema",
208 schemaPath,
209 "--output-last-message",
210 outputPath,
211 "-",
212 ],
213 {
214 cwd,
215 stdin: {
216 stream: Stream.make(new TextEncoder().encode(prompt)),
217 },
218 },
219 );
220​
221 const child = yield* commandSpawner
222 .spawn(command)
223 .pipe(
224 Effect.mapError((cause) =>
225 normalizeCodexError(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.map((value) => Number(value)),
235 Effect.mapError((cause) =>
236 normalizeCodexError(operation, cause, "Failed to read Codex CLI exit code"),
237 ),
238 ),
239 ],
240 { concurrency: "unbounded" },
241 );
242​
243 if (exitCode !== 0) {
244 const stderrDetail = stderr.trim();
245 const stdoutDetail = stdout.trim();
246 const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
247 return yield* new TextGenerationError({
248 operation,
249 detail:
250 detail.length > 0
251 ? `Codex CLI command failed: ${detail}`
252 : `Codex CLI command failed with code ${exitCode}.`,
253 });
254 }
255 });
256​
257 const cleanup = Effect.all([safeUnlink(schemaPath), safeUnlink(outputPath)], {
258 concurrency: "unbounded",
259 }).pipe(Effect.asVoid);
260​
261 return yield* Effect.gen(function* () {
262 yield* runCodexCommand.pipe(
263 Effect.scoped,
264 Effect.timeoutOption(CODEX_TIMEOUT_MS),
265 Effect.flatMap(
266 Option.match({
267 onNone: () =>
268 Effect.fail(
269 new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
270 ),
271 onSome: () => Effect.void,
272 }),
273 ),
274 );
275​
276 const rawOutput = yield* fileSystem.readFileString(outputPath).pipe(
277 Effect.mapError(
278 (cause) =>
279 new TextGenerationError({
280 operation,
281 detail: "Failed to read Codex output file.",
282 cause,
283 }),
284 ),
285 );
286 const trimmed = rawOutput.trim();
287 if (trimmed.length === 0) {
288 return yield* new TextGenerationError({
289 operation,
290 detail: "Codex returned an empty response.",
291 });
292 }
293​
294 const parsedJson = yield* Effect.try({
295 try: () => JSON.parse(trimmed) as unknown,
296 catch: (cause) =>
297 new TextGenerationError({
298 operation,
299 detail: "Codex returned invalid JSON output.",
300 cause,
301 }),
302 });
303​
304 return yield* Effect.try({
305 try: () => parse(parsedJson),
306 catch: (cause) =>
307 normalizeCodexError(operation, cause, "Codex returned invalid structured output"),
308 });
309 }).pipe(Effect.ensuring(cleanup));
310 });
311​
312 const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = (input) => {
313 const prompt = [
314 "You write concise git commit messages.",
315 "Return a JSON object with keys: subject, body.",
316 "Rules:",
317 "- subject must be imperative, <= 72 chars, and no trailing period",
318 "- body can be empty string or short bullet points",
319 "- capture the primary user-visible or developer-visible change",
320 "",
321 `Branch: ${input.branch ?? "(detached)"}`,
322 "",
323 "Staged files:",
324 limitSection(input.stagedSummary, 6_000),
325 "",
326 "Staged patch:",
327 limitSection(input.stagedPatch, 40_000),
328 ].join("\n");
329​
330 return runCodexJson({
331 operation: "generateCommitMessage",
332 cwd: input.cwd,
333 prompt,
334 outputSchemaJson: COMMIT_OUTPUT_SCHEMA_JSON,
335 parse: (raw) => parseCommitOutput(raw),
336 }).pipe(
337 Effect.map(
338 (generated) =>
339 ({
340 subject: sanitizeCommitSubject(generated.subject),
341 body: generated.body.trim(),
342 }) satisfies CommitMessageGenerationResult,
343 ),
344 );
345 };
346​
347 const generatePrContent: TextGenerationShape["generatePrContent"] = (input) => {
348 const prompt = [
349 "You write GitHub pull request content.",
350 "Return a JSON object with keys: title, body.",
351 "Rules:",
352 "- title should be concise and specific",
353 "- body must be markdown and include headings '## Summary' and '## Testing'",
354 "- under Summary, provide short bullet points",
355 "- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
356 "",
357 `Base branch: ${input.baseBranch}`,
358 `Head branch: ${input.headBranch}`,
359 "",
360 "Commits:",
361 limitSection(input.commitSummary, 12_000),
362 "",
363 "Diff stat:",
364 limitSection(input.diffSummary, 12_000),
365 "",
366 "Diff patch:",
367 limitSection(input.diffPatch, 40_000),
368 ].join("\n");
369​
370 return runCodexJson({
371 operation: "generatePrContent",
372 cwd: input.cwd,
373 prompt,
374 outputSchemaJson: PR_OUTPUT_SCHEMA_JSON,
375 parse: (raw) => parsePrOutput(raw),
376 }).pipe(
377 Effect.map(
378 (generated) =>
379 ({
380 title: sanitizePrTitle(generated.title),
381 body: generated.body.trim(),
382 }) satisfies PrContentGenerationResult,
383 ),
384 );
385 };
386​
387 return {
388 generateCommitMessage,
389 generatePrContent,
390 } satisfies TextGenerationShape;
391});
392​
393export const CodexTextGenerationLive = Layer.effect(TextGeneration, makeCodexTextGeneration);