tuxevil-rotator 3.7.0 → 3.7.2

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/rotator.ts CHANGED
@@ -59,6 +59,7 @@ import {
59
59
  primaryProviderId,
60
60
  findProviderForModel,
61
61
  getProviderIdForPoolKey,
62
+ isOllamaQuotaPoolKey,
62
63
  PROVIDER_ORDER,
63
64
  } from "./providers/registry.js";
64
65
  import type { QuotaFetchContext } from "./providers/adapter.js";
@@ -177,8 +178,13 @@ function projectModelKey(projectId: string, modelKey: string): string {
177
178
  }
178
179
 
179
180
  const REQUEST_QUEUE_TIMEOUT_MS = 300_000;
181
+ // Node clamps delays above the signed 32-bit millisecond limit to 1ms. Long
182
+ // provider cooldowns (for example Codex weekly resets) must be rechecked in
183
+ // safe-sized timer slices instead of creating a hot timer loop.
184
+ const MAX_NODE_TIMEOUT_MS = 2_147_483_647;
180
185
 
181
186
  interface AccountRequestWaiter {
187
+ queueKey: string;
182
188
  model?: string;
183
189
  signal?: AbortSignal;
184
190
  timer: ReturnType<typeof setTimeout>;
@@ -191,6 +197,9 @@ interface AccountRequestWaiter {
191
197
  const QUOTA_POOL_FOR_KICKSTART_MODEL: Record<string, string> = {
192
198
  "gpt-oss-120b-medium": "claude",
193
199
  "gemini-3-flash": "gemini",
200
+ "gpt-5.6-luna": CODEX_QUOTA_MODEL_KEY,
201
+ // Legacy manual kickstart compatibility. New Ollama quota polling/routes
202
+ // use `monthly`; this alias is only for callers that still name `session`.
194
203
  "gpt-oss:20b": "session",
195
204
  };
196
205
 
@@ -330,6 +339,8 @@ export class AccountRotator {
330
339
  account: string;
331
340
  }> = [];
332
341
  private routingDiagnostics: Record<string, RoutingModelDiagnostics> = {};
342
+ private routingWarningLastLoggedAt = new Map<string, number>();
343
+ private static readonly ROUTING_WARNING_DEDUP_MS = 60_000;
333
344
  private autoWarmupEnabled = false;
334
345
  // Debounced state writer: batches multiple saveState() calls within a 1s window
335
346
  // to a single disk write. Hot paths (markError, recordRequest, etc.) call
@@ -1044,10 +1055,9 @@ export class AccountRotator {
1044
1055
  ? account.quota.find((candidate) => candidate.providerId === OPENCODE_ZEN_PROVIDER_ID)
1045
1056
  : undefined);
1046
1057
  if (!q) return -1;
1047
- // Ollama: the session pool is gated by the weekly pool. If the weekly
1048
- // quota is fully exhausted (0%), the account cannot accept any requests
1049
- // regardless of how much session quota remains. Treat it as 0 so the
1050
- // account is skipped at all call sites that check `quota === 0`.
1058
+ // Legacy Ollama state used a session pool gated by a weekly pool. Keep
1059
+ // that compatibility rule only for old in-memory state; current Ollama
1060
+ // accounts expose one monthly pool and need no secondary gate.
1051
1061
  if (quotaKey === "session") {
1052
1062
  const weekly = account.quota.find((w) => w.modelKey === "weekly");
1053
1063
  if (weekly && weekly.percentRemaining === 0) return 0;
@@ -1059,7 +1069,7 @@ export class AccountRotator {
1059
1069
  private getModelTimerType(
1060
1070
  account: AccountRuntime,
1061
1071
  modelKey: string,
1062
- ): "fresh" | "5h" | "7d" {
1072
+ ): ModelQuota["timerType"] {
1063
1073
  const quotaKey = isStaticAntigravityModel(modelKey)
1064
1074
  ? modelKey
1065
1075
  : dynamicCatalog.resolveQuotaPool(modelKey) ?? modelKey;
@@ -1080,8 +1090,8 @@ export class AccountRotator {
1080
1090
 
1081
1091
  /**
1082
1092
  * Resolve kickstart by quota-pool owner, never by the account's primary
1083
- * provider. Parent accounts may hold several credentials, and Codex pools
1084
- * deliberately have no kickstart implementation.
1093
+ * provider. Parent accounts may hold several credentials, and each provider
1094
+ * supplies its own kickstart implementation.
1085
1095
  */
1086
1096
  private getKickstartTarget(
1087
1097
  account: AccountRuntime,
@@ -1096,12 +1106,7 @@ export class AccountRotator {
1096
1106
  const quota = account.quota.find((candidate) => candidate.modelKey === poolKey);
1097
1107
  const providerId =
1098
1108
  quota?.providerId ??
1099
- (poolKey === "session"
1100
- ? "ollama"
1101
- : poolKey === CODEX_QUOTA_MODEL_KEY ||
1102
- poolKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)
1103
- ? "openai-codex"
1104
- : DEFAULT_PROVIDER);
1109
+ getProviderIdForPoolKey(poolKey);
1105
1110
  if (!hasCredential(account.config, providerId)) return null;
1106
1111
 
1107
1112
  const adapter = getProviderAdapter(providerId);
@@ -1252,19 +1257,31 @@ export class AccountRotator {
1252
1257
  let best: AccountRuntime | null = null;
1253
1258
  let bestLoad = Infinity;
1254
1259
  let bestDistance = Infinity;
1260
+ let bestTier = Infinity;
1261
+ const policy = this.config.routingPolicy || "timer-first";
1255
1262
 
1256
1263
  for (let i = 0; i < this.accounts.length; i++) {
1257
1264
  const account = this.accounts[i];
1258
1265
  if (!this.isRoutableForModel(account, modelKey, now)) continue;
1259
1266
  const load = account.inFlightRequests;
1267
+ const tier = this.getTierRank(account);
1260
1268
  const distance = this.requestCursorIndex < 0
1261
1269
  ? i
1262
1270
  : (i - this.requestCursorIndex + this.accounts.length) %
1263
1271
  this.accounts.length || this.accounts.length;
1264
- if (load < bestLoad || (load === bestLoad && distance < bestDistance)) {
1272
+ // Concurrent balancing must keep tier-first's preference: load-balance
1273
+ // within the best eligible tier, and use lower tiers only as fallback.
1274
+ const betterTier = policy === "tier-first" && tier < bestTier;
1275
+ const sameTier = policy !== "tier-first" || tier === bestTier;
1276
+ if (
1277
+ betterTier ||
1278
+ (sameTier &&
1279
+ (load < bestLoad || (load === bestLoad && distance < bestDistance)))
1280
+ ) {
1265
1281
  best = account;
1266
1282
  bestLoad = load;
1267
1283
  bestDistance = distance;
1284
+ bestTier = tier;
1268
1285
  }
1269
1286
  }
1270
1287
 
@@ -1482,11 +1499,12 @@ export class AccountRotator {
1482
1499
  return { reason: "disabled", detail: "account disabled" };
1483
1500
  if (account.flagged)
1484
1501
  return { reason: "flagged", detail: "account quarantined or flagged" };
1485
- if (!this.isProviderEligibleForKey(account, modelKey))
1486
- return {
1487
- reason: "provider-ineligible",
1488
- detail: "account lacks a credential for this provider pool",
1489
- };
1502
+ const providerRejection = this.getProviderEligibilityRejection(
1503
+ account,
1504
+ modelKey,
1505
+ now,
1506
+ );
1507
+ if (providerRejection) return providerRejection;
1490
1508
  const defaultCooldown = account.cooldownsByModel["__default__"] ?? 0;
1491
1509
  if (defaultCooldown > now)
1492
1510
  return { reason: "cooldown", detail: "default cooldown active" };
@@ -1494,13 +1512,13 @@ export class AccountRotator {
1494
1512
  account.cooldownsByModel[this.resolveQuotaStateKey(modelKey)] ?? 0;
1495
1513
  if (modelCooldown > now)
1496
1514
  return { reason: "cooldown", detail: "model cooldown active" };
1497
- // Ollama Cloud (pool key "session") imposes no per-account
1515
+ // Ollama Cloud quota pools impose no per-account
1498
1516
  // concurrency limit — the in-flight check would otherwise wedge
1499
1517
  // long-running streams while the same model on another account is
1500
1518
  // still serving. Antigravity keeps the per-account limit.
1501
1519
  if (
1502
1520
  !ignoreConcurrency &&
1503
- modelKey !== "session" &&
1521
+ !isOllamaQuotaPoolKey(modelKey) &&
1504
1522
  account.inFlightRequests >=
1505
1523
  (this.config.maxConcurrentRequestsPerAccount ?? 5)
1506
1524
  ) {
@@ -1851,26 +1869,39 @@ export class AccountRotator {
1851
1869
  signal?: AbortSignal,
1852
1870
  ): Promise<AccountRuntime | null> {
1853
1871
  if (signal?.aborted) return null;
1872
+ const queueKey = this.getRequestQueueKey(model);
1854
1873
  if (
1855
- this.requestWaiters.length > 0 ||
1874
+ this.hasQueuedRequest(queueKey) ||
1856
1875
  this.isConcurrencySaturated(model)
1857
1876
  ) {
1858
- return this.enqueueAccountRequest(model, signal);
1877
+ return this.enqueueAccountRequest(model, signal, queueKey);
1859
1878
  }
1860
1879
 
1861
1880
  const account = await this.tryGetActiveAccount(model);
1862
1881
  if (account || !this.isConcurrencySaturated(model)) return account;
1863
- return this.enqueueAccountRequest(model, signal);
1882
+ return this.enqueueAccountRequest(model, signal, queueKey);
1883
+ }
1884
+
1885
+ /** Keep fairness within a provider pool without making unrelated providers wait. */
1886
+ private getRequestQueueKey(model?: string): string {
1887
+ if (!model) return DEFAULT_PROVIDER;
1888
+ return getProviderIdForPoolKey(this.resolveRequestPoolKey(model));
1889
+ }
1890
+
1891
+ private hasQueuedRequest(queueKey: string): boolean {
1892
+ return this.requestWaiters.some((waiter) => waiter.queueKey === queueKey);
1864
1893
  }
1865
1894
 
1866
1895
  private enqueueAccountRequest(
1867
1896
  model?: string,
1868
1897
  signal?: AbortSignal,
1898
+ queueKey = this.getRequestQueueKey(model),
1869
1899
  ): Promise<AccountRuntime | null> {
1870
1900
  if (signal?.aborted) return Promise.resolve(null);
1871
1901
 
1872
1902
  return new Promise<AccountRuntime | null>((resolve, reject) => {
1873
1903
  const waiter = {} as AccountRequestWaiter;
1904
+ waiter.queueKey = queueKey;
1874
1905
  waiter.model = model;
1875
1906
  waiter.signal = signal;
1876
1907
  waiter.resolve = resolve;
@@ -1935,6 +1966,10 @@ export class AccountRotator {
1935
1966
  }
1936
1967
  this.clearRequestWaiterWake();
1937
1968
  this.requestWaiterWakeAt = wakeAt;
1969
+ const delayMs = Math.min(
1970
+ MAX_NODE_TIMEOUT_MS,
1971
+ Math.max(1, wakeAt - Date.now()),
1972
+ );
1938
1973
  this.requestWaiterWakeTimer = setTimeout(() => {
1939
1974
  this.requestWaiterWakeTimer = null;
1940
1975
  if (this.requestWaiters.length === 0) {
@@ -1947,7 +1982,7 @@ export class AccountRotator {
1947
1982
  }
1948
1983
  this.requestWaiterWakeAt = 0;
1949
1984
  this.requestWaiterDrain();
1950
- }, Math.max(1, wakeAt - Date.now()));
1985
+ }, delayMs);
1951
1986
  }
1952
1987
 
1953
1988
  private requestWaiterDrain(): void {
@@ -1965,11 +2000,18 @@ export class AccountRotator {
1965
2000
  do {
1966
2001
  this.requestWaiterDrainRequested = false;
1967
2002
  progressed = false;
1968
- for (const waiter of [...this.requestWaiters]) {
2003
+ const queueKeys = [
2004
+ ...new Set(this.requestWaiters.map((waiter) => waiter.queueKey)),
2005
+ ];
2006
+ for (const queueKey of queueKeys) {
2007
+ const waiter = this.requestWaiters.find(
2008
+ (candidate) => candidate.queueKey === queueKey,
2009
+ );
2010
+ if (!waiter) continue;
1969
2011
  if (waiter.signal?.aborted) {
1970
2012
  this.settleAccountRequestWaiter(waiter, null);
1971
2013
  progressed = true;
1972
- break;
2014
+ continue;
1973
2015
  }
1974
2016
 
1975
2017
  let account: AccountRuntime | null;
@@ -1978,7 +2020,7 @@ export class AccountRotator {
1978
2020
  } catch (error) {
1979
2021
  this.rejectAccountRequestWaiter(waiter, error);
1980
2022
  progressed = true;
1981
- break;
2023
+ continue;
1982
2024
  }
1983
2025
 
1984
2026
  if (!this.requestWaiters.includes(waiter)) {
@@ -1991,16 +2033,16 @@ export class AccountRotator {
1991
2033
  );
1992
2034
  }
1993
2035
  progressed = true;
1994
- break;
2036
+ continue;
1995
2037
  }
1996
2038
  if (account) {
1997
2039
  this.settleAccountRequestWaiter(waiter, account);
1998
2040
  progressed = true;
1999
- break;
2041
+ continue;
2000
2042
  }
2001
2043
  if (this.requestWaiterDrainRequested) {
2002
2044
  progressed = true;
2003
- break;
2045
+ continue;
2004
2046
  }
2005
2047
  const wakeAt = this.getNextRequestAvailabilityAt(waiter.model);
2006
2048
  if (wakeAt !== null) this.scheduleRequestWaiterWake(wakeAt);
@@ -2008,7 +2050,6 @@ export class AccountRotator {
2008
2050
  this.settleAccountRequestWaiter(waiter, null);
2009
2051
  progressed = true;
2010
2052
  }
2011
- break;
2012
2053
  }
2013
2054
  } while (progressed || this.requestWaiterDrainRequested);
2014
2055
  } finally {
@@ -2088,6 +2129,16 @@ export class AccountRotator {
2088
2129
  const hasActiveRequests = this.accounts.some(
2089
2130
  (account) => account.inFlightRequests > 0,
2090
2131
  );
2132
+ const policy = this.config.routingPolicy || "timer-first";
2133
+ if (modelKey && policy === "tier-first" && !hasActiveRequests) {
2134
+ const preferred = this.pickBestModelAccount(modelKey, now);
2135
+ if (preferred && preferred !== current) {
2136
+ // A persisted assignment may have been selected under a previous
2137
+ // policy or before account tiers were corrected. Re-evaluate it while
2138
+ // idle so tier-first does not keep serving a lower-tier account.
2139
+ return this.rotateModelForRequest(modelKey, now, idx);
2140
+ }
2141
+ }
2091
2142
  if (modelKey && hasActiveRequests) {
2092
2143
  const leastLoaded = this.pickLeastLoadedModelAccount(modelKey, now);
2093
2144
  if (leastLoaded && leastLoaded !== current) {
@@ -2110,12 +2161,32 @@ export class AccountRotator {
2110
2161
  }
2111
2162
  }
2112
2163
 
2113
- if (current && modelKey && !this.isProviderEligibleForKey(current, modelKey)) {
2114
- this.log(
2115
- `${current.config.label || current.config.email}: provider mismatch for model, rotating`,
2116
- "warn",
2164
+ if (current && modelKey) {
2165
+ const providerRejection = this.getProviderEligibilityRejection(
2166
+ current,
2167
+ modelKey,
2168
+ now,
2117
2169
  );
2118
- return this.rotateModelForRequest(modelKey, now, idx);
2170
+ if (providerRejection) {
2171
+ // A cooldown is expected after a provider 429 and can be hit by many
2172
+ // concurrent callers. Keep that path quiet; diagnostics already show
2173
+ // the cooldown and the generic no-route warning is deduplicated below.
2174
+ if (providerRejection.reason === "provider-ineligible") {
2175
+ const warningKey = `${modelKey}:provider-ineligible`;
2176
+ const lastLoggedAt = this.routingWarningLastLoggedAt.get(warningKey);
2177
+ if (
2178
+ lastLoggedAt === undefined ||
2179
+ now - lastLoggedAt >= AccountRotator.ROUTING_WARNING_DEDUP_MS
2180
+ ) {
2181
+ this.routingWarningLastLoggedAt.set(warningKey, now);
2182
+ this.log(
2183
+ `${current.config.label || current.config.email}: provider unavailable for model (${providerRejection.detail}), rotating`,
2184
+ "warn",
2185
+ );
2186
+ }
2187
+ }
2188
+ return this.rotateModelForRequest(modelKey, now, idx);
2189
+ }
2119
2190
  }
2120
2191
  if (
2121
2192
  current &&
@@ -2331,10 +2402,17 @@ export class AccountRotator {
2331
2402
  } else {
2332
2403
  const diagnostics = this.buildRoutingDiagnostics(modelKey, now);
2333
2404
  this.routingDiagnostics[modelKey] = diagnostics;
2334
- this.log(
2335
- `[${modelKey}] All accounts disabled or unavailable: ${diagnostics.reason}`,
2336
- "warn",
2337
- );
2405
+ const lastLoggedAt = this.routingWarningLastLoggedAt.get(modelKey);
2406
+ if (
2407
+ lastLoggedAt === undefined ||
2408
+ now - lastLoggedAt >= AccountRotator.ROUTING_WARNING_DEDUP_MS
2409
+ ) {
2410
+ this.routingWarningLastLoggedAt.set(modelKey, now);
2411
+ this.log(
2412
+ `[${modelKey}] All accounts disabled or unavailable: ${diagnostics.reason}`,
2413
+ "warn",
2414
+ );
2415
+ }
2338
2416
  }
2339
2417
  return null;
2340
2418
  }
@@ -2615,11 +2693,14 @@ export class AccountRotator {
2615
2693
  }
2616
2694
  }
2617
2695
 
2618
- getPredictionSummary(): Record<string, ExhaustionPrediction> {
2696
+ getPredictionSummary(): Record<string, ExhaustionPrediction> {
2619
2697
  const result: Record<string, ExhaustionPrediction> = {};
2620
2698
  const now = Date.now();
2621
2699
  for (const account of this.accounts) {
2622
2700
  if (!hasCredential(account.config, "ollama")) continue;
2701
+ // The predictor is calibrated for the legacy dual-window response.
2702
+ // Current monthly usage remains routable, but has no calibrated token
2703
+ // budget yet, so do not publish a misleading forecast for it.
2623
2704
  const session = account.quota.find((q) => q.modelKey === "session");
2624
2705
  const weekly = account.quota.find((q) => q.modelKey === "weekly");
2625
2706
  if (
@@ -2982,7 +3063,7 @@ export class AccountRotator {
2982
3063
  const modelKey = model
2983
3064
  ? this.resolveAccountPoolKey(account, model)
2984
3065
  : "__default__";
2985
- if (model && (modelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`) || isCodexRequestModel(model))) {
3066
+ if (model && (this.isCodexPoolKey(modelKey) || isCodexRequestModel(model))) {
2986
3067
  this.setProviderCooldown(account, "openai-codex", cooldownMs);
2987
3068
  }
2988
3069
  account.cooldownsByModel[modelKey] = now + cooldownMs;
@@ -2994,12 +3075,19 @@ export class AccountRotator {
2994
3075
  const quota = account.quota.find(
2995
3076
  (candidate) =>
2996
3077
  candidate.modelKey === modelKey &&
2997
- candidate.providerId === DEFAULT_PROVIDER,
3078
+ (candidate.providerId === DEFAULT_PROVIDER ||
3079
+ candidate.providerId === "ollama" ||
3080
+ candidate.providerId === "openai-codex" ||
3081
+ candidate.providerId === undefined),
2998
3082
  );
2999
3083
  if (quota) {
3000
3084
  quota.percentRemaining = 0;
3001
3085
  quota.resetTime = new Date(now + cooldownMs).toISOString();
3002
- quota.timerType = cooldownMs < 6 * 60 * 60 * 1000 ? "5h" : "7d";
3086
+ quota.timerType = quota.modelKey === "monthly"
3087
+ ? "monthly"
3088
+ : cooldownMs < 6 * 60 * 60 * 1000
3089
+ ? "5h"
3090
+ : "7d";
3003
3091
  }
3004
3092
  }
3005
3093
 
@@ -3018,14 +3106,16 @@ export class AccountRotator {
3018
3106
  providerResourceExhausted = false,
3019
3107
  ): void {
3020
3108
  const now = Date.now();
3021
- if (model && isCodexRequestModel(model)) {
3109
+ const poolKey = model ? this.resolveAccountPoolKey(account, model) : null;
3110
+ if (model && (isCodexRequestModel(model) || (poolKey && this.isCodexPoolKey(poolKey)))) {
3022
3111
  this.setProviderCooldown(account, "openai-codex", cooldownMs);
3023
3112
  return;
3024
3113
  }
3025
- const poolKey = model ? this.resolveAccountPoolKey(account, model) : null;
3026
3114
  const isAccountScopedProvider =
3027
3115
  providerResourceExhausted ||
3028
- (poolKey && (poolKey.startsWith("opencode-zen") || poolKey.startsWith("session")));
3116
+ (poolKey &&
3117
+ (poolKey.startsWith("opencode-zen") ||
3118
+ getProviderIdForPoolKey(poolKey) === "ollama"));
3029
3119
 
3030
3120
  if (isAccountScopedProvider) {
3031
3121
  // Account-level daily/weekly quota exhaustion or per-key rate limit is not a model outage:
@@ -3451,7 +3541,8 @@ export class AccountRotator {
3451
3541
  }
3452
3542
 
3453
3543
  private isCodexPoolKey(modelKey: string): boolean {
3454
- return modelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`);
3544
+ return modelKey === CODEX_QUOTA_MODEL_KEY ||
3545
+ modelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`);
3455
3546
  }
3456
3547
 
3457
3548
  private async ensureValidTokenForModel(
@@ -3514,11 +3605,11 @@ export class AccountRotator {
3514
3605
  const modelCooldown =
3515
3606
  account.cooldownsByModel[this.resolveQuotaStateKey(modelKey)] ?? 0;
3516
3607
  if (modelCooldown > now) return false;
3517
- // Ollama Cloud (pool key "session") imposes no per-account concurrency
3608
+ // Ollama Cloud quota pools impose no per-account concurrency
3518
3609
  // limit. Antigravity keeps it so long streams don't pile up on a
3519
3610
  // single account while siblings sit idle.
3520
3611
  if (
3521
- modelKey !== "session" &&
3612
+ !isOllamaQuotaPoolKey(modelKey) &&
3522
3613
  account.inFlightRequests >=
3523
3614
  (this.config.maxConcurrentRequestsPerAccount ?? 5)
3524
3615
  )
@@ -3556,9 +3647,9 @@ export class AccountRotator {
3556
3647
  startRequest(account: AccountRuntime, modelKey?: string): void {
3557
3648
  const key = modelKey ?? "__default__";
3558
3649
  // Ollama Cloud imposes no per-account concurrency limit, so its
3559
- // requests must not activate in-flight tracking at all (pool key
3560
- // "session" and raw ollama model names from benchmark probes).
3561
- if (key === "session" || this.ollamaModels.has(key)) {
3650
+ // requests must not activate in-flight tracking at all (the monthly
3651
+ // pool and raw ollama model names from benchmark probes).
3652
+ if (isOllamaQuotaPoolKey(key) || this.ollamaModels.has(key)) {
3562
3653
  this.consumeTokenBucket(account, Date.now());
3563
3654
  return;
3564
3655
  }
@@ -3570,7 +3661,7 @@ export class AccountRotator {
3570
3661
 
3571
3662
  finishRequest(account: AccountRuntime, modelKey?: string): void {
3572
3663
  const key = modelKey ?? "__default__";
3573
- if (key === "session" || this.ollamaModels.has(key)) return;
3664
+ if (isOllamaQuotaPoolKey(key) || this.ollamaModels.has(key)) return;
3574
3665
  account.inFlightByModel[key] = Math.max(
3575
3666
  0,
3576
3667
  (account.inFlightByModel[key] ?? 0) - 1,
@@ -3591,18 +3682,54 @@ export class AccountRotator {
3591
3682
  account: AccountRuntime,
3592
3683
  modelKey: string,
3593
3684
  ): boolean {
3685
+ return this.getProviderEligibilityRejection(account, modelKey) === null;
3686
+ }
3687
+
3688
+ private getProviderEligibilityRejection(
3689
+ account: AccountRuntime,
3690
+ modelKey: string,
3691
+ now = Date.now(),
3692
+ ): { reason: RoutingRejectionReason; detail: string } | null {
3594
3693
  const accountId = getAccountIdentity(account);
3595
3694
  if (
3596
3695
  !isStaticAntigravityModel(modelKey) &&
3597
3696
  dynamicCatalog.hasOwnershipForModel(modelKey) &&
3598
3697
  !dynamicCatalog.hasModelForAccount(accountId, modelKey)
3599
3698
  ) {
3600
- return false;
3699
+ return {
3700
+ reason: "provider-ineligible",
3701
+ detail: "account does not own this provider model",
3702
+ };
3601
3703
  }
3602
3704
  const providerId = getProviderIdForPoolKey(modelKey);
3603
- return hasCredential(account.config, providerId) &&
3604
- !account.invalidProviders?.[providerId] &&
3605
- (account.providerCooldowns?.[providerId] ?? 0) <= Date.now();
3705
+ if (!hasCredential(account.config, providerId)) {
3706
+ return {
3707
+ reason: "provider-ineligible",
3708
+ detail: `account has no ${providerId} credential for this provider pool`,
3709
+ };
3710
+ }
3711
+ if (account.invalidProviders?.[providerId]) {
3712
+ return {
3713
+ reason: "provider-ineligible",
3714
+ detail: `${providerId} credential is invalid; re-authentication required`,
3715
+ };
3716
+ }
3717
+ if (
3718
+ providerId === "openai-codex" &&
3719
+ !getProviderAdapter(providerId).hasValidCredentials(account)
3720
+ ) {
3721
+ return {
3722
+ reason: "provider-ineligible",
3723
+ detail: "Codex credential is missing or empty",
3724
+ };
3725
+ }
3726
+ if ((account.providerCooldowns?.[providerId] ?? 0) > now) {
3727
+ return {
3728
+ reason: "cooldown",
3729
+ detail: "provider cooldown active",
3730
+ };
3731
+ }
3732
+ return null;
3606
3733
  }
3607
3734
 
3608
3735
  /** Public pool-key resolution for quota routing display/logging. */
@@ -3667,10 +3794,10 @@ export class AccountRotator {
3667
3794
  private resolvePoolKey(account: AccountRuntime, key: string): string {
3668
3795
  if (
3669
3796
  hasCredential(account.config, "ollama") &&
3670
- key !== "session" &&
3797
+ !isOllamaQuotaPoolKey(key) &&
3671
3798
  this.ollamaModels.has(key)
3672
3799
  ) {
3673
- return "session";
3800
+ return "monthly";
3674
3801
  }
3675
3802
  return key;
3676
3803
  }
@@ -4425,8 +4552,8 @@ export class AccountRotator {
4425
4552
  }
4426
4553
 
4427
4554
  /**
4428
- * Send a minimal single-token request to the upstream Antigravity endpoint for a specific
4429
- * quota pool key on a given account. Uses the cheapest model in that pool to minimise cost.
4555
+ * Send a provider-native minimal request for a specific quota pool key on a given account.
4556
+ * Uses the cheapest model in that pool to minimise cost.
4430
4557
  * Applies normal error handling (markExhausted, markFlagged, markError) so the account state
4431
4558
  * stays consistent with regular traffic.
4432
4559
  */
@@ -4471,7 +4598,8 @@ export class AccountRotator {
4471
4598
 
4472
4599
  const kickstartAdapter = target.adapter;
4473
4600
  const isOllamaAccount = kickstartAdapter.id === "ollama";
4474
- if (!account.accessToken && !isOllamaAccount) {
4601
+ const hasNativeKickstart = Boolean(kickstartAdapter.forwardKickstartRequest);
4602
+ if (!account.accessToken && !isOllamaAccount && !hasNativeKickstart) {
4475
4603
  return { ok: false, status: 401, upstreamModel: "", error: "no access token" };
4476
4604
  }
4477
4605
 
@@ -4495,7 +4623,22 @@ export class AccountRotator {
4495
4623
  const timeout = setTimeout(() => controller.abort(), 15_000);
4496
4624
 
4497
4625
  let response: Response;
4498
- if (isOllamaAccount) {
4626
+ if (kickstartAdapter.forwardKickstartRequest) {
4627
+ try {
4628
+ const forwarded = await kickstartAdapter.forwardKickstartRequest(
4629
+ account,
4630
+ upstreamModel,
4631
+ controller.signal,
4632
+ );
4633
+ response = forwarded.response;
4634
+ } catch (err) {
4635
+ clearTimeout(timeout);
4636
+ const msg = `kickstart network error: ${err instanceof Error ? err.message : String(err)}`;
4637
+ this.markError(account, msg);
4638
+ return { ok: false, status: 0, upstreamModel, error: msg };
4639
+ }
4640
+ clearTimeout(timeout);
4641
+ } else if (isOllamaAccount) {
4499
4642
  const ollamaBody: RequestBody = {
4500
4643
  project: "",
4501
4644
  model: upstreamModel,
@@ -4574,7 +4717,7 @@ export class AccountRotator {
4574
4717
  const providerResourceExhausted =
4575
4718
  classifyRateLimitReason(errorText, response.status) === "quota-exhausted";
4576
4719
  const cooldownMs = providerResourceExhausted
4577
- ? target.providerId === DEFAULT_PROVIDER
4720
+ ? target.providerId === DEFAULT_PROVIDER || target.providerId === "openai-codex"
4578
4721
  ? parseRetryAfterMs(
4579
4722
  errorText,
4580
4723
  response.headers,
@@ -4605,11 +4748,12 @@ export class AccountRotator {
4605
4748
  }
4606
4749
 
4607
4750
  if (response.status === 401 || response.status === 403) {
4608
- this.markFlagged(
4609
- account,
4610
- `kickstart ${response.status} on ${upstreamModel}`,
4611
- { triggerProtectivePause: false },
4612
- );
4751
+ const reason = `kickstart ${response.status} on ${upstreamModel}`;
4752
+ if (target.providerId === "openai-codex") {
4753
+ this.markProviderInvalid(account, target.providerId, reason);
4754
+ } else {
4755
+ this.markFlagged(account, reason, { triggerProtectivePause: false });
4756
+ }
4613
4757
  return { ok: false, status: response.status, upstreamModel };
4614
4758
  }
4615
4759
 
@@ -4620,6 +4764,7 @@ export class AccountRotator {
4620
4764
 
4621
4765
  if (response.ok) {
4622
4766
  this.recordRequest(account, poolKey);
4767
+ target.adapter.clearQuotaCache?.(account);
4623
4768
  this.log(
4624
4769
  `${label} [${poolKey}]: kickstart sent via ${upstreamModel} — ${refreshQuota ? "refreshing quota" : "bulk quota refresh pending"}`,
4625
4770
  );
@@ -416,6 +416,7 @@
416
416
  .timer-fresh { background: rgba(52, 211, 153, 0.1); color: var(--green); }
417
417
  .timer-7d { background: rgba(96, 165, 250, 0.1); color: var(--blue); }
418
418
  .timer-5h { background: rgba(251, 191, 36, 0.1); color: var(--yellow); }
419
+ .timer-monthly { background: rgba(96, 165, 250, 0.1); color: var(--blue); }
419
420
 
420
421
  .quota-bar-bg {
421
422
  flex: 1;