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

codexTextGenerator.ts

252 lines7.0 KB

1import { randomUUID } from "node:crypto";
2import fs from "node:fs/promises";
3import os from "node:os";
4import path from "node:path";
5​
6import type {
7 CommitMessageGenerationInput,
8 CommitMessageGenerationResult,
9 PrContentGenerationInput,
10 PrContentGenerationResult,
11 TextGenerationService,
12} from "./coreServices";
13import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
14​
15type ProcessRunner = (
16 command: string,
17 args: readonly string[],
18 options?: ProcessRunOptions,
19) => Promise<ProcessRunResult>;
20​
21const CODEX_MODEL = "gpt-5.3-codex";
22const CODEX_REASONING_EFFORT = "low";
23​
24const COMMIT_OUTPUT_SCHEMA_JSON = {
25 type: "object",
26 properties: {
27 subject: { type: "string" },
28 body: { type: "string" },
29 },
30 required: ["subject", "body"],
31 additionalProperties: false,
32} as const;
33​
34const PR_OUTPUT_SCHEMA_JSON = {
35 type: "object",
36 properties: {
37 title: { type: "string" },
38 body: { type: "string" },
39 },
40 required: ["title", "body"],
41 additionalProperties: false,
42} as const;
43​
44function parseCommitOutput(raw: unknown): { subject: string; body: string } {
45 if (!raw || typeof raw !== "object") {
46 throw new Error("Codex returned a non-object commit message payload.");
47 }
48 const record = raw as Record<string, unknown>;
49 const subject = typeof record.subject === "string" ? record.subject.trim() : "";
50 const body = typeof record.body === "string" ? record.body : "";
51 if (subject.length === 0) {
52 throw new Error("Codex returned an empty commit subject.");
53 }
54 return { subject, body };
56​
57function parsePrOutput(raw: unknown): { title: string; body: string } {
58 if (!raw || typeof raw !== "object") {
59 throw new Error("Codex returned a non-object PR payload.");
60 }
61 const record = raw as Record<string, unknown>;
62 const title = typeof record.title === "string" ? record.title.trim() : "";
63 const body = typeof record.body === "string" ? record.body.trim() : "";
64 if (title.length === 0 || body.length === 0) {
65 throw new Error("Codex returned an invalid PR title/body payload.");
66 }
67 return { title, body };
69​
70function limitSection(value: string, maxChars: number): string {
71 if (value.length <= maxChars) return value;
72 const truncated = value.slice(0, maxChars);
73 return `${truncated}\n\n[truncated]`;
75​
76async function writeTempFile(prefix: string, content: string): Promise<string> {
77 const filePath = path.join(os.tmpdir(), `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`);
78 await fs.writeFile(filePath, content, "utf8");
79 return filePath;
81​
82async function safeUnlink(filePath: string): Promise<void> {
83 try {
84 await fs.unlink(filePath);
85 } catch {
86 // Best-effort cleanup.
87 }
89​
90function sanitizeCommitSubject(raw: string): string {
91 const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
92 const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
93 if (withoutTrailingPeriod.length === 0) {
94 return "Update project files";
95 }
96​
97 if (withoutTrailingPeriod.length <= 72) {
98 return withoutTrailingPeriod;
99 }
100 return withoutTrailingPeriod.slice(0, 72).trimEnd();
102​
103function sanitizePrTitle(raw: string): string {
104 const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
105 if (singleLine.length > 0) {
106 return singleLine;
107 }
108 return "Update project changes";
110​
111async function runCodexJson<T>({
112 cwd,
113 prompt,
114 outputSchemaJson,
115 parse,
116 run,
117}: {
118 cwd: string;
119 prompt: string;
120 outputSchemaJson: object;
121 parse: (raw: unknown) => T;
122 run: ProcessRunner;
123}): Promise<T> {
124 const schemaPath = await writeTempFile("codex-schema", JSON.stringify(outputSchemaJson));
125 let outputPath: string | null = null;
126​
127 try {
128 outputPath = await writeTempFile("codex-output", "");
129 await run(
130 "codex",
131 [
132 "exec",
133 "--ephemeral",
134 "-s",
135 "read-only",
136 "--model",
137 CODEX_MODEL,
138 "--config",
139 `model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
140 "--output-schema",
141 schemaPath,
142 "--output-last-message",
143 outputPath,
144 "-",
145 ],
146 {
147 cwd,
148 timeoutMs: 180_000,
149 stdin: prompt,
150 },
151 );
152​
153 const rawOutput = (await fs.readFile(outputPath, "utf8")).trim();
154 if (rawOutput.length === 0) {
155 throw new Error("Codex returned an empty response.");
156 }
157​
158 let parsedJson: unknown;
159 try {
160 parsedJson = JSON.parse(rawOutput);
161 } catch {
162 throw new Error("Codex returned invalid JSON output.");
163 }
164​
165 return parse(parsedJson);
166 } finally {
167 await Promise.all([safeUnlink(schemaPath), ...(outputPath ? [safeUnlink(outputPath)] : [])]);
168 }
170​
171interface CodexTextGeneratorDeps {
172 runProcess?: ProcessRunner;
174​
175export class CodexTextGenerator implements TextGenerationService {
176 private readonly run: ProcessRunner;
177​
178 constructor(deps: CodexTextGeneratorDeps = {}) {
179 this.run = deps.runProcess ?? runProcess;
180 }
181​
182 async generateCommitMessage(
183 input: CommitMessageGenerationInput,
184 ): Promise<CommitMessageGenerationResult> {
185 const prompt = [
186 "You write concise git commit messages.",
187 "Return a JSON object with keys: subject, body.",
188 "Rules:",
189 "- subject must be imperative, <= 72 chars, and no trailing period",
190 "- body can be empty string or short bullet points",
191 "- capture the primary user-visible or developer-visible change",
192 "",
193 `Branch: ${input.branch ?? "(detached)"}`,
194 "",
195 "Staged files:",
196 limitSection(input.stagedSummary, 6_000),
197 "",
198 "Staged patch:",
199 limitSection(input.stagedPatch, 40_000),
200 ].join("\n");
201​
202 const generated = await runCodexJson({
203 cwd: input.cwd,
204 prompt,
205 outputSchemaJson: COMMIT_OUTPUT_SCHEMA_JSON,
206 parse: (raw) => parseCommitOutput(raw),
207 run: this.run,
208 });
209​
210 return {
211 subject: sanitizeCommitSubject(generated.subject),
212 body: generated.body.trim(),
213 };
214 }
215​
216 async generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult> {
217 const prompt = [
218 "You write GitHub pull request content.",
219 "Return a JSON object with keys: title, body.",
220 "Rules:",
221 "- title should be concise and specific",
222 "- body must be markdown and include headings '## Summary' and '## Testing'",
223 "- under Summary, provide short bullet points",
224 "- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
225 "",
226 `Base branch: ${input.baseBranch}`,
227 `Head branch: ${input.headBranch}`,
228 "",
229 "Commits:",
230 limitSection(input.commitSummary, 12_000),
231 "",
232 "Diff stat:",
233 limitSection(input.diffSummary, 12_000),
234 "",
235 "Diff patch:",
236 limitSection(input.diffPatch, 40_000),
237 ].join("\n");
238​
239 const generated = await runCodexJson({
240 cwd: input.cwd,
241 prompt,
242 outputSchemaJson: PR_OUTPUT_SCHEMA_JSON,
243 parse: (raw) => parsePrOutput(raw),
244 run: this.run,
245 });
246​
247 return {
248 title: sanitizePrTitle(generated.title),
249 body: generated.body.trim(),
250 };
251 }