tuxevil-rotator 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/onboarding.ts CHANGED
@@ -15,6 +15,21 @@ import {
15
15
  defaultAccountEmail,
16
16
  validateApiKey,
17
17
  } from "./providers/ollama/api-key-validation.js";
18
+ import {
19
+ validateApiKey as validateZenApiKey,
20
+ } from "./providers/opencode-zen/login.js";
21
+ import {
22
+ defaultAccountEmail as zenDefaultAccountEmail,
23
+ OPENCODE_ZEN_PROVIDER_ID,
24
+ } from "./providers/opencode-zen/credentials.js";
25
+ import {
26
+ codexOAuthErrorMessage,
27
+ createCodexAuthorizationFlow,
28
+ exchangeCodexAuthorizationCode,
29
+ getCodexOAuthConfig,
30
+ parseCodexIdentity,
31
+ type CodexOAuthConfig,
32
+ } from "./providers/openai-codex/oauth.js";
18
33
  import type { AccountConfig } from "./types.js";
19
34
 
20
35
  interface AccountSink {
@@ -261,11 +276,13 @@ export function startHostedLogin(
261
276
  // user signs in and pastes the redirect URL back, server exchanges the code.
262
277
 
263
278
  interface CliLoginSession {
279
+ provider: "google-antigravity" | "openai-codex";
264
280
  verifier: string;
265
281
  challenge: string;
266
282
  oauthState: string;
267
283
  authUrl: string;
268
284
  createdAt: number;
285
+ codexConfig?: CodexOAuthConfig;
269
286
  }
270
287
 
271
288
  const cliLoginSessions = new Map<string, CliLoginSession>();
@@ -283,27 +300,44 @@ export function serveCliLogin(res: ServerResponse): void {
283
300
  pruneCliSessions();
284
301
  const { verifier, challenge } = generatePkce();
285
302
  const oauthState = generateState();
286
- let authUrl: string;
303
+ let authUrl: string | null = null;
304
+ let sessionId: string | null = null;
287
305
  try {
288
306
  authUrl = buildAuthUrl(oauthState, challenge);
289
- } catch (err) {
290
- res.writeHead(503, { "Content-Type": "text/html; charset=utf-8" });
291
- res.end(
292
- renderPage(
293
- "OAuth Not Configured",
294
- `<h1>OAuth Login Isn’t Ready</h1><p>${escapeHtml(err instanceof Error ? err.message : String(err))}</p>`,
295
- ),
296
- );
297
- return;
307
+ sessionId = generateState();
308
+ cliLoginSessions.set(sessionId, {
309
+ provider: "google-antigravity",
310
+ verifier,
311
+ challenge,
312
+ oauthState,
313
+ authUrl,
314
+ createdAt: Date.now(),
315
+ });
316
+ } catch {
317
+ // Google is optional for this provider-aware page. Codex and Ollama stay
318
+ // available when Antigravity OAuth is not configured.
319
+ }
320
+
321
+ let codexAuthUrl: string | null = null;
322
+ let codexSessionId: string | null = null;
323
+ try {
324
+ const codexConfig = getCodexOAuthConfig();
325
+ const codexFlow = createCodexAuthorizationFlow(codexConfig);
326
+ codexSessionId = generateState();
327
+ codexAuthUrl = codexFlow.url;
328
+ cliLoginSessions.set(codexSessionId, {
329
+ provider: "openai-codex",
330
+ verifier: codexFlow.verifier,
331
+ challenge: "",
332
+ oauthState: codexFlow.state,
333
+ authUrl: codexFlow.url,
334
+ createdAt: Date.now(),
335
+ codexConfig,
336
+ });
337
+ } catch {
338
+ // Keep Google/Ollama login usable if an operator supplied malformed Codex
339
+ // OAuth environment overrides.
298
340
  }
299
- const sessionId = generateState();
300
- cliLoginSessions.set(sessionId, {
301
- verifier,
302
- challenge,
303
- oauthState,
304
- authUrl,
305
- createdAt: Date.now(),
306
- });
307
341
 
308
342
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
309
343
  res.end(
@@ -314,11 +348,12 @@ export function serveCliLogin(res: ServerResponse): void {
314
348
 
315
349
  <div class="tabs">
316
350
  <button class="tab active" data-panel="panel-google">Google (Antigravity)</button>
351
+ <button class="tab" data-panel="panel-codex">OpenAI Codex</button>
317
352
  <button class="tab" data-panel="panel-ollama">Ollama Cloud</button>
318
353
  </div>
319
354
 
320
355
  <div class="panel active" id="panel-google">
321
- <h3 style="margin:24px 0 8px;font-size:18px;">Step 1 &mdash; Sign in with Google</h3>
356
+ ${authUrl && sessionId ? `<h3 style="margin:24px 0 8px;font-size:18px;">Step 1 &mdash; Sign in with Google</h3>
322
357
  <p>Click the button below to open the Google sign-in page in a new tab:</p>
323
358
  <a class="cta" href="${escapeHtml(authUrl)}" target="_blank" rel="noopener" style="font-size:16px;">
324
359
  Sign in with Google &nearr;
@@ -336,7 +371,29 @@ export function serveCliLogin(res: ServerResponse): void {
336
371
  <button type="submit" class="cta" style="cursor:pointer;border:none;font-family:inherit;font-size:16px;margin-top:12px;">
337
372
  Connect Account
338
373
  </button>
339
- </form>
374
+ </form>` : `<div class="note error">Google OAuth is not configured for this server. Set ANTIGRAVITY_CLIENT_ID, ANTIGRAVITY_CLIENT_SECRET and ANTIGRAVITY_REDIRECT_URI to enable it.</div>`}
375
+ </div>
376
+
377
+ <div class="panel" id="panel-codex">
378
+ ${codexAuthUrl && codexSessionId ? `<h3 style="margin:24px 0 8px;font-size:18px;">Step 1 &mdash; Sign in with ChatGPT</h3>
379
+ <p>Open the OpenAI sign-in page in a new tab. Codex OAuth will return to the loopback URL configured for the Codex CLI.</p>
380
+ <a class="cta" href="${escapeHtml(codexAuthUrl)}" target="_blank" rel="noopener" style="font-size:16px;">
381
+ Sign in with OpenAI Codex &nearr;
382
+ </a>
383
+
384
+ <h3 style="margin:24px 0 8px;font-size:18px;">Step 2 &mdash; Paste the callback URL</h3>
385
+ <p>Copy the complete URL from the browser address bar, even if the loopback page does not load, and paste it here:</p>
386
+ <form id="codexPasteForm" style="margin-top:12px;">
387
+ <input type="hidden" name="session" value="${escapeHtml(codexSessionId)}" />
388
+ <textarea name="redirectUrl" rows="4" placeholder="Paste the Codex callback URL (http://localhost:1455/auth/callback?... )" style="
389
+ width:100%;font-family:'IBM Plex Mono',monospace;font-size:13px;
390
+ padding:12px 14px;border-radius:12px;border:1px solid rgba(31,42,31,0.15);
391
+ background:rgba(31,42,31,0.03);resize:vertical;
392
+ "></textarea>
393
+ <button type="submit" class="cta" style="cursor:pointer;border:none;font-family:inherit;font-size:16px;margin-top:12px;">
394
+ Connect Codex Account
395
+ </button>
396
+ </form>` : `<div class="note error">Codex OAuth is not available because its configuration is invalid. Check the CODEX_OAUTH_* environment variables and reload this page.</div>`}
340
397
  </div>
341
398
 
342
399
  <div class="panel" id="panel-ollama">
@@ -367,7 +424,8 @@ function showResult(html) {
367
424
  document.getElementById('result').innerHTML = html;
368
425
  }
369
426
 
370
- document.getElementById('pasteForm').addEventListener('submit', async (e) => {
427
+ const googleForm = document.getElementById('pasteForm');
428
+ if (googleForm) googleForm.addEventListener('submit', async (e) => {
371
429
  e.preventDefault();
372
430
  const form = e.target;
373
431
  const btn = form.querySelector('button[type=submit]');
@@ -453,6 +511,48 @@ document.getElementById('keyForm').addEventListener('submit', async (e) => {
453
511
  btn.textContent = 'Connect Account';
454
512
  }
455
513
  });
514
+
515
+ const codexForm = document.getElementById('codexPasteForm');
516
+ if (codexForm) codexForm.addEventListener('submit', async (e) => {
517
+ e.preventDefault();
518
+ const form = e.target;
519
+ const btn = form.querySelector('button[type=submit]');
520
+ const redirectUrl = form.redirectUrl.value.trim();
521
+ const session = form.session.value;
522
+ if (!redirectUrl) { showResult('<div class="note error">Please paste the Codex callback URL.</div>'); return; }
523
+ btn.disabled = true;
524
+ btn.textContent = 'Connecting...';
525
+ showResult('<div class="note">Exchanging the Codex authorization code securely...</div>');
526
+ try {
527
+ const params = new URLSearchParams(window.location.search);
528
+ const token = params.get('token') || '';
529
+ const res = await fetch('/api/cli-login', {
530
+ method: 'POST',
531
+ headers: { 'Content-Type': 'application/json', ...(token ? { 'X-Rotator-Admin-Token': token } : {}) },
532
+ body: JSON.stringify({ provider: 'openai-codex', session, redirectUrl }),
533
+ });
534
+ const data = await res.json();
535
+ if (data.ok) {
536
+ showResult('<div class="note" style="border-left-color:var(--accent);background:rgba(30,107,82,0.12);"><strong id="codexLoginResultEmail"></strong> ' + (data.isNew ? 'added' : 'updated') + ' successfully. The isolated Codex pool is ready.</div>');
537
+ document.getElementById('codexLoginResultEmail').textContent = data.email || '';
538
+ } else {
539
+ const errorDiv = document.createElement('div');
540
+ errorDiv.className = 'note error';
541
+ errorDiv.textContent = data.error || 'Unknown error';
542
+ document.getElementById('result').innerHTML = '';
543
+ document.getElementById('result').appendChild(errorDiv);
544
+ }
545
+ } catch (err) {
546
+ const errorDiv = document.createElement('div');
547
+ errorDiv.className = 'note error';
548
+ errorDiv.textContent = 'Request failed: ' + err.message;
549
+ document.getElementById('result').innerHTML = '';
550
+ document.getElementById('result').appendChild(errorDiv);
551
+ } finally {
552
+ btn.disabled = false;
553
+ btn.textContent = 'Connect Codex Account';
554
+ }
555
+ });
456
556
  </script>
457
557
  `,
458
558
  ),
@@ -499,6 +599,11 @@ export async function handleCliLoginApi(
499
599
  return;
500
600
  }
501
601
 
602
+ if (provider === "openai-codex") {
603
+ await handleCodexCliLogin(body, res, rotator);
604
+ return;
605
+ }
606
+
502
607
  if (provider !== "google-antigravity") {
503
608
  res.writeHead(400, { "Content-Type": "application/json" });
504
609
  res.end(JSON.stringify({ ok: false, error: `Unknown provider "${provider}"` }));
@@ -533,6 +638,11 @@ export async function handleCliLoginApi(
533
638
  );
534
639
  return;
535
640
  }
641
+ if (session.provider !== "google-antigravity") {
642
+ res.writeHead(400, { "Content-Type": "application/json" });
643
+ res.end(JSON.stringify({ ok: false, error: "Session does not belong to Google login" }));
644
+ return;
645
+ }
536
646
 
537
647
  // Parse the redirect URL to extract code
538
648
  let code: string | undefined;
@@ -612,6 +722,107 @@ export async function handleCliLoginApi(
612
722
  }
613
723
  }
614
724
 
725
+ async function handleCodexCliLogin(
726
+ body: { session?: string; redirectUrl?: string },
727
+ res: ServerResponse,
728
+ rotator: AccountSink,
729
+ ): Promise<void> {
730
+ const sessionId = body.session;
731
+ const redirectUrl = body.redirectUrl;
732
+ if (
733
+ typeof sessionId !== "string" ||
734
+ typeof redirectUrl !== "string" ||
735
+ sessionId.length === 0 ||
736
+ redirectUrl.length === 0 ||
737
+ sessionId.length > 256 ||
738
+ redirectUrl.length > 8 * 1024
739
+ ) {
740
+ res.writeHead(400, { "Content-Type": "application/json" });
741
+ res.end(JSON.stringify({ ok: false, error: "Missing session or redirectUrl" }));
742
+ return;
743
+ }
744
+
745
+ pruneCliSessions();
746
+ const session = cliLoginSessions.get(sessionId);
747
+ if (!session || session.provider !== "openai-codex" || !session.codexConfig) {
748
+ res.writeHead(400, { "Content-Type": "application/json" });
749
+ res.end(JSON.stringify({
750
+ ok: false,
751
+ error: "Session expired or invalid. Reload the page and try again.",
752
+ }));
753
+ return;
754
+ }
755
+
756
+ let code: string | undefined;
757
+ let state: string | null;
758
+ try {
759
+ const url = new URL(redirectUrl.trim());
760
+ code = url.searchParams.get("code") ?? undefined;
761
+ state = url.searchParams.get("state");
762
+ } catch {
763
+ res.writeHead(400, { "Content-Type": "application/json" });
764
+ res.end(JSON.stringify({
765
+ ok: false,
766
+ error: "Could not parse the URL. Paste the complete Codex callback URL.",
767
+ }));
768
+ return;
769
+ }
770
+
771
+ if (!code) {
772
+ res.writeHead(400, { "Content-Type": "application/json" });
773
+ res.end(JSON.stringify({ ok: false, error: "No authorization code found in the URL." }));
774
+ return;
775
+ }
776
+ if (state !== session.oauthState) {
777
+ res.writeHead(400, { "Content-Type": "application/json" });
778
+ res.end(JSON.stringify({
779
+ ok: false,
780
+ error: "State mismatch - reload the login page and try again.",
781
+ }));
782
+ return;
783
+ }
784
+
785
+ // Consume the one-time browser session before exchanging the authorization
786
+ // code. A retry must start a new PKCE flow.
787
+ cliLoginSessions.delete(sessionId);
788
+
789
+ try {
790
+ const tokens = await exchangeCodexAuthorizationCode(
791
+ code,
792
+ session.verifier,
793
+ session.codexConfig,
794
+ );
795
+ const identity = parseCodexIdentity(tokens.accessToken, tokens.idToken);
796
+ const email = identity.email ??
797
+ (identity.providerAccountId ? `${identity.providerAccountId}@codex.local` : undefined);
798
+ if (!email) throw new Error("Codex OAuth did not return an account identity");
799
+
800
+ const entry: AccountConfig = {
801
+ email,
802
+ label: email.split("@")[0],
803
+ provider: "openai-codex",
804
+ credentials: [{
805
+ provider: "openai-codex",
806
+ refreshToken: tokens.refreshToken,
807
+ ...(identity.providerAccountId ? { providerAccountId: identity.providerAccountId } : {}),
808
+ }],
809
+ };
810
+ const { isNew } = await addAccountToConfig(entry);
811
+ await rotator.addOrUpdateAccount(entry);
812
+
813
+ res.writeHead(200, { "Content-Type": "application/json" });
814
+ res.end(JSON.stringify({ ok: true, email: entry.email, isNew, provider: "openai-codex" }));
815
+ } catch (error) {
816
+ res.writeHead(400, { "Content-Type": "application/json" });
817
+ res.end(JSON.stringify({
818
+ ok: false,
819
+ error: error instanceof Error && error.message.startsWith("Codex OAuth")
820
+ ? codexOAuthErrorMessage(error)
821
+ : "Unable to complete Codex login. Please reload and try again.",
822
+ }));
823
+ }
824
+ }
825
+
615
826
  const MAX_ACCOUNT_EMAIL_LENGTH = 320;
616
827
  const MAX_ACCOUNT_LABEL_LENGTH = 200;
617
828
 
@@ -42,6 +42,17 @@ export interface QuotaFetchContext {
42
42
  statusCode: number,
43
43
  errorText: string,
44
44
  ): void;
45
+ /** Provider-scoped invalidation/cooldown hooks; never affect sibling providers. */
46
+ markProviderInvalid?(
47
+ account: AccountRuntime,
48
+ providerId: string,
49
+ reason: string,
50
+ ): void;
51
+ setProviderCooldown?(
52
+ account: AccountRuntime,
53
+ providerId: string,
54
+ durationMs: number,
55
+ ): void;
45
56
  }
46
57
 
47
58
  export type CredentialValidationResult =
@@ -9,6 +9,7 @@ export interface CredentialEntry {
9
9
  apiKey?: string;
10
10
  refreshToken?: string;
11
11
  projectId?: string;
12
+ providerAccountId?: string;
12
13
  projectSource?: "google" | "manual";
13
14
  proxyUrl?: string;
14
15
  }
@@ -19,6 +20,8 @@ export interface AccountLike {
19
20
  apiKey?: string;
20
21
  refreshToken?: string;
21
22
  projectId?: string;
23
+ codexRefreshToken?: string;
24
+ codexAccountId?: string;
22
25
  projectSource?: "google" | "manual";
23
26
  proxyUrl?: string;
24
27
  }
@@ -50,6 +53,10 @@ export function getCredential(
50
53
  if (account.apiKey !== undefined) legacy.apiKey = account.apiKey;
51
54
  if (account.refreshToken !== undefined) legacy.refreshToken = account.refreshToken;
52
55
  if (account.projectId !== undefined) legacy.projectId = account.projectId;
56
+ if (providerId === "openai-codex") {
57
+ if (account.codexRefreshToken !== undefined) legacy.refreshToken = account.codexRefreshToken;
58
+ if (account.codexAccountId !== undefined) legacy.providerAccountId = account.codexAccountId;
59
+ }
53
60
  if (account.projectSource !== undefined) legacy.projectSource = account.projectSource;
54
61
  if (account.proxyUrl !== undefined) legacy.proxyUrl = account.proxyUrl;
55
62
  return legacy;
@@ -353,6 +353,14 @@ export function convertToolChoiceToGemini(
353
353
  return { functionCallingConfig: { mode: "AUTO" } };
354
354
  }
355
355
 
356
+ function forcesToolUse(toolChoice: unknown): boolean {
357
+ if (toolChoice === "required") return true;
358
+ return isRecord(toolChoice) &&
359
+ toolChoice.type === "function" &&
360
+ ((isRecord(toolChoice.function) && isNonEmptyString(toolChoice.function.name)) ||
361
+ isNonEmptyString(toolChoice.name));
362
+ }
363
+
356
364
  export function validateMessages(value: unknown): value is ChatMessage[] {
357
365
  return (
358
366
  Array.isArray(value) &&
@@ -1089,26 +1097,27 @@ export function openAIToAntigravityBody(
1089
1097
  }
1090
1098
  }
1091
1099
 
1092
- if (isClaude) {
1093
- while (contents.at(-1)?.role === "model") {
1094
- const lastContent = contents.at(-1);
1095
- const hasFunctionCall =
1096
- lastContent?.parts.some((p: any) => isRecord(p) && p.functionCall) ??
1097
- false;
1098
- if (hasFunctionCall) {
1099
- contents.pop();
1100
- continue;
1101
- }
1102
- contents.push({
1103
- role: "user",
1104
- parts: [
1105
- {
1106
- text: "Continue from the previous assistant message. Do not repeat completed tool calls unless new user input asks for them.",
1107
- },
1108
- ],
1109
- });
1110
- break;
1100
+ // Google rejects compatibility requests whose final contents turn is a
1101
+ // model turn. Claude additionally needs dangling tool-call turns removed;
1102
+ // other models keep the call history but still need a user turn to resume.
1103
+ while (contents.at(-1)?.role === "model") {
1104
+ const lastContent = contents.at(-1);
1105
+ const hasFunctionCall =
1106
+ lastContent?.parts.some((p: any) => isRecord(p) && p.functionCall) ??
1107
+ false;
1108
+ if (isClaude && hasFunctionCall) {
1109
+ contents.pop();
1110
+ continue;
1111
1111
  }
1112
+ contents.push({
1113
+ role: "user",
1114
+ parts: [
1115
+ {
1116
+ text: "Continue from the previous assistant message. Do not repeat completed tool calls unless new user input asks for them.",
1117
+ },
1118
+ ],
1119
+ });
1120
+ break;
1112
1121
  }
1113
1122
 
1114
1123
  if (contents.length === 0)
@@ -1135,7 +1144,7 @@ export function openAIToAntigravityBody(
1135
1144
  }
1136
1145
 
1137
1146
  let thinkingConfigObj: Record<string, unknown> | undefined;
1138
- if (modelFamily === "claude" && isThinking) {
1147
+ if (modelFamily === "claude" && isThinking && !forcesToolUse(input.tool_choice)) {
1139
1148
  const tb = modelSpec.thinkingBudget;
1140
1149
  thinkingConfigObj = { include_thoughts: true, thinking_budget: tb };
1141
1150
  if (!maxOutputTokens || maxOutputTokens <= tb) {
@@ -1144,7 +1153,7 @@ export function openAIToAntigravityBody(
1144
1153
  `Adjusted Claude maxOutputTokens → ${maxOutputTokens}`,
1145
1154
  );
1146
1155
  }
1147
- } else if (isThinking) {
1156
+ } else if (isThinking && modelFamily !== "claude") {
1148
1157
  const tb = modelSpec.thinkingBudget;
1149
1158
  thinkingConfigObj =
1150
1159
  tb === -1
@@ -0,0 +1,117 @@
1
+ import type { AccountRuntime } from "../../types.js";
2
+ import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
3
+ import { getCodexAccountId, getCodexTokenState } from "./credentials.js";
4
+ import { codexBaseUrl } from "./forward.js";
5
+ import { CODEX_PROVIDER_ID } from "./oauth.js";
6
+
7
+ export interface CodexModel {
8
+ id: string;
9
+ contextWindow: number;
10
+ reasoning: boolean;
11
+ multimodal: boolean;
12
+ tools: boolean;
13
+ source: "allowlist" | "discovered";
14
+ }
15
+
16
+ // Only models validated by the initial unauthenticated/public spike are in the
17
+ // safe base list. Authenticated discovery can add provider-owned GPT-5 IDs.
18
+ // The Codex /models endpoint can expose models from other ChatGPT-backed
19
+ // providers (for example Claude), so model IDs alone must be filtered before
20
+ // they influence routing.
21
+ const CODEX_CONTEXT_WINDOW = 272_000;
22
+ const CODEX_DISCOVERED_ID_PATTERN = /^gpt-5(?:\.\d+)?(?:-[a-z0-9]+)+$/i;
23
+ export const CODEX_BASE_MODELS: readonly CodexModel[] = [
24
+ { id: "gpt-5.6-sol", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
25
+ { id: "gpt-5.6-terra", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
26
+ { id: "gpt-5.6-luna", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
27
+ ];
28
+
29
+ let discoveredModels: CodexModel[] = [];
30
+
31
+ export function isCodexModel(model: string): boolean {
32
+ return getCodexModel(model) !== undefined;
33
+ }
34
+
35
+ export function isCodexRequestModel(model: string): boolean {
36
+ return isCodexModel(model);
37
+ }
38
+
39
+ export function getCodexModel(model: string): CodexModel | undefined {
40
+ const normalized = model.trim().toLowerCase();
41
+ return [...discoveredModels, ...CODEX_BASE_MODELS].find(
42
+ (entry) => entry.id.toLowerCase() === normalized,
43
+ );
44
+ }
45
+
46
+ export function getCodexModels(): CodexModel[] {
47
+ const merged = new Map<string, CodexModel>();
48
+ for (const entry of [...CODEX_BASE_MODELS, ...discoveredModels]) merged.set(entry.id, entry);
49
+ return [...merged.values()];
50
+ }
51
+
52
+ export function isCodexProviderModelId(value: unknown): value is string {
53
+ return typeof value === "string" &&
54
+ isSafeModelId(value) &&
55
+ CODEX_DISCOVERED_ID_PATTERN.test(value);
56
+ }
57
+
58
+ export function setDiscoveredCodexModels(models: CodexModel[]): void {
59
+ discoveredModels = models.filter((model) => isCodexProviderModelId(model.id));
60
+ }
61
+
62
+ function isSafeModelId(value: unknown): value is string {
63
+ return typeof value === "string" && /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(value);
64
+ }
65
+
66
+ function parseModel(value: unknown): CodexModel | null {
67
+ if (typeof value === "string") {
68
+ return isCodexProviderModelId(value)
69
+ ? { id: value, contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "discovered" }
70
+ : null;
71
+ }
72
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
73
+ const record = value as Record<string, unknown>;
74
+ const id = record.id ?? record.model ?? record.name;
75
+ if (!isCodexProviderModelId(id)) return null;
76
+ const contextWindow = [record.context_window, record.contextWindow, record.context_length]
77
+ .find((candidate) => typeof candidate === "number" && Number.isFinite(candidate) && candidate > 0);
78
+ return {
79
+ id,
80
+ contextWindow: typeof contextWindow === "number" ? Math.min(contextWindow, 2_000_000) : CODEX_CONTEXT_WINDOW,
81
+ reasoning: record.reasoning !== false,
82
+ multimodal: record.multimodal !== false && record.vision !== false,
83
+ tools: record.tools !== false && record.tool_calling !== false,
84
+ source: "discovered",
85
+ };
86
+ }
87
+
88
+ export async function fetchCodexCatalog(
89
+ account: AccountRuntime,
90
+ signal?: AbortSignal,
91
+ ): Promise<CodexModel[]> {
92
+ const token = getCodexTokenState(account).accessToken;
93
+ if (!token) return getCodexModels();
94
+ const base = codexBaseUrl();
95
+ const endpoint = base.endsWith("/models") ? base : `${base}/models`;
96
+ try {
97
+ const headers: Record<string, string> = {
98
+ Authorization: `Bearer ${token}`,
99
+ Accept: "application/json",
100
+ };
101
+ const accountId = getCodexAccountId(account.config);
102
+ if (accountId) headers["chatgpt-account-id"] = accountId;
103
+ const response = await fetch(endpoint, {
104
+ headers,
105
+ signal: signal ?? AbortSignal.timeout(8_000),
106
+ dispatcher: getAccountProxyDispatcher(account, CODEX_PROVIDER_ID),
107
+ } as RequestInit & { dispatcher?: unknown });
108
+ if (!response.ok) return getCodexModels();
109
+ const data = await response.json() as Record<string, unknown>;
110
+ const raw = Array.isArray(data.data) ? data.data : Array.isArray(data.models) ? data.models : [];
111
+ const parsed = raw.map(parseModel).filter((model): model is CodexModel => model !== null);
112
+ if (parsed.length > 0) setDiscoveredCodexModels(parsed);
113
+ } catch {
114
+ // Discovery is optional; the safe allowlist remains available.
115
+ }
116
+ return getCodexModels();
117
+ }