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

CodexTextGeneration.ts

392 lines11.9 KB

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