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