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