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