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

CodexProvider.ts

565 lines16.5 KB

1import * as OS from "node:os";
2import type {
3 ModelCapabilities,
4 CodexSettings,
5 ServerProvider,
6 ServerProviderModel,
7 ServerProviderAuth,
8 ServerProviderState,
9} from "@t3tools/contracts";
10import {
11 Cache,
12 Duration,
13 Effect,
14 Equal,
15 FileSystem,
16 Layer,
17 Option,
18 Path,
19 Result,
20 Stream,
21} from "effect";
22import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
23​
24import {
25 buildServerProvider,
26 DEFAULT_TIMEOUT_MS,
27 detailFromResult,
28 extractAuthBoolean,
29 isCommandMissingCause,
30 parseGenericCliVersion,
31 providerModelsFromSettings,
32 spawnAndCollect,
33 type CommandResult,
34} from "../providerSnapshot";
35import { makeManagedServerProvider } from "../makeManagedServerProvider";
36import {
37 formatCodexCliUpgradeMessage,
38 isCodexCliVersionSupported,
39 parseCodexCliVersion,
40} from "../codexCliVersion";
41import {
42 adjustCodexModelsForAccount,
43 codexAuthSubLabel,
44 codexAuthSubType,
45 type CodexAccountSnapshot,
46} from "../codexAccount";
47import { probeCodexAccount } from "../codexAppServer";
48import { CodexProvider } from "../Services/CodexProvider";
49import { ServerSettingsService } from "../../serverSettings";
50import { ServerSettingsError } from "@t3tools/contracts";
51​
52const PROVIDER = "codex" as const;
53const OPENAI_AUTH_PROVIDERS = new Set(["openai"]);
54const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
55 {
56 slug: "gpt-5.4",
57 name: "GPT-5.4",
58 isCustom: false,
59 capabilities: {
60 reasoningEffortLevels: [
61 { value: "xhigh", label: "Extra High" },
62 { value: "high", label: "High", isDefault: true },
63 { value: "medium", label: "Medium" },
64 { value: "low", label: "Low" },
65 ],
66 supportsFastMode: true,
67 supportsThinkingToggle: false,
68 contextWindowOptions: [],
69 promptInjectedEffortLevels: [],
70 },
71 },
72 {
73 slug: "gpt-5.4-mini",
74 name: "GPT-5.4 Mini",
75 isCustom: false,
76 capabilities: {
77 reasoningEffortLevels: [
78 { value: "xhigh", label: "Extra High" },
79 { value: "high", label: "High", isDefault: true },
80 { value: "medium", label: "Medium" },
81 { value: "low", label: "Low" },
82 ],
83 supportsFastMode: true,
84 supportsThinkingToggle: false,
85 contextWindowOptions: [],
86 promptInjectedEffortLevels: [],
87 },
88 },
89 {
90 slug: "gpt-5.3-codex",
91 name: "GPT-5.3 Codex",
92 isCustom: false,
93 capabilities: {
94 reasoningEffortLevels: [
95 { value: "xhigh", label: "Extra High" },
96 { value: "high", label: "High", isDefault: true },
97 { value: "medium", label: "Medium" },
98 { value: "low", label: "Low" },
99 ],
100 supportsFastMode: true,
101 supportsThinkingToggle: false,
102 contextWindowOptions: [],
103 promptInjectedEffortLevels: [],
104 },
105 },
106 {
107 slug: "gpt-5.3-codex-spark",
108 name: "GPT-5.3 Codex Spark",
109 isCustom: false,
110 capabilities: {
111 reasoningEffortLevels: [
112 { value: "xhigh", label: "Extra High" },
113 { value: "high", label: "High", isDefault: true },
114 { value: "medium", label: "Medium" },
115 { value: "low", label: "Low" },
116 ],
117 supportsFastMode: true,
118 supportsThinkingToggle: false,
119 contextWindowOptions: [],
120 promptInjectedEffortLevels: [],
121 },
122 },
123 {
124 slug: "gpt-5.2-codex",
125 name: "GPT-5.2 Codex",
126 isCustom: false,
127 capabilities: {
128 reasoningEffortLevels: [
129 { value: "xhigh", label: "Extra High" },
130 { value: "high", label: "High", isDefault: true },
131 { value: "medium", label: "Medium" },
132 { value: "low", label: "Low" },
133 ],
134 supportsFastMode: true,
135 supportsThinkingToggle: false,
136 contextWindowOptions: [],
137 promptInjectedEffortLevels: [],
138 },
139 },
140 {
141 slug: "gpt-5.2",
142 name: "GPT-5.2",
143 isCustom: false,
144 capabilities: {
145 reasoningEffortLevels: [
146 { value: "xhigh", label: "Extra High" },
147 { value: "high", label: "High", isDefault: true },
148 { value: "medium", label: "Medium" },
149 { value: "low", label: "Low" },
150 ],
151 supportsFastMode: true,
152 supportsThinkingToggle: false,
153 contextWindowOptions: [],
154 promptInjectedEffortLevels: [],
155 },
156 },
157];
158​
159export function getCodexModelCapabilities(model: string | null | undefined): ModelCapabilities {
160 const slug = model?.trim();
161 return (
162 BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? {
163 reasoningEffortLevels: [],
164 supportsFastMode: false,
165 supportsThinkingToggle: false,
166 contextWindowOptions: [],
167 promptInjectedEffortLevels: [],
168 }
169 );
171​
172export function parseAuthStatusFromOutput(result: CommandResult): {
173 readonly status: Exclude<ServerProviderState, "disabled">;
174 readonly auth: Pick<ServerProviderAuth, "status">;
175 readonly message?: string;
176} {
177 const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
178​
179 if (
180 lowerOutput.includes("unknown command") ||
181 lowerOutput.includes("unrecognized command") ||
182 lowerOutput.includes("unexpected argument")
183 ) {
184 return {
185 status: "warning",
186 auth: { status: "unknown" },
187 message: "Codex CLI authentication status command is unavailable in this Codex version.",
188 };
189 }
190​
191 if (
192 lowerOutput.includes("not logged in") ||
193 lowerOutput.includes("login required") ||
194 lowerOutput.includes("authentication required") ||
195 lowerOutput.includes("run `codex login`") ||
196 lowerOutput.includes("run codex login")
197 ) {
198 return {
199 status: "error",
200 auth: { status: "unauthenticated" },
201 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
202 };
203 }
204​
205 const parsedAuth = (() => {
206 const trimmed = result.stdout.trim();
207 if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
208 return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
209 }
210 try {
211 return {
212 attemptedJsonParse: true as const,
213 auth: extractAuthBoolean(JSON.parse(trimmed)),
214 };
215 } catch {
216 return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
217 }
218 })();
219​
220 if (parsedAuth.auth === true) {
221 return { status: "ready", auth: { status: "authenticated" } };
222 }
223 if (parsedAuth.auth === false) {
224 return {
225 status: "error",
226 auth: { status: "unauthenticated" },
227 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
228 };
229 }
230 if (parsedAuth.attemptedJsonParse) {
231 return {
232 status: "warning",
233 auth: { status: "unknown" },
234 message:
235 "Could not verify Codex authentication status from JSON output (missing auth marker).",
236 };
237 }
238 if (result.code === 0) {
239 return { status: "ready", auth: { status: "authenticated" } };
240 }
241​
242 const detail = detailFromResult(result);
243 return {
244 status: "warning",
245 auth: { status: "unknown" },
246 message: detail
247 ? `Could not verify Codex authentication status. ${detail}`
248 : "Could not verify Codex authentication status.",
249 };
251​
252export const readCodexConfigModelProvider = Effect.fn("readCodexConfigModelProvider")(function* () {
253 const fileSystem = yield* FileSystem.FileSystem;
254 const path = yield* Path.Path;
255 const settingsService = yield* ServerSettingsService;
256 const codexHome = yield* settingsService.getSettings.pipe(
257 Effect.map(
258 (settings) =>
259 settings.providers.codex.homePath ||
260 process.env.CODEX_HOME ||
261 path.join(OS.homedir(), ".codex"),
262 ),
263 );
264 const configPath = path.join(codexHome, "config.toml");
265​
266 const content = yield* fileSystem
267 .readFileString(configPath)
268 .pipe(Effect.orElseSucceed(() => undefined));
269 if (content === undefined) {
270 return undefined;
271 }
272​
273 let inTopLevel = true;
274 for (const line of content.split("\n")) {
275 const trimmed = line.trim();
276 if (!trimmed || trimmed.startsWith("#")) continue;
277 if (trimmed.startsWith("[")) {
278 inTopLevel = false;
279 continue;
280 }
281 if (!inTopLevel) continue;
282​
283 const match = trimmed.match(/^model_provider\s*=\s*["']([^"']+)["']/);
284 if (match) return match[1];
285 }
286 return undefined;
287});
288​
289export const hasCustomModelProvider = readCodexConfigModelProvider().pipe(
290 Effect.map((provider) => provider !== undefined && !OPENAI_AUTH_PROVIDERS.has(provider)),
291 Effect.orElseSucceed(() => false),
292);
293​
294const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
295​
296const probeCodexCapabilities = (input: {
297 readonly binaryPath: string;
298 readonly homePath?: string;
299}) =>
300 Effect.tryPromise((signal) => probeCodexAccount({ ...input, signal })).pipe(
301 Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
302 Effect.result,
303 Effect.map((result) => {
304 if (Result.isFailure(result)) return undefined;
305 return Option.isSome(result.success) ? result.success.value : undefined;
306 }),
307 );
308​
309const runCodexCommand = Effect.fn("runCodexCommand")(function* (args: ReadonlyArray<string>) {
310 const settingsService = yield* ServerSettingsService;
311 const codexSettings = yield* settingsService.getSettings.pipe(
312 Effect.map((settings) => settings.providers.codex),
313 );
314 const command = ChildProcess.make(codexSettings.binaryPath, [...args], {
315 shell: process.platform === "win32",
316 env: {
317 ...process.env,
318 ...(codexSettings.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
319 },
320 });
321 return yield* spawnAndCollect(codexSettings.binaryPath, command);
322});
323​
324export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
325 resolveAccount?: (input: {
326 readonly binaryPath: string;
327 readonly homePath?: string;
328 }) => Effect.Effect<CodexAccountSnapshot | undefined>,
329): Effect.fn.Return<
330 ServerProvider,
331 ServerSettingsError,
332 | ChildProcessSpawner.ChildProcessSpawner
333 | FileSystem.FileSystem
334 | Path.Path
335 | ServerSettingsService
336> {
337 const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
338 Effect.flatMap((service) => service.getSettings),
339 Effect.map((settings) => settings.providers.codex),
340 );
341 const checkedAt = new Date().toISOString();
342 const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, codexSettings.customModels);
343​
344 if (!codexSettings.enabled) {
345 return buildServerProvider({
346 provider: PROVIDER,
347 enabled: false,
348 checkedAt,
349 models,
350 probe: {
351 installed: false,
352 version: null,
353 status: "warning",
354 auth: { status: "unknown" },
355 message: "Codex is disabled in T3 Code settings.",
356 },
357 });
358 }
359​
360 const versionProbe = yield* runCodexCommand(["--version"]).pipe(
361 Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
362 Effect.result,
363 );
364​
365 if (Result.isFailure(versionProbe)) {
366 const error = versionProbe.failure;
367 return buildServerProvider({
368 provider: PROVIDER,
369 enabled: codexSettings.enabled,
370 checkedAt,
371 models,
372 probe: {
373 installed: !isCommandMissingCause(error),
374 version: null,
375 status: "error",
376 auth: { status: "unknown" },
377 message: isCommandMissingCause(error)
378 ? "Codex CLI (`codex`) is not installed or not on PATH."
379 : `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
380 },
381 });
382 }
383​
384 if (Option.isNone(versionProbe.success)) {
385 return buildServerProvider({
386 provider: PROVIDER,
387 enabled: codexSettings.enabled,
388 checkedAt,
389 models,
390 probe: {
391 installed: true,
392 version: null,
393 status: "error",
394 auth: { status: "unknown" },
395 message: "Codex CLI is installed but failed to run. Timed out while running command.",
396 },
397 });
398 }
399​
400 const version = versionProbe.success.value;
401 const parsedVersion =
402 parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ??
403 parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
404 if (version.code !== 0) {
405 const detail = detailFromResult(version);
406 return buildServerProvider({
407 provider: PROVIDER,
408 enabled: codexSettings.enabled,
409 checkedAt,
410 models,
411 probe: {
412 installed: true,
413 version: parsedVersion,
414 status: "error",
415 auth: { status: "unknown" },
416 message: detail
417 ? `Codex CLI is installed but failed to run. ${detail}`
418 : "Codex CLI is installed but failed to run.",
419 },
420 });
421 }
422​
423 if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
424 return buildServerProvider({
425 provider: PROVIDER,
426 enabled: codexSettings.enabled,
427 checkedAt,
428 models,
429 probe: {
430 installed: true,
431 version: parsedVersion,
432 status: "error",
433 auth: { status: "unknown" },
434 message: formatCodexCliUpgradeMessage(parsedVersion),
435 },
436 });
437 }
438​
439 if (yield* hasCustomModelProvider) {
440 return buildServerProvider({
441 provider: PROVIDER,
442 enabled: codexSettings.enabled,
443 checkedAt,
444 models,
445 probe: {
446 installed: true,
447 version: parsedVersion,
448 status: "ready",
449 auth: { status: "unknown" },
450 message: "Using a custom Codex model provider; OpenAI login check skipped.",
451 },
452 });
453 }
454​
455 const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
456 Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
457 Effect.result,
458 );
459 const account = resolveAccount
460 ? yield* resolveAccount({
461 binaryPath: codexSettings.binaryPath,
462 homePath: codexSettings.homePath,
463 })
464 : undefined;
465 const resolvedModels = adjustCodexModelsForAccount(models, account);
466​
467 if (Result.isFailure(authProbe)) {
468 const error = authProbe.failure;
469 return buildServerProvider({
470 provider: PROVIDER,
471 enabled: codexSettings.enabled,
472 checkedAt,
473 models: resolvedModels,
474 probe: {
475 installed: true,
476 version: parsedVersion,
477 status: "warning",
478 auth: { status: "unknown" },
479 message:
480 error instanceof Error
481 ? `Could not verify Codex authentication status: ${error.message}.`
482 : "Could not verify Codex authentication status.",
483 },
484 });
485 }
486​
487 if (Option.isNone(authProbe.success)) {
488 return buildServerProvider({
489 provider: PROVIDER,
490 enabled: codexSettings.enabled,
491 checkedAt,
492 models: resolvedModels,
493 probe: {
494 installed: true,
495 version: parsedVersion,
496 status: "warning",
497 auth: { status: "unknown" },
498 message: "Could not verify Codex authentication status. Timed out while running command.",
499 },
500 });
501 }
502​
503 const parsed = parseAuthStatusFromOutput(authProbe.success.value);
504 const authType = codexAuthSubType(account);
505 const authLabel = codexAuthSubLabel(account);
506 return buildServerProvider({
507 provider: PROVIDER,
508 enabled: codexSettings.enabled,
509 checkedAt,
510 models: resolvedModels,
511 probe: {
512 installed: true,
513 version: parsedVersion,
514 status: parsed.status,
515 auth: {
516 ...parsed.auth,
517 ...(authType ? { type: authType } : {}),
518 ...(authLabel ? { label: authLabel } : {}),
519 },
520 ...(parsed.message ? { message: parsed.message } : {}),
521 },
522 });
523});
524​
525export const CodexProviderLive = Layer.effect(
526 CodexProvider,
527 Effect.gen(function* () {
528 const serverSettings = yield* ServerSettingsService;
529 const fileSystem = yield* FileSystem.FileSystem;
530 const path = yield* Path.Path;
531 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
532 const accountProbeCache = yield* Cache.make({
533 capacity: 4,
534 timeToLive: Duration.minutes(5),
535 lookup: (key: string) => {
536 const [binaryPath, homePath] = JSON.parse(key) as [string, string | undefined];
537 return probeCodexCapabilities({
538 binaryPath,
539 ...(homePath ? { homePath } : {}),
540 });
541 },
542 });
543​
544 const checkProvider = checkCodexProviderStatus((input) =>
545 Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath])),
546 ).pipe(
547 Effect.provideService(ServerSettingsService, serverSettings),
548 Effect.provideService(FileSystem.FileSystem, fileSystem),
549 Effect.provideService(Path.Path, path),
550 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
551 );
552​
553 return yield* makeManagedServerProvider<CodexSettings>({
554 getSettings: serverSettings.getSettings.pipe(
555 Effect.map((settings) => settings.providers.codex),
556 Effect.orDie,
557 ),
558 streamSettings: serverSettings.streamChanges.pipe(
559 Stream.map((settings) => settings.providers.codex),
560 ),
561 haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
562 checkProvider,
563 });
564 }),
565);