Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CodexTextGeneration.ts

407 lines13.2 KB

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