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

CodexProvider.ts

649 lines18.6 KB

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