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

CodexTextGeneration.ts

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