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 { sanitizeBranchFragment, 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 writeTempFile = (
83 operation: string,
84 prefix: string,
85 content: string,
86 ): Effect.Effect<string, TextGenerationError, Scope.Scope> =>
87 fileSystem
88 .makeTempFileScoped({
89 prefix: `t3code-${prefix}-${process.pid}-`,
90 })
91 .pipe(
92 Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)),
93 Effect.mapError(
94 (cause) =>
95 new TextGenerationError({
96 operation,
97 detail: `Failed to write temp file`,
98 cause,
99 }),
100 ),
101 );
102
103 const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
104 fileSystem.remove(filePath).pipe(Effect.ignore);
105
106 const encodeJsonForOperation = (
107 operation:
108 | "generateCommitMessage"
109 | "generatePrContent"
110 | "generateBranchName"
111 | "generateThreadTitle",
112 value: unknown,
113 ): Effect.Effect<string, TextGenerationError> =>
114 encodeJsonString(value).pipe(
115 Effect.mapError(
116 (cause) =>
117 new TextGenerationError({
118 operation,
119 detail: "Failed to encode structured output schema.",
120 cause,
121 }),
122 ),
123 );
124
125 const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
126 _operation:
127 | "generateCommitMessage"
128 | "generatePrContent"
129 | "generateBranchName"
130 | "generateThreadTitle",
131 attachments: TextGeneration.BranchNameGenerationInput["attachments"],
132 ): Effect.fn.Return<MaterializedImageAttachments, TextGenerationError> {
133 if (!attachments || attachments.length === 0) {
134 return { imagePaths: [] };
135 }
136
137 const imagePaths: string[] = [];
138 for (const attachment of attachments) {
139 if (attachment.type !== "image") {
140 continue;
141 }
142
143 const resolvedPath = resolveAttachmentPath({
144 attachmentsDir: serverConfig.attachmentsDir,
145 attachment,
146 });
147 if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
148 continue;
149 }
150 const fileInfo = yield* fileSystem.stat(resolvedPath).pipe(Effect.orElseSucceed(() => null));
151 if (!fileInfo || fileInfo.type !== "File") {
152 continue;
153 }
154 imagePaths.push(resolvedPath);
155 }
156 return { imagePaths };
157 });
158
159 const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
160 operation,
161 cwd,
162 prompt,
163 outputSchemaJson,
164 imagePaths = [],
165 cleanupPaths = [],
166 modelSelection,
167 }: {
168 operation:
169 | "generateCommitMessage"
170 | "generatePrContent"
171 | "generateBranchName"
172 | "generateThreadTitle";
173 cwd: string;
174 prompt: string;
175 outputSchemaJson: S;
176 imagePaths?: ReadonlyArray<string>;
177 cleanupPaths?: ReadonlyArray<string>;
178 modelSelection: ModelSelection;
179 }): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
180 const schemaJson = yield* encodeJsonForOperation(
181 operation,
182 toJsonSchemaObject(outputSchemaJson),
183 );
184 const schemaPath = yield* writeTempFile(operation, "codex-schema", schemaJson);
185 const outputPath = yield* writeTempFile(operation, "codex-output", "");
186
187 const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
188 const resolved = resolveRuntime
189 ? yield* resolveRuntime.pipe(
190 Effect.mapError(
191 (cause) => new TextGenerationError({ operation, detail: cause.detail }),
192 ),
193 )
194 : undefined;
195 const effectiveConfig = resolved?.config ?? codexConfig;
196 const effectiveEnvironment = resolved?.environment ?? resolvedEnvironment;
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(effectiveConfig.launchArgs, effectiveEnvironment);
206 const reasoningEffort =
207 getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
208 DEFAULT_TEXT_GENERATION_REASONING_EFFORT;
209 const serviceTier = resolved ? undefined : getCodexServiceTierOptionValue(modelSelection);
210 const spawnCommand = yield* resolveSpawnCommand(
211 effectiveConfig.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: effectiveEnvironment },
232 );
233 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
234 env: {
235 ...effectiveEnvironment,
236 ...(effectiveConfig.homePath
237 ? { CODEX_HOME: expandHomePath(effectiveConfig.homePath) }
238 : {}),
239 },
240 cwd,
241 shell: spawnCommand.shell,
242 stdin: {
243 stream: Stream.encodeText(Stream.make(prompt)),
244 },
245 });
246
247 const child = yield* commandSpawner
248 .spawn(command)
249 .pipe(
250 Effect.mapError((cause) =>
251 normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
252 ),
253 );
254
255 const [stdout, stderr, exitCode] = yield* Effect.all(
256 [
257 readStreamAsString(operation, child.stdout),
258 readStreamAsString(operation, child.stderr),
259 child.exitCode.pipe(
260 Effect.mapError((cause) =>
261 normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
262 ),
263 ),
264 ],
265 { concurrency: "unbounded" },
266 );
267
268 if (exitCode !== 0) {
269 const stderrDetail = stderr.trim();
270 const stdoutDetail = stdout.trim();
271 const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
272 return yield* new TextGenerationError({
273 operation,
274 detail:
275 detail.length > 0
276 ? `Codex CLI command failed: ${detail}`
277 : `Codex CLI command failed with code ${exitCode}.`,
278 });
279 }
280 });
281
282 const cleanup = Effect.forEach(
283 [schemaPath, outputPath, ...cleanupPaths],
284 (filePath) => safeUnlink(filePath),
285 {
286 concurrency: "unbounded",
287 },
288 ).pipe(Effect.asVoid);
289
290 return yield* Effect.gen(function* () {
291 yield* runCodexCommand().pipe(
292 Effect.scoped,
293 Effect.timeoutOption(CODEX_TIMEOUT_MS),
294 Effect.flatMap(
295 Option.match({
296 onNone: () =>
297 Effect.fail(
298 new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
299 ),
300 onSome: () => Effect.void,
301 }),
302 ),
303 );
304
305 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
306
307 return yield* fileSystem.readFileString(outputPath).pipe(
308 Effect.mapError(
309 (cause) =>
310 new TextGenerationError({
311 operation,
312 detail: "Failed to read Codex output file.",
313 cause,
314 }),
315 ),
316 Effect.flatMap(decodeOutput),
317 Effect.catchTags({
318 SchemaError: (cause) =>
319 Effect.fail(
320 new TextGenerationError({
321 operation,
322 detail: "Codex returned invalid structured output.",
323 cause,
324 }),
325 ),
326 }),
327 );
328 }).pipe(Effect.ensuring(cleanup));
329 });
330
331 const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
332 Effect.fn("CodexTextGeneration.generateCommitMessage")(function* (input) {
333 const { prompt, outputSchema } = buildCommitMessagePrompt({
334 branch: input.branch,
335 stagedSummary: input.stagedSummary,
336 stagedPatch: input.stagedPatch,
337 includeBranch: input.includeBranch === true,
338 policy: input.policy,
339 });
340
341 const generated = yield* runCodexJson({
342 operation: "generateCommitMessage",
343 cwd: input.cwd,
344 prompt,
345 outputSchemaJson: outputSchema,
346 modelSelection: input.modelSelection,
347 });
348
349 return {
350 subject: sanitizeCommitSubject(generated.subject),
351 body: generated.body.trim(),
352 ...("branch" in generated && typeof generated.branch === "string"
353 ? { branch: sanitizeFeatureBranchName(generated.branch) }
354 : {}),
355 };
356 });
357
358 const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
359 Effect.fn("CodexTextGeneration.generatePrContent")(function* (input) {
360 const { prompt, outputSchema } = buildPrContentPrompt({
361 baseBranch: input.baseBranch,
362 headBranch: input.headBranch,
363 commitSummary: input.commitSummary,
364 diffSummary: input.diffSummary,
365 diffPatch: input.diffPatch,
366 policy: input.policy,
367 changeRequestTemplate: input.changeRequestTemplate,
368 });
369
370 const generated = yield* runCodexJson({
371 operation: "generatePrContent",
372 cwd: input.cwd,
373 prompt,
374 outputSchemaJson: outputSchema,
375 modelSelection: input.modelSelection,
376 });
377
378 return {
379 title: sanitizePrTitle(generated.title),
380 body: generated.body.trim(),
381 };
382 });
383
384 const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
385 Effect.fn("CodexTextGeneration.generateBranchName")(function* (input) {
386 const { imagePaths } = yield* materializeImageAttachments(
387 "generateBranchName",
388 input.attachments,
389 );
390 const { prompt, outputSchema } = buildBranchNamePrompt({
391 message: input.message,
392 attachments: input.attachments,
393 });
394
395 const generated = yield* runCodexJson({
396 operation: "generateBranchName",
397 cwd: input.cwd,
398 prompt,
399 outputSchemaJson: outputSchema,
400 imagePaths,
401 modelSelection: input.modelSelection,
402 });
403
404 return {
405 branch: sanitizeBranchFragment(generated.branch),
406 };
407 });
408
409 const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
410 Effect.fn("CodexTextGeneration.generateThreadTitle")(function* (input) {
411 const { imagePaths } = yield* materializeImageAttachments(
412 "generateThreadTitle",
413 input.attachments,
414 );
415 const { prompt, outputSchema } = buildThreadTitlePrompt({
416 message: input.message,
417 previousTitle: input.previousTitle,
418 linkedContext: input.linkedContext,
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 ...(generated.needsRefinement ? { needsRefinement: true } : {}),
434 } satisfies TextGeneration.ThreadTitleGenerationResult;
435 });
436
437 return {
438 generateCommitMessage,
439 generatePrContent,
440 generateBranchName,
441 generateThreadTitle,
442 } satisfies TextGeneration.TextGeneration["Service"];
443});