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

CodexTextGeneration.ts

405 lines13.9 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 { 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 }),
182 );
183 const [stdout, , exitCode] = yield* Effect.all(
184 [
185 child.stdout.pipe(Stream.decodeText(), Stream.mkString),
186 child.stderr.pipe(Stream.runDrain),
187 child.exitCode,
188 ],
189 { concurrency: "unbounded" },
190 );
191 if (exitCode !== 0) {
192 yield* Effect.logWarning("codex mcp list failed; text generation keeps its MCP servers", {
193 reason: "exit",
194 exitCode,
195 });
196 return [];
197 }
198 const servers = yield* decodeCodexMcpServers(stdout).pipe(
199 Effect.tapError(() =>
200 Effect.logWarning("codex mcp list failed; text generation keeps its MCP servers", {
201 reason: "decode",
202 }),
203 ),
204 );
205 return servers.filter((server) => server.enabled).map((server) => server.name);
206 },
207 Effect.scoped,
208 Effect.timeoutOption(CODEX_MCP_LIST_TIMEOUT_MS),
209 Effect.flatMap(
210 Option.match({
211 onNone: () =>
212 Effect.logWarning("codex mcp list failed; text generation keeps its MCP servers", {
213 reason: "timeout",
214 }).pipe(Effect.as<ReadonlyArray<string>>([])),
215 onSome: (names) => Effect.succeed(names),
216 }),
217 ),
218 Effect.orElseSucceed((): ReadonlyArray<string> => []),
219 );
220​
221 const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
222 operation,
223 cwd,
224 prompt,
225 outputSchema: outputSchemaJson,
226 modelSelection,
227 attachments,
228 investigate,
229 }: TextGenerationOperations.Request<S>): Effect.fn.Return<
230 S["Type"],
231 TextGenerationError,
232 S["DecodingServices"]
233 > {
234 const imagePaths = yield* materializeImageAttachments(attachments);
235 const schemaJson = yield* encodeJsonForOperation(
236 operation,
237 toJsonSchemaObject(outputSchemaJson),
238 );
239 const schemaPath = yield* writeTempFile(operation, "codex-schema", schemaJson);
240 const outputPath = yield* writeTempFile(operation, "codex-output", "").pipe(
241 Effect.onError(() => removeTempFileDir(schemaPath)),
242 );
243​
244 const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
245 const resolved = resolveRuntime
246 ? yield* resolveRuntime.pipe(
247 Effect.mapError(
248 (cause) => new TextGenerationError({ operation, detail: cause.detail }),
249 ),
250 )
251 : undefined;
252 const effectiveConfig = resolved?.config ?? codexConfig;
253 const effectiveEnvironment = resolved?.environment ?? resolvedEnvironment;
254 const models = yield* getModels;
255 const requestedModel = modelSelection.model;
256 const model =
257 models.find((candidate) => candidate.slug === requestedModel)?.slug ??
258 models.find(
259 (candidate) => !candidate.isCustom && codexModelFamily(candidate.slug) === requestedModel,
260 )?.slug ??
261 requestedModel;
262 const launchArgs = resolveCodexLaunchArgs(effectiveConfig.launchArgs, effectiveEnvironment);
263 const reasoningEffort =
264 getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
265 DEFAULT_TEXT_GENERATION_REASONING_EFFORT;
266 const serviceTier = resolved ? undefined : getCodexServiceTierOptionValue(modelSelection);
267 const binary = effectiveConfig.binaryPath || "codex";
268 const env = {
269 ...effectiveEnvironment,
270 ...(effectiveConfig.homePath
271 ? {
272 CODEX_HOME: expandHomePath(
273 effectiveConfig.homePath,
274 yield* HostProcess.HomeDirectory,
275 ),
276 }
277 : {}),
278 };
279 const execLaunchArgs = codexExecLaunchArgs(launchArgs);
280 const mcpServersOff = yield* listEnabledMcpServers({
281 binary,
282 cwd,
283 env,
284 // `codex mcp` rejects --strict-config; the overrides still apply.
285 launchArgs: execLaunchArgs.filter((arg) => arg !== "--strict-config"),
286 }).pipe(Effect.map(codexMcpServersOff));
287 const spawnCommand = yield* resolveSpawnCommand(
288 binary,
289 [
290 "exec",
291 ...execLaunchArgs,
292 // Text generation needs only the prompt. A user's MCP server would
293 // otherwise start and could act on it, as Claude's --strict-mcp-config
294 // prevents for Claude.
295 ...CODEX_NO_PLUGIN_ARGS,
296 ...(mcpServersOff ? ["--config", mcpServersOff] : []),
297 "--ephemeral",
298 "--skip-git-repo-check",
299 "-s",
300 "read-only",
301 "--model",
302 model,
303 "--config",
304 `model_reasoning_effort="${reasoningEffort}"`,
305 ...(serviceTier ? ["--config", `service_tier="${serviceTier}"`] : []),
306 "--output-schema",
307 schemaPath,
308 "--output-last-message",
309 outputPath,
310 ...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
311 "-",
312 ],
313 { env: effectiveEnvironment },
314 );
315 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
316 env,
317 cwd,
318 shell: spawnCommand.shell,
319 stdin: {
320 stream: Stream.encodeText(Stream.make(prompt)),
321 },
322 });
323​
324 const child = yield* commandSpawner
325 .spawn(command)
326 .pipe(
327 Effect.mapError((cause) =>
328 normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
329 ),
330 );
331​
332 const [stdout, stderr, exitCode] = yield* Effect.all(
333 [
334 readStreamAsString(operation, child.stdout),
335 readStreamAsString(operation, child.stderr),
336 child.exitCode.pipe(
337 Effect.mapError((cause) =>
338 normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
339 ),
340 ),
341 ],
342 { concurrency: "unbounded" },
343 );
344​
345 if (exitCode !== 0) {
346 const stderrDetail = stderr.trim();
347 const stdoutDetail = stdout.trim();
348 const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
349 return yield* new TextGenerationError({
350 operation,
351 detail:
352 detail.length > 0
353 ? `Codex CLI command failed: ${detail}`
354 : `Codex CLI command failed with code ${exitCode}.`,
355 });
356 }
357 });
358​
359 const cleanup = Effect.all([removeTempFileDir(schemaPath), removeTempFileDir(outputPath)], {
360 concurrency: "unbounded",
361 }).pipe(Effect.asVoid);
362​
363 return yield* Effect.gen(function* () {
364 yield* runCodexCommand().pipe(
365 Effect.scoped,
366 Effect.timeoutOption(investigate?.timeoutMs ?? CODEX_TIMEOUT_MS),
367 Effect.flatMap(
368 Option.match({
369 onNone: () =>
370 Effect.fail(
371 new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
372 ),
373 onSome: () => Effect.void,
374 }),
375 ),
376 );
377​
378 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
379​
380 return yield* fileSystem.readFileString(outputPath).pipe(
381 Effect.mapError(
382 (cause) =>
383 new TextGenerationError({
384 operation,
385 detail: "Failed to read Codex output file.",
386 cause,
387 }),
388 ),
389 Effect.flatMap(decodeOutput),
390 Effect.catchTags({
391 SchemaError: (cause) =>
392 Effect.fail(
393 new TextGenerationError({
394 operation,
395 detail: "Codex returned invalid structured output.",
396 cause,
397 }),
398 ),
399 }),
400 );
401 }).pipe(Effect.ensuring(cleanup));
402 });
403​
404 return TextGenerationOperations.fromRunner("CodexTextGeneration", runCodexJson);
405});