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

CodexTextGeneration.ts

316 lines10.8 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 investigate,
154 }: TextGenerationOperations.Request<S>): Effect.fn.Return<
155 S["Type"],
156 TextGenerationError,
157 S["DecodingServices"]
158 > {
159 const imagePaths = yield* materializeImageAttachments(attachments);
160 const schemaJson = yield* encodeJsonForOperation(
161 operation,
162 toJsonSchemaObject(outputSchemaJson),
163 );
164 const schemaPath = yield* writeTempFile(operation, "codex-schema", schemaJson);
165 const outputPath = yield* writeTempFile(operation, "codex-output", "").pipe(
166 Effect.onError(() => removeTempFileDir(schemaPath)),
167 );
168​
169 const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
170 const resolved = resolveRuntime
171 ? yield* resolveRuntime.pipe(
172 Effect.mapError(
173 (cause) => new TextGenerationError({ operation, detail: cause.detail }),
174 ),
175 )
176 : undefined;
177 const effectiveConfig = resolved?.config ?? codexConfig;
178 const effectiveEnvironment = resolved?.environment ?? resolvedEnvironment;
179 const models = yield* getModels;
180 const requestedModel = modelSelection.model;
181 const model =
182 models.find((candidate) => candidate.slug === requestedModel)?.slug ??
183 models.find(
184 (candidate) => !candidate.isCustom && codexModelFamily(candidate.slug) === requestedModel,
185 )?.slug ??
186 requestedModel;
187 const launchArgs = resolveCodexLaunchArgs(effectiveConfig.launchArgs, effectiveEnvironment);
188 const reasoningEffort =
189 getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
190 DEFAULT_TEXT_GENERATION_REASONING_EFFORT;
191 const serviceTier = resolved ? undefined : getCodexServiceTierOptionValue(modelSelection);
192 const spawnCommand = yield* resolveSpawnCommand(
193 effectiveConfig.binaryPath || "codex",
194 [
195 "exec",
196 ...codexExecLaunchArgs(launchArgs),
197 "--ephemeral",
198 "--skip-git-repo-check",
199 "-s",
200 "read-only",
201 "--model",
202 model,
203 "--config",
204 `model_reasoning_effort="${reasoningEffort}"`,
205 ...(serviceTier ? ["--config", `service_tier="${serviceTier}"`] : []),
206 "--output-schema",
207 schemaPath,
208 "--output-last-message",
209 outputPath,
210 ...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
211 "-",
212 ],
213 { env: effectiveEnvironment },
214 );
215 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
216 env: {
217 ...effectiveEnvironment,
218 ...(effectiveConfig.homePath
219 ? {
220 CODEX_HOME: expandHomePath(
221 effectiveConfig.homePath,
222 yield* HostProcess.HomeDirectory,
223 ),
224 }
225 : {}),
226 },
227 cwd,
228 shell: spawnCommand.shell,
229 stdin: {
230 stream: Stream.encodeText(Stream.make(prompt)),
231 },
232 });
233​
234 const child = yield* commandSpawner
235 .spawn(command)
236 .pipe(
237 Effect.mapError((cause) =>
238 normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
239 ),
240 );
241​
242 const [stdout, stderr, exitCode] = yield* Effect.all(
243 [
244 readStreamAsString(operation, child.stdout),
245 readStreamAsString(operation, child.stderr),
246 child.exitCode.pipe(
247 Effect.mapError((cause) =>
248 normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
249 ),
250 ),
251 ],
252 { concurrency: "unbounded" },
253 );
254​
255 if (exitCode !== 0) {
256 const stderrDetail = stderr.trim();
257 const stdoutDetail = stdout.trim();
258 const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
259 return yield* new TextGenerationError({
260 operation,
261 detail:
262 detail.length > 0
263 ? `Codex CLI command failed: ${detail}`
264 : `Codex CLI command failed with code ${exitCode}.`,
265 });
266 }
267 });
268​
269 const cleanup = Effect.all([removeTempFileDir(schemaPath), removeTempFileDir(outputPath)], {
270 concurrency: "unbounded",
271 }).pipe(Effect.asVoid);
272​
273 return yield* Effect.gen(function* () {
274 yield* runCodexCommand().pipe(
275 Effect.scoped,
276 // The read-only sandbox already holds an investigation to reading; it only needs longer.
277 Effect.timeoutOption(investigate?.timeoutMs ?? CODEX_TIMEOUT_MS),
278 Effect.flatMap(
279 Option.match({
280 onNone: () =>
281 Effect.fail(
282 new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
283 ),
284 onSome: () => Effect.void,
285 }),
286 ),
287 );
288​
289 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
290​
291 return yield* fileSystem.readFileString(outputPath).pipe(
292 Effect.mapError(
293 (cause) =>
294 new TextGenerationError({
295 operation,
296 detail: "Failed to read Codex output file.",
297 cause,
298 }),
299 ),
300 Effect.flatMap(decodeOutput),
301 Effect.catchTags({
302 SchemaError: (cause) =>
303 Effect.fail(
304 new TextGenerationError({
305 operation,
306 detail: "Codex returned invalid structured output.",
307 cause,
308 }),
309 ),
310 }),
311 );
312 }).pipe(Effect.ensuring(cleanup));
313 });
314​
315 return TextGenerationOperations.fromRunner("CodexTextGeneration", runCodexJson);
316});