tuxevil-rotator 3.1.0 → 3.2.1

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/dashboard.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  deleteVirtualKey,
16
16
  } from "./virtual-keys.js";
17
17
  import { getSpendLogs, getDailySpendSummary, getSpendByKey } from "./spend-logger.js";
18
+ import { buildOpenAIModelCatalog } from "./compat.js";
18
19
  import { logger } from "./logger.js";
19
20
 
20
21
  const dashboardLogger = logger.child("dashboard");
@@ -47,7 +48,7 @@ export function serveDashboard(res: ServerResponse): void {
47
48
  export function serveStaticCss(res: ServerResponse): void {
48
49
  res.writeHead(200, {
49
50
  "Content-Type": "text/css; charset=utf-8",
50
- "Cache-Control": "public, max-age=3600",
51
+ "Cache-Control": "no-cache, must-revalidate",
51
52
  });
52
53
  res.end(DASHBOARD_CSS);
53
54
  }
@@ -55,7 +56,7 @@ export function serveStaticCss(res: ServerResponse): void {
55
56
  export function serveStaticJs(res: ServerResponse): void {
56
57
  res.writeHead(200, {
57
58
  "Content-Type": "application/javascript; charset=utf-8",
58
- "Cache-Control": "public, max-age=3600",
59
+ "Cache-Control": "no-cache, must-revalidate",
59
60
  });
60
61
  res.end(DASHBOARD_JS);
61
62
  }
@@ -63,7 +64,7 @@ export function serveStaticJs(res: ServerResponse): void {
63
64
  export function serveStaticKeysJs(res: ServerResponse): void {
64
65
  res.writeHead(200, {
65
66
  "Content-Type": "application/javascript; charset=utf-8",
66
- "Cache-Control": "public, max-age=3600",
67
+ "Cache-Control": "no-cache, must-revalidate",
67
68
  });
68
69
  res.end(DASHBOARD_KEYS_JS);
69
70
  }
@@ -71,7 +72,7 @@ export function serveStaticKeysJs(res: ServerResponse): void {
71
72
  export function serveStaticLogsJs(res: ServerResponse): void {
72
73
  res.writeHead(200, {
73
74
  "Content-Type": "application/javascript; charset=utf-8",
74
- "Cache-Control": "public, max-age=3600",
75
+ "Cache-Control": "no-cache, must-revalidate",
75
76
  });
76
77
  res.end(DASHBOARD_LOGS_JS);
77
78
  }
@@ -108,6 +109,33 @@ export function serveConfigApi(
108
109
  res.end(JSON.stringify(rotator.getConfig()));
109
110
  }
110
111
 
112
+ /**
113
+ * Admin /api/models — returns the full provider model catalog grouped by
114
+ * provider. Powers the "Allowed Models" checkboxes in the Generate/Edit
115
+ * Virtual Key modal so the dashboard can show models from every active
116
+ * provider (Google Antigravity, Ollama, OpenAI Codex, OpenCode Zen) instead
117
+ * of the legacy hardcoded list.
118
+ *
119
+ * The shape mirrors /v1/models so the client can reuse metadata for tooltips.
120
+ */
121
+ export function serveModelsApi(
122
+ res: ServerResponse,
123
+ rotator: AccountRotator,
124
+ ): void {
125
+ const catalog = buildOpenAIModelCatalog(rotator);
126
+ res.writeHead(200, {
127
+ "Content-Type": "application/json",
128
+ "Cache-Control": "no-store",
129
+ });
130
+ res.end(
131
+ JSON.stringify({
132
+ ok: true,
133
+ count: catalog.length,
134
+ data: catalog,
135
+ }),
136
+ );
137
+ }
138
+
111
139
  export function serveConfigExportApi(
112
140
  res: ServerResponse,
113
141
  rotator: AccountRotator,
@@ -897,44 +925,17 @@ const DASHBOARD_KEYS_HTML = renderAppShell({
897
925
  </div>
898
926
  </div>
899
927
 
900
- <div class="model-grid">
901
- <div class="model-category">
902
- <div class="cat-title">Gemini 3.1 Pro</div>
903
- <div class="cat-grid">
904
- <label class="model-card"><input type="checkbox" value="gemini-3.1-pro-low" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">gemini-3.1-pro-low</span></label>
905
- <label class="model-card"><input type="checkbox" value="gemini-3.1-pro-high" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">gemini-3.1-pro-high</span></label>
906
- </div>
907
- </div>
908
- <div class="model-category">
909
- <div class="cat-title">Gemini 3.5 Flash</div>
910
- <div class="cat-grid">
911
- <label class="model-card"><input type="checkbox" value="gemini-3.5-flash-medium" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">gemini-3.5-flash-medium</span></label>
912
- <label class="model-card"><input type="checkbox" value="gemini-3.5-flash-high" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">gemini-3.5-flash-high</span></label>
913
- <label class="model-card"><input type="checkbox" value="gemini-3-flash" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">gemini-3-flash</span></label>
914
- </div>
915
- </div>
916
- <div class="model-category">
917
- <div class="cat-title">Gemini 3.6 Flash</div>
918
- <div class="cat-grid">
919
- <label class="model-card"><input type="checkbox" value="gemini-3.6-flash-low" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">gemini-3.6-flash-low</span></label>
920
- <label class="model-card"><input type="checkbox" value="gemini-3.6-flash-medium" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">gemini-3.6-flash-medium</span></label>
921
- <label class="model-card"><input type="checkbox" value="gemini-3.6-flash-high" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">gemini-3.6-flash-high</span></label>
922
- <label class="model-card"><input type="checkbox" value="gemini-3.6-flash-tiered" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">gemini-3.6-flash-tiered</span></label>
923
- </div>
924
- </div>
925
- <div class="model-category">
926
- <div class="cat-title">Claude</div>
927
- <div class="cat-grid">
928
- <label class="model-card"><input type="checkbox" value="claude-sonnet-4-6" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">claude-sonnet-4-6</span></label>
929
- <label class="model-card"><input type="checkbox" value="claude-opus-4-6-thinking" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">claude-opus-4-6-thinking</span></label>
930
- </div>
931
- </div>
932
- <div class="model-category">
933
- <div class="cat-title">GPT-OSS</div>
934
- <div class="cat-grid">
935
- <label class="model-card"><input type="checkbox" value="gpt-oss-120b-medium" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">gpt-oss-120b-medium</span></label>
936
- </div>
937
- </div>
928
+ <!--
929
+ The model grid is populated dynamically by dashboard-keys.js from
930
+ GET /api/models, which returns the live provider catalog (Google
931
+ Antigravity + every active Ollama / OpenAI Codex / OpenCode Zen
932
+ account). Each entry is grouped by its owned_by provider so the
933
+ checkbox UI surfaces every model the rotator can actually route
934
+ today, including those added by future providers.
935
+ -->
936
+ <div class="model-grid" id="modelGrid"></div>
937
+ <div class="model-grid-empty" id="modelGridEmpty" style="display:none;color:var(--text-dim);font-size:0.85rem;padding:8px 0">
938
+ No models available. Configure a provider or refresh.
938
939
  </div>
939
940
  </div>
940
941
 
package/src/index.ts CHANGED
@@ -21,7 +21,7 @@ import {
21
21
  } from "./compat.js";
22
22
  import { setModelAliasesOverride } from "./types.js";
23
23
  import { readTextFile, writeTextFileAtomic } from "./storage.js";
24
- import { initDb } from "./db-store.js";
24
+ import { initDb, isDbConfigured } from "./db-store.js";
25
25
  import { runKeyMigrations } from "./key-migrations.js";
26
26
  import { flushSpendLogs, stopRetentionCleanup, startRetentionCleanup } from "./spend-logger.js";
27
27
  import { stopPendingSessionReaper } from "./onboarding.js";
@@ -170,7 +170,11 @@ export async function main(): Promise<void> {
170
170
 
171
171
  await initDb();
172
172
  await runKeyMigrations();
173
- await importLegacyOllamaRotatorAccounts();
173
+ // PostgreSQL is the authoritative account store. Importing the legacy
174
+ // Ollama JSON here would allow a stale disk credential to re-enter on boot.
175
+ if (!isDbConfigured()) {
176
+ await importLegacyOllamaRotatorAccounts();
177
+ }
174
178
  startRetentionCleanup();
175
179
 
176
180
  const config = loadConfig();
package/src/onboarding.ts CHANGED
@@ -350,6 +350,7 @@ export function serveCliLogin(res: ServerResponse): void {
350
350
  <button class="tab active" data-panel="panel-google">Google (Antigravity)</button>
351
351
  <button class="tab" data-panel="panel-codex">OpenAI Codex</button>
352
352
  <button class="tab" data-panel="panel-ollama">Ollama Cloud</button>
353
+ <button class="tab" data-panel="panel-zen">OpenCode Zen</button>
353
354
  </div>
354
355
 
355
356
  <div class="panel active" id="panel-google">
@@ -410,6 +411,20 @@ ${codexAuthUrl && codexSessionId ? `<h3 style="margin:24px 0 8px;font-size:18px;
410
411
  </form>
411
412
  </div>
412
413
 
414
+ <div class="panel" id="panel-zen">
415
+ <p>Paste an OpenCode Zen API key to add the account to this rotator. The key is validated against opencode.ai/zen before saving.</p>
416
+ <p class="mono">Create a key at https://opencode.ai/zen</p>
417
+ <form id="zenForm" style="margin-top:12px;">
418
+ <label for="zenEmail">Account identifier (email or label)</label>
419
+ <input id="zenEmail" name="email" class="field" placeholder="me@example.com (optional)" autocomplete="off" />
420
+ <label for="zenApiKey">OpenCode Zen API key</label>
421
+ <input id="zenApiKey" name="apiKey" class="field" type="password" placeholder="sk-..." autocomplete="off" required />
422
+ <button type="submit" class="cta" style="cursor:pointer;border:none;font-family:inherit;font-size:16px;margin-top:12px;">
423
+ Connect Account
424
+ </button>
425
+ </form>
426
+ </div>
427
+
413
428
  <div id="result" style="margin-top:18px;"></div>
414
429
 
415
430
  <script>
@@ -553,6 +568,48 @@ if (codexForm) codexForm.addEventListener('submit', async (e) => {
553
568
  btn.textContent = 'Connect Codex Account';
554
569
  }
555
570
  });
571
+
572
+ const zenForm = document.getElementById('zenForm');
573
+ if (zenForm) zenForm.addEventListener('submit', async (e) => {
574
+ e.preventDefault();
575
+ const form = e.target;
576
+ const btn = form.querySelector('button[type=submit]');
577
+ const apiKey = form.apiKey.value.trim();
578
+ const email = form.email.value.trim();
579
+ if (!apiKey) { showResult('<div class="note error">Please paste an API key.</div>'); return; }
580
+ btn.disabled = true;
581
+ btn.textContent = 'Validating...';
582
+ showResult('<div class="note">Checking the key against opencode.ai/zen...</div>');
583
+ try {
584
+ const params = new URLSearchParams(window.location.search);
585
+ const token = params.get('token') || '';
586
+ const res = await fetch('/api/cli-login', {
587
+ method: 'POST',
588
+ headers: { 'Content-Type': 'application/json', ...(token ? { 'X-Rotator-Admin-Token': token } : {}) },
589
+ body: JSON.stringify({ provider: 'opencode-zen', email, apiKey }),
590
+ });
591
+ const data = await res.json();
592
+ if (data.ok) {
593
+ showResult('<div class="note" style="border-left-color:var(--accent);background:rgba(30,107,82,0.12);">' +
594
+ '<strong>' + (data.email || '') + '</strong> ' + (data.isNew ? 'added' : 'updated') + ' successfully. The rotator will start using OpenCode Zen on the next poll.</div>');
595
+ } else {
596
+ var zenErrDiv = document.createElement('div');
597
+ zenErrDiv.className = 'note error';
598
+ zenErrDiv.textContent = data.error || 'Unknown error';
599
+ document.getElementById('result').innerHTML = '';
600
+ document.getElementById('result').appendChild(zenErrDiv);
601
+ }
602
+ } catch (err) {
603
+ var zenErr2 = document.createElement('div');
604
+ zenErr2.className = 'note error';
605
+ zenErr2.textContent = 'Request failed: ' + err.message;
606
+ document.getElementById('result').innerHTML = '';
607
+ document.getElementById('result').appendChild(zenErr2);
608
+ } finally {
609
+ btn.disabled = false;
610
+ btn.textContent = 'Connect Account';
611
+ }
612
+ });
556
613
  </script>
557
614
  `,
558
615
  ),
@@ -604,6 +661,11 @@ export async function handleCliLoginApi(
604
661
  return;
605
662
  }
606
663
 
664
+ if (provider === "opencode-zen") {
665
+ await handleZenCliLogin(body, res, rotator);
666
+ return;
667
+ }
668
+
607
669
  if (provider !== "google-antigravity") {
608
670
  res.writeHead(400, { "Content-Type": "application/json" });
609
671
  res.end(JSON.stringify({ ok: false, error: `Unknown provider "${provider}"` }));
@@ -862,12 +924,12 @@ async function handleOllamaCliLogin(
862
924
  return;
863
925
  }
864
926
 
865
- const entry = {
927
+ const entry: AccountConfig = {
866
928
  email: email || defaultAccountEmail(apiKey),
867
- apiKey,
929
+ credentials: [{ provider: "ollama", apiKey }],
868
930
  label: email || defaultAccountEmail(apiKey).split("@")[0],
869
931
  };
870
- if (entry.label.length > MAX_ACCOUNT_LABEL_LENGTH) {
932
+ if (typeof entry.label !== "string" || entry.label.length > MAX_ACCOUNT_LABEL_LENGTH) {
871
933
  res.writeHead(400, { "Content-Type": "application/json" });
872
934
  res.end(JSON.stringify({ ok: false, error: "Account label too long" }));
873
935
  return;
@@ -880,6 +942,61 @@ async function handleOllamaCliLogin(
880
942
  res.end(JSON.stringify({ ok: true, email: entry.email, isNew }));
881
943
  }
882
944
 
945
+ async function handleZenCliLogin(
946
+ body: { email?: string; apiKey?: string },
947
+ res: ServerResponse,
948
+ rotator: AccountSink,
949
+ ): Promise<void> {
950
+ const apiKey = typeof body.apiKey === "string" ? body.apiKey.trim() : "";
951
+ const email = typeof body.email === "string" ? body.email.trim() : "";
952
+
953
+ if (!apiKey) {
954
+ res.writeHead(400, { "Content-Type": "application/json" });
955
+ res.end(JSON.stringify({ ok: false, error: "Missing apiKey" }));
956
+ return;
957
+ }
958
+ if (apiKey.length > 4096) {
959
+ res.writeHead(400, { "Content-Type": "application/json" });
960
+ res.end(JSON.stringify({ ok: false, error: "API key too long" }));
961
+ return;
962
+ }
963
+ if (email.length > MAX_ACCOUNT_EMAIL_LENGTH) {
964
+ res.writeHead(400, { "Content-Type": "application/json" });
965
+ res.end(JSON.stringify({ ok: false, error: "Account identifier too long" }));
966
+ return;
967
+ }
968
+
969
+ const validation = await validateZenApiKey(apiKey);
970
+ if (!validation.ok) {
971
+ res.writeHead(400, { "Content-Type": "application/json" });
972
+ res.end(
973
+ JSON.stringify({
974
+ ok: false,
975
+ error: `Key rejected (${validation.status}): ${validation.error}`,
976
+ }),
977
+ );
978
+ return;
979
+ }
980
+
981
+ const derivedEmail = email || zenDefaultAccountEmail(apiKey);
982
+ const entry: AccountConfig = {
983
+ email: derivedEmail,
984
+ credentials: [
985
+ {
986
+ provider: OPENCODE_ZEN_PROVIDER_ID,
987
+ apiKey,
988
+ },
989
+ ],
990
+ label: email || derivedEmail.split("@")[0],
991
+ };
992
+
993
+ const { isNew } = await addAccountToConfig(entry);
994
+ await rotator.addOrUpdateAccount(entry);
995
+
996
+ res.writeHead(200, { "Content-Type": "application/json" });
997
+ res.end(JSON.stringify({ ok: true, email: entry.email, isNew, provider: OPENCODE_ZEN_PROVIDER_ID }));
998
+ }
999
+
883
1000
  export async function handleHostedCallback(
884
1001
  req: IncomingMessage,
885
1002
  res: ServerResponse,
@@ -131,6 +131,13 @@ export interface ProviderAdapter {
131
131
  createStreamAccumulator(): StreamAccumulator;
132
132
 
133
133
  // --- Catalog / helpers ---
134
+ /** Whether a model belongs to this provider. */
135
+ ownsModel?(
136
+ model: string,
137
+ context?: { ollamaModels?: Set<string>; codexModels?: Set<string> },
138
+ ): boolean;
139
+ /** Returns the pool key for a model served by this provider. */
140
+ getPoolKey?(model: string): string;
134
141
  /** Cheap upstream model that warms a quota pool during kickstart. */
135
142
  getKickstartModelForPool(quotaModelKey: string): string | undefined;
136
143
  /** Benchmark request used to measure account latency/health. */
@@ -77,3 +77,60 @@ export function getProviderProxyUrl(
77
77
  if (credential?.proxyUrl !== undefined) return credential.proxyUrl;
78
78
  return undefined;
79
79
  }
80
+
81
+ export const PROVIDER_ORDER: string[] = [
82
+ "google-antigravity",
83
+ "ollama",
84
+ "opencode-zen",
85
+ "openai-codex",
86
+ ];
87
+
88
+ export const PROVIDER_ORDER_RANK: Record<string, number> = {
89
+ "google-antigravity": 1,
90
+ ollama: 2,
91
+ "opencode-zen": 3,
92
+ "openai-codex": 4,
93
+ };
94
+
95
+ export function getProviderIdForPoolKey(poolKey: string): string {
96
+ if (poolKey.startsWith("codex:") || poolKey.startsWith("openai-codex")) return "openai-codex";
97
+ if (poolKey.startsWith("opencode-zen:") || poolKey === "opencode-zen") return "opencode-zen";
98
+ if (poolKey === "session" || poolKey === "weekly") return "ollama";
99
+ if (poolKey === "claude" || poolKey === "gemini") return "google-antigravity";
100
+ if (PROVIDER_ORDER_RANK[poolKey] !== undefined) return poolKey;
101
+ return DEFAULT_PROVIDER;
102
+ }
103
+
104
+ export type QuotaPoolLike = {
105
+ modelKey: string;
106
+ providerId?: string;
107
+ };
108
+
109
+ export function getQuotaItemProviderId(q: QuotaPoolLike): string {
110
+ if (q.providerId && PROVIDER_ORDER_RANK[q.providerId] !== undefined) {
111
+ return q.providerId;
112
+ }
113
+ return getProviderIdForPoolKey(q.modelKey);
114
+ }
115
+
116
+ export function sortQuotaPools<T extends QuotaPoolLike>(quotas: T[]): T[] {
117
+ return [...quotas].sort((a, b) => {
118
+ const rankA = PROVIDER_ORDER_RANK[getQuotaItemProviderId(a)] ?? 99;
119
+ const rankB = PROVIDER_ORDER_RANK[getQuotaItemProviderId(b)] ?? 99;
120
+ if (rankA !== rankB) {
121
+ return rankA - rankB;
122
+ }
123
+ return 0;
124
+ });
125
+ }
126
+
127
+ export function sortAccountCredentials<T extends { provider: string }>(credentials: T[]): T[] {
128
+ return [...credentials].sort((a, b) => {
129
+ const rankA = PROVIDER_ORDER_RANK[a.provider] ?? 99;
130
+ const rankB = PROVIDER_ORDER_RANK[b.provider] ?? 99;
131
+ if (rankA !== rankB) {
132
+ return rankA - rankB;
133
+ }
134
+ return 0;
135
+ });
136
+ }
@@ -28,6 +28,7 @@ import {
28
28
  import {
29
29
  TOKEN_URL,
30
30
  KICKSTART_MODEL_FOR_QUOTA_POOL,
31
+ resolveQuotaModelKey,
31
32
  } from "../../types.js";
32
33
  import type { AccountRuntime } from "../../types.js";
33
34
  import { fetchWithRetry } from "../../fetch-with-retry.js";
@@ -159,6 +160,14 @@ export const googleAntigravityAdapter: ProviderAdapter = {
159
160
  return KICKSTART_MODEL_FOR_QUOTA_POOL[quotaModelKey];
160
161
  },
161
162
 
163
+ ownsModel(model: string): boolean {
164
+ return resolveQuotaModelKey(model) !== null || model.includes("gemini") || model.includes("claude");
165
+ },
166
+
167
+ getPoolKey(model: string): string {
168
+ return resolveQuotaModelKey(model) ?? model;
169
+ },
170
+
162
171
  getBenchmark(account: AccountRuntime) {
163
172
  return getBenchmarkSpec(account);
164
173
  },
@@ -14,6 +14,7 @@ import {
14
14
  import { fetchWithRetry } from "../../fetch-with-retry.js";
15
15
  import type { QuotaFetchContext } from "../adapter.js";
16
16
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
17
+ import { sortQuotaPools } from "../registry.js";
17
18
 
18
19
  /**
19
20
  * Extract per-model quotas from a Google quota response, preserving the
@@ -126,7 +127,7 @@ export async function fetchProviderQuota(
126
127
  fresh.forEach(
127
128
  (q) => ((q as { providerId?: string }).providerId = "google-antigravity"),
128
129
  );
129
- account.quota = [...otherProviders, ...fresh];
130
+ account.quota = sortQuotaPools([...otherProviders, ...fresh]);
130
131
  account.lastQuotaPoll = Date.now();
131
132
 
132
133
  // Stash the provider-local poll log for the rotator to emit as a
@@ -836,6 +836,38 @@ export function convertResponsesToChatRequest(
836
836
  };
837
837
  }
838
838
 
839
+ /**
840
+ * Canonical model ID whose thinking level follows an OpenAI-style
841
+ * reasoning_effort. Matched case-insensitively against the exact ID only;
842
+ * virtual siblings (e.g. `gemini-3.7-flash-tiered-high`) are excluded.
843
+ */
844
+ export const TIERED_EFFORT_MODEL_ID = "gemini-3.7-flash-tiered";
845
+
846
+ /**
847
+ * Map an OpenAI Chat `reasoning_effort` to a Gemini `thinkingLevel` for
848
+ * `gemini-3.7-flash-tiered` only. Accepts exactly low/medium/high
849
+ * (case-insensitive); anything else returns undefined so the caller falls
850
+ * back to the existing adaptive/fixed-budget semantics and never emits an
851
+ * invalid upstream enum.
852
+ */
853
+ export function mapTieredReasoningEffortToThinkingLevel(
854
+ effort: string | undefined,
855
+ modelId: string,
856
+ ): "LOW" | "MEDIUM" | "HIGH" | undefined {
857
+ if (modelId.toLowerCase() !== TIERED_EFFORT_MODEL_ID) return undefined;
858
+ if (!isNonEmptyString(effort)) return undefined;
859
+ switch (effort.toLowerCase()) {
860
+ case "low":
861
+ return "LOW";
862
+ case "medium":
863
+ return "MEDIUM";
864
+ case "high":
865
+ return "HIGH";
866
+ default:
867
+ return undefined;
868
+ }
869
+ }
870
+
839
871
  export function openAIToAntigravityBody(
840
872
  input: OpenAIChatCompletionRequest,
841
873
  ): RequestBody {
@@ -1155,10 +1187,28 @@ export function openAIToAntigravityBody(
1155
1187
  }
1156
1188
  } else if (isThinking && modelFamily !== "claude") {
1157
1189
  const tb = modelSpec.thinkingBudget;
1158
- thinkingConfigObj =
1190
+ // Only the exact tiered model selects its thinking level from an
1191
+ // OpenAI-style reasoning_effort, and only while its spec stays adaptive
1192
+ // (thinkingBudget === -1). A fixed budget — bundled or set by an operator
1193
+ // modelSpecs override — deterministically wins and is never combined
1194
+ // with thinkingLevel.
1195
+ const tieredThinkingLevel =
1159
1196
  tb === -1
1160
- ? { includeThoughts: true }
1161
- : { includeThoughts: true, thinkingBudget: tb };
1197
+ ? mapTieredReasoningEffortToThinkingLevel(
1198
+ input.reasoning_effort,
1199
+ input.model,
1200
+ )
1201
+ : undefined;
1202
+ if (tieredThinkingLevel) {
1203
+ thinkingConfigObj = {
1204
+ includeThoughts: true,
1205
+ thinkingLevel: tieredThinkingLevel,
1206
+ };
1207
+ } else if (tb === -1) {
1208
+ thinkingConfigObj = { includeThoughts: true };
1209
+ } else {
1210
+ thinkingConfigObj = { includeThoughts: true, thinkingBudget: tb };
1211
+ }
1162
1212
  if (tb !== -1 && (!maxOutputTokens || maxOutputTokens <= tb)) {
1163
1213
  maxOutputTokens = Math.min(tb + 8192, modelSpec.maxOutputTokens);
1164
1214
  compatLogger.debug(
@@ -77,6 +77,14 @@ export const ollamaAdapter: ProviderAdapter = {
77
77
  return quotaModelKey === "session" ? "gpt-oss:20b" : undefined;
78
78
  },
79
79
 
80
+ ownsModel(model: string, context?: { ollamaModels?: Set<string> }): boolean {
81
+ return context?.ollamaModels?.has(model) ?? false;
82
+ },
83
+
84
+ getPoolKey(): string {
85
+ return "session";
86
+ },
87
+
80
88
  getBenchmark() {
81
89
  return getBenchmarkSpec();
82
90
  },
@@ -15,6 +15,7 @@ import {
15
15
  SESSION_WINDOW_MS,
16
16
  } from "./usage-windows.js";
17
17
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
18
+ import { sortQuotaPools } from "../registry.js";
18
19
 
19
20
  /**
20
21
  * Poll `GET /api/usage` for one account and store the parsed pool quotas.
@@ -66,7 +67,7 @@ export async function fetchProviderUsage(
66
67
  fresh.forEach(
67
68
  (q) => ((q as { providerId?: string }).providerId = "ollama"),
68
69
  );
69
- account.quota = [...otherProviders, ...fresh];
70
+ account.quota = sortQuotaPools([...otherProviders, ...fresh]);
70
71
  account.lastQuotaPoll = Date.now();
71
72
  void recordUsagePoll(account.config.email, new Date().toISOString(), data);
72
73
 
@@ -18,7 +18,8 @@ import {
18
18
  extractCodexUsage,
19
19
  forwardCodexRequest,
20
20
  } from "./forward.js";
21
- import { fetchCodexQuota } from "./quota.js";
21
+ import { fetchCodexQuota, CODEX_QUOTA_MODEL_KEY } from "./quota.js";
22
+ import { isCodexRequestModel, isCodexProviderModelId } from "./catalog.js";
22
23
 
23
24
  const providerLog = logger.child("provider/openai-codex");
24
25
  const refreshFlights = new Map<string, Promise<void>>();
@@ -123,6 +124,16 @@ export const openaiCodexAdapter: ProviderAdapter = {
123
124
 
124
125
  getKickstartModelForPool(): string | undefined { return undefined; },
125
126
 
127
+ ownsModel(model: string, context?: { codexModels?: Set<string> }): boolean {
128
+ if (isCodexRequestModel(model)) return true;
129
+ if (isCodexProviderModelId(model) && (context?.codexModels?.has(model) ?? false)) return true;
130
+ return false;
131
+ },
132
+
133
+ getPoolKey(model: string): string {
134
+ return `${CODEX_QUOTA_MODEL_KEY}:${model}`;
135
+ },
136
+
126
137
  getBenchmark() {
127
138
  return {
128
139
  body: {
@@ -3,6 +3,7 @@ import type { QuotaFetchContext } from "../adapter.js";
3
3
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
4
4
  import { getCodexAccountId, getCodexTokenState } from "./credentials.js";
5
5
  import { CODEX_PROVIDER_ID } from "./oauth.js";
6
+ import { sortQuotaPools } from "../registry.js";
6
7
 
7
8
  export const CODEX_QUOTA_MODEL_KEY = "openai-codex";
8
9
  export const CODEX_SPARK_QUOTA_MODEL_KEY = "openai-codex-spark";
@@ -215,5 +216,16 @@ function applyQuotaRows(account: AccountRuntime, snapshot: CodexQuotaSnapshot):
215
216
  const other = (account.quota ?? []).filter(
216
217
  (quota) => quota.providerId !== CODEX_PROVIDER_ID,
217
218
  );
218
- account.quota = [...other, ...codexQuotaRows(snapshot)];
219
+ const codexRows = codexQuotaRows(snapshot);
220
+ account.quota = sortQuotaPools([...other, ...codexRows]);
221
+
222
+ account.lastPollByProvider ??= {};
223
+ account.lastPollByProvider[CODEX_PROVIDER_ID] = codexRows
224
+ .map((q) => {
225
+ const remain = q.resetTime
226
+ ? Math.round((new Date(q.resetTime).getTime() - Date.now()) / 60000) + "m"
227
+ : "no_reset";
228
+ return `[${q.modelKey}: ${q.timerType} ${q.percentRemaining}% in ${remain}]`;
229
+ })
230
+ .join(" | ");
219
231
  }
@@ -10,8 +10,6 @@ export const OPENCODE_ZEN_FREE_MODELS = [
10
10
  "nemotron-3-ultra-free",
11
11
  "mimo-v2.5-free",
12
12
  "hy3-free",
13
- "ling-3.0-tiny-free",
14
- "laguna-s-2.1-free",
15
13
  ] as const;
16
14
 
17
15
  export type OpenCodeZenModel = (typeof OPENCODE_ZEN_FREE_MODELS)[number];
@@ -2,7 +2,7 @@
2
2
 
3
3
  import type { AccountConfig } from "../../types.js";
4
4
  import type { CredentialValidationResult } from "../adapter.js";
5
- import { getCredential } from "../registry.js";
5
+ import { getCredential } from "../credential-helpers.js";
6
6
 
7
7
  export const OPENCODE_ZEN_PROVIDER_ID = "opencode-zen";
8
8
 
@@ -31,9 +31,21 @@ const HOP_BY_HOP = new Set([
31
31
 
32
32
  export function buildOpenCodeZenPayload(body: RequestBody): Record<string, unknown> {
33
33
  const request = isRecord(body.request) ? body.request : {};
34
+ // OpenCode Zen does not support the `developer` role (an OpenAI o1/o3 extension).
35
+ // Normalise it to `system` so the upstream deserialises the request correctly.
36
+ const messages = Array.isArray(request.messages)
37
+ ? (request.messages as unknown[]).map((msg) => {
38
+ if (isRecord(msg) && msg.role === "developer") {
39
+ return { ...msg, role: "system" };
40
+ }
41
+ return msg;
42
+ })
43
+ : request.messages;
34
44
  return {
35
45
  ...request,
46
+ ...(messages !== request.messages ? { messages } : {}),
36
47
  model: body.model,
48
+ stream: Boolean(request.stream),
37
49
  };
38
50
  }
39
51
 
@@ -49,16 +61,19 @@ export async function forwardRequest(
49
61
  const forwardHeaders: Record<string, string> = {};
50
62
  for (const [key, value] of Object.entries(originalHeaders)) {
51
63
  const lower = key.toLowerCase();
52
- if (!HOP_BY_HOP.has(lower) && lower !== "authorization") {
64
+ if (
65
+ !HOP_BY_HOP.has(lower) &&
66
+ lower !== "authorization" &&
67
+ lower !== "content-type" &&
68
+ lower !== "accept"
69
+ ) {
53
70
  forwardHeaders[key] = value;
54
71
  }
55
72
  }
56
73
 
57
74
  forwardHeaders["Authorization"] = `Bearer ${apiKey}`;
58
75
  forwardHeaders["Content-Type"] = "application/json";
59
- if (!forwardHeaders["Accept"] && !forwardHeaders["accept"]) {
60
- forwardHeaders["Accept"] = payload.stream === false ? "application/json" : "text/event-stream";
61
- }
76
+ forwardHeaders["Accept"] = payload.stream === true ? "text/event-stream" : "application/json";
62
77
 
63
78
  const endpoint = OPENCODE_ZEN_CHAT_URL;
64
79
  const response = await fetch(endpoint, {