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 {
11 type CodexSettings,
12 DEFAULT_TEXT_GENERATION_REASONING_EFFORT,
13 type ModelSelection,
14 TextGenerationError,
15} from "@t3tools/contracts";
16import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
17import { resolveSpawnCommand } from "@t3tools/shared/shell";
18
19import { resolveAttachmentPath } from "../attachmentStore.ts";
20import * as ServerConfig from "../config.ts";
21import { expandHomePath } from "../pathExpansion.ts";
22import { codexExecLaunchArgs, resolveCodexLaunchArgs } from "../provider/Layers/codexLaunchArgs.ts";
23import * as TextGeneration from "./TextGeneration.ts";
24import {
25 buildBranchNamePrompt,
26 buildCommitMessagePrompt,
27 buildPrContentPrompt,
28 buildThreadTitlePrompt,
29} from "./TextGenerationPrompts.ts";
30import {
31 normalizeCliError,
32 sanitizeCommitSubject,
33 sanitizePrTitle,
34 sanitizeThreadTitle,
35 toJsonSchemaObject,
36} from "./TextGenerationUtils.ts";
37import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
38import { getCodexServiceTierOptionValue } from "../codexModelOptions.ts";
39
40const CODEX_TIMEOUT_MS = 180_000;
41const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
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.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: TextGeneration.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 launchArgs = resolveCodexLaunchArgs(codexConfig.launchArgs, resolvedEnvironment);
182 const reasoningEffort =
183 getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
184 DEFAULT_TEXT_GENERATION_REASONING_EFFORT;
185 const serviceTier = getCodexServiceTierOptionValue(modelSelection);
186 const spawnCommand = yield* resolveSpawnCommand(
187 codexConfig.binaryPath || "codex",
188 [
189 "exec",
190 ...codexExecLaunchArgs(launchArgs),
191 "--ephemeral",
192 "--skip-git-repo-check",
193 "-s",
194 "read-only",
195 "--model",
196 modelSelection.model,
197 "--config",
198 `model_reasoning_effort="${reasoningEffort}"`,
199 ...(serviceTier ? ["--config", `service_tier="${serviceTier}"`] : []),
200 "--output-schema",
201 schemaPath,
202 "--output-last-message",
203 outputPath,
204 ...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
205 "-",
206 ],
207 { env: resolvedEnvironment },
208 );
209 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
210 env: {
211 ...resolvedEnvironment,
212 ...(codexConfig.homePath ? { CODEX_HOME: expandHomePath(codexConfig.homePath) } : {}),
213 },
214 cwd,
215 shell: spawnCommand.shell,
216 stdin: {
217 stream: Stream.encodeText(Stream.make(prompt)),
218 },
219 });
220
221 const child = yield* commandSpawner
222 .spawn(command)
223 .pipe(
224 Effect.mapError((cause) =>
225 normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
226 ),
227 );
228
229 const [stdout, stderr, exitCode] = yield* Effect.all(
230 [
231 readStreamAsString(operation, child.stdout),
232 readStreamAsString(operation, child.stderr),
233 child.exitCode.pipe(
234 Effect.mapError((cause) =>
235 normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
236 ),
237 ),
238 ],
239 { concurrency: "unbounded" },
240 );
241
242 if (exitCode !== 0) {
243 const stderrDetail = stderr.trim();
244 const stdoutDetail = stdout.trim();
245 const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
246 return yield* new TextGenerationError({
247 operation,
248 detail:
249 detail.length > 0
250 ? `Codex CLI command failed: ${detail}`
251 : `Codex CLI command failed with code ${exitCode}.`,
252 });
253 }
254 });
255
256 const cleanup = Effect.all(
257 [schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
258 {
259 concurrency: "unbounded",
260 },
261 ).pipe(Effect.asVoid);
262
263 return yield* Effect.gen(function* () {
264 yield* runCodexCommand().pipe(
265 Effect.scoped,
266 Effect.timeoutOption(CODEX_TIMEOUT_MS),
267 Effect.flatMap(
268 Option.match({
269 onNone: () =>
270 Effect.fail(
271 new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
272 ),
273 onSome: () => Effect.void,
274 }),
275 ),
276 );
277
278 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
279
280 return yield* fileSystem.readFileString(outputPath).pipe(
281 Effect.mapError(
282 (cause) =>
283 new TextGenerationError({
284 operation,
285 detail: "Failed to read Codex output file.",
286 cause,
287 }),
288 ),
289 Effect.flatMap(decodeOutput),
290 Effect.catchTags({
291 SchemaError: (cause) =>
292 Effect.fail(
293 new TextGenerationError({
294 operation,
295 detail: "Codex returned invalid structured output.",
296 cause,
297 }),
298 ),
299 }),
300 );
301 }).pipe(Effect.ensuring(cleanup));
302 });
303
304 const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
305 Effect.fn("CodexTextGeneration.generateCommitMessage")(function* (input) {
306 const { prompt, outputSchema } = buildCommitMessagePrompt({
307 branch: input.branch,
308 stagedSummary: input.stagedSummary,
309 stagedPatch: input.stagedPatch,
310 includeBranch: input.includeBranch === true,
311 policy: input.policy,
312 });
313
314 const generated = yield* runCodexJson({
315 operation: "generateCommitMessage",
316 cwd: input.cwd,
317 prompt,
318 outputSchemaJson: outputSchema,
319 modelSelection: input.modelSelection,
320 });
321
322 return {
323 subject: sanitizeCommitSubject(generated.subject),
324 body: generated.body.trim(),
325 ...("branch" in generated && typeof generated.branch === "string"
326 ? { branch: sanitizeFeatureBranchName(generated.branch) }
327 : {}),
328 };
329 });
330
331 const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
332 Effect.fn("CodexTextGeneration.generatePrContent")(function* (input) {
333 const { prompt, outputSchema } = buildPrContentPrompt({
334 baseBranch: input.baseBranch,
335 headBranch: input.headBranch,
336 commitSummary: input.commitSummary,
337 diffSummary: input.diffSummary,
338 diffPatch: input.diffPatch,
339 policy: input.policy,
340 changeRequestTemplate: input.changeRequestTemplate,
341 });
342
343 const generated = yield* runCodexJson({
344 operation: "generatePrContent",
345 cwd: input.cwd,
346 prompt,
347 outputSchemaJson: outputSchema,
348 modelSelection: input.modelSelection,
349 });
350
351 return {
352 title: sanitizePrTitle(generated.title),
353 body: generated.body.trim(),
354 };
355 });
356
357 const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
358 Effect.fn("CodexTextGeneration.generateBranchName")(function* (input) {
359 const { imagePaths } = yield* materializeImageAttachments(
360 "generateBranchName",
361 input.attachments,
362 );
363 const { prompt, outputSchema } = buildBranchNamePrompt({
364 message: input.message,
365 attachments: input.attachments,
366 });
367
368 const generated = yield* runCodexJson({
369 operation: "generateBranchName",
370 cwd: input.cwd,
371 prompt,
372 outputSchemaJson: outputSchema,
373 imagePaths,
374 modelSelection: input.modelSelection,
375 });
376
377 return {
378 branch: sanitizeBranchFragment(generated.branch),
379 };
380 });
381
382 const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
383 Effect.fn("CodexTextGeneration.generateThreadTitle")(function* (input) {
384 const { imagePaths } = yield* materializeImageAttachments(
385 "generateThreadTitle",
386 input.attachments,
387 );
388 const { prompt, outputSchema } = buildThreadTitlePrompt({
389 message: input.message,
390 previousTitle: input.previousTitle,
391 attachments: input.attachments,
392 });
393
394 const generated = yield* runCodexJson({
395 operation: "generateThreadTitle",
396 cwd: input.cwd,
397 prompt,
398 outputSchemaJson: outputSchema,
399 imagePaths,
400 modelSelection: input.modelSelection,
401 });
402
403 return {
404 title: sanitizeThreadTitle(generated.title),
405 } satisfies TextGeneration.ThreadTitleGenerationResult;
406 });
407
408 return {
409 generateCommitMessage,
410 generatePrContent,
411 generateBranchName,
412 generateThreadTitle,
413 } satisfies TextGeneration.TextGeneration["Service"];
414});