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

CodexTextGeneration.ts

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