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