Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CodexTextGeneration.ts

435 lines15.4 KB

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