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

CodexTextGeneration.ts

314 lines10.7 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 encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
33/**
34 * Build a Codex text-generation closure bound to a specific `CodexSettings`
35 * payload. See `makeCodexAdapter` for the overall per-instance rationale.
36 */
37export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(function* (
38 codexConfig: CodexSettings,
39 environment?: NodeJS.ProcessEnv,
40 getModels: Effect.Effect<ReadonlyArray<ServerProviderModel>> = Effect.succeed([]),
41 resolveRuntime?: Effect.Effect<
42 import("../provider/CodexManagedRuntime.ts").CodexEffectiveRuntime,
43 import("@t3tools/contracts").ProviderSetupError,
44 Scope.Scope
45 >,
46) {
47 const fileSystem = yield* FileSystem.FileSystem;
48 const path = yield* Path.Path;
49 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
50 const serverConfig = yield* Effect.service(ServerConfig.ServerConfig);
51 const resolvedEnvironment = environment ?? process.env;
52​
53 const readStreamAsString = <E>(
54 operation: string,
55 stream: Stream.Stream<Uint8Array, E>,
56 ): Effect.Effect<string, TextGenerationError> =>
57 stream.pipe(
58 Stream.decodeText(),
59 Stream.runFold(
60 () => "",
61 (acc, chunk) => acc + chunk,
62 ),
63 Effect.mapError((cause) =>
64 normalizeCliError("codex", operation, cause, "Failed to collect process output"),
65 ),
66 );
67​
68 const removeTempFileDir = (filePath: string): Effect.Effect<void, never> =>
69 fileSystem
70 .remove(path.dirname(filePath), { recursive: true })
71 .pipe(Effect.catch(() => Effect.void));
72​
73 // Deliberately unscoped: text generation runs from background fibers whose
74 // ambient scope may already be closed (a closed scope reaps the temp
75 // directory the moment it is created). Each allocation removes its own
76 // directory on failure; success-path cleanup is explicit in runCodexJson.
77 const writeTempFile = (
78 operation: string,
79 prefix: string,
80 content: string,
81 ): Effect.Effect<string, TextGenerationError> =>
82 fileSystem
83 .makeTempFile({
84 prefix: `t3code-${prefix}-${process.pid}-`,
85 })
86 .pipe(
87 Effect.tap((filePath) =>
88 fileSystem
89 .writeFileString(filePath, content)
90 .pipe(Effect.onError(() => removeTempFileDir(filePath))),
91 ),
92 Effect.mapError(
93 (cause) =>
94 new TextGenerationError({
95 operation,
96 detail: `Failed to write temp file`,
97 cause,
98 }),
99 ),
100 );
101​
102 const encodeJsonForOperation = (
103 operation: TextGenerationOperations.Operation,
104 value: unknown,
105 ): Effect.Effect<string, TextGenerationError> =>
106 encodeJsonString(value).pipe(
107 Effect.mapError(
108 (cause) =>
109 new TextGenerationError({
110 operation,
111 detail: "Failed to encode structured output schema.",
112 cause,
113 }),
114 ),
115 );
116​
117 const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
118 attachments: TextGenerationOperations.Request<Schema.Top>["attachments"],
119 ) {
120 if (!attachments || attachments.length === 0) {
121 return [];
122 }
123​
124 const imagePaths: string[] = [];
125 for (const attachment of attachments) {
126 if (attachment.type !== "image") {
127 continue;
128 }
129​
130 const resolvedPath = resolveAttachmentPath({
131 attachmentsDir: serverConfig.attachmentsDir,
132 attachment,
133 });
134 if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
135 continue;
136 }
137 const fileInfo = yield* fileSystem.stat(resolvedPath).pipe(Effect.orElseSucceed(() => null));
138 if (!fileInfo || fileInfo.type !== "File") {
139 continue;
140 }
141 imagePaths.push(resolvedPath);
142 }
143 return imagePaths;
144 });
145​
146 const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
147 operation,
148 cwd,
149 prompt,
150 outputSchema: outputSchemaJson,
151 modelSelection,
152 attachments,
153 }: TextGenerationOperations.Request<S>): Effect.fn.Return<
154 S["Type"],
155 TextGenerationError,
156 S["DecodingServices"]
157 > {
158 const imagePaths = yield* materializeImageAttachments(attachments);
159 const schemaJson = yield* encodeJsonForOperation(
160 operation,
161 toJsonSchemaObject(outputSchemaJson),
162 );
163 const schemaPath = yield* writeTempFile(operation, "codex-schema", schemaJson);
164 const outputPath = yield* writeTempFile(operation, "codex-output", "").pipe(
165 Effect.onError(() => removeTempFileDir(schemaPath)),
166 );
167​
168 const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
169 const resolved = resolveRuntime
170 ? yield* resolveRuntime.pipe(
171 Effect.mapError(
172 (cause) => new TextGenerationError({ operation, detail: cause.detail }),
173 ),
174 )
175 : undefined;
176 const effectiveConfig = resolved?.config ?? codexConfig;
177 const effectiveEnvironment = resolved?.environment ?? resolvedEnvironment;
178 const models = yield* getModels;
179 const requestedModel = modelSelection.model;
180 const model =
181 models.find((candidate) => candidate.slug === requestedModel)?.slug ??
182 models.find(
183 (candidate) => !candidate.isCustom && codexModelFamily(candidate.slug) === requestedModel,
184 )?.slug ??
185 requestedModel;
186 const launchArgs = resolveCodexLaunchArgs(effectiveConfig.launchArgs, effectiveEnvironment);
187 const reasoningEffort =
188 getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
189 DEFAULT_TEXT_GENERATION_REASONING_EFFORT;
190 const serviceTier = resolved ? undefined : getCodexServiceTierOptionValue(modelSelection);
191 const spawnCommand = yield* resolveSpawnCommand(
192 effectiveConfig.binaryPath || "codex",
193 [
194 "exec",
195 ...codexExecLaunchArgs(launchArgs),
196 "--ephemeral",
197 "--skip-git-repo-check",
198 "-s",
199 "read-only",
200 "--model",
201 model,
202 "--config",
203 `model_reasoning_effort="${reasoningEffort}"`,
204 ...(serviceTier ? ["--config", `service_tier="${serviceTier}"`] : []),
205 "--output-schema",
206 schemaPath,
207 "--output-last-message",
208 outputPath,
209 ...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
210 "-",
211 ],
212 { env: effectiveEnvironment },
213 );
214 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
215 env: {
216 ...effectiveEnvironment,
217 ...(effectiveConfig.homePath
218 ? {
219 CODEX_HOME: expandHomePath(
220 effectiveConfig.homePath,
221 yield* HostProcess.HomeDirectory,
222 ),
223 }
224 : {}),
225 },
226 cwd,
227 shell: spawnCommand.shell,
228 stdin: {
229 stream: Stream.encodeText(Stream.make(prompt)),
230 },
231 });
232​
233 const child = yield* commandSpawner
234 .spawn(command)
235 .pipe(
236 Effect.mapError((cause) =>
237 normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
238 ),
239 );
240​
241 const [stdout, stderr, exitCode] = yield* Effect.all(
242 [
243 readStreamAsString(operation, child.stdout),
244 readStreamAsString(operation, child.stderr),
245 child.exitCode.pipe(
246 Effect.mapError((cause) =>
247 normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
248 ),
249 ),
250 ],
251 { concurrency: "unbounded" },
252 );
253​
254 if (exitCode !== 0) {
255 const stderrDetail = stderr.trim();
256 const stdoutDetail = stdout.trim();
257 const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
258 return yield* new TextGenerationError({
259 operation,
260 detail:
261 detail.length > 0
262 ? `Codex CLI command failed: ${detail}`
263 : `Codex CLI command failed with code ${exitCode}.`,
264 });
265 }
266 });
267​
268 const cleanup = Effect.all([removeTempFileDir(schemaPath), removeTempFileDir(outputPath)], {
269 concurrency: "unbounded",
270 }).pipe(Effect.asVoid);
271​
272 return yield* Effect.gen(function* () {
273 yield* runCodexCommand().pipe(
274 Effect.scoped,
275 Effect.timeoutOption(CODEX_TIMEOUT_MS),
276 Effect.flatMap(
277 Option.match({
278 onNone: () =>
279 Effect.fail(
280 new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
281 ),
282 onSome: () => Effect.void,
283 }),
284 ),
285 );
286​
287 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
288​
289 return yield* fileSystem.readFileString(outputPath).pipe(
290 Effect.mapError(
291 (cause) =>
292 new TextGenerationError({
293 operation,
294 detail: "Failed to read Codex output file.",
295 cause,
296 }),
297 ),
298 Effect.flatMap(decodeOutput),
299 Effect.catchTags({
300 SchemaError: (cause) =>
301 Effect.fail(
302 new TextGenerationError({
303 operation,
304 detail: "Codex returned invalid structured output.",
305 cause,
306 }),
307 ),
308 }),
309 );
310 }).pipe(Effect.ensuring(cleanup));
311 });
312​
313 return TextGenerationOperations.fromRunner("CodexTextGeneration", runCodexJson);
314});