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