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