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