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