Open History to see the last commit
1import { randomUUID } from "node:crypto";
2
3import { Effect, FileSystem, Layer, Option, Path, Schema, Scope, Stream } from "effect";
4import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
5
6import { CodexModelSelection } from "@t3tools/contracts";
7import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
8
9import { resolveAttachmentPath } from "../../attachmentStore.ts";
10import { ServerConfig } from "../../config.ts";
11import { expandHomePath } from "../../pathExpansion.ts";
12import { TextGenerationError } from "@t3tools/contracts";
13import {
14 type BranchNameGenerationInput,
15 type ThreadTitleGenerationResult,
16 type TextGenerationShape,
17 TextGeneration,
18} from "../Services/TextGeneration.ts";
19import {
20 buildBranchNamePrompt,
21 buildCommitMessagePrompt,
22 buildPrContentPrompt,
23 buildThreadTitlePrompt,
24} from "../Prompts.ts";
25import {
26 normalizeCliError,
27 sanitizeCommitSubject,
28 sanitizePrTitle,
29 sanitizeThreadTitle,
30 toJsonSchemaObject,
31} from "../Utils.ts";
32import { ServerSettingsService } from "../../serverSettings.ts";
33import {
34 getModelSelectionBooleanOptionValue,
35 getModelSelectionStringOptionValue,
36} from "@t3tools/shared/model";
37
38const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
39const CODEX_TIMEOUT_MS = 180_000;
40const makeCodexTextGeneration = Effect.gen(function* () {
41 const fileSystem = yield* FileSystem.FileSystem;
42 const path = yield* Path.Path;
43 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
44 const serverConfig = yield* Effect.service(ServerConfig);
45 const serverSettingsService = yield* Effect.service(ServerSettingsService);
46
47 type MaterializedImageAttachments = {
48 readonly imagePaths: ReadonlyArray<string>;
49 };
50
51 const readStreamAsString = <E>(
52 operation: string,
53 stream: Stream.Stream<Uint8Array, E>,
54 ): Effect.Effect<string, TextGenerationError> =>
55 stream.pipe(
56 Stream.decodeText(),
57 Stream.runFold(
58 () => "",
59 (acc, chunk) => acc + chunk,
60 ),
61 Effect.mapError((cause) =>
62 normalizeCliError("codex", operation, cause, "Failed to collect process output"),
63 ),
64 );
65
66 const writeTempFile = (
67 operation: string,
68 prefix: string,
69 content: string,
70 ): Effect.Effect<string, TextGenerationError, Scope.Scope> => {
71 return fileSystem
72 .makeTempFileScoped({
73 prefix: `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`,
74 })
75 .pipe(
76 Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)),
77 Effect.mapError(
78 (cause) =>
79 new TextGenerationError({
80 operation,
81 detail: `Failed to write temp file`,
82 cause,
83 }),
84 ),
85 );
86 };
87
88 const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
89 fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
90
91 const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
92 _operation:
93 | "generateCommitMessage"
94 | "generatePrContent"
95 | "generateBranchName"
96 | "generateThreadTitle",
97 attachments: BranchNameGenerationInput["attachments"],
98 ): Effect.fn.Return<MaterializedImageAttachments, TextGenerationError> {
99 if (!attachments || attachments.length === 0) {
100 return { imagePaths: [] };
101 }
102
103 const imagePaths: string[] = [];
104 for (const attachment of attachments) {
105 if (attachment.type !== "image") {
106 continue;
107 }
108
109 const resolvedPath = resolveAttachmentPath({
110 attachmentsDir: serverConfig.attachmentsDir,
111 attachment,
112 });
113 if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
114 continue;
115 }
116 const fileInfo = yield* fileSystem
117 .stat(resolvedPath)
118 .pipe(Effect.catch(() => Effect.succeed(null)));
119 if (!fileInfo || fileInfo.type !== "File") {
120 continue;
121 }
122 imagePaths.push(resolvedPath);
123 }
124 return { imagePaths };
125 });
126
127 const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
128 operation,
129 cwd,
130 prompt,
131 outputSchemaJson,
132 imagePaths = [],
133 cleanupPaths = [],
134 modelSelection,
135 }: {
136 operation:
137 | "generateCommitMessage"
138 | "generatePrContent"
139 | "generateBranchName"
140 | "generateThreadTitle";
141 cwd: string;
142 prompt: string;
143 outputSchemaJson: S;
144 imagePaths?: ReadonlyArray<string>;
145 cleanupPaths?: ReadonlyArray<string>;
146 modelSelection: CodexModelSelection;
147 }): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
148 const schemaPath = yield* writeTempFile(
149 operation,
150 "codex-schema",
151 JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
152 );
153 const outputPath = yield* writeTempFile(operation, "codex-output", "");
154
155 const codexSettings = yield* Effect.map(
156 serverSettingsService.getSettings,
157 (settings) => settings.providers.codex,
158 ).pipe(Effect.catch(() => Effect.undefined));
159
160 const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
161 const reasoningEffort =
162 getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
163 CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
164 const command = ChildProcess.make(
165 codexSettings?.binaryPath || "codex",
166 [
167 "exec",
168 "--ephemeral",
169 "--skip-git-repo-check",
170 "-s",
171 "read-only",
172 "--model",
173 modelSelection.model,
174 "--config",
175 `model_reasoning_effort="${reasoningEffort}"`,
176 ...(getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true
177 ? ["--config", `service_tier="fast"`]
178 : []),
179 "--output-schema",
180 schemaPath,
181 "--output-last-message",
182 outputPath,
183 ...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
184 "-",
185 ],
186 {
187 env: {
188 ...process.env,
189 ...(codexSettings?.homePath
190 ? { CODEX_HOME: expandHomePath(codexSettings.homePath) }
191 : {}),
192 },
193 cwd,
194 shell: process.platform === "win32",
195 stdin: {
196 stream: Stream.encodeText(Stream.make(prompt)),
197 },
198 },
199 );
200
201 const child = yield* commandSpawner
202 .spawn(command)
203 .pipe(
204 Effect.mapError((cause) =>
205 normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
206 ),
207 );
208
209 const [stdout, stderr, exitCode] = yield* Effect.all(
210 [
211 readStreamAsString(operation, child.stdout),
212 readStreamAsString(operation, child.stderr),
213 child.exitCode.pipe(
214 Effect.mapError((cause) =>
215 normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
216 ),
217 ),
218 ],
219 { concurrency: "unbounded" },
220 );
221
222 if (exitCode !== 0) {
223 const stderrDetail = stderr.trim();
224 const stdoutDetail = stdout.trim();
225 const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
226 return yield* new TextGenerationError({
227 operation,
228 detail:
229 detail.length > 0
230 ? `Codex CLI command failed: ${detail}`
231 : `Codex CLI command failed with code ${exitCode}.`,
232 });
233 }
234 });
235
236 const cleanup = Effect.all(
237 [schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
238 {
239 concurrency: "unbounded",
240 },
241 ).pipe(Effect.asVoid);
242
243 return yield* Effect.gen(function* () {
244 yield* runCodexCommand().pipe(
245 Effect.scoped,
246 Effect.timeoutOption(CODEX_TIMEOUT_MS),
247 Effect.flatMap(
248 Option.match({
249 onNone: () =>
250 Effect.fail(
251 new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
252 ),
253 onSome: () => Effect.void,
254 }),
255 ),
256 );
257
258 return yield* fileSystem.readFileString(outputPath).pipe(
259 Effect.mapError(
260 (cause) =>
261 new TextGenerationError({
262 operation,
263 detail: "Failed to read Codex output file.",
264 cause,
265 }),
266 ),
267 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
268 Effect.catchTag("SchemaError", (cause) =>
269 Effect.fail(
270 new TextGenerationError({
271 operation,
272 detail: "Codex returned invalid structured output.",
273 cause,
274 }),
275 ),
276 ),
277 );
278 }).pipe(Effect.ensuring(cleanup));
279 });
280
281 const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
282 "CodexTextGeneration.generateCommitMessage",
283 )(function* (input) {
284 const { prompt, outputSchema } = buildCommitMessagePrompt({
285 branch: input.branch,
286 stagedSummary: input.stagedSummary,
287 stagedPatch: input.stagedPatch,
288 includeBranch: input.includeBranch === true,
289 });
290
291 if (input.modelSelection.provider !== "codex") {
292 return yield* new TextGenerationError({
293 operation: "generateCommitMessage",
294 detail: "Invalid model selection.",
295 });
296 }
297
298 const generated = yield* runCodexJson({
299 operation: "generateCommitMessage",
300 cwd: input.cwd,
301 prompt,
302 outputSchemaJson: outputSchema,
303 modelSelection: input.modelSelection,
304 });
305
306 return {
307 subject: sanitizeCommitSubject(generated.subject),
308 body: generated.body.trim(),
309 ...("branch" in generated && typeof generated.branch === "string"
310 ? { branch: sanitizeFeatureBranchName(generated.branch) }
311 : {}),
312 };
313 });
314
315 const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
316 "CodexTextGeneration.generatePrContent",
317 )(function* (input) {
318 const { prompt, outputSchema } = buildPrContentPrompt({
319 baseBranch: input.baseBranch,
320 headBranch: input.headBranch,
321 commitSummary: input.commitSummary,
322 diffSummary: input.diffSummary,
323 diffPatch: input.diffPatch,
324 });
325
326 if (input.modelSelection.provider !== "codex") {
327 return yield* new TextGenerationError({
328 operation: "generatePrContent",
329 detail: "Invalid model selection.",
330 });
331 }
332
333 const generated = yield* runCodexJson({
334 operation: "generatePrContent",
335 cwd: input.cwd,
336 prompt,
337 outputSchemaJson: outputSchema,
338 modelSelection: input.modelSelection,
339 });
340
341 return {
342 title: sanitizePrTitle(generated.title),
343 body: generated.body.trim(),
344 };
345 });
346
347 const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
348 "CodexTextGeneration.generateBranchName",
349 )(function* (input) {
350 const { imagePaths } = yield* materializeImageAttachments(
351 "generateBranchName",
352 input.attachments,
353 );
354 const { prompt, outputSchema } = buildBranchNamePrompt({
355 message: input.message,
356 attachments: input.attachments,
357 });
358
359 if (input.modelSelection.provider !== "codex") {
360 return yield* new TextGenerationError({
361 operation: "generateBranchName",
362 detail: "Invalid model selection.",
363 });
364 }
365
366 const generated = yield* runCodexJson({
367 operation: "generateBranchName",
368 cwd: input.cwd,
369 prompt,
370 outputSchemaJson: outputSchema,
371 imagePaths,
372 modelSelection: input.modelSelection,
373 });
374
375 return {
376 branch: sanitizeBranchFragment(generated.branch),
377 };
378 });
379
380 const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
381 "CodexTextGeneration.generateThreadTitle",
382 )(function* (input) {
383 const { imagePaths } = yield* materializeImageAttachments(
384 "generateThreadTitle",
385 input.attachments,
386 );
387 const { prompt, outputSchema } = buildThreadTitlePrompt({
388 message: input.message,
389 attachments: input.attachments,
390 });
391
392 if (input.modelSelection.provider !== "codex") {
393 return yield* new TextGenerationError({
394 operation: "generateThreadTitle",
395 detail: "Invalid model selection.",
396 });
397 }
398
399 const generated = yield* runCodexJson({
400 operation: "generateThreadTitle",
401 cwd: input.cwd,
402 prompt,
403 outputSchemaJson: outputSchema,
404 imagePaths,
405 modelSelection: input.modelSelection,
406 });
407
408 return {
409 title: sanitizeThreadTitle(generated.title),
410 } satisfies ThreadTitleGenerationResult;
411 });
412
413 return {
414 generateCommitMessage,
415 generatePrContent,
416 generateBranchName,
417 generateThreadTitle,
418 } satisfies TextGenerationShape;
419});
420
421export const CodexTextGenerationLive = Layer.effect(TextGeneration, makeCodexTextGeneration);