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