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

CodexTextGeneration.ts

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