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