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

CodexTextGeneration.ts

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