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.
@@ -5,6 +5,7 @@ import { runLogin } from "./login.js";
5
5
  import { getOpenCodeZenApiKey, validateCredentials, OPENCODE_ZEN_PROVIDER_ID } from "./credentials.js";
6
6
  import { forwardRequest, OpenCodeZenSseAccumulator, getBenchmarkSpec } from "./forward.js";
7
7
  import { fetchOpenCodeZenQuota } from "./quota.js";
8
+ import { isOpenCodeZenModel } from "./catalog.js";
8
9
  import type { AccountRuntime } from "../../types.js";
9
10
 
10
11
  const OPENCODE_ZEN_TIER_RANKING = {
@@ -56,6 +57,14 @@ export const opencodeZenAdapter: ProviderAdapter = {
56
57
  return undefined;
57
58
  },
58
59
 
60
+ ownsModel(model: string): boolean {
61
+ return isOpenCodeZenModel(model);
62
+ },
63
+
64
+ getPoolKey(model: string): string {
65
+ return `${OPENCODE_ZEN_PROVIDER_ID}:${model}`;
66
+ },
67
+
59
68
  getBenchmark() {
60
69
  return getBenchmarkSpec();
61
70
  },
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { createInterface } from "node:readline";
4
4
  import type { AccountConfig } from "../../types.js";
5
- import { OPENCODE_ZEN_MODELS_URL } from "./catalog.ts";
5
+ import { OPENCODE_ZEN_MODELS_URL } from "./catalog.js";
6
6
  import { defaultAccountEmail, OPENCODE_ZEN_PROVIDER_ID } from "./credentials.js";
7
7
 
8
8
  function askQuestion(prompt: string): Promise<string> {
@@ -6,6 +6,7 @@ import type { QuotaFetchContext } from "../adapter.js";
6
6
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
7
7
  import { OPENCODE_ZEN_MODELS_URL } from "./catalog.js";
8
8
  import { getOpenCodeZenApiKey, OPENCODE_ZEN_PROVIDER_ID } from "./credentials.js";
9
+ import { sortQuotaPools } from "../registry.js";
9
10
 
10
11
  export async function fetchOpenCodeZenQuota(
11
12
  account: AccountRuntime,
@@ -54,7 +55,7 @@ export async function fetchOpenCodeZenQuota(
54
55
  timerType: "fresh",
55
56
  };
56
57
 
57
- account.quota = [...otherProviders, freshQuota];
58
+ account.quota = sortQuotaPools([...otherProviders, freshQuota]);
58
59
  account.lastQuotaPoll = Date.now();
59
60
 
60
61
  account.lastPollByProvider ??= {};
@@ -10,14 +10,11 @@ import type { ProviderAdapter } from "./adapter.js";
10
10
  import { googleAntigravityAdapter } from "./google-antigravity/index.js";
11
11
  import { ollamaAdapter } from "./ollama/index.js";
12
12
  import { openaiCodexAdapter } from "./openai-codex/index.js";
13
+ import { opencodeZenAdapter } from "./opencode-zen/index.js";
13
14
  import { logger } from "../logger.js";
14
15
  import {
15
16
  DEFAULT_PROVIDER,
16
17
  primaryProviderId,
17
- hasCredential,
18
- getCredential,
19
- type CredentialEntry,
20
- type AccountLike as ProviderCredentialLike,
21
18
  } from "./credential-helpers.js";
22
19
 
23
20
  export {
@@ -27,12 +24,20 @@ export {
27
24
  getCredential,
28
25
  type CredentialEntry,
29
26
  type AccountLike as ProviderCredentialLike,
27
+ PROVIDER_ORDER,
28
+ PROVIDER_ORDER_RANK,
29
+ getProviderIdForPoolKey,
30
+ getQuotaItemProviderId,
31
+ sortQuotaPools,
32
+ sortAccountCredentials,
33
+ type QuotaPoolLike,
30
34
  } from "./credential-helpers.js";
31
35
 
32
36
  const PROVIDERS: Record<string, ProviderAdapter> = {
33
37
  "google-antigravity": googleAntigravityAdapter,
34
38
  ollama: ollamaAdapter,
35
39
  "openai-codex": openaiCodexAdapter,
40
+ "opencode-zen": opencodeZenAdapter,
36
41
  };
37
42
 
38
43
  export function getProviderAdapter(providerId: string): ProviderAdapter {
@@ -53,6 +58,19 @@ export function isKnownProvider(providerId: string): boolean {
53
58
  return Object.prototype.hasOwnProperty.call(PROVIDERS, providerId);
54
59
  }
55
60
 
61
+ export function findProviderForModel(
62
+ model: string,
63
+ context?: { ollamaModels?: Set<string>; codexModels?: Set<string> },
64
+ ): ProviderAdapter | null {
65
+ // Check non-default explicit providers first to prevent Google fallback overlap
66
+ for (const adapter of [opencodeZenAdapter, openaiCodexAdapter, ollamaAdapter, googleAntigravityAdapter]) {
67
+ if (adapter.ownsModel?.(model, context)) {
68
+ return adapter;
69
+ }
70
+ }
71
+ return null;
72
+ }
73
+
56
74
  export function getProviderForAccount(
57
75
  account: { credentials?: Array<{ provider: string }>; provider?: string },
58
76
  providerId?: string,
package/src/proxy.ts CHANGED
@@ -15,15 +15,9 @@ import {
15
15
  resolveQuotaModelKey,
16
16
  resolveDisplayModelKey,
17
17
  } from "./types.js";
18
- import {
19
- isCodexRequestModel,
20
- isCodexProviderModelId,
21
- } from "./providers/openai-codex/catalog.js";
22
- import { isOpenCodeZenModel } from "./providers/opencode-zen/catalog.js";
23
- import { OPENCODE_ZEN_PROVIDER_ID } from "./providers/opencode-zen/index.js";
24
18
  import type { AccountRuntime } from "./types.js";
25
19
  import type { AccountRotator } from "./rotator.js";
26
- import { DEFAULT_PROVIDER, getProviderAdapter, getProviderForAccount } from "./providers/registry.js";
20
+ import { DEFAULT_PROVIDER, getProviderAdapter, getProviderForAccount, findProviderForModel, isKnownProvider } from "./providers/registry.js";
27
21
  import { isRecord } from "./compat/schema-sanitizer.js";
28
22
  import type { ProviderAdapter, StreamAccumulator } from "./providers/adapter.js";
29
23
  import {
@@ -64,6 +58,7 @@ import {
64
58
  serveGetSpendLogsApi,
65
59
  serveGetSpendSummaryApi,
66
60
  serveGetSpendByKeyApi,
61
+ serveModelsApi,
67
62
  serveDashboardKeys,
68
63
  serveDashboardLogs,
69
64
  serveStaticKeysJs,
@@ -108,45 +103,22 @@ export function providerAdapterForModel(
108
103
  rotator?: { getOllamaModels?: () => string[]; getCodexModels?: () => string[] },
109
104
  ): ProviderAdapter {
110
105
  const creds = account.config.credentials ?? [];
111
- if (model && isOpenCodeZenModel(model)) {
112
- return getProviderAdapter(OPENCODE_ZEN_PROVIDER_ID);
113
- }
114
- let isCodex = Boolean(model && isCodexRequestModel(model));
115
- try {
116
- if (
117
- model &&
118
- isCodexProviderModelId(model) &&
119
- rotator?.getCodexModels?.().includes(model)
120
- ) isCodex = true;
121
- } catch {
122
- // Ignore catalog read failures and retain the safe static allowlist.
123
- }
124
- if (isCodex) {
125
- // Codex models are provider-owned and never fall back to Google/Ollama.
126
- return getProviderAdapter("openai-codex");
106
+ if (model) {
107
+ const context = {
108
+ ollamaModels: new Set(rotator?.getOllamaModels?.() ?? []),
109
+ codexModels: new Set(rotator?.getCodexModels?.() ?? []),
110
+ };
111
+ const matched = findProviderForModel(model, context);
112
+ if (matched) return matched;
127
113
  }
128
114
  if (creds.length > 0) {
129
- const onlyZen = creds.every((c) => c.provider === OPENCODE_ZEN_PROVIDER_ID);
130
- const onlyOllama = creds.every((c) => c.provider === "ollama");
131
- const onlyGoogle = creds.every((c) => c.provider === DEFAULT_PROVIDER);
132
- if (onlyZen) return getProviderAdapter(OPENCODE_ZEN_PROVIDER_ID);
133
- if (onlyOllama) return getProviderAdapter("ollama");
134
- if (onlyGoogle) return getProviderAdapter(DEFAULT_PROVIDER);
135
- }
136
- let isOllamaModel = false;
137
- try {
138
- const ollamaList = rotator?.getOllamaModels?.() ?? [];
139
- if (ollamaList.length > 0 && model) {
140
- isOllamaModel = ollamaList.includes(model);
115
+ const providers = new Set(creds.map((c) => c.provider));
116
+ if (providers.size === 1) {
117
+ const soleProvider = Array.from(providers)[0];
118
+ if (isKnownProvider(soleProvider)) {
119
+ return getProviderAdapter(soleProvider);
120
+ }
141
121
  }
142
- } catch {
143
- // ignore — fall through to primary dispatch
144
- }
145
- if (isOllamaModel) {
146
- return getProviderAdapter("ollama");
147
- }
148
- if (creds.some((credential) => credential.provider === DEFAULT_PROVIDER)) {
149
- return getProviderAdapter(DEFAULT_PROVIDER);
150
122
  }
151
123
  const fallback = getProviderForAccount(account.config);
152
124
  return fallback.id === "openai-codex"
@@ -532,7 +504,9 @@ async function handleUpstreamAccountAction(
532
504
  );
533
505
 
534
506
  const shouldRetryProviderRateLimit =
535
- provider.id === "openai-codex" || action.providerResourceExhausted;
507
+ provider.id === "openai-codex" ||
508
+ provider.id === "opencode-zen" ||
509
+ action.providerResourceExhausted;
536
510
  if (
537
511
  shouldRetryProviderRateLimit &&
538
512
  options.canRetry &&
@@ -1477,16 +1451,18 @@ async function handleProxyRequest(
1477
1451
  proxyLog(`[${body.model}] No healthy account available: ${reason}`, "warn");
1478
1452
  const retryAfterMs = rotator.getRetryAfterMs(body.model);
1479
1453
  if (retryAfterMs > 0) {
1454
+ const retrySec = Math.ceil(retryAfterMs / 1000);
1480
1455
  res.writeHead(429, {
1481
1456
  "Content-Type": "application/json",
1482
- "Retry-After": String(Math.ceil(retryAfterMs / 1000)),
1457
+ "Retry-After": String(retrySec),
1483
1458
  });
1484
1459
  res.end(
1485
1460
  JSON.stringify({
1486
- error: "All accounts cooling down or model circuit breaker active",
1461
+ error: `Rate limit exceeded. All accounts cooling down. Please wait ${retrySec} seconds before retrying.`,
1487
1462
  reason,
1488
1463
  model: body.model,
1489
1464
  retryAfterMs,
1465
+ retryAfterSeconds: retrySec,
1490
1466
  }),
1491
1467
  );
1492
1468
  return;
@@ -2315,6 +2291,15 @@ export function startProxy(
2315
2291
  return;
2316
2292
  }
2317
2293
 
2294
+ // Admin-only model catalog used by the dashboard's Generate/Edit
2295
+ // Virtual Key modal so every active provider's models (Ollama, OpenCode
2296
+ // Zen, OpenAI Codex, Google Antigravity) can be selected.
2297
+ if (method === "GET" && pathname === "/api/models") {
2298
+ if (!requireAdmin(req, res)) return;
2299
+ serveModelsApi(res, rotator);
2300
+ return;
2301
+ }
2302
+
2318
2303
  if (pathname.startsWith("/api/keys/")) {
2319
2304
  if (!requireAdmin(req, res)) return;
2320
2305
  const hash = decodeURIComponent(pathname.slice("/api/keys/".length));
@@ -38,7 +38,8 @@ export function classifyRateLimitReason(errorText: string, status?: number): Rat
38
38
  lower.includes("rate_limit_exceeded") ||
39
39
  lower.includes("rate limit") ||
40
40
  lower.includes("too many requests") ||
41
- lower.includes("throttl")
41
+ lower.includes("throttl") ||
42
+ lower.includes("freeusagelimit")
42
43
  ) {
43
44
  return "rate-limit";
44
45
  }
package/src/rotator.ts CHANGED
@@ -41,6 +41,7 @@ import {
41
41
  applyConfigDefaults,
42
42
  saveAccountsConfig,
43
43
  removeAccountFromConfig,
44
+ mergeCredentials,
44
45
  } from "./account-store.js";
45
46
  import { isHostedOAuthConfigured } from "./providers/google-antigravity/oauth.js";
46
47
  import type { RequestBody } from "./proxy.js";
@@ -54,6 +55,9 @@ import {
54
55
  getProviderForAccount,
55
56
  hasCredential,
56
57
  primaryProviderId,
58
+ findProviderForModel,
59
+ getProviderIdForPoolKey,
60
+ PROVIDER_ORDER,
57
61
  } from "./providers/registry.js";
58
62
  import type { QuotaFetchContext } from "./providers/adapter.js";
59
63
  import { logger } from "./logger.js";
@@ -66,6 +70,7 @@ import {
66
70
  } from "./providers/openai-codex/catalog.js";
67
71
  import { CodexOAuthError } from "./providers/openai-codex/oauth.js";
68
72
  import { CODEX_QUOTA_MODEL_KEY } from "./providers/openai-codex/quota.js";
73
+ import { OPENCODE_ZEN_PROVIDER_ID } from "./providers/opencode-zen/credentials.js";
69
74
  import { getUpdateInfo } from "./version-check.js";
70
75
  import { getNotifications } from "./notification-poller.js";
71
76
  import { getConfiguredAdminToken } from "./admin-auth.js";
@@ -628,7 +633,7 @@ export class AccountRotator {
628
633
  private logConsolidatedPoll(account: AccountRuntime): void {
629
634
  const stash = account.lastPollByProvider;
630
635
  if (!stash) return;
631
- const ordered = ["google-antigravity", "ollama", "openai-codex", "opencode-zen"]
636
+ const ordered = PROVIDER_ORDER
632
637
  .filter((pid) => stash[pid])
633
638
  .map((pid) => `${pid}: ${stash[pid]}`);
634
639
  if (ordered.length > 0) {
@@ -792,8 +797,19 @@ export class AccountRotator {
792
797
  const q = account.quota.find((q) => q.modelKey === modelKey) ??
793
798
  (modelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)
794
799
  ? account.quota.find((candidate) => candidate.modelKey === CODEX_QUOTA_MODEL_KEY)
795
- : undefined);
796
- return q ? q.percentRemaining : -1;
800
+ : modelKey.startsWith(`${OPENCODE_ZEN_PROVIDER_ID}:`)
801
+ ? account.quota.find((candidate) => candidate.providerId === OPENCODE_ZEN_PROVIDER_ID)
802
+ : undefined);
803
+ if (!q) return -1;
804
+ // Ollama: the session pool is gated by the weekly pool. If the weekly
805
+ // quota is fully exhausted (0%), the account cannot accept any requests
806
+ // regardless of how much session quota remains. Treat it as 0 so the
807
+ // account is skipped at all call sites that check `quota === 0`.
808
+ if (modelKey === "session") {
809
+ const weekly = account.quota.find((w) => w.modelKey === "weekly");
810
+ if (weekly && weekly.percentRemaining === 0) return 0;
811
+ }
812
+ return q.percentRemaining;
797
813
  }
798
814
 
799
815
  // Get timer type for a specific model on an account
@@ -804,7 +820,9 @@ export class AccountRotator {
804
820
  const q = account.quota.find((q) => q.modelKey === modelKey) ??
805
821
  (modelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)
806
822
  ? account.quota.find((candidate) => candidate.modelKey === CODEX_QUOTA_MODEL_KEY)
807
- : undefined);
823
+ : modelKey.startsWith(`${OPENCODE_ZEN_PROVIDER_ID}:`)
824
+ ? account.quota.find((candidate) => candidate.providerId === OPENCODE_ZEN_PROVIDER_ID)
825
+ : undefined);
808
826
  return q?.timerType ?? "fresh";
809
827
  }
810
828
 
@@ -2344,6 +2362,7 @@ export class AccountRotator {
2344
2362
  const lower = model.toLowerCase();
2345
2363
  if (lower.includes("opus")) pricing = MODEL_PRICING["claude-opus-4-6-thinking"];
2346
2364
  else if (lower.includes("sonnet")) pricing = MODEL_PRICING["claude-sonnet-4-6"];
2365
+ else if (lower.includes("3.7-flash")) pricing = MODEL_PRICING["gemini-3.7-flash-tiered"];
2347
2366
  else if (lower.includes("3.6-flash")) pricing = MODEL_PRICING["gemini-3.6-flash-high"];
2348
2367
  else if (lower.includes("3.5-flash")) pricing = MODEL_PRICING["gemini-3.5-flash-high"];
2349
2368
  else if (lower.includes("flash")) pricing = MODEL_PRICING["gemini-3-flash"];
@@ -2428,8 +2447,13 @@ export class AccountRotator {
2428
2447
  this.setProviderCooldown(account, "openai-codex", cooldownMs);
2429
2448
  return;
2430
2449
  }
2431
- if (providerResourceExhausted) {
2432
- // Account-level daily/weekly quota exhaustion is not a model outage:
2450
+ const poolKey = model ? this.resolvePoolKeyForModel(model) : null;
2451
+ const isAccountScopedProvider =
2452
+ providerResourceExhausted ||
2453
+ (poolKey && (poolKey.startsWith("opencode-zen") || poolKey.startsWith("session")));
2454
+
2455
+ if (isAccountScopedProvider) {
2456
+ // Account-level daily/weekly quota exhaustion or per-key rate limit is not a model outage:
2433
2457
  // the account already gets an individual cooldown from markExhausted,
2434
2458
  // so it must not arm the project or model circuit breaker and block
2435
2459
  // healthy accounts that still have quota.
@@ -2701,7 +2725,11 @@ export class AccountRotator {
2701
2725
  return true;
2702
2726
  }
2703
2727
 
2704
- async ensureValidToken(account: AccountRuntime): Promise<void> {
2728
+ async ensureValidToken(account: AccountRuntime, providerId?: string): Promise<void> {
2729
+ if (providerId) {
2730
+ await this.ensureValidTokenForProvider(account, providerId);
2731
+ return;
2732
+ }
2705
2733
  const adapter = getProviderForAccount(account.config);
2706
2734
  try {
2707
2735
  await adapter.ensureValidToken(account);
@@ -2748,12 +2776,9 @@ export class AccountRotator {
2748
2776
  account: AccountRuntime,
2749
2777
  modelKey: string | null,
2750
2778
  ): Promise<void> {
2751
- if (modelKey?.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)) {
2752
- await this.ensureValidTokenForProvider(account, "openai-codex");
2753
- return;
2754
- }
2755
- if (modelKey === "session") {
2756
- await this.ensureValidTokenForProvider(account, "ollama");
2779
+ if (modelKey) {
2780
+ const providerId = getProviderIdForPoolKey(modelKey);
2781
+ await this.ensureValidToken(account, providerId);
2757
2782
  return;
2758
2783
  }
2759
2784
  await this.ensureValidToken(account);
@@ -2800,10 +2825,9 @@ export class AccountRotator {
2800
2825
  now: number,
2801
2826
  ): boolean {
2802
2827
  if (!this.isAvailable(account, now)) return false;
2803
- if (modelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)) {
2804
- if (account.invalidProviders?.["openai-codex"]) return false;
2805
- if ((account.providerCooldowns?.["openai-codex"] ?? 0) > now) return false;
2806
- }
2828
+ const providerId = getProviderIdForPoolKey(modelKey);
2829
+ if (account.invalidProviders?.[providerId]) return false;
2830
+ if ((account.providerCooldowns?.[providerId] ?? 0) > now) return false;
2807
2831
  const modelCooldown = account.cooldownsByModel[modelKey] ?? 0;
2808
2832
  if (modelCooldown > now) return false;
2809
2833
  // Ollama Cloud (pool key "session") imposes no per-account concurrency
@@ -2879,17 +2903,10 @@ export class AccountRotator {
2879
2903
  account: AccountRuntime,
2880
2904
  modelKey: string,
2881
2905
  ): boolean {
2882
- if (modelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)) {
2883
- return hasCredential(account.config, "openai-codex") &&
2884
- !account.invalidProviders?.["openai-codex"] &&
2885
- (account.providerCooldowns?.["openai-codex"] ?? 0) <= Date.now();
2886
- }
2887
- if (modelKey === "session") {
2888
- return hasCredential(account.config, "ollama");
2889
- }
2890
- // Google pools (claude/gemini) require a google credential. A dual
2891
- // account (google + ollama) must stay eligible here — it can serve both.
2892
- return hasCredential(account.config, DEFAULT_PROVIDER);
2906
+ const providerId = getProviderIdForPoolKey(modelKey);
2907
+ return hasCredential(account.config, providerId) &&
2908
+ !account.invalidProviders?.[providerId] &&
2909
+ (account.providerCooldowns?.[providerId] ?? 0) <= Date.now();
2893
2910
  }
2894
2911
 
2895
2912
  /** Public pool-key resolution for quota routing display/logging. */
@@ -2898,10 +2915,14 @@ export class AccountRotator {
2898
2915
  }
2899
2916
 
2900
2917
  private resolvePoolKeyForModel(model: string): string | null {
2901
- if (this.codexModels.has(model) || isCodexRequestModel(model)) {
2902
- return `${CODEX_QUOTA_MODEL_KEY}:${model}`;
2918
+ const context = {
2919
+ ollamaModels: this.ollamaModels,
2920
+ codexModels: this.codexModels,
2921
+ };
2922
+ const adapter = findProviderForModel(model, context);
2923
+ if (adapter?.getPoolKey) {
2924
+ return adapter.getPoolKey(model);
2903
2925
  }
2904
- if (this.ollamaModels.has(model)) return "session";
2905
2926
  return resolveQuotaModelKey(model) ?? null;
2906
2927
  }
2907
2928
 
@@ -3146,13 +3167,17 @@ export class AccountRotator {
3146
3167
  const previous = new Map(
3147
3168
  this.accounts.map((account) => [account.config.email, account]),
3148
3169
  );
3149
- this.config = normalized;
3150
- this.accounts = normalized.accounts.map((config) => {
3170
+ const mergedAccounts = normalized.accounts.map((config) => {
3151
3171
  const existing = previous.get(config.email);
3152
3172
  if (existing) {
3173
+ const mergedConfig = {
3174
+ ...existing.config,
3175
+ ...config,
3176
+ credentials: mergeCredentials(existing.config.credentials, config.credentials),
3177
+ };
3153
3178
  return {
3154
3179
  ...existing,
3155
- config: { ...existing.config, ...config },
3180
+ config: mergedConfig,
3156
3181
  };
3157
3182
  }
3158
3183
  return {
@@ -3188,6 +3213,8 @@ export class AccountRotator {
3188
3213
  },
3189
3214
  };
3190
3215
  });
3216
+ this.config = { ...normalized, accounts: mergedAccounts.map((account) => account.config) };
3217
+ this.accounts = mergedAccounts;
3191
3218
  await saveAccountsConfig(this.config);
3192
3219
  await this.saveState();
3193
3220
  this.refreshHealthScores();
@@ -3249,6 +3276,7 @@ export class AccountRotator {
3249
3276
  existing.config = {
3250
3277
  ...existing.config,
3251
3278
  ...accountConfig,
3279
+ credentials: mergeCredentials(existing.config.credentials, accountConfig.credentials),
3252
3280
  tier: accountConfig.tier || existing.config.tier || "unknown",
3253
3281
  };
3254
3282
  existing.disabled = false;
@@ -118,8 +118,11 @@ export class PostgresSettingsRepository implements ISettingsRepository {
118
118
  this.cache.set(row.key, row.value);
119
119
  }
120
120
 
121
- // Migrate from disk for any keys not already in DB
121
+ // Migrate non-account settings from disk for any keys not already in DB.
122
+ // accounts.json is deliberately excluded: when PostgreSQL is configured,
123
+ // it must be the sole source of account credentials.
122
124
  for (const [key, spec] of Object.entries(DISK_FILES)) {
125
+ if (key === "accounts_json") continue;
123
126
  if (this.cache.has(key)) continue;
124
127
  try {
125
128
  const path = join(getConfigDir(), spec.filename);
@@ -166,21 +169,21 @@ export class PostgresSettingsRepository implements ISettingsRepository {
166
169
  async set(key: string, value: string): Promise<void> {
167
170
  this.cache.set(key, value);
168
171
  if (this.pool) {
169
- // Non-blocking background save
170
- this.pool
171
- .query(
172
+ try {
173
+ // Account changes must be durable before the API reports success.
174
+ // A background-only write could be lost when the service restarts.
175
+ await this.pool.query(
172
176
  `INSERT INTO rotator_settings (key, value, updated_at)
173
- VALUES ($1, $2, CURRENT_TIMESTAMP)
174
- ON CONFLICT (key) DO UPDATE
175
- SET value = EXCLUDED.value, updated_at = CURRENT_TIMESTAMP`,
177
+ VALUES ($1, $2, CURRENT_TIMESTAMP)
178
+ ON CONFLICT (key) DO UPDATE
179
+ SET value = EXCLUDED.value, updated_at = CURRENT_TIMESTAMP`,
176
180
  [key, value],
177
- )
178
- .catch((err) => {
179
- console.error(
180
- `Failed to save ${key} to database in background: ${err}`,
181
- );
182
- this.enqueueRetry(key, value);
183
- });
181
+ );
182
+ } catch (err) {
183
+ console.error(`Failed to save ${key} to database: ${err}`);
184
+ this.enqueueRetry(key, value);
185
+ throw err;
186
+ }
184
187
  }
185
188
  }
186
189
 
@@ -223,6 +223,8 @@ export function calculateCost(model: string, promptTokens: number, completionTok
223
223
  pricing = MODEL_PRICING["claude-opus-4-6-thinking"];
224
224
  } else if (lower.includes("sonnet")) {
225
225
  pricing = MODEL_PRICING["claude-sonnet-4-6"];
226
+ } else if (lower.includes("3.7-flash")) {
227
+ pricing = MODEL_PRICING["gemini-3.7-flash-tiered"];
226
228
  } else if (lower.includes("3.6-flash")) {
227
229
  pricing = MODEL_PRICING["gemini-3.6-flash-high"];
228
230
  } else if (lower.includes("3.5-flash")) {