Open History to see the last commit
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/process";
9
10import {
11 type CodexSettings,
12 DEFAULT_TEXT_GENERATION_REASONING_EFFORT,
13 type ServerProviderModel,
14 TextGenerationError,
15} from "@t3tools/contracts";
16import { resolveSpawnCommand } from "@t3tools/shared/shell";
17
18import { resolveAttachmentPath } from "../attachmentStore.ts";
19import * as ServerConfig from "../config.ts";
20import { expandHomePath } from "../pathExpansion.ts";
21import { codexExecLaunchArgs, resolveCodexLaunchArgs } from "../provider/codexLaunchArgs.ts";
22import * as TextGenerationOperations from "./TextGenerationOperations.ts";
23import { normalizeCliError, toJsonSchemaObject } from "./TextGenerationUtils.ts";
24import { codexModelFamily, getModelSelectionStringOptionValue } from "@t3tools/shared/model";
25import { getCodexServiceTierOptionValue } from "../codexModelOptions.ts";
26
27const CODEX_TIMEOUT_MS = 180_000;
28const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
29/**
30 * Build a Codex text-generation closure bound to a specific `CodexSettings`
31 * payload. See `makeCodexAdapter` for the overall per-instance rationale.
32 */
33export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(function* (
34 codexConfig: CodexSettings,
35 environment?: NodeJS.ProcessEnv,
36 getModels: Effect.Effect<ReadonlyArray<ServerProviderModel>> = Effect.succeed([]),
37 resolveRuntime?: Effect.Effect<
38 import("../provider/CodexManagedRuntime.ts").CodexEffectiveRuntime,
39 import("@t3tools/contracts").ProviderSetupError,
40 Scope.Scope
41 >,
42) {
43 const fileSystem = yield* FileSystem.FileSystem;
44 const path = yield* Path.Path;
45 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
46 const serverConfig = yield* Effect.service(ServerConfig.ServerConfig);
47 const resolvedEnvironment = environment ?? process.env;
48
49 const readStreamAsString = <E>(
50 operation: string,
51 stream: Stream.Stream<Uint8Array, E>,
52 ): Effect.Effect<string, TextGenerationError> =>
53 stream.pipe(
54 Stream.decodeText(),
55 Stream.runFold(
56 () => "",
57 (acc, chunk) => acc + chunk,
58 ),
59 Effect.mapError((cause) =>
60 normalizeCliError("codex", operation, cause, "Failed to collect process output"),
61 ),
62 );
63
64 const removeTempFileDir = (filePath: string): Effect.Effect<void, never> =>
65 fileSystem
66 .remove(path.dirname(filePath), { recursive: true })
67 .pipe(Effect.catch(() => Effect.void));
68
69 // Deliberately unscoped: text generation runs from background fibers whose
70 // ambient scope may already be closed (a closed scope reaps the temp
71 // directory the moment it is created). Each allocation removes its own
72 // directory on failure; success-path cleanup is explicit in runCodexJson.
73 const writeTempFile = (
74 operation: string,
75 prefix: string,
76 content: string,
77 ): Effect.Effect<string, TextGenerationError> =>
78 fileSystem
79 .makeTempFile({
80 prefix: `t3code-${prefix}-${process.pid}-`,
81 })
82 .pipe(
83 Effect.tap((filePath) =>
84 fileSystem
85 .writeFileString(filePath, content)
86 .pipe(Effect.onError(() => removeTempFileDir(filePath))),
87 ),
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 encodeJsonForOperation = (
99 operation: TextGenerationOperations.Operation,
100 value: unknown,
101 ): Effect.Effect<string, TextGenerationError> =>
102 encodeJsonString(value).pipe(
103 Effect.mapError(
104 (cause) =>
105 new TextGenerationError({
106 operation,
107 detail: "Failed to encode structured output schema.",
108 cause,
109 }),
110 ),
111 );
112
113 const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
114 attachments: TextGenerationOperations.Request<Schema.Top>["attachments"],
115 ) {
116 if (!attachments || attachments.length === 0) {
117 return [];
118 }
119
120 const imagePaths: string[] = [];
121 for (const attachment of attachments) {
122 if (attachment.type !== "image") {
123 continue;
124 }
125
126 const resolvedPath = resolveAttachmentPath({
127 attachmentsDir: serverConfig.attachmentsDir,
128 attachment,
129 });
130 if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
131 continue;
132 }
133 const fileInfo = yield* fileSystem.stat(resolvedPath).pipe(Effect.orElseSucceed(() => null));
134 if (!fileInfo || fileInfo.type !== "File") {
135 continue;
136 }
137 imagePaths.push(resolvedPath);
138 }
139 return imagePaths;
140 });
141
142 const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
143 operation,
144 cwd,
145 prompt,
146 outputSchema: outputSchemaJson,
147 modelSelection,
148 attachments,
149 }: TextGenerationOperations.Request<S>): Effect.fn.Return<
150 S["Type"],
151 TextGenerationError,
152 S["DecodingServices"]
153 > {
154 const imagePaths = yield* materializeImageAttachments(attachments);
155 const schemaJson = yield* encodeJsonForOperation(
156 operation,
157 toJsonSchemaObject(outputSchemaJson),
158 );
159 const schemaPath = yield* writeTempFile(operation, "codex-schema", schemaJson);
160 const outputPath = yield* writeTempFile(operation, "codex-output", "").pipe(
161 Effect.onError(() => removeTempFileDir(schemaPath)),
162 );
163
164 const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
165 const resolved = resolveRuntime
166 ? yield* resolveRuntime.pipe(
167 Effect.mapError(
168 (cause) => new TextGenerationError({ operation, detail: cause.detail }),
169 ),
170 )
171 : undefined;
172 const effectiveConfig = resolved?.config ?? codexConfig;
173 const effectiveEnvironment = resolved?.environment ?? resolvedEnvironment;
174 const models = yield* getModels;
175 const requestedModel = modelSelection.model;
176 const model =
177 models.find((candidate) => candidate.slug === requestedModel)?.slug ??
178 models.find(
179 (candidate) => !candidate.isCustom && codexModelFamily(candidate.slug) === requestedModel,
180 )?.slug ??
181 requestedModel;
182 const launchArgs = resolveCodexLaunchArgs(effectiveConfig.launchArgs, effectiveEnvironment);
183 const reasoningEffort =
184 getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
185 DEFAULT_TEXT_GENERATION_REASONING_EFFORT;
186 const serviceTier = resolved ? undefined : getCodexServiceTierOptionValue(modelSelection);
187 const spawnCommand = yield* resolveSpawnCommand(
188 effectiveConfig.binaryPath || "codex",
189 [
190 "exec",
191 ...codexExecLaunchArgs(launchArgs),
192 "--ephemeral",
193 "--skip-git-repo-check",
194 "-s",
195 "read-only",
196 "--model",
197 model,
198 "--config",
199 `model_reasoning_effort="${reasoningEffort}"`,
200 ...(serviceTier ? ["--config", `service_tier="${serviceTier}"`] : []),
201 "--output-schema",
202 schemaPath,
203 "--output-last-message",
204 outputPath,
205 ...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
206 "-",
207 ],
208 { env: effectiveEnvironment },
209 );
210 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
211 env: {
212 ...effectiveEnvironment,
213 ...(effectiveConfig.homePath
214 ? { CODEX_HOME: expandHomePath(effectiveConfig.homePath) }
215 : {}),
216 },
217 cwd,
218 shell: spawnCommand.shell,
219 stdin: {
220 stream: Stream.encodeText(Stream.make(prompt)),
221 },
222 });
223
224 const child = yield* commandSpawner
225 .spawn(command)
226 .pipe(
227 Effect.mapError((cause) =>
228 normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
229 ),
230 );
231
232 const [stdout, stderr, exitCode] = yield* Effect.all(
233 [
234 readStreamAsString(operation, child.stdout),
235 readStreamAsString(operation, child.stderr),
236 child.exitCode.pipe(
237 Effect.mapError((cause) =>
238 normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
239 ),
240 ),
241 ],
242 { concurrency: "unbounded" },
243 );
244
245 if (exitCode !== 0) {
246 const stderrDetail = stderr.trim();
247 const stdoutDetail = stdout.trim();
248 const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
249 return yield* new TextGenerationError({
250 operation,
251 detail:
252 detail.length > 0
253 ? `Codex CLI command failed: ${detail}`
254 : `Codex CLI command failed with code ${exitCode}.`,
255 });
256 }
257 });
258
259 const cleanup = Effect.all([removeTempFileDir(schemaPath), removeTempFileDir(outputPath)], {
260 concurrency: "unbounded",
261 }).pipe(Effect.asVoid);
262
263 return yield* Effect.gen(function* () {
264 yield* runCodexCommand().pipe(
265 Effect.scoped,
266 Effect.timeoutOption(CODEX_TIMEOUT_MS),
267 Effect.flatMap(
268 Option.match({
269 onNone: () =>
270 Effect.fail(
271 new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
272 ),
273 onSome: () => Effect.void,
274 }),
275 ),
276 );
277
278 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
279
280 return yield* fileSystem.readFileString(outputPath).pipe(
281 Effect.mapError(
282 (cause) =>
283 new TextGenerationError({
284 operation,
285 detail: "Failed to read Codex output file.",
286 cause,
287 }),
288 ),
289 Effect.flatMap(decodeOutput),
290 Effect.catchTags({
291 SchemaError: (cause) =>
292 Effect.fail(
293 new TextGenerationError({
294 operation,
295 detail: "Codex returned invalid structured output.",
296 cause,
297 }),
298 ),
299 }),
300 );
301 }).pipe(Effect.ensuring(cleanup));
302 });
303
304 return TextGenerationOperations.fromRunner("CodexTextGeneration", runCodexJson);
305});