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