tuxevil-rotator 4.2.1 → 4.3.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.
Files changed (41) hide show
  1. package/CHANGELOG.md +48 -1
  2. package/README.md +20 -6
  3. package/package.json +3 -3
  4. package/plugins/opencode-discovery/capabilities.d.mts +7 -0
  5. package/plugins/opencode-discovery/capabilities.mjs +54 -0
  6. package/plugins/opencode-discovery/index.d.mts +60 -0
  7. package/plugins/opencode-discovery/index.mjs +333 -0
  8. package/plugins/opencode-discovery/package.json +24 -0
  9. package/src/audio-transcription.ts +32 -6
  10. package/src/cli.ts +3 -3
  11. package/src/compat/model-specs.ts +4 -0
  12. package/src/compat.ts +34 -6
  13. package/src/dashboard-app.ts +1 -0
  14. package/src/install-agent.ts +252 -143
  15. package/src/install-opencode.ts +211 -43
  16. package/src/providers/google-antigravity/catalog.ts +45 -166
  17. package/src/providers/google-antigravity/dynamic-catalog.ts +107 -10
  18. package/src/providers/google-antigravity/forward.ts +4 -2
  19. package/src/providers/google-antigravity/index.ts +12 -4
  20. package/src/providers/google-antigravity/quota.ts +9 -7
  21. package/src/providers/ollama/forward.ts +10 -0
  22. package/src/providers/openai-codex/catalog.ts +157 -18
  23. package/src/proxy.ts +54 -5
  24. package/src/rotator.ts +32 -22
  25. package/src/types.ts +79 -67
  26. package/src/web/app.tsx +4 -0
  27. package/src/web/lib/audio-recorder.ts +159 -0
  28. package/src/web/lib/colors.ts +4 -0
  29. package/src/web/lib/playground-storage.ts +261 -0
  30. package/src/web/lib/playground.ts +448 -0
  31. package/src/web/nav.ts +1 -0
  32. package/src/web/pages/Playground.tsx +1111 -0
  33. package/src/web/pages/Transcription.tsx +428 -0
  34. package/src/web/state/api.ts +3 -0
  35. package/src/web/state/playground-client.ts +136 -0
  36. package/src/web/state/playground.ts +69 -0
  37. package/src/web/state/router.ts +2 -2
  38. package/src/web/state/transcription-client.ts +93 -0
  39. package/src/web/styles/app.css +45 -0
  40. package/tools/telemetry-receiver/receiver.js +59 -46
  41. package/plugins/opencode-discovery.js +0 -174
@@ -8,6 +8,7 @@ import {
8
8
  QUOTA_MODEL_KEYS,
9
9
  type GoogleQuotaResponse,
10
10
  type PersistedDynamicModelOwnership,
11
+ type PersistedDynamicModelSnapshots,
11
12
  } from "../../types.js";
12
13
 
13
14
  export interface DynamicModelEntry {
@@ -60,8 +61,7 @@ function isDiscoverableModelId(value: string): boolean {
60
61
  return isSafeModelId(id) &&
61
62
  !RESERVED_QUOTA_MODEL_IDS.has(lower) &&
62
63
  !lower.startsWith("chat_") &&
63
- !lower.startsWith("tab_") &&
64
- (!lower.startsWith("gemini-3.5-") || lower === "gemini-3.5-flash-lite");
64
+ !lower.startsWith("tab_");
65
65
  }
66
66
 
67
67
  /** Validate and sanitize the untrusted runtime catalog response. */
@@ -213,6 +213,7 @@ function familyDefaults(
213
213
  export class DynamicModelRegistry {
214
214
  private static instance: DynamicModelRegistry | null = null;
215
215
  private accountModels = new Map<string, Map<string, DynamicModelEntry>>();
216
+ private snapshotTimes = new Map<string, number>();
216
217
  private defaultAgentModelIds = new Map<string, string>();
217
218
  private discoveredModels = new Map<
218
219
  string,
@@ -225,6 +226,7 @@ export class DynamicModelRegistry {
225
226
  ActiveAccountGeneration
226
227
  > | null = null;
227
228
  private nextAccountEpoch = 0;
229
+ snapshotRevision = 0;
228
230
 
229
231
  static getInstance(): DynamicModelRegistry {
230
232
  DynamicModelRegistry.instance ??= new DynamicModelRegistry();
@@ -234,6 +236,7 @@ export class DynamicModelRegistry {
234
236
  /** Reset dynamic account state (primarily for tests). */
235
237
  reset(): void {
236
238
  this.accountModels.clear();
239
+ this.snapshotTimes.clear();
237
240
  this.defaultAgentModelIds.clear();
238
241
  this.discoveredModels.clear();
239
242
  this.accountModelOwnership.clear();
@@ -285,13 +288,6 @@ export class DynamicModelRegistry {
285
288
  );
286
289
  let newModelsCount = 0;
287
290
 
288
- if (data.defaultAgentModelId) {
289
- this.defaultAgentModelIds.delete(key);
290
- this.defaultAgentModelIds.set(key, data.defaultAgentModelId);
291
- } else {
292
- this.defaultAgentModelIds.delete(key);
293
- }
294
-
295
291
  for (const [rawId, info] of Object.entries(data.models)) {
296
292
  const normalizedId = rawId.trim();
297
293
  const lowerId = normalizedId.toLowerCase();
@@ -356,6 +352,36 @@ export class DynamicModelRegistry {
356
352
  if (!knownBefore.has(lowerId)) newModelsCount++;
357
353
  }
358
354
 
355
+ const reportedIds = Object.keys(data.models);
356
+ const hasUsableQuotaData = reportedIds.some((id) =>
357
+ Object.keys(data.models[id]?.quotaInfo ?? {}).length > 0,
358
+ );
359
+ if (
360
+ reportedIds.length > 0 &&
361
+ next.size === 0 &&
362
+ !hasUsableQuotaData &&
363
+ reportedIds.every((id) => {
364
+ const lower = id.toLowerCase();
365
+ return RESERVED_QUOTA_MODEL_IDS.has(lower) ||
366
+ lower.startsWith("chat_") ||
367
+ lower.startsWith("tab_");
368
+ })
369
+ ) {
370
+ // Quota-family rows without usable quota values are not a fresh model
371
+ // snapshot. Keep the last model list instead of clearing it on a
372
+ // response whose only model-like key was malformed quota data.
373
+ return 0;
374
+ }
375
+
376
+ if (data.defaultAgentModelId) {
377
+ this.defaultAgentModelIds.delete(key);
378
+ this.defaultAgentModelIds.set(key, data.defaultAgentModelId);
379
+ } else {
380
+ this.defaultAgentModelIds.delete(key);
381
+ }
382
+
383
+ this.snapshotRevision++;
384
+ this.snapshotTimes.set(key, Date.now());
359
385
  this.accountModels.set(key, next);
360
386
  this.accountModelOwnership.set(key, new Set(next.keys()));
361
387
  return newModelsCount;
@@ -386,6 +412,7 @@ export class DynamicModelRegistry {
386
412
  (previousGeneration !== undefined && previousGeneration !== nextGeneration)
387
413
  ) {
388
414
  this.accountModels.delete(key);
415
+ this.snapshotTimes.delete(key);
389
416
  }
390
417
  }
391
418
  for (const key of this.accountModelOwnership.keys()) {
@@ -463,7 +490,8 @@ export class DynamicModelRegistry {
463
490
  }
464
491
 
465
492
  wasDiscovered(id: string): boolean {
466
- return this.discoveredModels.has(id.trim().toLowerCase());
493
+ const lower = id.trim().toLowerCase();
494
+ return this.discoveredModels.has(lower);
467
495
  }
468
496
 
469
497
  getObservedModelId(id: string): string | undefined {
@@ -479,6 +507,75 @@ export class DynamicModelRegistry {
479
507
  return pools;
480
508
  }
481
509
 
510
+ getPersistedSnapshots(accounts: Iterable<PersistedOwnershipAccount>): PersistedDynamicModelSnapshots {
511
+ const snapshots: PersistedDynamicModelSnapshots = { version: 1, accounts: Object.create(null) };
512
+ for (const account of accounts) {
513
+ const id = accountKey(account.id);
514
+ const models = this.accountModels.get(id);
515
+ if (!models) continue;
516
+ snapshots.accounts[id] = {
517
+ credentialGenerationFingerprint: account.credentialGenerationFingerprint,
518
+ capturedAt: this.snapshotTimes.get(id)!,
519
+ models: Array.from(models.values(), (model) => ({ ...model })),
520
+ defaultAgentModelId: this.defaultAgentModelIds.get(id),
521
+ };
522
+ }
523
+ return snapshots;
524
+ }
525
+
526
+ restorePersistedSnapshots(value: unknown, accounts: Iterable<PersistedOwnershipAccount>): void {
527
+ if (!isRecord(value) || value.version !== 1 || !isRecord(value.accounts)) return;
528
+ for (const account of accounts) {
529
+ const id = accountKey(account.id);
530
+ const snapshot = value.accounts[id];
531
+ if (!isRecord(snapshot) ||
532
+ snapshot.credentialGenerationFingerprint !== account.credentialGenerationFingerprint ||
533
+ typeof snapshot.capturedAt !== "number" || !Number.isFinite(snapshot.capturedAt) ||
534
+ snapshot.capturedAt <= 0 || !Array.isArray(snapshot.models)) continue;
535
+ const models = new Map<string, DynamicModelEntry>();
536
+ let valid = true;
537
+ for (const raw of snapshot.models) {
538
+ if (!isRecord(raw) || typeof raw.id !== "string" || !isDiscoverableModelId(raw.id) ||
539
+ typeof raw.family !== "string" || !isSafeModelId(raw.family) ||
540
+ typeof raw.quotaPool !== "string" || !["gemini", "claude"].includes(raw.quotaPool) ||
541
+ !["ctx", "maxOutputTokens"].every((key) => typeof raw[key] === "number" && Number.isFinite(raw[key]) && raw[key] > 0) ||
542
+ typeof raw.thinkingBudget !== "number" || !Number.isFinite(raw.thinkingBudget) || raw.thinkingBudget < -1 ||
543
+ (raw.thinkingBudget < 0 && raw.thinkingBudget !== -1) ||
544
+ (raw.minThinkingBudget !== undefined && (typeof raw.minThinkingBudget !== "number" || !Number.isFinite(raw.minThinkingBudget) || raw.minThinkingBudget < 0)) ||
545
+ !["multimodal", "tools", "isThinking", "isTiered"].every((key) => typeof raw[key] === "boolean") ||
546
+ (raw.displayName !== undefined && typeof raw.displayName !== "string")) {
547
+ valid = false;
548
+ break;
549
+ }
550
+ models.set(raw.id.trim().toLowerCase(), {
551
+ id: raw.id.trim(),
552
+ family: raw.family as string,
553
+ quotaPool: raw.quotaPool as string,
554
+ ctx: raw.ctx as number,
555
+ maxOutputTokens: raw.maxOutputTokens as number,
556
+ thinkingBudget: raw.thinkingBudget as number,
557
+ ...(raw.minThinkingBudget !== undefined ? { minThinkingBudget: raw.minThinkingBudget as number } : {}),
558
+ multimodal: raw.multimodal as boolean,
559
+ tools: raw.tools as boolean,
560
+ isThinking: raw.isThinking as boolean,
561
+ isTiered: raw.isTiered as boolean,
562
+ ...(raw.displayName !== undefined ? { displayName: raw.displayName as string } : {}),
563
+ });
564
+ }
565
+ const defaultId = snapshot.defaultAgentModelId;
566
+ if (!valid || (defaultId !== undefined && (typeof defaultId !== "string" || !isSafeModelId(defaultId)))) continue;
567
+ this.accountModels.set(id, models);
568
+ this.snapshotTimes.set(id, snapshot.capturedAt);
569
+ this.accountModelOwnership.set(id, new Set(models.keys()));
570
+ this.defaultAgentModelIds.delete(id);
571
+ if (typeof defaultId === "string") this.defaultAgentModelIds.set(id, defaultId);
572
+ for (const [key, model] of models) {
573
+ this.discoveredModels.set(key, { id: model.id, quotaPool: model.quotaPool });
574
+ this.ownershipScopedModels.add(key);
575
+ }
576
+ }
577
+ }
578
+
482
579
  getPersistedModelOwnership(
483
580
  accounts: Iterable<PersistedOwnershipAccount>,
484
581
  ): PersistedDynamicModelOwnership {
@@ -177,7 +177,7 @@ function extractTextFromSseEvent(eventText: string): string | null {
177
177
  try {
178
178
  const parsed = JSON.parse(payload);
179
179
  if (parsed && typeof parsed === "object") {
180
- const p = parsed as Record<string, unknown>;
180
+ const p = isRecord(parsed.response) ? parsed.response : parsed;
181
181
  if (
182
182
  Array.isArray(p.candidates) &&
183
183
  p.candidates[0] &&
@@ -191,6 +191,7 @@ function extractTextFromSseEvent(eventText: string): string | null {
191
191
  .map((part) =>
192
192
  part &&
193
193
  typeof part === "object" &&
194
+ (part as Record<string, unknown>).thought !== true &&
194
195
  typeof (part as Record<string, unknown>).text === "string"
195
196
  ? (part as Record<string, unknown>).text
196
197
  : "",
@@ -282,7 +283,8 @@ function benchmarkUsage(raw: string): { outputTokens: number } | null {
282
283
  for (const event of raw.split(/\r?\n\r?\n/)) {
283
284
  const usage = extractUsageFromSseEvent(event);
284
285
  if (usage) {
285
- outputTokens += usage.outputTokens;
286
+ // Antigravity repeats cumulative usage in content and final events.
287
+ outputTokens = Math.max(outputTokens, usage.outputTokens);
286
288
  }
287
289
  }
288
290
  return { outputTokens };
@@ -10,7 +10,11 @@ import type {
10
10
  ProviderModel,
11
11
  QuotaFetchContext,
12
12
  } from "../adapter.js";
13
- import { getEffectiveAntigravityModels, isBuiltInAntigravityModel } from "./catalog.js";
13
+ import {
14
+ getEffectiveAntigravityModels,
15
+ isDynamicallyAvailableAntigravityModel,
16
+ } from "./catalog.js";
17
+ import { dynamicCatalog } from "./dynamic-catalog.js";
14
18
  import { fetchProviderQuota } from "./quota.js";
15
19
  import {
16
20
  forwardRequest,
@@ -30,6 +34,7 @@ import {
30
34
  import {
31
35
  TOKEN_URL,
32
36
  KICKSTART_MODEL_FOR_QUOTA_POOL,
37
+ applyModelAlias,
33
38
  resolveQuotaModelKey,
34
39
  } from "../../types.js";
35
40
  import type { AccountRuntime } from "../../types.js";
@@ -175,16 +180,19 @@ export const googleAntigravityAdapter: ProviderAdapter = {
175
180
  id: model.id,
176
181
  contextWindow: model.ctx,
177
182
  quotaPool: model.quotaPool,
178
- source: isBuiltInAntigravityModel(model.id) ? "catalog" : "discovered",
183
+ source: "discovered",
179
184
  }));
180
185
  },
181
186
 
182
187
  ownsModel(model: string): boolean {
183
- return resolveQuotaModelKey(model) !== null || model.includes("gemini") || model.includes("claude");
188
+ return isDynamicallyAvailableAntigravityModel(model);
184
189
  },
185
190
 
186
191
  getPoolKey(model: string): string {
187
- return resolveQuotaModelKey(model) ?? model;
192
+ const normalize = (value: string) => value.trim().replace(/^models\//i, "");
193
+ const observed = dynamicCatalog.getModel(normalize(model)) ??
194
+ dynamicCatalog.getModel(normalize(applyModelAlias(model)));
195
+ return observed?.id ?? resolveQuotaModelKey(model) ?? model;
188
196
  },
189
197
 
190
198
  getBenchmark(account: AccountRuntime) {
@@ -10,6 +10,8 @@ import {
10
10
  QUOTA_API_URL,
11
11
  QUOTA_USER_AGENT,
12
12
  QUOTA_MODEL_KEYS,
13
+ REQUEST_CLIENT_METADATA,
14
+ REQUEST_GOOG_API_CLIENT,
13
15
  } from "../../types.js";
14
16
  import { fetchWithRetry } from "../../fetch-with-retry.js";
15
17
  import {
@@ -104,16 +106,14 @@ export function extractQuotas(
104
106
 
105
107
  for (const [, config] of Object.entries(QUOTA_MODEL_KEYS)) {
106
108
  const candidates: GoogleModelInfoWithQuota[] = [];
107
- for (const candidate of [config.key, ...config.altKeys]) {
108
- const info = data.models[candidate];
109
- if (hasUsableQuotaInfo(info)) {
110
- candidates.push(info);
111
- }
109
+ const sharedPoolInfo = data.models[config.key];
110
+ if (hasUsableQuotaInfo(sharedPoolInfo)) {
111
+ candidates.push(sharedPoolInfo);
112
112
  }
113
113
 
114
114
  for (const [modelKey, info] of Object.entries(data.models)) {
115
115
  if (
116
- ![config.key, ...config.altKeys].includes(modelKey) &&
116
+ modelKey !== config.key &&
117
117
  DynamicModelRegistry.inferFamilyAndPool(modelKey).quotaPool === config.key &&
118
118
  hasUsableQuotaInfo(info)
119
119
  ) {
@@ -202,6 +202,8 @@ export async function fetchProviderQuota(
202
202
  "Content-Type": "application/json",
203
203
  Authorization: `Bearer ${account.accessToken}`,
204
204
  "User-Agent": QUOTA_USER_AGENT,
205
+ "X-Goog-Api-Client": REQUEST_GOOG_API_CLIENT,
206
+ "Client-Metadata": REQUEST_CLIENT_METADATA,
205
207
  },
206
208
  body: JSON.stringify({
207
209
  project: getProviderProjectId(account.config, DEFAULT_PROVIDER),
@@ -236,7 +238,6 @@ export async function fetchProviderQuota(
236
238
  if (!data) return;
237
239
  const oldQuota = account.quota || [];
238
240
  const fresh = extractQuotas(data, oldQuota);
239
- if (fresh.length === 0) return;
240
241
  const newModels = dynamicCatalog.updateFromEndpointResponse(
241
242
  data,
242
243
  accountId,
@@ -248,6 +249,7 @@ export async function fetchProviderQuota(
248
249
  `${account.config.email}: discovered ${newModels} Antigravity model(s) from quota response`,
249
250
  );
250
251
  }
252
+ if (fresh.length === 0) return;
251
253
  // Drop the previous Antigravity entries so the new ones fully replace
252
254
  // them; keep entries from OTHER providers (Ollama) so multi-provider
253
255
  // accounts accumulate quotas across credentials without overwriting
@@ -86,6 +86,16 @@ export function buildOllamaPayload(body: RequestBody): Record<string, unknown> {
86
86
  if (!isRecord(msg)) return msg;
87
87
  const normalized = { ...msg };
88
88
  normalizeOllamaMessageContent(normalized);
89
+ // Ollama decodes images[] directly as base64. OpenAI/Anthropic image
90
+ // blocks use data URLs, whose prefix fails decoding at the ':' byte.
91
+ // Normalize after merging so native images and content blocks both work.
92
+ if (Array.isArray(normalized.images)) {
93
+ normalized.images = normalized.images.map((image: unknown) =>
94
+ typeof image === "string"
95
+ ? image.replace(/^data:[^,]*;base64,/i, "")
96
+ : image,
97
+ );
98
+ }
89
99
  return normalized;
90
100
  });
91
101
  const payload: Record<string, unknown> = {
@@ -8,6 +8,8 @@ export interface CodexModel {
8
8
  id: string;
9
9
  contextWindow: number;
10
10
  reasoning: boolean;
11
+ reasoningEfforts?: string[];
12
+ defaultReasoningEffort?: string;
11
13
  multimodal: boolean;
12
14
  tools: boolean;
13
15
  source: "allowlist" | "discovered";
@@ -29,12 +31,66 @@ const CODEX_DISCOVERED_MAX_CONTEXT_WINDOW = 2_000_000;
29
31
  const DEFAULT_CODEX_CLIENT_VERSION = "0.162.1";
30
32
  const CODEX_DISCOVERED_ID_PATTERN = /^gpt-\d+(?:\.\d+)*(?:-[a-z0-9]+)+$/i;
31
33
  export const CODEX_BASE_MODELS: readonly CodexModel[] = [
32
- { id: "gpt-6-astra", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
33
- { id: "gpt-6-sol", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
34
- { id: "gpt-6-luna", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
35
- { id: "gpt-5.6-sol", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
36
- { id: "gpt-5.6-terra", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
37
- { id: "gpt-5.6-luna", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
34
+ {
35
+ id: "gpt-6-astra",
36
+ contextWindow: CODEX_CONTEXT_WINDOW,
37
+ reasoning: true,
38
+ multimodal: true,
39
+ tools: true,
40
+ source: "allowlist",
41
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max"],
42
+ defaultReasoningEffort: "medium",
43
+ },
44
+ {
45
+ id: "gpt-6-sol",
46
+ contextWindow: CODEX_CONTEXT_WINDOW,
47
+ reasoning: true,
48
+ multimodal: true,
49
+ tools: true,
50
+ source: "allowlist",
51
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max"],
52
+ defaultReasoningEffort: "medium",
53
+ },
54
+ {
55
+ id: "gpt-6-luna",
56
+ contextWindow: CODEX_CONTEXT_WINDOW,
57
+ reasoning: true,
58
+ multimodal: true,
59
+ tools: true,
60
+ source: "allowlist",
61
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max"],
62
+ defaultReasoningEffort: "medium",
63
+ },
64
+ {
65
+ id: "gpt-5.6-sol",
66
+ contextWindow: CODEX_CONTEXT_WINDOW,
67
+ reasoning: true,
68
+ multimodal: true,
69
+ tools: true,
70
+ source: "allowlist",
71
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max"],
72
+ defaultReasoningEffort: "medium",
73
+ },
74
+ {
75
+ id: "gpt-5.6-terra",
76
+ contextWindow: CODEX_CONTEXT_WINDOW,
77
+ reasoning: true,
78
+ multimodal: true,
79
+ tools: true,
80
+ source: "allowlist",
81
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max"],
82
+ defaultReasoningEffort: "medium",
83
+ },
84
+ {
85
+ id: "gpt-5.6-luna",
86
+ contextWindow: CODEX_CONTEXT_WINDOW,
87
+ reasoning: true,
88
+ multimodal: true,
89
+ tools: true,
90
+ source: "allowlist",
91
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max"],
92
+ defaultReasoningEffort: "medium",
93
+ },
38
94
  ];
39
95
 
40
96
  let discoveredModels: CodexModel[] = [];
@@ -56,14 +112,17 @@ export function getCodexModel(model: string): CodexModel | undefined {
56
112
 
57
113
  export function getCodexModels(): CodexModel[] {
58
114
  const merged = new Map<string, CodexModel>();
59
- for (const entry of [...CODEX_BASE_MODELS, ...discoveredModels]) merged.set(entry.id, entry);
115
+ for (const entry of [...CODEX_BASE_MODELS, ...discoveredModels])
116
+ merged.set(entry.id, entry);
60
117
  return [...merged.values()];
61
118
  }
62
119
 
63
120
  export function isCodexProviderModelId(value: unknown): value is string {
64
- return typeof value === "string" &&
121
+ return (
122
+ typeof value === "string" &&
65
123
  isSafeModelId(value) &&
66
- CODEX_DISCOVERED_ID_PATTERN.test(value);
124
+ CODEX_DISCOVERED_ID_PATTERN.test(value)
125
+ );
67
126
  }
68
127
 
69
128
  export function setDiscoveredCodexModels(models: CodexModel[]): void {
@@ -71,28 +130,99 @@ export function setDiscoveredCodexModels(models: CodexModel[]): void {
71
130
  }
72
131
 
73
132
  function isSafeModelId(value: unknown): value is string {
74
- return typeof value === "string" && /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(value);
133
+ return (
134
+ typeof value === "string" &&
135
+ /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(value)
136
+ );
137
+ }
138
+
139
+ const REASONING_EFFORTS = new Set([
140
+ "none",
141
+ "minimal",
142
+ "low",
143
+ "medium",
144
+ "high",
145
+ "xhigh",
146
+ "max",
147
+ ]);
148
+ function reasoningMetadata(
149
+ record: Record<string, unknown>,
150
+ id: string,
151
+ ): Pick<CodexModel, "reasoningEfforts" | "defaultReasoningEffort"> {
152
+ if (record.reasoning === false) return { reasoningEfforts: [] };
153
+ const known = CODEX_BASE_MODELS.find((model) => model.id === id);
154
+ const raw =
155
+ record.supported_reasoning_levels ??
156
+ record.supported_reasoning_efforts ??
157
+ record.reasoning_efforts;
158
+ const efforts = Array.isArray(raw)
159
+ ? [
160
+ ...new Set(
161
+ raw.flatMap((value) => {
162
+ const effort =
163
+ typeof value === "string"
164
+ ? value
165
+ : value && typeof value === "object"
166
+ ? (value as Record<string, unknown>).effort
167
+ : null;
168
+ return typeof effort === "string" && REASONING_EFFORTS.has(effort)
169
+ ? [effort]
170
+ : [];
171
+ }),
172
+ ),
173
+ ]
174
+ : known?.reasoningEfforts;
175
+ const defaultEffort =
176
+ record.default_reasoning_level ??
177
+ record.default_reasoning_effort ??
178
+ known?.defaultReasoningEffort;
179
+ return {
180
+ ...(efforts ? { reasoningEfforts: efforts } : {}),
181
+ ...(typeof defaultEffort === "string" && efforts?.includes(defaultEffort)
182
+ ? { defaultReasoningEffort: defaultEffort }
183
+ : {}),
184
+ };
75
185
  }
76
186
 
77
187
  function parseModel(value: unknown): CodexModel | null {
78
188
  if (typeof value === "string") {
79
189
  return isCodexProviderModelId(value)
80
- ? { id: value, contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "discovered" }
190
+ ? {
191
+ id: value,
192
+ contextWindow: CODEX_CONTEXT_WINDOW,
193
+ reasoning: true,
194
+ multimodal: true,
195
+ tools: true,
196
+ source: "discovered",
197
+ ...reasoningMetadata({}, value),
198
+ }
81
199
  : null;
82
200
  }
83
201
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
84
202
  const record = value as Record<string, unknown>;
85
203
  const id = record.id ?? record.slug ?? record.model ?? record.name;
86
204
  if (!isCodexProviderModelId(id)) return null;
87
- const contextWindow = [record.context_window, record.contextWindow, record.context_length]
88
- .find((candidate) => typeof candidate === "number" && Number.isFinite(candidate) && candidate > 0);
205
+ const contextWindow = [
206
+ record.context_window,
207
+ record.contextWindow,
208
+ record.context_length,
209
+ ].find(
210
+ (candidate) =>
211
+ typeof candidate === "number" &&
212
+ Number.isFinite(candidate) &&
213
+ candidate > 0,
214
+ );
89
215
  return {
90
216
  id,
91
- contextWindow: typeof contextWindow === "number" ? Math.min(contextWindow, CODEX_DISCOVERED_MAX_CONTEXT_WINDOW) : CODEX_CONTEXT_WINDOW,
217
+ contextWindow:
218
+ typeof contextWindow === "number"
219
+ ? Math.min(contextWindow, CODEX_DISCOVERED_MAX_CONTEXT_WINDOW)
220
+ : CODEX_CONTEXT_WINDOW,
92
221
  reasoning: record.reasoning !== false,
93
222
  multimodal: record.multimodal !== false && record.vision !== false,
94
223
  tools: record.tools !== false && record.tool_calling !== false,
95
224
  source: "discovered",
225
+ ...reasoningMetadata(record, id),
96
226
  };
97
227
  }
98
228
 
@@ -106,7 +236,10 @@ export async function fetchCodexCatalog(
106
236
  const endpoint = base.endsWith("/models") ? base : `${base}/models`;
107
237
  try {
108
238
  const url = new URL(endpoint);
109
- url.searchParams.set("client_version", process.env.CODEX_CLIENT_VERSION?.trim() || DEFAULT_CODEX_CLIENT_VERSION);
239
+ url.searchParams.set(
240
+ "client_version",
241
+ process.env.CODEX_CLIENT_VERSION?.trim() || DEFAULT_CODEX_CLIENT_VERSION,
242
+ );
110
243
  const headers: Record<string, string> = {
111
244
  Authorization: `Bearer ${token}`,
112
245
  Accept: "application/json",
@@ -119,9 +252,15 @@ export async function fetchCodexCatalog(
119
252
  dispatcher: getAccountProxyDispatcher(account, CODEX_PROVIDER_ID),
120
253
  } as RequestInit & { dispatcher?: unknown });
121
254
  if (!response.ok) return getCodexModels();
122
- const data = await response.json() as Record<string, unknown>;
123
- const raw = Array.isArray(data.data) ? data.data : Array.isArray(data.models) ? data.models : [];
124
- const parsed = raw.map(parseModel).filter((model): model is CodexModel => model !== null);
255
+ const data = (await response.json()) as Record<string, unknown>;
256
+ const raw = Array.isArray(data.data)
257
+ ? data.data
258
+ : Array.isArray(data.models)
259
+ ? data.models
260
+ : [];
261
+ const parsed = raw
262
+ .map(parseModel)
263
+ .filter((model): model is CodexModel => model !== null);
125
264
  if (parsed.length > 0) setDiscoveredCodexModels(parsed);
126
265
  } catch {
127
266
  // Discovery is optional; the safe allowlist remains available.