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";
29import * as HostProcess from "@t3tools/shared/HostProcess";
30
31const CODEX_TIMEOUT_MS = 180_000;
32const CODEX_MCP_LIST_TIMEOUT_MS = 10_000;
33// Plugins and apps bring MCP servers of their own; the user's are listed and
34// turned off by name below. These follow the user's launch args, so they win
35// over a `-c features.plugins=true` there, which `--disable plugins` does not.
36const CODEX_NO_PLUGIN_ARGS = [
37 "--config",
38 "features.plugins=false",
39 "--config",
40 "features.apps=false",
41] as const;
42const CodexMcpServers = Schema.fromJsonString(
43 Schema.Array(Schema.Struct({ name: Schema.String, enabled: Schema.Boolean })),
44);
45const decodeCodexMcpServers = Schema.decodeEffect(CodexMcpServers);
46
47/**
48 * `mcp_servers={}` merges into the user's servers rather than replacing them,
49 * so each is named; quoting the name keeps one with a dot a single key.
50 */
51const codexMcpServersOff = (names: ReadonlyArray<string>): string | null =>
52 names.length === 0
53 ? null
54 : `mcp_servers={${names.map((name) => `${JSON.stringify(name)}={enabled=false}`).join(",")}}`;
55const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
56export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(function* (
57 codexConfig: CodexSettings,
58 environment?: NodeJS.ProcessEnv,
59 getModels: Effect.Effect<ReadonlyArray<ServerProviderModel>> = Effect.succeed([]),
60 resolveRuntime?: Effect.Effect<
61 import("../provider/CodexManagedRuntime.ts").CodexEffectiveRuntime,
62 import("@t3tools/contracts").ProviderSetupError,
63 Scope.Scope
64 >,
65) {
66 const fileSystem = yield* FileSystem.FileSystem;
67 const path = yield* Path.Path;
68 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
69 const serverConfig = yield* Effect.service(ServerConfig.ServerConfig);
70 const resolvedEnvironment = environment ?? process.env;
71
72 const readStreamAsString = <E>(
73 operation: string,
74 stream: Stream.Stream<Uint8Array, E>,
75 ): Effect.Effect<string, TextGenerationError> =>
76 stream.pipe(
77 Stream.decodeText(),
78 Stream.runFold(
79 () => "",
80 (acc, chunk) => acc + chunk,
81 ),
82 Effect.mapError((cause) =>
83 normalizeCliError("codex", operation, cause, "Failed to collect process output"),
84 ),
85 );
86
87 const removeTempFileDir = (filePath: string): Effect.Effect<void, never> =>
88 fileSystem
89 .remove(path.dirname(filePath), { recursive: true })
90 .pipe(Effect.catch(() => Effect.void));
91
92 // Deliberately unscoped: text generation runs from background fibers whose
93 // ambient scope may already be closed (a closed scope reaps the temp
94 // directory the moment it is created).
95 const writeTempFile = (
96 operation: string,
97 prefix: string,
98 content: string,
99 ): Effect.Effect<string, TextGenerationError> =>
100 fileSystem
101 .makeTempFile({
102 prefix: `t3code-${prefix}-${process.pid}-`,
103 })
104 .pipe(
105 Effect.tap((filePath) =>
106 fileSystem
107 .writeFileString(filePath, content)
108 .pipe(Effect.onError(() => removeTempFileDir(filePath))),
109 ),
110 Effect.mapError(
111 (cause) =>
112 new TextGenerationError({
113 operation,
114 detail: `Failed to write temp file`,
115 cause,
116 }),
117 ),
118 );
119
120 const encodeJsonForOperation = (
121 operation: TextGenerationOperations.Operation,
122 value: unknown,
123 ): Effect.Effect<string, TextGenerationError> =>
124 encodeJsonString(value).pipe(
125 Effect.mapError(
126 (cause) =>
127 new TextGenerationError({
128 operation,
129 detail: "Failed to encode structured output schema.",
130 cause,
131 }),
132 ),
133 );
134
135 const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
136 attachments: TextGenerationOperations.Request<Schema.Top>["attachments"],
137 ) {
138 if (!attachments || attachments.length === 0) {
139 return [];
140 }
141
142 const imagePaths: string[] = [];
143 for (const attachment of attachments) {
144 if (attachment.type !== "image") {
145 continue;
146 }
147
148 const resolvedPath = resolveAttachmentPath({
149 attachmentsDir: serverConfig.attachmentsDir,
150 attachment,
151 });
152 if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
153 continue;
154 }
155 const fileInfo = yield* fileSystem.stat(resolvedPath).pipe(Effect.orElseSucceed(() => null));
156 if (!fileInfo || fileInfo.type !== "File") {
157 continue;
158 }
159 imagePaths.push(resolvedPath);
160 }
161 return imagePaths;
162 });
163
164 const listEnabledMcpServers = Effect.fn("listEnabledMcpServers")(
165 function* (input: {
166 readonly binary: string;
167 readonly cwd: string;
168 readonly env: NodeJS.ProcessEnv;
169 readonly launchArgs: ReadonlyArray<string>;
170 }) {
171 const spawnCommand = yield* resolveSpawnCommand(
172 input.binary,
173 [...input.launchArgs, ...CODEX_NO_PLUGIN_ARGS, "mcp", "list", "--json"],
174 { env: input.env },
175 );
176 const child = yield* commandSpawner.spawn(
177 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
178 env: input.env,
179 cwd: input.cwd,
180 shell: spawnCommand.shell,
181 forceKillAfter: "1 second",
182 }),
183 );
184 const [stdout, , exitCode] = yield* Effect.all(
185 [
186 child.stdout.pipe(Stream.decodeText(), Stream.mkString),
187 child.stderr.pipe(Stream.runDrain),
188 child.exitCode,
189 ],
190 { concurrency: "unbounded" },
191 );
192 if (exitCode !== 0) {
193 yield* Effect.logWarning("codex mcp list failed; text generation keeps its MCP servers", {
194 reason: "exit",
195 exitCode,
196 });
197 return [];
198 }
199 const servers = yield* decodeCodexMcpServers(stdout).pipe(
200 Effect.tapError(() =>
201 Effect.logWarning("codex mcp list failed; text generation keeps its MCP servers", {
202 reason: "decode",
203 }),
204 ),
205 );
206 return servers.filter((server) => server.enabled).map((server) => server.name);
207 },
208 Effect.scoped,
209 Effect.timeoutOption(CODEX_MCP_LIST_TIMEOUT_MS),
210 Effect.flatMap(
211 Option.match({
212 onNone: () =>
213 Effect.logWarning("codex mcp list failed; text generation keeps its MCP servers", {
214 reason: "timeout",
215 }).pipe(Effect.as<ReadonlyArray<string>>([])),
216 onSome: (names) => Effect.succeed(names),
217 }),
218 ),
219 Effect.orElseSucceed((): ReadonlyArray<string> => []),
220 );
221
222 const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
223 operation,
224 cwd,
225 prompt,
226 outputSchema: outputSchemaJson,
227 modelSelection,
228 attachments,
229 investigate,
230 }: TextGenerationOperations.Request<S>): Effect.fn.Return<
231 S["Type"],
232 TextGenerationError,
233 S["DecodingServices"]
234 > {
235 const imagePaths = yield* materializeImageAttachments(attachments);
236 const schemaJson = yield* encodeJsonForOperation(
237 operation,
238 toJsonSchemaObject(outputSchemaJson),
239 );
240 const schemaPath = yield* writeTempFile(operation, "codex-schema", schemaJson);
241 const outputPath = yield* writeTempFile(operation, "codex-output", "").pipe(
242 Effect.onError(() => removeTempFileDir(schemaPath)),
243 );
244
245 const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
246 const resolved = resolveRuntime
247 ? yield* resolveRuntime.pipe(
248 Effect.mapError(
249 (cause) => new TextGenerationError({ operation, detail: cause.detail }),
250 ),
251 )
252 : undefined;
253 const effectiveConfig = resolved?.config ?? codexConfig;
254 const effectiveEnvironment = resolved?.environment ?? resolvedEnvironment;
255 const models = yield* getModels;
256 const requestedModel = modelSelection.model;
257 const model =
258 models.find((candidate) => candidate.slug === requestedModel)?.slug ??
259 models.find(
260 (candidate) => !candidate.isCustom && codexModelFamily(candidate.slug) === requestedModel,
261 )?.slug ??
262 requestedModel;
263 const launchArgs = resolveCodexLaunchArgs(effectiveConfig.launchArgs, effectiveEnvironment);
264 const reasoningEffort =
265 getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
266 DEFAULT_TEXT_GENERATION_REASONING_EFFORT;
267 const serviceTier = resolved ? undefined : getCodexServiceTierOptionValue(modelSelection);
268 const binary = effectiveConfig.binaryPath || "codex";
269 const env = {
270 ...effectiveEnvironment,
271 ...(effectiveConfig.homePath
272 ? {
273 CODEX_HOME: expandHomePath(
274 effectiveConfig.homePath,
275 yield* HostProcess.HomeDirectory,
276 ),
277 }
278 : {}),
279 };
280 const execLaunchArgs = codexExecLaunchArgs(launchArgs);
281 const mcpServersOff = yield* listEnabledMcpServers({
282 binary,
283 cwd,
284 env,
285 // `codex mcp` rejects --strict-config; the overrides still apply.
286 launchArgs: execLaunchArgs.filter((arg) => arg !== "--strict-config"),
287 }).pipe(Effect.map(codexMcpServersOff));
288 const spawnCommand = yield* resolveSpawnCommand(
289 binary,
290 [
291 "exec",
292 ...execLaunchArgs,
293 // Text generation needs only the prompt. A user's MCP server would
294 // otherwise start and could act on it, as Claude's --strict-mcp-config
295 // prevents for Claude.
296 ...CODEX_NO_PLUGIN_ARGS,
297 ...(mcpServersOff ? ["--config", mcpServersOff] : []),
298 "--ephemeral",
299 "--skip-git-repo-check",
300 "-s",
301 "read-only",
302 "--model",
303 model,
304 "--config",
305 `model_reasoning_effort="${reasoningEffort}"`,
306 ...(serviceTier ? ["--config", `service_tier="${serviceTier}"`] : []),
307 "--output-schema",
308 schemaPath,
309 "--output-last-message",
310 outputPath,
311 ...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
312 "-",
313 ],
314 { env: effectiveEnvironment },
315 );
316 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
317 env,
318 cwd,
319 shell: spawnCommand.shell,
320 stdin: {
321 stream: Stream.encodeText(Stream.make(prompt)),
322 },
323 forceKillAfter: "1 second",
324 });
325
326 const child = yield* commandSpawner
327 .spawn(command)
328 .pipe(
329 Effect.mapError((cause) =>
330 normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
331 ),
332 );
333
334 const [stdout, stderr, exitCode] = yield* Effect.all(
335 [
336 readStreamAsString(operation, child.stdout),
337 readStreamAsString(operation, child.stderr),
338 child.exitCode.pipe(
339 Effect.mapError((cause) =>
340 normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
341 ),
342 ),
343 ],
344 { concurrency: "unbounded" },
345 );
346
347 if (exitCode !== 0) {
348 const stderrDetail = stderr.trim();
349 const stdoutDetail = stdout.trim();
350 const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
351 return yield* new TextGenerationError({
352 operation,
353 detail:
354 detail.length > 0
355 ? `Codex CLI command failed: ${detail}`
356 : `Codex CLI command failed with code ${exitCode}.`,
357 });
358 }
359 });
360
361 const cleanup = Effect.all([removeTempFileDir(schemaPath), removeTempFileDir(outputPath)], {
362 concurrency: "unbounded",
363 }).pipe(Effect.asVoid);
364
365 return yield* Effect.gen(function* () {
366 yield* runCodexCommand().pipe(
367 Effect.scoped,
368 Effect.timeoutOption(investigate?.timeoutMs ?? CODEX_TIMEOUT_MS),
369 Effect.flatMap(
370 Option.match({
371 onNone: () =>
372 Effect.fail(
373 new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
374 ),
375 onSome: () => Effect.void,
376 }),
377 ),
378 );
379
380 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
381
382 return yield* fileSystem.readFileString(outputPath).pipe(
383 Effect.mapError(
384 (cause) =>
385 new TextGenerationError({
386 operation,
387 detail: "Failed to read Codex output file.",
388 cause,
389 }),
390 ),
391 Effect.flatMap(decodeOutput),
392 Effect.catchTags({
393 SchemaError: (cause) =>
394 Effect.fail(
395 new TextGenerationError({
396 operation,
397 detail: "Codex returned invalid structured output.",
398 cause,
399 }),
400 ),
401 }),
402 );
403 }).pipe(Effect.ensuring(cleanup));
404 });
405
406 return TextGenerationOperations.fromRunner("CodexTextGeneration", runCodexJson);
407});