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

CodexTextGeneration.ts

427 lines13.8 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.ignore);
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.forEach(
267 [schemaPath, outputPath, ...cleanupPaths],
268 (filePath) => safeUnlink(filePath),
269 {
270 concurrency: "unbounded",
271 },
272 ).pipe(Effect.asVoid);
273​
274 return yield* Effect.gen(function* () {
275 yield* runCodexCommand().pipe(
276 Effect.scoped,
277 Effect.timeoutOption(CODEX_TIMEOUT_MS),
278 Effect.flatMap(
279 Option.match({
280 onNone: () =>
281 Effect.fail(
282 new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
283 ),
284 onSome: () => Effect.void,
285 }),
286 ),
287 );
288​
289 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
290​
291 return yield* fileSystem.readFileString(outputPath).pipe(
292 Effect.mapError(
293 (cause) =>
294 new TextGenerationError({
295 operation,
296 detail: "Failed to read Codex output file.",
297 cause,
298 }),
299 ),
300 Effect.flatMap(decodeOutput),
301 Effect.catchTags({
302 SchemaError: (cause) =>
303 Effect.fail(
304 new TextGenerationError({
305 operation,
306 detail: "Codex returned invalid structured output.",
307 cause,
308 }),
309 ),
310 }),
311 );
312 }).pipe(Effect.ensuring(cleanup));
313 });
314​
315 const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
316 Effect.fn("CodexTextGeneration.generateCommitMessage")(function* (input) {
317 const { prompt, outputSchema } = buildCommitMessagePrompt({
318 branch: input.branch,
319 stagedSummary: input.stagedSummary,
320 stagedPatch: input.stagedPatch,
321 includeBranch: input.includeBranch === true,
322 policy: input.policy,
323 });
324​
325 const generated = yield* runCodexJson({
326 operation: "generateCommitMessage",
327 cwd: input.cwd,
328 prompt,
329 outputSchemaJson: outputSchema,
330 modelSelection: input.modelSelection,
331 });
332​
333 return {
334 subject: sanitizeCommitSubject(generated.subject),
335 body: generated.body.trim(),
336 ...("branch" in generated && typeof generated.branch === "string"
337 ? { branch: sanitizeFeatureBranchName(generated.branch) }
338 : {}),
339 };
340 });
341​
342 const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
343 Effect.fn("CodexTextGeneration.generatePrContent")(function* (input) {
344 const { prompt, outputSchema } = buildPrContentPrompt({
345 baseBranch: input.baseBranch,
346 headBranch: input.headBranch,
347 commitSummary: input.commitSummary,
348 diffSummary: input.diffSummary,
349 diffPatch: input.diffPatch,
350 policy: input.policy,
351 changeRequestTemplate: input.changeRequestTemplate,
352 });
353​
354 const generated = yield* runCodexJson({
355 operation: "generatePrContent",
356 cwd: input.cwd,
357 prompt,
358 outputSchemaJson: outputSchema,
359 modelSelection: input.modelSelection,
360 });
361​
362 return {
363 title: sanitizePrTitle(generated.title),
364 body: generated.body.trim(),
365 };
366 });
367​
368 const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
369 Effect.fn("CodexTextGeneration.generateBranchName")(function* (input) {
370 const { imagePaths } = yield* materializeImageAttachments(
371 "generateBranchName",
372 input.attachments,
373 );
374 const { prompt, outputSchema } = buildBranchNamePrompt({
375 message: input.message,
376 attachments: input.attachments,
377 });
378​
379 const generated = yield* runCodexJson({
380 operation: "generateBranchName",
381 cwd: input.cwd,
382 prompt,
383 outputSchemaJson: outputSchema,
384 imagePaths,
385 modelSelection: input.modelSelection,
386 });
387​
388 return {
389 branch: sanitizeBranchFragment(generated.branch),
390 };
391 });
392​
393 const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
394 Effect.fn("CodexTextGeneration.generateThreadTitle")(function* (input) {
395 const { imagePaths } = yield* materializeImageAttachments(
396 "generateThreadTitle",
397 input.attachments,
398 );
399 const { prompt, outputSchema } = buildThreadTitlePrompt({
400 message: input.message,
401 previousTitle: input.previousTitle,
402 linkedContext: input.linkedContext,
403 attachments: input.attachments,
404 });
405​
406 const generated = yield* runCodexJson({
407 operation: "generateThreadTitle",
408 cwd: input.cwd,
409 prompt,
410 outputSchemaJson: outputSchema,
411 imagePaths,
412 modelSelection: input.modelSelection,
413 });
414​
415 return {
416 title: sanitizeThreadTitle(generated.title),
417 ...(generated.needsRefinement ? { needsRefinement: true } : {}),
418 } satisfies TextGeneration.ThreadTitleGenerationResult;
419 });
420​
421 return {
422 generateCommitMessage,
423 generatePrContent,
424 generateBranchName,
425 generateThreadTitle,
426 } satisfies TextGeneration.TextGeneration["Service"];
427});