Open History to see the last commit
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 { resolveAttachmentPath } from "../../attachmentStore.ts";
7import { ServerConfig } from "../../config.ts";
8import { TextGenerationError } from "../Errors.ts";
9import {
10 type BranchNameGenerationInput,
11 type BranchNameGenerationResult,
12 type CommitMessageGenerationResult,
13 type PrContentGenerationResult,
14 type TextGenerationShape,
15 TextGeneration,
16} from "../Services/TextGeneration.ts";
17
18const CODEX_MODEL = "gpt-5.3-codex";
19const CODEX_REASONING_EFFORT = "low";
20const CODEX_TIMEOUT_MS = 180_000;
21
22function toCodexOutputJsonSchema(schema: Schema.Top): unknown {
23 const document = Schema.toJsonSchemaDocument(schema);
24 if (document.definitions && Object.keys(document.definitions).length > 0) {
25 return {
26 ...document.schema,
27 $defs: document.definitions,
28 };
29 }
30 return document.schema;
31}
32
33function normalizeCodexError(
34 operation: string,
35 error: unknown,
36 fallback: string,
37): TextGenerationError {
38 if (Schema.is(TextGenerationError)(error)) {
39 return error;
40 }
41
42 if (error instanceof Error) {
43 const lower = error.message.toLowerCase();
44 if (
45 error.message.includes("Command not found: codex") ||
46 lower.includes("spawn codex") ||
47 lower.includes("enoent")
48 ) {
49 return new TextGenerationError({
50 operation,
51 detail: "Codex CLI (`codex`) is required but not available on PATH.",
52 cause: error,
53 });
54 }
55 return new TextGenerationError({
56 operation,
57 detail: `${fallback}: ${error.message}`,
58 cause: error,
59 });
60 }
61
62 return new TextGenerationError({
63 operation,
64 detail: fallback,
65 cause: error,
66 });
67}
68
69function limitSection(value: string, maxChars: number): string {
70 if (value.length <= maxChars) return value;
71 const truncated = value.slice(0, maxChars);
72 return `${truncated}\n\n[truncated]`;
73}
74
75function sanitizeCommitSubject(raw: string): string {
76 const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
77 const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
78 if (withoutTrailingPeriod.length === 0) {
79 return "Update project files";
80 }
81
82 if (withoutTrailingPeriod.length <= 72) {
83 return withoutTrailingPeriod;
84 }
85 return withoutTrailingPeriod.slice(0, 72).trimEnd();
86}
87
88function sanitizePrTitle(raw: string): string {
89 const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
90 if (singleLine.length > 0) {
91 return singleLine;
92 }
93 return "Update project changes";
94}
95
96function sanitizeBranchName(raw: string): string {
97 const normalized = raw
98 .trim()
99 .toLowerCase()
100 .replace(/['"`]/g, "")
101 .replace(/^[./\s_-]+|[./\s_-]+$/g, "");
102
103 const branchFragment = normalized
104 .replace(/[^a-z0-9/_-]+/g, "-")
105 .replace(/\/+/g, "/")
106 .replace(/-+/g, "-")
107 .replace(/^[./_-]+|[./_-]+$/g, "")
108 .slice(0, 64)
109 .replace(/[./_-]+$/g, "");
110
111 return branchFragment.length > 0 ? branchFragment : "update";
112}
113
114const makeCodexTextGeneration = Effect.gen(function* () {
115 const fileSystem = yield* FileSystem.FileSystem;
116 const path = yield* Path.Path;
117 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
118 const serverConfig = yield* Effect.service(ServerConfig);
119
120 type MaterializedImageAttachments = {
121 readonly imagePaths: ReadonlyArray<string>;
122 };
123
124 const readStreamAsString = <E>(
125 operation: string,
126 stream: Stream.Stream<Uint8Array, E>,
127 ): Effect.Effect<string, TextGenerationError> =>
128 Effect.gen(function* () {
129 let text = "";
130 yield* Stream.runForEach(stream, (chunk) =>
131 Effect.sync(() => {
132 text += Buffer.from(chunk).toString("utf8");
133 }),
134 ).pipe(
135 Effect.mapError((cause) =>
136 normalizeCodexError(operation, cause, "Failed to collect process output"),
137 ),
138 );
139 return text;
140 });
141
142 const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
143
144 const writeTempFile = (
145 operation: string,
146 prefix: string,
147 content: string,
148 ): Effect.Effect<string, TextGenerationError> => {
149 const filePath = path.join(tempDir, `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`);
150 return fileSystem.writeFileString(filePath, content).pipe(
151 Effect.mapError(
152 (cause) =>
153 new TextGenerationError({
154 operation,
155 detail: `Failed to write temp file at ${filePath}.`,
156 cause,
157 }),
158 ),
159 Effect.as(filePath),
160 );
161 };
162
163 const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
164 fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
165
166 const materializeImageAttachments = (
167 _operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName",
168 attachments: BranchNameGenerationInput["attachments"],
169 ): Effect.Effect<MaterializedImageAttachments, TextGenerationError> =>
170 Effect.gen(function* () {
171 if (!attachments || attachments.length === 0) {
172 return { imagePaths: [] };
173 }
174
175 const imagePaths: string[] = [];
176 for (const attachment of attachments) {
177 if (attachment.type !== "image") {
178 continue;
179 }
180
181 const resolvedPath = resolveAttachmentPath({
182 stateDir: serverConfig.stateDir,
183 attachment,
184 });
185 if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
186 continue;
187 }
188 const fileInfo = yield* fileSystem
189 .stat(resolvedPath)
190 .pipe(Effect.catch(() => Effect.succeed(null)));
191 if (!fileInfo || fileInfo.type !== "File") {
192 continue;
193 }
194 imagePaths.push(resolvedPath);
195 }
196 return { imagePaths };
197 });
198
199 const runCodexJson = <S extends Schema.Top>({
200 operation,
201 cwd,
202 prompt,
203 outputSchemaJson,
204 imagePaths = [],
205 cleanupPaths = [],
206 }: {
207 operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
208 cwd: string;
209 prompt: string;
210 outputSchemaJson: S;
211 imagePaths?: ReadonlyArray<string>;
212 cleanupPaths?: ReadonlyArray<string>;
213 }): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
214 Effect.gen(function* () {
215 const schemaPath = yield* writeTempFile(
216 operation,
217 "codex-schema",
218 JSON.stringify(toCodexOutputJsonSchema(outputSchemaJson)),
219 );
220 const outputPath = yield* writeTempFile(operation, "codex-output", "");
221
222 const runCodexCommand = Effect.gen(function* () {
223 const command = ChildProcess.make(
224 "codex",
225 [
226 "exec",
227 "--ephemeral",
228 "-s",
229 "read-only",
230 "--model",
231 CODEX_MODEL,
232 "--config",
233 `model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
234 "--output-schema",
235 schemaPath,
236 "--output-last-message",
237 outputPath,
238 ...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
239 "-",
240 ],
241 {
242 cwd,
243 stdin: {
244 stream: Stream.make(new TextEncoder().encode(prompt)),
245 },
246 },
247 );
248
249 const child = yield* commandSpawner
250 .spawn(command)
251 .pipe(
252 Effect.mapError((cause) =>
253 normalizeCodexError(operation, cause, "Failed to spawn Codex CLI process"),
254 ),
255 );
256
257 const [stdout, stderr, exitCode] = yield* Effect.all(
258 [
259 readStreamAsString(operation, child.stdout),
260 readStreamAsString(operation, child.stderr),
261 child.exitCode.pipe(
262 Effect.map((value) => Number(value)),
263 Effect.mapError((cause) =>
264 normalizeCodexError(operation, cause, "Failed to read Codex CLI exit code"),
265 ),
266 ),
267 ],
268 { concurrency: "unbounded" },
269 );
270
271 if (exitCode !== 0) {
272 const stderrDetail = stderr.trim();
273 const stdoutDetail = stdout.trim();
274 const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
275 return yield* new TextGenerationError({
276 operation,
277 detail:
278 detail.length > 0
279 ? `Codex CLI command failed: ${detail}`
280 : `Codex CLI command failed with code ${exitCode}.`,
281 });
282 }
283 });
284
285 const cleanup = Effect.all(
286 [schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
287 {
288 concurrency: "unbounded",
289 },
290 ).pipe(Effect.asVoid);
291
292 return yield* Effect.gen(function* () {
293 yield* runCodexCommand.pipe(
294 Effect.scoped,
295 Effect.timeoutOption(CODEX_TIMEOUT_MS),
296 Effect.flatMap(
297 Option.match({
298 onNone: () =>
299 Effect.fail(
300 new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
301 ),
302 onSome: () => Effect.void,
303 }),
304 ),
305 );
306
307 return yield* fileSystem.readFileString(outputPath).pipe(
308 Effect.mapError(
309 (cause) =>
310 new TextGenerationError({
311 operation,
312 detail: "Failed to read Codex output file.",
313 cause,
314 }),
315 ),
316 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
317 Effect.catchTag("SchemaError", (cause) =>
318 Effect.fail(
319 new TextGenerationError({
320 operation,
321 detail: "Codex returned invalid structured output.",
322 cause,
323 }),
324 ),
325 ),
326 );
327 }).pipe(Effect.ensuring(cleanup));
328 });
329
330 const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = (input) => {
331 const prompt = [
332 "You write concise git commit messages.",
333 "Return a JSON object with keys: subject, body.",
334 "Rules:",
335 "- subject must be imperative, <= 72 chars, and no trailing period",
336 "- body can be empty string or short bullet points",
337 "- capture the primary user-visible or developer-visible change",
338 "",
339 `Branch: ${input.branch ?? "(detached)"}`,
340 "",
341 "Staged files:",
342 limitSection(input.stagedSummary, 6_000),
343 "",
344 "Staged patch:",
345 limitSection(input.stagedPatch, 40_000),
346 ].join("\n");
347
348 return runCodexJson({
349 operation: "generateCommitMessage",
350 cwd: input.cwd,
351 prompt,
352 outputSchemaJson: Schema.Struct({
353 subject: Schema.String,
354 body: Schema.String,
355 }),
356 }).pipe(
357 Effect.map(
358 (generated) =>
359 ({
360 subject: sanitizeCommitSubject(generated.subject),
361 body: generated.body.trim(),
362 }) satisfies CommitMessageGenerationResult,
363 ),
364 );
365 };
366
367 const generatePrContent: TextGenerationShape["generatePrContent"] = (input) => {
368 const prompt = [
369 "You write GitHub pull request content.",
370 "Return a JSON object with keys: title, body.",
371 "Rules:",
372 "- title should be concise and specific",
373 "- body must be markdown and include headings '## Summary' and '## Testing'",
374 "- under Summary, provide short bullet points",
375 "- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
376 "",
377 `Base branch: ${input.baseBranch}`,
378 `Head branch: ${input.headBranch}`,
379 "",
380 "Commits:",
381 limitSection(input.commitSummary, 12_000),
382 "",
383 "Diff stat:",
384 limitSection(input.diffSummary, 12_000),
385 "",
386 "Diff patch:",
387 limitSection(input.diffPatch, 40_000),
388 ].join("\n");
389
390 return runCodexJson({
391 operation: "generatePrContent",
392 cwd: input.cwd,
393 prompt,
394 outputSchemaJson: Schema.Struct({
395 title: Schema.String,
396 body: Schema.String,
397 }),
398 }).pipe(
399 Effect.map(
400 (generated) =>
401 ({
402 title: sanitizePrTitle(generated.title),
403 body: generated.body.trim(),
404 }) satisfies PrContentGenerationResult,
405 ),
406 );
407 };
408
409 const generateBranchName: TextGenerationShape["generateBranchName"] = (input) => {
410 return Effect.gen(function* () {
411 const { imagePaths } = yield* materializeImageAttachments("generateBranchName", input.attachments);
412 const attachmentLines = (input.attachments ?? []).map(
413 (attachment) =>
414 `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
415 );
416
417 const promptSections = [
418 "You generate concise git branch names.",
419 "Return a JSON object with key: branch.",
420 "Rules:",
421 "- Branch should describe the requested work from the user message.",
422 "- Keep it short and specific (2-6 words).",
423 "- Use plain words only, no issue prefixes and no punctuation-heavy text.",
424 "- If images are attached, use them as primary context for visual/UI issues.",
425 "",
426 "User message:",
427 limitSection(input.message, 8_000),
428 ];
429 if (attachmentLines.length > 0) {
430 promptSections.push(
431 "",
432 "Attachment metadata:",
433 limitSection(attachmentLines.join("\n"), 4_000),
434 );
435 }
436 const prompt = promptSections.join("\n");
437
438 const generated = yield* runCodexJson({
439 operation: "generateBranchName",
440 cwd: input.cwd,
441 prompt,
442 outputSchemaJson: Schema.Struct({
443 branch: Schema.String,
444 }),
445 imagePaths,
446 });
447
448 return {
449 branch: sanitizeBranchName(generated.branch),
450 } satisfies BranchNameGenerationResult;
451 });
452 };
453
454 return {
455 generateCommitMessage,
456 generatePrContent,
457 generateBranchName,
458 } satisfies TextGenerationShape;
459});
460
461export const CodexTextGenerationLive = Layer.effect(TextGeneration, makeCodexTextGeneration);