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

CodexTextGeneration.ts

416 lines12.7 KB

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