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

CodexTextGeneration.ts

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