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 { ServerSettingsError, ServerSettingsService } from "../../serverSettings";
50​
51const PROVIDER = "codex" as const;
52const OPENAI_AUTH_PROVIDERS = new Set(["openai"]);
53const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
54 {
55 slug: "gpt-5.4",
56 name: "GPT-5.4",
57 isCustom: false,
58 capabilities: {
59 reasoningEffortLevels: [
60 { value: "xhigh", label: "Extra High" },
61 { value: "high", label: "High", isDefault: true },
62 { value: "medium", label: "Medium" },
63 { value: "low", label: "Low" },
64 ],
65 supportsFastMode: true,
66 supportsThinkingToggle: false,
67 contextWindowOptions: [],
68 promptInjectedEffortLevels: [],
69 },
70 },
71 {
72 slug: "gpt-5.4-mini",
73 name: "GPT-5.4 Mini",
74 isCustom: false,
75 capabilities: {
76 reasoningEffortLevels: [
77 { value: "xhigh", label: "Extra High" },
78 { value: "high", label: "High", isDefault: true },
79 { value: "medium", label: "Medium" },
80 { value: "low", label: "Low" },
81 ],
82 supportsFastMode: true,
83 supportsThinkingToggle: false,
84 contextWindowOptions: [],
85 promptInjectedEffortLevels: [],
86 },
87 },
88 {
89 slug: "gpt-5.3-codex",
90 name: "GPT-5.3 Codex",
91 isCustom: false,
92 capabilities: {
93 reasoningEffortLevels: [
94 { value: "xhigh", label: "Extra High" },
95 { value: "high", label: "High", isDefault: true },
96 { value: "medium", label: "Medium" },
97 { value: "low", label: "Low" },
98 ],
99 supportsFastMode: true,
100 supportsThinkingToggle: false,
101 contextWindowOptions: [],
102 promptInjectedEffortLevels: [],
103 },
104 },
105 {
106 slug: "gpt-5.3-codex-spark",
107 name: "GPT-5.3 Codex Spark",
108 isCustom: false,
109 capabilities: {
110 reasoningEffortLevels: [
111 { value: "xhigh", label: "Extra High" },
112 { value: "high", label: "High", isDefault: true },
113 { value: "medium", label: "Medium" },
114 { value: "low", label: "Low" },
115 ],
116 supportsFastMode: true,
117 supportsThinkingToggle: false,
118 contextWindowOptions: [],
119 promptInjectedEffortLevels: [],
120 },
121 },
122 {
123 slug: "gpt-5.2-codex",
124 name: "GPT-5.2 Codex",
125 isCustom: false,
126 capabilities: {
127 reasoningEffortLevels: [
128 { value: "xhigh", label: "Extra High" },
129 { value: "high", label: "High", isDefault: true },
130 { value: "medium", label: "Medium" },
131 { value: "low", label: "Low" },
132 ],
133 supportsFastMode: true,
134 supportsThinkingToggle: false,
135 contextWindowOptions: [],
136 promptInjectedEffortLevels: [],
137 },
138 },
139 {
140 slug: "gpt-5.2",
141 name: "GPT-5.2",
142 isCustom: false,
143 capabilities: {
144 reasoningEffortLevels: [
145 { value: "xhigh", label: "Extra High" },
146 { value: "high", label: "High", isDefault: true },
147 { value: "medium", label: "Medium" },
148 { value: "low", label: "Low" },
149 ],
150 supportsFastMode: true,
151 supportsThinkingToggle: false,
152 contextWindowOptions: [],
153 promptInjectedEffortLevels: [],
154 },
155 },
156];
157​
158export function getCodexModelCapabilities(model: string | null | undefined): ModelCapabilities {
159 const slug = model?.trim();
160 return (
161 BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? {
162 reasoningEffortLevels: [],
163 supportsFastMode: false,
164 supportsThinkingToggle: false,
165 contextWindowOptions: [],
166 promptInjectedEffortLevels: [],
167 }
168 );
170​
171export function parseAuthStatusFromOutput(result: CommandResult): {
172 readonly status: Exclude<ServerProviderState, "disabled">;
173 readonly auth: Pick<ServerProviderAuth, "status">;
174 readonly message?: string;
175} {
176 const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
177​
178 if (
179 lowerOutput.includes("unknown command") ||
180 lowerOutput.includes("unrecognized command") ||
181 lowerOutput.includes("unexpected argument")
182 ) {
183 return {
184 status: "warning",
185 auth: { status: "unknown" },
186 message: "Codex CLI authentication status command is unavailable in this Codex version.",
187 };
188 }
189​
190 if (
191 lowerOutput.includes("not logged in") ||
192 lowerOutput.includes("login required") ||
193 lowerOutput.includes("authentication required") ||
194 lowerOutput.includes("run `codex login`") ||
195 lowerOutput.includes("run codex login")
196 ) {
197 return {
198 status: "error",
199 auth: { status: "unauthenticated" },
200 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
201 };
202 }
203​
204 const parsedAuth = (() => {
205 const trimmed = result.stdout.trim();
206 if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
207 return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
208 }
209 try {
210 return {
211 attemptedJsonParse: true as const,
212 auth: extractAuthBoolean(JSON.parse(trimmed)),
213 };
214 } catch {
215 return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
216 }
217 })();
218​
219 if (parsedAuth.auth === true) {
220 return { status: "ready", auth: { status: "authenticated" } };
221 }
222 if (parsedAuth.auth === false) {
223 return {
224 status: "error",
225 auth: { status: "unauthenticated" },
226 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
227 };
228 }
229 if (parsedAuth.attemptedJsonParse) {
230 return {
231 status: "warning",
232 auth: { status: "unknown" },
233 message:
234 "Could not verify Codex authentication status from JSON output (missing auth marker).",
235 };
236 }
237 if (result.code === 0) {
238 return { status: "ready", auth: { status: "authenticated" } };
239 }
240​
241 const detail = detailFromResult(result);
242 return {
243 status: "warning",
244 auth: { status: "unknown" },
245 message: detail
246 ? `Could not verify Codex authentication status. ${detail}`
247 : "Could not verify Codex authentication status.",
248 };
250​
251export const readCodexConfigModelProvider = Effect.fn("readCodexConfigModelProvider")(function* () {
252 const fileSystem = yield* FileSystem.FileSystem;
253 const path = yield* Path.Path;
254 const settingsService = yield* ServerSettingsService;
255 const codexHome = yield* settingsService.getSettings.pipe(
256 Effect.map(
257 (settings) =>
258 settings.providers.codex.homePath ||
259 process.env.CODEX_HOME ||
260 path.join(OS.homedir(), ".codex"),
261 ),
262 );
263 const configPath = path.join(codexHome, "config.toml");
264​
265 const content = yield* fileSystem
266 .readFileString(configPath)
267 .pipe(Effect.orElseSucceed(() => undefined));
268 if (content === undefined) {
269 return undefined;
270 }
271​
272 let inTopLevel = true;
273 for (const line of content.split("\n")) {
274 const trimmed = line.trim();
275 if (!trimmed || trimmed.startsWith("#")) continue;
276 if (trimmed.startsWith("[")) {
277 inTopLevel = false;
278 continue;
279 }
280 if (!inTopLevel) continue;
281​
282 const match = trimmed.match(/^model_provider\s*=\s*["']([^"']+)["']/);
283 if (match) return match[1];
284 }
285 return undefined;
286});
287​
288export const hasCustomModelProvider = readCodexConfigModelProvider().pipe(
289 Effect.map((provider) => provider !== undefined && !OPENAI_AUTH_PROVIDERS.has(provider)),
290 Effect.orElseSucceed(() => false),
291);
292​
293const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
294​
295const probeCodexCapabilities = (input: {
296 readonly binaryPath: string;
297 readonly homePath?: string;
298}) =>
299 Effect.tryPromise((signal) => probeCodexAccount({ ...input, signal })).pipe(
300 Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
301 Effect.result,
302 Effect.map((result) => {
303 if (Result.isFailure(result)) return undefined;
304 return Option.isSome(result.success) ? result.success.value : undefined;
305 }),
306 );
307​
308const runCodexCommand = (args: ReadonlyArray<string>) =>
309 Effect.gen(function* () {
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);