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