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

CodexTextGeneration.ts

411 lines13.3 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.fromJsonString(Schema.Unknown));
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 policy: input.policy,
309 });
310​
311 const generated = yield* runCodexJson({
312 operation: "generateCommitMessage",
313 cwd: input.cwd,
314 prompt,
315 outputSchemaJson: outputSchema,
316 modelSelection: input.modelSelection,
317 });
318​
319 return {
320 subject: sanitizeCommitSubject(generated.subject),
321 body: generated.body.trim(),
322 ...("branch" in generated && typeof generated.branch === "string"
323 ? { branch: sanitizeFeatureBranchName(generated.branch) }
324 : {}),
325 };
326 });
327​
328 const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
329 Effect.fn("CodexTextGeneration.generatePrContent")(function* (input) {
330 const { prompt, outputSchema } = buildPrContentPrompt({
331 baseBranch: input.baseBranch,
332 headBranch: input.headBranch,
333 commitSummary: input.commitSummary,
334 diffSummary: input.diffSummary,
335 diffPatch: input.diffPatch,
336 policy: input.policy,
337 changeRequestTemplate: input.changeRequestTemplate,
338 });
339​
340 const generated = yield* runCodexJson({
341 operation: "generatePrContent",
342 cwd: input.cwd,
343 prompt,
344 outputSchemaJson: outputSchema,
345 modelSelection: input.modelSelection,
346 });
347​
348 return {
349 title: sanitizePrTitle(generated.title),
350 body: generated.body.trim(),
351 };
352 });
353​
354 const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
355 Effect.fn("CodexTextGeneration.generateBranchName")(function* (input) {
356 const { imagePaths } = yield* materializeImageAttachments(
357 "generateBranchName",
358 input.attachments,
359 );
360 const { prompt, outputSchema } = buildBranchNamePrompt({
361 message: input.message,
362 attachments: input.attachments,
363 });
364​
365 const generated = yield* runCodexJson({
366 operation: "generateBranchName",
367 cwd: input.cwd,
368 prompt,
369 outputSchemaJson: outputSchema,
370 imagePaths,
371 modelSelection: input.modelSelection,
372 });
373​
374 return {
375 branch: sanitizeBranchFragment(generated.branch),
376 };
377 });
378​
379 const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
380 Effect.fn("CodexTextGeneration.generateThreadTitle")(function* (input) {
381 const { imagePaths } = yield* materializeImageAttachments(
382 "generateThreadTitle",
383 input.attachments,
384 );
385 const { prompt, outputSchema } = buildThreadTitlePrompt({
386 message: input.message,
387 previousTitle: input.previousTitle,
388 attachments: input.attachments,
389 });
390​
391 const generated = yield* runCodexJson({
392 operation: "generateThreadTitle",
393 cwd: input.cwd,
394 prompt,
395 outputSchemaJson: outputSchema,
396 imagePaths,
397 modelSelection: input.modelSelection,
398 });
399​
400 return {
401 title: sanitizeThreadTitle(generated.title),
402 } satisfies TextGeneration.ThreadTitleGenerationResult;
403 });
404​
405 return {
406 generateCommitMessage,
407 generatePrContent,
408 generateBranchName,
409 generateThreadTitle,
410 } satisfies TextGeneration.TextGeneration["Service"];
411});