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 ServerProvider,
14 TextGenerationError,
15} from "@t3tools/contracts";
16import { resolveSpawnCommand } from "@t3tools/shared/shell";
17import { compareSemverVersions, parseSemver } from "@t3tools/shared/semver";
18
19import { resolveAttachmentPath } from "../attachmentStore.ts";
20import * as ServerConfig from "../config.ts";
21import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
22import {
23 codexExecLaunchArgs,
24 codexMcpListLaunchArgs,
25 resolveCodexLaunchArgs,
26} from "../provider/codexLaunchArgs.ts";
27import { codexAppServerEnvironment } from "../provider/CodexProvider.ts";
28import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations";
29import {
30 normalizeCliError,
31 toJsonSchemaObject,
32} from "@t3tools/provider-core/server/textGenerationUtils";
33import {
34 codexModelFamily,
35 getModelSelectionStringOptionValue,
36 readCustomModelEntries,
37} from "@t3tools/shared/model";
38import { getCodexServiceTierOptionValue } from "../codexModelOptions.ts";
39import * as HostProcess from "@t3tools/shared/HostProcess";
40
41const CODEX_TIMEOUT_MS = 180_000;
42const CODEX_MCP_LIST_TIMEOUT_MS = 10_000;
43// Plugins/apps add MCP servers; use trailing config overrides because --disable loses to user -c flags.
44// Codex also reads the legacy connectors key for apps.
45const CODEX_NO_PLUGIN_ARGS = [
46 "--config",
47 "features.connectors=false",
48 "--config",
49 "features.plugins=false",
50 "--config",
51 "features.apps=false",
52] as const;
53const CodexMcpServers = Schema.fromJsonString(
54 Schema.Array(Schema.Struct({ name: Schema.String, enabled: Schema.Boolean })),
55);
56const decodeCodexMcpServers = Schema.decodeEffect(CodexMcpServers);
57
58// mcp_servers={} merges instead of replacing; disable named entries and quote dotted names.
59const codexMcpServersOff = (names: ReadonlyArray<string>): string | null =>
60 names.length === 0
61 ? null
62 : `mcp_servers={${names.map((name) => `${JSON.stringify(name)}={enabled=false}`).join(",")}}`;
63// Codex splits -c keys at the first "=" and on every dot, so only those names take a dotted flag.
64const codexMcpServerOffFlags = (names: ReadonlyArray<string>) =>
65 names
66 .filter((name) => !name.includes(".") && !name.includes("="))
67 .flatMap((name) => ["--config", `mcp_servers.${name}.enabled=false`]);
68const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
69type CodexTextGenerationSnapshot = Pick<ServerProvider, "models" | "version" | "installedVersion">;
70// Codex's own snake_case feature names; Codex special-cases an ephemeral "thread_title".
71const CODEX_THREAD_SOURCE = {
72 generateThreadTitle: "thread_title",
73 generateCommitMessage: "commit_message",
74 generatePrContent: "pr_content",
75 generateBranchName: "branch_name",
76 generateReviewGuide: "review_guide",
77 generateTranscriptionPostProcessing: "transcription_post_processing",
78} as const satisfies Record<TextGenerationOperations.Operation, string>;
79// Without it `codex exec` tags these threads "user", like a user's own chat. Codex 0.150 added it.
80const codexThreadSourceArgs = (
81 snapshot: CodexTextGenerationSnapshot,
82 operation: TextGenerationOperations.Operation,
83) => {
84 const version =
85 snapshot.installedVersion !== undefined ? snapshot.installedVersion : snapshot.version;
86 return version != null &&
87 parseSemver(version) !== null &&
88 compareSemverVersions(version, "0.150.0") >= 0
89 ? ["--thread-source", CODEX_THREAD_SOURCE[operation]]
90 : [];
91};
92export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(function* (
93 codexConfig: CodexSettings,
94 environment?: NodeJS.ProcessEnv,
95 getSnapshot: Effect.Effect<CodexTextGenerationSnapshot> = Effect.succeed({
96 models: [],
97 version: null,
98 }),
99 resolveRuntime?: Effect.Effect<
100 import("../provider/CodexManagedRuntime.ts").CodexEffectiveRuntime,
101 import("@t3tools/contracts").ProviderSetupError,
102 Scope.Scope
103 >,
104) {
105 const fileSystem = yield* FileSystem.FileSystem;
106 const path = yield* Path.Path;
107 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
108 const serverConfig = yield* Effect.service(ServerConfig.ServerConfig);
109 const resolvedEnvironment = environment ?? process.env;
110
111 const readStreamAsString = <E>(
112 operation: string,
113 stream: Stream.Stream<Uint8Array, E>,
114 ): Effect.Effect<string, TextGenerationError> =>
115 stream.pipe(
116 Stream.decodeText(),
117 Stream.runFold(
118 () => "",
119 (acc, chunk) => acc + chunk,
120 ),
121 Effect.mapError((cause) =>
122 normalizeCliError("codex", operation, cause, "Failed to collect process output"),
123 ),
124 );
125
126 const removeTempFileDir = (filePath: string): Effect.Effect<void, never> =>
127 fileSystem.remove(path.dirname(filePath), { recursive: true }).pipe(Effect.ignore);
128
129 // Background fibers may inherit closed scopes that immediately reap temp files; write unscoped.
130 const writeTempFile = (
131 operation: string,
132 prefix: string,
133 content: string,
134 ): Effect.Effect<string, TextGenerationError> =>
135 fileSystem
136 .makeTempFile({
137 prefix: `t3code-${prefix}-${process.pid}-`,
138 })
139 .pipe(
140 Effect.tap((filePath) =>
141 fileSystem
142 .writeFileString(filePath, content)
143 .pipe(Effect.onError(() => removeTempFileDir(filePath))),
144 ),
145 Effect.mapError(
146 (cause) =>
147 new TextGenerationError({
148 operation,
149 detail: `Failed to write temp file`,
150 cause,
151 }),
152 ),
153 );
154
155 const encodeJsonForOperation = (
156 operation: TextGenerationOperations.Operation,
157 value: unknown,
158 ): Effect.Effect<string, TextGenerationError> =>
159 encodeJsonString(value).pipe(
160 Effect.mapError(
161 (cause) =>
162 new TextGenerationError({
163 operation,
164 detail: "Failed to encode structured output schema.",
165 cause,
166 }),
167 ),
168 );
169
170 const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
171 attachments: TextGenerationOperations.Request<Schema.Top>["attachments"],
172 ) {
173 if (!attachments || attachments.length === 0) {
174 return [];
175 }
176
177 const imagePaths: string[] = [];
178 for (const attachment of attachments) {
179 if (attachment.type !== "image") {
180 continue;
181 }
182
183 const resolvedPath = resolveAttachmentPath({
184 attachmentsDir: serverConfig.attachmentsDir,
185 attachment,
186 });
187 if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
188 continue;
189 }
190 const fileInfo = yield* fileSystem.stat(resolvedPath).pipe(Effect.orElseSucceed(() => null));
191 if (!fileInfo || fileInfo.type !== "File") {
192 continue;
193 }
194 imagePaths.push(resolvedPath);
195 }
196 return imagePaths;
197 });
198
199 const listEnabledMcpServers = Effect.fn("listEnabledMcpServers")(
200 function* (input: {
201 readonly binary: string;
202 readonly cwd: string;
203 readonly env: NodeJS.ProcessEnv;
204 readonly launchArgs: ReadonlyArray<string>;
205 }) {
206 const spawnCommand = yield* resolveSpawnCommand(
207 input.binary,
208 [...input.launchArgs, ...CODEX_NO_PLUGIN_ARGS, "mcp", "list", "--json"],
209 { env: input.env },
210 );
211 const child = yield* commandSpawner.spawn(
212 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
213 env: input.env,
214 cwd: input.cwd,
215 shell: spawnCommand.shell,
216 forceKillAfter: "1 second",
217 }),
218 );
219 const [stdout, , exitCode] = yield* Effect.all(
220 [
221 child.stdout.pipe(Stream.decodeText(), Stream.mkString),
222 child.stderr.pipe(Stream.runDrain),
223 child.exitCode,
224 ],
225 { concurrency: "unbounded" },
226 );
227 if (exitCode !== 0) {
228 yield* Effect.logWarning("codex mcp list failed; text generation keeps its MCP servers", {
229 reason: "exit",
230 exitCode,
231 });
232 return [];
233 }
234 const servers = yield* decodeCodexMcpServers(stdout).pipe(
235 Effect.tapError(() =>
236 Effect.logWarning("codex mcp list failed; text generation keeps its MCP servers", {
237 reason: "decode",
238 }),
239 ),
240 );
241 return servers.filter((server) => server.enabled).map((server) => server.name);
242 },
243 Effect.scoped,
244 Effect.timeoutOption(CODEX_MCP_LIST_TIMEOUT_MS),
245 Effect.flatMap(
246 Option.match({
247 onNone: () =>
248 Effect.logWarning("codex mcp list failed; text generation keeps its MCP servers", {
249 reason: "timeout",
250 }).pipe(Effect.as<ReadonlyArray<string>>([])),
251 onSome: (names) => Effect.succeed(names),
252 }),
253 ),
254 Effect.orElseSucceed((): ReadonlyArray<string> => []),
255 );
256
257 const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
258 operation,
259 cwd,
260 prompt,
261 outputSchema: outputSchemaJson,
262 modelSelection,
263 attachments,
264 investigate,
265 }: TextGenerationOperations.Request<S>): Effect.fn.Return<
266 S["Type"],
267 TextGenerationError,
268 S["DecodingServices"]
269 > {
270 const imagePaths = yield* materializeImageAttachments(attachments);
271 const schemaJson = yield* encodeJsonForOperation(
272 operation,
273 toJsonSchemaObject(outputSchemaJson),
274 );
275 const schemaPath = yield* writeTempFile(operation, "codex-schema", schemaJson);
276 const outputPath = yield* writeTempFile(operation, "codex-output", "").pipe(
277 Effect.onError(() => removeTempFileDir(schemaPath)),
278 );
279
280 const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
281 const resolved = resolveRuntime
282 ? yield* resolveRuntime.pipe(
283 Effect.mapError(
284 (cause) => new TextGenerationError({ operation, detail: cause.detail }),
285 ),
286 )
287 : undefined;
288 const effectiveConfig = resolved?.config ?? codexConfig;
289 const effectiveEnvironment = resolved?.environment ?? resolvedEnvironment;
290 const snapshot = yield* getSnapshot;
291 const models = snapshot.models;
292 const requestedModel = modelSelection.model;
293 const listed = models.filter((candidate) => !candidate.isCustom);
294 // An unlisted slug is one this account can't run, e.g. gpt-6-luna on a ChatGPT login.
295 const requestedFamily = codexModelFamily(requestedModel);
296 const matchedModel =
297 models.find((candidate) => candidate.slug === requestedModel)?.slug ??
298 // Managed snapshots omit configured custom models; send those as requested.
299 readCustomModelEntries(codexConfig.customModels).find(
300 (entry) => entry.slug === requestedModel,
301 )?.slug ??
302 listed.find((candidate) => codexModelFamily(candidate.slug) === requestedFamily)?.slug;
303 const model =
304 matchedModel ??
305 listed.find((candidate) => candidate.isDefault)?.slug ??
306 listed.find((candidate) => !candidate.isLegacy)?.slug ??
307 listed[0]?.slug ??
308 requestedModel;
309 // The selection's options were chosen for the requested model and may not fit a fallback.
310 const fellBack = matchedModel === undefined && model !== requestedModel;
311 const launchArgs = resolveCodexLaunchArgs(effectiveConfig.launchArgs, effectiveEnvironment);
312 const reasoningEffort =
313 (fellBack
314 ? undefined
315 : getModelSelectionStringOptionValue(modelSelection, "reasoningEffort")) ??
316 DEFAULT_TEXT_GENERATION_REASONING_EFFORT;
317 const serviceTier =
318 resolved || fellBack ? undefined : getCodexServiceTierOptionValue(modelSelection);
319 const binary = effectiveConfig.binaryPath || "codex";
320 const env = {
321 ...codexAppServerEnvironment(effectiveEnvironment),
322 ...(effectiveConfig.homePath
323 ? {
324 CODEX_HOME: expandHomePath(
325 effectiveConfig.homePath,
326 yield* HostProcess.HomeDirectory,
327 ),
328 }
329 : {}),
330 };
331 const enabledMcpServers = yield* listEnabledMcpServers({
332 binary,
333 cwd,
334 env,
335 launchArgs: codexMcpListLaunchArgs(launchArgs),
336 });
337 const mcpServersOff = codexMcpServersOff(enabledMcpServers);
338 const execLaunchArgs = codexExecLaunchArgs(launchArgs);
339 // A launch-arg mcp_servers={...} table replaces ours and can re-enable dotted names.
340 const launchArgsSetMcpTable = execLaunchArgs.some((arg) => /\bmcp_servers\s*=/.test(arg));
341 const spawnCommand = yield* resolveSpawnCommand(
342 binary,
343 [
344 "exec",
345 // Before launch args: a later table would replace servers their -c flags define.
346 ...(mcpServersOff ? ["--config", mcpServersOff] : []),
347 ...execLaunchArgs,
348 // A user's MCP server could act on the text-generation prompt.
349 ...CODEX_NO_PLUGIN_ARGS,
350 ...(mcpServersOff && launchArgsSetMcpTable ? ["--config", mcpServersOff] : []),
351 // After launch args, so a launch arg's enabled=true cannot turn a server back on.
352 ...codexMcpServerOffFlags(enabledMcpServers),
353 "--ephemeral",
354 ...codexThreadSourceArgs(snapshot, operation),
355 "--skip-git-repo-check",
356 "-s",
357 "read-only",
358 "--model",
359 model,
360 "--config",
361 `model_reasoning_effort="${reasoningEffort}"`,
362 // Current Codex gives hooks precedence over the historical codex_hooks alias.
363 "--config",
364 "features.codex_hooks=false",
365 "--config",
366 "features.hooks=false",
367 ...(serviceTier ? ["--config", `service_tier="${serviceTier}"`] : []),
368 "--output-schema",
369 schemaPath,
370 "--output-last-message",
371 outputPath,
372 ...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
373 "-",
374 ],
375 { env: effectiveEnvironment },
376 );
377 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
378 env,
379 cwd,
380 shell: spawnCommand.shell,
381 stdin: {
382 stream: Stream.encodeText(Stream.make(prompt)),
383 },
384 forceKillAfter: "1 second",
385 });
386
387 const child = yield* commandSpawner
388 .spawn(command)
389 .pipe(
390 Effect.mapError((cause) =>
391 normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
392 ),
393 );
394
395 const [stdout, stderr, exitCode] = yield* Effect.all(
396 [
397 readStreamAsString(operation, child.stdout),
398 readStreamAsString(operation, child.stderr),
399 child.exitCode.pipe(
400 Effect.mapError((cause) =>
401 normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
402 ),
403 ),
404 ],
405 { concurrency: "unbounded" },
406 );
407
408 if (exitCode !== 0) {
409 const stderrDetail = stderr.trim();
410 const stdoutDetail = stdout.trim();
411 const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
412 return yield* new TextGenerationError({
413 operation,
414 detail:
415 detail.length > 0
416 ? `Codex CLI command failed: ${detail}`
417 : `Codex CLI command failed with code ${exitCode}.`,
418 });
419 }
420 });
421
422 const cleanup = Effect.all([removeTempFileDir(schemaPath), removeTempFileDir(outputPath)], {
423 concurrency: "unbounded",
424 }).pipe(Effect.asVoid);
425
426 return yield* Effect.gen(function* () {
427 yield* runCodexCommand().pipe(
428 Effect.scoped,
429 Effect.timeoutOption(investigate?.timeoutMs ?? CODEX_TIMEOUT_MS),
430 Effect.flatMap(
431 Option.match({
432 onNone: () =>
433 Effect.fail(
434 new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
435 ),
436 onSome: () => Effect.void,
437 }),
438 ),
439 );
440
441 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
442
443 return yield* fileSystem.readFileString(outputPath).pipe(
444 Effect.mapError(
445 (cause) =>
446 new TextGenerationError({
447 operation,
448 detail: "Failed to read Codex output file.",
449 cause,
450 }),
451 ),
452 Effect.flatMap(decodeOutput),
453 Effect.catchTags({
454 SchemaError: (cause) =>
455 Effect.fail(
456 new TextGenerationError({
457 operation,
458 detail: "Codex returned invalid structured output.",
459 cause,
460 }),
461 ),
462 }),
463 );
464 }).pipe(Effect.ensuring(cleanup));
465 });
466
467 return TextGenerationOperations.fromRunner("CodexTextGeneration", runCodexJson);
468});