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

CodexTextGeneration.ts

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