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

CodexProvider.ts

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