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 TextGenerationShape,
18 TextGeneration,
19} from "../Services/TextGeneration.ts";
20
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 attachmentsDir: serverConfig.attachmentsDir,
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 model,
191 }: {
192 operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
193 cwd: string;
194 prompt: string;
195 outputSchemaJson: S;
196 imagePaths?: ReadonlyArray<string>;
197 cleanupPaths?: ReadonlyArray<string>;
198 model?: string;
199 }): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
200 Effect.gen(function* () {
201 const schemaPath = yield* writeTempFile(
202 operation,
203 "codex-schema",
204 JSON.stringify(toCodexOutputJsonSchema(outputSchemaJson)),
205 );
206 const outputPath = yield* writeTempFile(operation, "codex-output", "");
207
208 const runCodexCommand = Effect.gen(function* () {
209 const command = ChildProcess.make(
210 "codex",
211 [
212 "exec",
213 "--ephemeral",
214 "-s",
215 "read-only",
216 "--model",
217 model ?? DEFAULT_GIT_TEXT_GENERATION_MODEL,
218 "--config",
219 `model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
220 "--output-schema",
221 schemaPath,
222 "--output-last-message",
223 outputPath,
224 ...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
225 "-",
226 ],
227 {
228 cwd,
229 shell: process.platform === "win32",
230 stdin: {
231 stream: Stream.make(new TextEncoder().encode(prompt)),
232 },
233 },
234 );
235
236 const child = yield* commandSpawner
237 .spawn(command)
238 .pipe(
239 Effect.mapError((cause) =>
240 normalizeCodexError(operation, cause, "Failed to spawn Codex CLI process"),
241 ),
242 );
243
244 const [stdout, stderr, exitCode] = yield* Effect.all(
245 [
246 readStreamAsString(operation, child.stdout),
247 readStreamAsString(operation, child.stderr),
248 child.exitCode.pipe(
249 Effect.map((value) => Number(value)),
250 Effect.mapError((cause) =>
251 normalizeCodexError(operation, cause, "Failed to read Codex CLI exit code"),
252 ),
253 ),
254 ],
255 { concurrency: "unbounded" },
256 );
257
258 if (exitCode !== 0) {
259 const stderrDetail = stderr.trim();
260 const stdoutDetail = stdout.trim();
261 const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
262 return yield* new TextGenerationError({
263 operation,
264 detail:
265 detail.length > 0
266 ? `Codex CLI command failed: ${detail}`
267 : `Codex CLI command failed with code ${exitCode}.`,
268 });
269 }
270 });
271
272 const cleanup = Effect.all(
273 [schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
274 {
275 concurrency: "unbounded",
276 },
277 ).pipe(Effect.asVoid);
278
279 return yield* Effect.gen(function* () {
280 yield* runCodexCommand.pipe(
281 Effect.scoped,
282 Effect.timeoutOption(CODEX_TIMEOUT_MS),
283 Effect.flatMap(
284 Option.match({
285 onNone: () =>
286 Effect.fail(
287 new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
288 ),
289 onSome: () => Effect.void,
290 }),
291 ),
292 );
293
294 return yield* fileSystem.readFileString(outputPath).pipe(
295 Effect.mapError(
296 (cause) =>
297 new TextGenerationError({
298 operation,
299 detail: "Failed to read Codex output file.",
300 cause,
301 }),
302 ),
303 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
304 Effect.catchTag("SchemaError", (cause) =>
305 Effect.fail(
306 new TextGenerationError({
307 operation,
308 detail: "Codex returned invalid structured output.",
309 cause,
310 }),
311 ),
312 ),
313 );
314 }).pipe(Effect.ensuring(cleanup));
315 });
316
317 const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = (input) => {
318 const wantsBranch = input.includeBranch === true;
319
320 const prompt = [
321 "You write concise git commit messages.",
322 wantsBranch
323 ? "Return a JSON object with keys: subject, body, branch."
324 : "Return a JSON object with keys: subject, body.",
325 "Rules:",
326 "- subject must be imperative, <= 72 chars, and no trailing period",
327 "- body can be empty string or short bullet points",
328 ...(wantsBranch
329 ? ["- branch must be a short semantic git branch fragment for this change"]
330 : []),
331 "- capture the primary user-visible or developer-visible change",
332 "",
333 `Branch: ${input.branch ?? "(detached)"}`,
334 "",
335 "Staged files:",
336 limitSection(input.stagedSummary, 6_000),
337 "",
338 "Staged patch:",
339 limitSection(input.stagedPatch, 40_000),
340 ].join("\n");
341
342 const outputSchemaJson = wantsBranch
343 ? Schema.Struct({
344 subject: Schema.String,
345 body: Schema.String,
346 branch: Schema.String,
347 })
348 : Schema.Struct({
349 subject: Schema.String,
350 body: Schema.String,
351 });
352
353 return runCodexJson({
354 operation: "generateCommitMessage",
355 cwd: input.cwd,
356 prompt,
357 outputSchemaJson,
358 ...(input.model ? { model: input.model } : {}),
359 }).pipe(
360 Effect.map(
361 (generated) =>
362 ({
363 subject: sanitizeCommitSubject(generated.subject),
364 body: generated.body.trim(),
365 ...("branch" in generated && typeof generated.branch === "string"
366 ? { branch: sanitizeFeatureBranchName(generated.branch) }
367 : {}),
368 }) satisfies CommitMessageGenerationResult,
369 ),
370 );
371 };
372
373 const generatePrContent: TextGenerationShape["generatePrContent"] = (input) => {
374 const prompt = [
375 "You write GitHub pull request content.",
376 "Return a JSON object with keys: title, body.",
377 "Rules:",
378 "- title should be concise and specific",
379 "- body must be markdown and include headings '## Summary' and '## Testing'",
380 "- under Summary, provide short bullet points",
381 "- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
382 "",
383 `Base branch: ${input.baseBranch}`,
384 `Head branch: ${input.headBranch}`,
385 "",
386 "Commits:",
387 limitSection(input.commitSummary, 12_000),
388 "",
389 "Diff stat:",
390 limitSection(input.diffSummary, 12_000),
391 "",
392 "Diff patch:",
393 limitSection(input.diffPatch, 40_000),
394 ].join("\n");
395
396 return runCodexJson({
397 operation: "generatePrContent",
398 cwd: input.cwd,
399 prompt,
400 outputSchemaJson: Schema.Struct({
401 title: Schema.String,
402 body: Schema.String,
403 }),
404 ...(input.model ? { model: input.model } : {}),
405 }).pipe(
406 Effect.map(
407 (generated) =>
408 ({
409 title: sanitizePrTitle(generated.title),
410 body: generated.body.trim(),
411 }) satisfies PrContentGenerationResult,
412 ),
413 );
414 };
415
416 const generateBranchName: TextGenerationShape["generateBranchName"] = (input) => {
417 return Effect.gen(function* () {
418 const { imagePaths } = yield* materializeImageAttachments(
419 "generateBranchName",
420 input.attachments,
421 );
422 const attachmentLines = (input.attachments ?? []).map(
423 (attachment) =>
424 `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
425 );
426
427 const promptSections = [
428 "You generate concise git branch names.",
429 "Return a JSON object with key: branch.",
430 "Rules:",
431 "- Branch should describe the requested work from the user message.",
432 "- Keep it short and specific (2-6 words).",
433 "- Use plain words only, no issue prefixes and no punctuation-heavy text.",
434 "- If images are attached, use them as primary context for visual/UI issues.",
435 "",
436 "User message:",
437 limitSection(input.message, 8_000),
438 ];
439 if (attachmentLines.length > 0) {
440 promptSections.push(
441 "",
442 "Attachment metadata:",
443 limitSection(attachmentLines.join("\n"), 4_000),
444 );
445 }
446 const prompt = promptSections.join("\n");
447
448 const generated = yield* runCodexJson({
449 operation: "generateBranchName",
450 cwd: input.cwd,
451 prompt,
452 outputSchemaJson: Schema.Struct({
453 branch: Schema.String,
454 }),
455 imagePaths,
456 ...(input.model ? { model: input.model } : {}),
457 });
458
459 return {
460 branch: sanitizeBranchFragment(generated.branch),
461 } satisfies BranchNameGenerationResult;
462 });
463 };
464
465 return {
466 generateCommitMessage,
467 generatePrContent,
468 generateBranchName,
469 } satisfies TextGenerationShape;
470});
471
472export const CodexTextGenerationLive = Layer.effect(TextGeneration, makeCodexTextGeneration);