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 "@t3tools/contracts";
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 = Effect.fn("materializeImageAttachments")(function* (
89 _operation:
90 | "generateCommitMessage"
91 | "generatePrContent"
92 | "generateBranchName"
93 | "generateThreadTitle",
94 attachments: BranchNameGenerationInput["attachments"],
95 ): Effect.fn.Return<MaterializedImageAttachments, TextGenerationError> {
96 if (!attachments || attachments.length === 0) {
97 return { imagePaths: [] };
98 }
99
100 const imagePaths: string[] = [];
101 for (const attachment of attachments) {
102 if (attachment.type !== "image") {
103 continue;
104 }
105
106 const resolvedPath = resolveAttachmentPath({
107 attachmentsDir: serverConfig.attachmentsDir,
108 attachment,
109 });
110 if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
111 continue;
112 }
113 const fileInfo = yield* fileSystem
114 .stat(resolvedPath)
115 .pipe(Effect.catch(() => Effect.succeed(null)));
116 if (!fileInfo || fileInfo.type !== "File") {
117 continue;
118 }
119 imagePaths.push(resolvedPath);
120 }
121 return { imagePaths };
122 });
123
124 const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
125 operation,
126 cwd,
127 prompt,
128 outputSchemaJson,
129 imagePaths = [],
130 cleanupPaths = [],
131 modelSelection,
132 }: {
133 operation:
134 | "generateCommitMessage"
135 | "generatePrContent"
136 | "generateBranchName"
137 | "generateThreadTitle";
138 cwd: string;
139 prompt: string;
140 outputSchemaJson: S;
141 imagePaths?: ReadonlyArray<string>;
142 cleanupPaths?: ReadonlyArray<string>;
143 modelSelection: CodexModelSelection;
144 }): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
145 const schemaPath = yield* writeTempFile(
146 operation,
147 "codex-schema",
148 JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
149 );
150 const outputPath = yield* writeTempFile(operation, "codex-output", "");
151
152 const codexSettings = yield* Effect.map(
153 serverSettingsService.getSettings,
154 (settings) => settings.providers.codex,
155 ).pipe(Effect.catch(() => Effect.undefined));
156
157 const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
158 const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
159 getCodexModelCapabilities(modelSelection.model),
160 modelSelection.options,
161 );
162 const reasoningEffort =
163 modelSelection.options?.reasoningEffort ?? 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 ...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
177 "--output-schema",
178 schemaPath,
179 "--output-last-message",
180 outputPath,
181 ...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
182 "-",
183 ],
184 {
185 env: {
186 ...process.env,
187 ...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
188 },
189 cwd,
190 shell: process.platform === "win32",
191 stdin: {
192 stream: Stream.encodeText(Stream.make(prompt)),
193 },
194 },
195 );
196
197 const child = yield* commandSpawner
198 .spawn(command)
199 .pipe(
200 Effect.mapError((cause) =>
201 normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
202 ),
203 );
204
205 const [stdout, stderr, exitCode] = yield* Effect.all(
206 [
207 readStreamAsString(operation, child.stdout),
208 readStreamAsString(operation, child.stderr),
209 child.exitCode.pipe(
210 Effect.mapError((cause) =>
211 normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
212 ),
213 ),
214 ],
215 { concurrency: "unbounded" },
216 );
217
218 if (exitCode !== 0) {
219 const stderrDetail = stderr.trim();
220 const stdoutDetail = stdout.trim();
221 const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
222 return yield* new TextGenerationError({
223 operation,
224 detail:
225 detail.length > 0
226 ? `Codex CLI command failed: ${detail}`
227 : `Codex CLI command failed with code ${exitCode}.`,
228 });
229 }
230 });
231
232 const cleanup = Effect.all(
233 [schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
234 {
235 concurrency: "unbounded",
236 },
237 ).pipe(Effect.asVoid);
238
239 return yield* Effect.gen(function* () {
240 yield* runCodexCommand().pipe(
241 Effect.scoped,
242 Effect.timeoutOption(CODEX_TIMEOUT_MS),
243 Effect.flatMap(
244 Option.match({
245 onNone: () =>
246 Effect.fail(
247 new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
248 ),
249 onSome: () => Effect.void,
250 }),
251 ),
252 );
253
254 return yield* fileSystem.readFileString(outputPath).pipe(
255 Effect.mapError(
256 (cause) =>
257 new TextGenerationError({
258 operation,
259 detail: "Failed to read Codex output file.",
260 cause,
261 }),
262 ),
263 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
264 Effect.catchTag("SchemaError", (cause) =>
265 Effect.fail(
266 new TextGenerationError({
267 operation,
268 detail: "Codex returned invalid structured output.",
269 cause,
270 }),
271 ),
272 ),
273 );
274 }).pipe(Effect.ensuring(cleanup));
275 });
276
277 const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
278 "CodexTextGeneration.generateCommitMessage",
279 )(function* (input) {
280 const { prompt, outputSchema } = buildCommitMessagePrompt({
281 branch: input.branch,
282 stagedSummary: input.stagedSummary,
283 stagedPatch: input.stagedPatch,
284 includeBranch: input.includeBranch === true,
285 });
286
287 if (input.modelSelection.provider !== "codex") {
288 return yield* new TextGenerationError({
289 operation: "generateCommitMessage",
290 detail: "Invalid model selection.",
291 });
292 }
293
294 const generated = yield* runCodexJson({
295 operation: "generateCommitMessage",
296 cwd: input.cwd,
297 prompt,
298 outputSchemaJson: outputSchema,
299 modelSelection: input.modelSelection,
300 });
301
302 return {
303 subject: sanitizeCommitSubject(generated.subject),
304 body: generated.body.trim(),
305 ...("branch" in generated && typeof generated.branch === "string"
306 ? { branch: sanitizeFeatureBranchName(generated.branch) }
307 : {}),
308 };
309 });
310
311 const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
312 "CodexTextGeneration.generatePrContent",
313 )(function* (input) {
314 const { prompt, outputSchema } = buildPrContentPrompt({
315 baseBranch: input.baseBranch,
316 headBranch: input.headBranch,
317 commitSummary: input.commitSummary,
318 diffSummary: input.diffSummary,
319 diffPatch: input.diffPatch,
320 });
321
322 if (input.modelSelection.provider !== "codex") {
323 return yield* new TextGenerationError({
324 operation: "generatePrContent",
325 detail: "Invalid model selection.",
326 });
327 }
328
329 const generated = yield* runCodexJson({
330 operation: "generatePrContent",
331 cwd: input.cwd,
332 prompt,
333 outputSchemaJson: outputSchema,
334 modelSelection: input.modelSelection,
335 });
336
337 return {
338 title: sanitizePrTitle(generated.title),
339 body: generated.body.trim(),
340 };
341 });
342
343 const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
344 "CodexTextGeneration.generateBranchName",
345 )(function* (input) {
346 const { imagePaths } = yield* materializeImageAttachments(
347 "generateBranchName",
348 input.attachments,
349 );
350 const { prompt, outputSchema } = buildBranchNamePrompt({
351 message: input.message,
352 attachments: input.attachments,
353 });
354
355 if (input.modelSelection.provider !== "codex") {
356 return yield* new TextGenerationError({
357 operation: "generateBranchName",
358 detail: "Invalid model selection.",
359 });
360 }
361
362 const generated = yield* runCodexJson({
363 operation: "generateBranchName",
364 cwd: input.cwd,
365 prompt,
366 outputSchemaJson: outputSchema,
367 imagePaths,
368 modelSelection: input.modelSelection,
369 });
370
371 return {
372 branch: sanitizeBranchFragment(generated.branch),
373 };
374 });
375
376 const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
377 "CodexTextGeneration.generateThreadTitle",
378 )(function* (input) {
379 const { imagePaths } = yield* materializeImageAttachments(
380 "generateThreadTitle",
381 input.attachments,
382 );
383 const { prompt, outputSchema } = buildThreadTitlePrompt({
384 message: input.message,
385 attachments: input.attachments,
386 });
387
388 if (input.modelSelection.provider !== "codex") {
389 return yield* new TextGenerationError({
390 operation: "generateThreadTitle",
391 detail: "Invalid model selection.",
392 });
393 }
394
395 const generated = yield* runCodexJson({
396 operation: "generateThreadTitle",
397 cwd: input.cwd,
398 prompt,
399 outputSchemaJson: outputSchema,
400 imagePaths,
401 modelSelection: input.modelSelection,
402 });
403
404 return {
405 title: sanitizeThreadTitle(generated.title),
406 } satisfies ThreadTitleGenerationResult;
407 });
408
409 return {
410 generateCommitMessage,
411 generatePrContent,
412 generateBranchName,
413 generateThreadTitle,
414 } satisfies TextGenerationShape;
415});
416
417export const CodexTextGenerationLive = Layer.effect(TextGeneration, makeCodexTextGeneration);