tuxevil-rotator 3.6.0 → 3.6.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/CHANGELOG.md CHANGED
@@ -2,6 +2,17 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [3.6.1] - 2026-09-05
6
+
7
+ ### Added
8
+
9
+ - **Effort-based model routing**: Optional aliases can dispatch requests to concrete model variants based on `reasoning_effort`, while preserving the alias in client-facing responses and tracking quotas against the concrete target ([#32](https://github.com/tuxevil/tuxevil-rotator/pull/32) by [@CyR1en](https://github.com/CyR1en)).
10
+
11
+ ### Fixed
12
+
13
+ - **Partial Google quota snapshots**: Reset-only quota entries are now treated as exhausted instead of being discarded, while omitted pools remain available from the last known-good snapshot.
14
+ - **Model-scoped cooldown reconciliation**: Shared Claude and Gemini pools now reconcile cooldowns independently, preventing one exhausted pool from blocking its sibling and honoring fresh provider reset deadlines.
15
+
5
16
  ## [3.6.0] - 2026-09-04
6
17
 
7
18
  ### Added
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tuxevil-rotator",
3
- "version": "3.6.0",
3
+ "version": "3.6.1",
4
4
  "description": "Multi-provider, multi-account AI proxy rotator with per-model routing, real-time quota tracking, and infringement detection (Google Antigravity, Ollama Cloud)",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/compat.ts CHANGED
@@ -23,6 +23,7 @@ import {
23
23
  type RotationAttemptContext,
24
24
  type RotationOutcome,
25
25
  } from "./proxy.js";
26
+ import { getEffortRouting } from "./types.js";
26
27
  import {
27
28
  isRecord,
28
29
  sanitizeGeminiSchema,
@@ -516,7 +517,7 @@ function recordCompatOutcome(
516
517
  },
517
518
  ): void {
518
519
  const ttfbMs = completion?.firstByteMs ?? totalMs;
519
- rotator.recordLatency(body.displayModel || body.model, ttfbMs, totalMs);
520
+ rotator.recordLatency(context.displayModelKey, ttfbMs, totalMs);
520
521
  rotator.recordRequestLog({
521
522
  model: context.displayModelKey,
522
523
  account: context.label,
@@ -1802,7 +1803,7 @@ async function completeResponsesViaRotator(
1802
1803
  );
1803
1804
  if (completion.inputTokens > 0 || completion.outputTokens > 0) {
1804
1805
  rotator.recordTokenUsage(
1805
- body.displayModel || body.model,
1806
+ context.displayModelKey,
1806
1807
  completion.inputTokens,
1807
1808
  completion.outputTokens,
1808
1809
  );
@@ -1898,7 +1899,7 @@ async function completeViaRotator(
1898
1899
  : parseAntigravitySse(raw);
1899
1900
  if (completion.inputTokens > 0 || completion.outputTokens > 0) {
1900
1901
  rotator.recordTokenUsage(
1901
- body.displayModel || body.model,
1902
+ context.displayModelKey,
1902
1903
  completion.inputTokens,
1903
1904
  completion.outputTokens,
1904
1905
  );
@@ -1931,7 +1932,7 @@ async function completeViaRotator(
1931
1932
  );
1932
1933
  if (completion.inputTokens > 0 || completion.outputTokens > 0) {
1933
1934
  rotator.recordTokenUsage(
1934
- body.displayModel || body.model,
1935
+ context.displayModelKey,
1935
1936
  completion.inputTokens,
1936
1937
  completion.outputTokens,
1937
1938
  );
@@ -2181,9 +2182,69 @@ export function getEffectiveAntigravityModels(): CompatModelEntry[] {
2181
2182
  isThinking: spec.isThinking,
2182
2183
  });
2183
2184
  }
2185
+
2184
2186
  return result;
2185
2187
  }
2186
2188
 
2189
+ function getOpenAIAntigravityModels(): CompatModelEntry[] {
2190
+ const result = getEffectiveAntigravityModels();
2191
+ const rules = getEffortRouting();
2192
+ if (!rules || Object.keys(rules).length === 0) {
2193
+ return result;
2194
+ }
2195
+
2196
+ const successfulAliases: Array<{
2197
+ alias: string;
2198
+ representative: CompatModelEntry;
2199
+ }> = [];
2200
+ const hiddenTargetIds = new Set<string>();
2201
+ const successfulAliasNames = new Set<string>();
2202
+
2203
+ for (const [alias, rule] of Object.entries(rules)) {
2204
+ const defaultEffortKey = rule.defaultEffort;
2205
+ const defaultTargetId = rule.targets[defaultEffortKey];
2206
+ if (!defaultTargetId) {
2207
+ compatLogger.warn(
2208
+ `Effort routing alias "${alias}" default effort "${defaultEffortKey}" target not found; skipping catalog swap`,
2209
+ );
2210
+ continue;
2211
+ }
2212
+ const representative = result.find(
2213
+ (m) => m.id.toLowerCase() === defaultTargetId.toLowerCase(),
2214
+ );
2215
+ if (!representative) {
2216
+ compatLogger.warn(
2217
+ `Effort routing alias "${alias}" default target "${defaultTargetId}" absent from catalog; skipping catalog swap`,
2218
+ );
2219
+ continue;
2220
+ }
2221
+ successfulAliases.push({ alias, representative });
2222
+ successfulAliasNames.add(alias.toLowerCase());
2223
+ for (const targetId of Object.values(rule.targets)) {
2224
+ hiddenTargetIds.add(targetId.toLowerCase());
2225
+ }
2226
+ }
2227
+
2228
+ if (successfulAliases.length === 0) {
2229
+ return result;
2230
+ }
2231
+
2232
+ const filtered = result.filter(
2233
+ (m) =>
2234
+ !hiddenTargetIds.has(m.id.toLowerCase()) &&
2235
+ !successfulAliasNames.has(m.id.toLowerCase()),
2236
+ );
2237
+
2238
+ for (const { alias, representative } of successfulAliases) {
2239
+ filtered.push({
2240
+ ...representative,
2241
+ id: alias,
2242
+ });
2243
+ }
2244
+
2245
+ return filtered;
2246
+ }
2247
+
2187
2248
  /**
2188
2249
  * Build the OpenAI-compatible `/v1/models` catalog for the proxy.
2189
2250
  *
@@ -2193,7 +2254,7 @@ export function getEffectiveAntigravityModels(): CompatModelEntry[] {
2193
2254
  export function buildOpenAIModelCatalog(
2194
2255
  rotator?: AccountRotator,
2195
2256
  ): OpenAIModelCatalogEntry[] {
2196
- const catalog: OpenAIModelCatalogEntry[] = getEffectiveAntigravityModels().map(
2257
+ const catalog: OpenAIModelCatalogEntry[] = getOpenAIAntigravityModels().map(
2197
2258
  ({
2198
2259
  id,
2199
2260
  ctx,
@@ -56,6 +56,8 @@ export function applyConfigDefaults(config: Config): Config {
56
56
  streamRecoveryMaxRetries: safeStreamRecoveryMaxRetries(config.streamRecoveryMaxRetries),
57
57
  compressionMode: config.compressionMode ?? "off",
58
58
  modelSpecs: config.modelSpecs,
59
+ modelAliases: config.modelAliases,
60
+ effortRouting: config.effortRouting,
59
61
  accounts: config.accounts ? config.accounts.map((account) => ({
60
62
  ...normalizeAccountConfig(account),
61
63
  tier: account.tier || "unknown",
package/src/index.ts CHANGED
@@ -19,7 +19,7 @@ import {
19
19
  loadResponsesStore,
20
20
  flushResponsesStore,
21
21
  } from "./compat.js";
22
- import { setModelAliasesOverride } from "./types.js";
22
+ import { setModelAliasesOverride, setEffortRoutingOverride } from "./types.js";
23
23
  import { readTextFile, writeTextFileAtomic } from "./storage.js";
24
24
  import { initDb, isDbConfigured } from "./db-store.js";
25
25
  import { runKeyMigrations } from "./key-migrations.js";
@@ -211,6 +211,7 @@ export async function main(): Promise<void> {
211
211
  warnIfInsecureTelemetryEndpoint();
212
212
  setModelSpecsOverride(config.modelSpecs ?? null);
213
213
  setModelAliasesOverride(config.modelAliases ?? null);
214
+ setEffortRoutingOverride(config.effortRouting ?? null);
214
215
  void loadResponsesStore();
215
216
 
216
217
  const rotator = new AccountRotator(config);
@@ -29,9 +29,7 @@ import {
29
29
 
30
30
  type GoogleModelInfo = GoogleQuotaResponse["models"][string];
31
31
  type GoogleModelInfoWithQuota = GoogleModelInfo & {
32
- quotaInfo: NonNullable<GoogleModelInfo["quotaInfo"]> & {
33
- remainingFraction: number;
34
- };
32
+ quotaInfo: NonNullable<GoogleModelInfo["quotaInfo"]>;
35
33
  };
36
34
 
37
35
  function hasUsableQuotaInfo(
@@ -39,10 +37,58 @@ function hasUsableQuotaInfo(
39
37
  ): info is GoogleModelInfoWithQuota {
40
38
  if (!info?.quotaInfo) return false;
41
39
  const remaining = info.quotaInfo.remainingFraction;
42
- return typeof remaining === "number" &&
43
- Number.isFinite(remaining) &&
44
- remaining >= 0 &&
45
- remaining <= 1;
40
+ if (remaining === undefined) {
41
+ // Google omits remainingFraction for active quota windows. A resetTime
42
+ // without a fraction is the partial shape used by the legacy parser.
43
+ return typeof info.quotaInfo.resetTime === "string" &&
44
+ info.quotaInfo.resetTime.trim().length > 0;
45
+ }
46
+ return typeof remaining === "number" && Number.isFinite(remaining) &&
47
+ remaining >= 0 && remaining <= 1;
48
+ }
49
+
50
+ function getRemainingFraction(info: GoogleModelInfoWithQuota): number {
51
+ const remaining = info.quotaInfo.remainingFraction;
52
+ return typeof remaining === "number" && Number.isFinite(remaining) &&
53
+ remaining >= 0 && remaining <= 1
54
+ ? remaining
55
+ : 0;
56
+ }
57
+
58
+ function applyActiveCooldown(
59
+ quota: ModelQuota,
60
+ cooldownUntil: number | undefined,
61
+ now: number,
62
+ ): void {
63
+ if (!cooldownUntil || !Number.isFinite(cooldownUntil) || cooldownUntil <= now) {
64
+ return;
65
+ }
66
+ const advertisedReset = quota.resetTime
67
+ ? new Date(quota.resetTime).getTime()
68
+ : 0;
69
+ const resetAt = Math.max(
70
+ cooldownUntil,
71
+ Number.isFinite(advertisedReset) && advertisedReset > now ? advertisedReset : 0,
72
+ );
73
+ quota.percentRemaining = 0;
74
+ quota.resetTime = new Date(resetAt).toISOString();
75
+ quota.timerType = resetAt - now < 6 * 60 * 60 * 1000 ? "5h" : "7d";
76
+ }
77
+
78
+ function getActiveCooldownForPool(
79
+ account: AccountRuntime,
80
+ poolKey: string,
81
+ ): number | undefined {
82
+ let cooldownUntil = account.cooldownsByModel[poolKey] ?? 0;
83
+ for (const [modelKey, deadline] of Object.entries(account.cooldownsByModel)) {
84
+ if (
85
+ modelKey !== poolKey &&
86
+ dynamicCatalog.resolveQuotaPool(modelKey) === poolKey
87
+ ) {
88
+ cooldownUntil = Math.max(cooldownUntil, deadline);
89
+ }
90
+ }
91
+ return cooldownUntil || undefined;
46
92
  }
47
93
 
48
94
  /**
@@ -57,29 +103,33 @@ export function extractQuotas(
57
103
  const now = Date.now();
58
104
 
59
105
  for (const [, config] of Object.entries(QUOTA_MODEL_KEYS)) {
60
- let modelInfo: GoogleModelInfoWithQuota | undefined;
106
+ const candidates: GoogleModelInfoWithQuota[] = [];
61
107
  for (const candidate of [config.key, ...config.altKeys]) {
62
108
  const info = data.models[candidate];
63
109
  if (hasUsableQuotaInfo(info)) {
64
- modelInfo = info;
65
- break;
110
+ candidates.push(info);
66
111
  }
67
112
  }
68
113
 
69
- if (!modelInfo) {
70
- for (const [modelKey, info] of Object.entries(data.models)) {
71
- if (
72
- DynamicModelRegistry.inferFamilyAndPool(modelKey).quotaPool === config.key &&
73
- hasUsableQuotaInfo(info)
74
- ) {
75
- modelInfo = info;
76
- break;
77
- }
114
+ for (const [modelKey, info] of Object.entries(data.models)) {
115
+ if (
116
+ ![config.key, ...config.altKeys].includes(modelKey) &&
117
+ DynamicModelRegistry.inferFamilyAndPool(modelKey).quotaPool === config.key &&
118
+ hasUsableQuotaInfo(info)
119
+ ) {
120
+ candidates.push(info);
78
121
  }
79
122
  }
80
123
 
124
+ // A shared pool is usable only as far as its most exhausted model. Google
125
+ // may report one sibling at 100% while the model we route to is exhausted.
126
+ const modelInfo = candidates.sort(
127
+ (a, b) => getRemainingFraction(a) - getRemainingFraction(b) ||
128
+ Number(Boolean(b.quotaInfo.resetTime)) -
129
+ Number(Boolean(a.quotaInfo.resetTime)),
130
+ )[0];
81
131
  if (modelInfo?.quotaInfo) {
82
- const remainingFraction = modelInfo.quotaInfo.remainingFraction;
132
+ const remainingFraction = getRemainingFraction(modelInfo);
83
133
  // Google can publish a nominal reset for an untouched pool; no usage means
84
134
  // there is no active quota window yet.
85
135
  const resetTime =
@@ -207,7 +257,32 @@ export async function fetchProviderQuota(
207
257
  fresh.forEach(
208
258
  (q) => ((q as { providerId?: string }).providerId = "google-antigravity"),
209
259
  );
210
- account.quota = sortQuotaPools([...otherProviders, ...fresh]);
260
+ const freshKeys = new Set(fresh.map((quota) => quota.modelKey));
261
+ const previousGooglePools = oldQuota.filter(
262
+ (q) => (q as { providerId?: string }).providerId === DEFAULT_PROVIDER &&
263
+ !freshKeys.has(q.modelKey),
264
+ );
265
+ for (const quota of [...previousGooglePools, ...fresh]) {
266
+ if (
267
+ freshKeys.has(quota.modelKey) &&
268
+ quota.percentRemaining === 0 &&
269
+ quota.resetTime
270
+ ) {
271
+ // A newly reported exhausted window is authoritative; the poll
272
+ // reconciler will persist its reset time instead of stale local state.
273
+ continue;
274
+ }
275
+ applyActiveCooldown(
276
+ quota,
277
+ getActiveCooldownForPool(account, quota.modelKey),
278
+ Date.now(),
279
+ );
280
+ }
281
+ account.quota = sortQuotaPools([
282
+ ...otherProviders,
283
+ ...previousGooglePools,
284
+ ...fresh,
285
+ ]);
211
286
  account.lastQuotaPoll = Date.now();
212
287
 
213
288
  // Stash the provider-local poll log for the rotator to emit as a
@@ -1,5 +1,5 @@
1
1
  import { logger, redactSensitive } from "../../logger.js";
2
- import { applyModelAlias } from "../../types.js";
2
+ import { applyModelAlias, getEffortRoutingRule } from "../../types.js";
3
3
  import type { RequestBody } from "../../proxy.js";
4
4
  import {
5
5
  isRecord,
@@ -136,7 +136,7 @@ export interface OpenAIChatCompletionRequest {
136
136
  tools?: OpenAITool[];
137
137
  tool_choice?: unknown;
138
138
  /** OpenAI-style reasoning effort. Mapped to Gemini thinkingLevel. */
139
- reasoning_effort?: string;
139
+ reasoning_effort?: unknown;
140
140
  [key: string]: unknown;
141
141
  }
142
142
 
@@ -893,7 +893,7 @@ export function isTieredEffortModel(modelId: string): boolean {
893
893
  * semantics and never emits an invalid upstream enum.
894
894
  */
895
895
  export function mapTieredReasoningEffortToThinkingLevel(
896
- effort: string | undefined,
896
+ effort: unknown,
897
897
  modelId: string,
898
898
  ): "LOW" | "MEDIUM" | "HIGH" | undefined {
899
899
  if (!isTieredEffortModel(modelId)) return undefined;
@@ -910,9 +910,35 @@ export function mapTieredReasoningEffortToThinkingLevel(
910
910
  }
911
911
  }
912
912
 
913
+ export function resolveEffortAliasModel(
914
+ requestedModel: string,
915
+ effort: unknown,
916
+ ): string | null {
917
+ const rule = getEffortRoutingRule(requestedModel);
918
+ if (!rule) return null;
919
+ const key = typeof effort === "string" ? effort.trim().toLowerCase() : "";
920
+ if (key && Object.hasOwn(rule.targets, key)) return rule.targets[key];
921
+ if (effort !== undefined) {
922
+ const supplied = typeof effort === "string"
923
+ ? JSON.stringify(effort.length > 40 ? `${effort.slice(0, 40)}…` : effort)
924
+ : `<${effort === null ? "null" : typeof effort}>`;
925
+ compatLogger.debug(
926
+ `Unrecognized effort ${supplied} for alias "${requestedModel.trim().toLowerCase()}", falling back to default`,
927
+ );
928
+ }
929
+ return Object.hasOwn(rule.targets, rule.defaultEffort)
930
+ ? rule.targets[rule.defaultEffort]
931
+ : null;
932
+ }
933
+
913
934
  export function openAIToAntigravityBody(
914
935
  input: OpenAIChatCompletionRequest,
915
936
  ): RequestBody {
937
+ const requestedModel = input.model;
938
+ const effortTarget =
939
+ resolveEffortAliasModel(requestedModel, input.reasoning_effort) ??
940
+ requestedModel;
941
+
916
942
  const systemParts: string[] = [];
917
943
  const conversationMessages = input.messages.filter((msg) => {
918
944
  if (msg.role === "system" || msg.role === "developer") {
@@ -926,8 +952,8 @@ export function openAIToAntigravityBody(
926
952
  return true;
927
953
  });
928
954
 
929
- const isClaude = /^claude-/i.test(input.model);
930
- const isThinking = isThinkingModel(input.model);
955
+ const isClaude = /^claude-/i.test(effortTarget);
956
+ const isThinking = isThinkingModel(effortTarget);
931
957
  const isGeminiThinking = !isClaude && isThinking;
932
958
 
933
959
  const contents: GeminiContent[] = [];
@@ -1206,13 +1232,13 @@ export function openAIToAntigravityBody(
1206
1232
  ? convertToolChoiceToGemini(input.tool_choice)
1207
1233
  : undefined;
1208
1234
 
1209
- const modelSpec = getModelSpec(input.model);
1210
- const modelFamily = getModelFamily(input.model);
1235
+ const modelSpec = getModelSpec(effortTarget);
1236
+ const modelFamily = getModelFamily(effortTarget);
1211
1237
  let maxOutputTokens =
1212
1238
  typeof input.max_tokens === "number" ? input.max_tokens : undefined;
1213
1239
  if (maxOutputTokens && maxOutputTokens > modelSpec.maxOutputTokens) {
1214
1240
  compatLogger.debug(
1215
- `Capping ${input.model} maxOutputTokens ${maxOutputTokens} → ${modelSpec.maxOutputTokens}`,
1241
+ `Capping ${effortTarget} maxOutputTokens ${maxOutputTokens} → ${modelSpec.maxOutputTokens}`,
1216
1242
  );
1217
1243
  maxOutputTokens = modelSpec.maxOutputTokens;
1218
1244
  }
@@ -1247,7 +1273,7 @@ export function openAIToAntigravityBody(
1247
1273
  tb === -1
1248
1274
  ? mapTieredReasoningEffortToThinkingLevel(
1249
1275
  input.reasoning_effort,
1250
- input.model,
1276
+ effortTarget,
1251
1277
  )
1252
1278
  : undefined;
1253
1279
  if (tieredThinkingLevel) {
@@ -1324,12 +1350,12 @@ export function openAIToAntigravityBody(
1324
1350
  if (geminiTools.length > 0) request.tools = geminiTools;
1325
1351
  if (geminiToolConfig) request.toolConfig = geminiToolConfig;
1326
1352
 
1327
- const mappedModel = applyModelAlias(input.model);
1353
+ const mappedModel = applyModelAlias(effortTarget);
1328
1354
 
1329
1355
  return {
1330
1356
  project: "compat-placeholder",
1331
1357
  model: mappedModel,
1332
- displayModel: input.model,
1358
+ displayModel: requestedModel,
1333
1359
  userAgent: "antigravity",
1334
1360
  requestType: "agent",
1335
1361
  request,
package/src/proxy.ts CHANGED
@@ -12,6 +12,8 @@ import {
12
12
  } from "node:http";
13
13
  import { Readable } from "node:stream";
14
14
  import {
15
+ classifyEffortRoutingModel,
16
+ getEffortRoutingRule,
15
17
  resolveQuotaModelKey,
16
18
  resolveDisplayModelKey,
17
19
  } from "./types.js";
@@ -108,6 +110,12 @@ export function providerAdapterForModel(
108
110
  ollamaModels: new Set(rotator?.getOllamaModels?.() ?? []),
109
111
  codexModels: new Set(rotator?.getCodexModels?.() ?? []),
110
112
  };
113
+ const effortRoutingKind = classifyEffortRoutingModel(model);
114
+ if (effortRoutingKind && context.ollamaModels.has(model)) {
115
+ proxyLogger.warn(
116
+ `Effort routing ${effortRoutingKind} "${model}" matches a live Ollama model; live provider dispatch wins`,
117
+ );
118
+ }
111
119
  const matched = findProviderForModel(model, context);
112
120
  if (matched) return matched;
113
121
  }
@@ -133,11 +141,20 @@ function routingModelKey(rotator: AccountRotator, model: string): string {
133
141
  return resolver?.call(rotator, model) ?? resolveQuotaModelKey(model) ?? model;
134
142
  }
135
143
 
136
- function observedModelKey(rotator: AccountRotator, model: string): string {
144
+ function observedModelKey(
145
+ rotator: AccountRotator,
146
+ displayModel: string,
147
+ effectiveModel?: string,
148
+ ): string {
149
+ const rule = getEffortRoutingRule(displayModel);
150
+ const observedModel = effectiveModel && rule ? effectiveModel : displayModel;
137
151
  const resolver = (rotator as unknown as {
138
152
  resolveObservedModelKey?: (value: string) => string;
139
153
  }).resolveObservedModelKey;
140
- return resolver?.call(rotator, model) ?? resolveDisplayModelKey(model);
154
+ return (
155
+ resolver?.call(rotator, observedModel) ??
156
+ resolveDisplayModelKey(displayModel, effectiveModel)
157
+ );
141
158
  }
142
159
  import { startVersionChecker, performSelfUpdate } from "./version-check.js";
143
160
  import { startNotificationPoller } from "./notification-poller.js";
@@ -1180,7 +1197,11 @@ export async function withRotation<T>(
1180
1197
 
1181
1198
  const label = account.config.label || account.config.email;
1182
1199
  const modelKey = routingModelKey(rotator, model);
1183
- const displayModelKey = observedModelKey(rotator, body.displayModel || model);
1200
+ const displayModelKey = observedModelKey(
1201
+ rotator,
1202
+ body.displayModel || model,
1203
+ body.model,
1204
+ );
1184
1205
  const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
1185
1206
  const requestStartMs = Date.now();
1186
1207
  let accountReleased = false;
package/src/rotator.ts CHANGED
@@ -1443,23 +1443,12 @@ export class AccountRotator {
1443
1443
  ): AccountStatus["status"] {
1444
1444
  const defaultCooldownActive =
1445
1445
  (account.cooldownsByModel.__default__ ?? 0) > now;
1446
- const knownPools = new Set(account.quota.map((quota) => quota.modelKey));
1447
- for (const [modelKey, cooldownUntil] of Object.entries(
1448
- account.cooldownsByModel,
1449
- )) {
1450
- if (modelKey !== "__default__" && cooldownUntil > now) {
1451
- knownPools.add(modelKey);
1452
- }
1453
- }
1454
- const allKnownPoolsCooling =
1455
- knownPools.size > 0 &&
1456
- [...knownPools].every(
1457
- (modelKey) => (account.cooldownsByModel[modelKey] ?? 0) > now,
1458
- );
1459
1446
  if (account.flagged) return "flagged";
1460
1447
  if (account.disabled) return "disabled";
1461
1448
  if (account.consecutiveErrors > 0 && !account.disabled) return "error";
1462
- if (defaultCooldownActive || allKnownPoolsCooling) return "cooldown";
1449
+ // Pool cooldowns stay visible in cooldownsByModel but must not make the
1450
+ // whole account unavailable for unrelated quota pools.
1451
+ if (defaultCooldownActive) return "cooldown";
1463
1452
  if (this.isDailySafetyStopped(account, now)) return "exhausted";
1464
1453
  if (activeForModels.length > 0) return "active";
1465
1454
  return "ready";
@@ -2991,6 +2980,21 @@ export class AccountRotator {
2991
2980
  account.cooldownsByModel[modelKey] = now + cooldownMs;
2992
2981
  account.quotaExhaustedAt = now;
2993
2982
 
2983
+ // Keep the dashboard aligned with provider truth. The quota endpoint can
2984
+ // report an untouched 100% pool while generation has already exhausted it.
2985
+ if (modelKey !== "__default__" && cooldownMs > 0) {
2986
+ const quota = account.quota.find(
2987
+ (candidate) =>
2988
+ candidate.modelKey === modelKey &&
2989
+ candidate.providerId === DEFAULT_PROVIDER,
2990
+ );
2991
+ if (quota) {
2992
+ quota.percentRemaining = 0;
2993
+ quota.resetTime = new Date(now + cooldownMs).toISOString();
2994
+ quota.timerType = cooldownMs < 6 * 60 * 60 * 1000 ? "5h" : "7d";
2995
+ }
2996
+ }
2997
+
2994
2998
  const errorDetail = errorText ? ` | ${errorText}` : "";
2995
2999
  this.log(
2996
3000
  `${account.config.label || account.config.email} [${modelKey}]: EXHAUSTED, cooldown ${Math.ceil(cooldownMs / 1000)}s${errorDetail}`,
@@ -4466,6 +4470,19 @@ export class AccountRotator {
4466
4470
  const upstreamModel = target.upstreamModel;
4467
4471
  const poolKey = target.poolKey;
4468
4472
 
4473
+ const activeCooldown = Math.max(
4474
+ account.cooldownsByModel[poolKey] ?? 0,
4475
+ account.cooldownsByModel.__default__ ?? 0,
4476
+ );
4477
+ if (activeCooldown > Date.now()) {
4478
+ return {
4479
+ ok: false,
4480
+ status: 429,
4481
+ upstreamModel,
4482
+ error: `quota cooldown active for ${Math.ceil((activeCooldown - Date.now()) / 1000)}s`,
4483
+ };
4484
+ }
4485
+
4469
4486
  const controller = new AbortController();
4470
4487
  const timeout = setTimeout(() => controller.abort(), 15_000);
4471
4488
 
package/src/types.ts CHANGED
@@ -149,6 +149,15 @@ export interface Config {
149
149
  // (e.g. "gemini-3.1-pro-high") to the upstream Antigravity name
150
150
  // (e.g. "gemini-pro-agent"). When set, replaces the bundled defaults.
151
151
  modelAliases?: Record<string, string>;
152
+ // Config-driven alias routing based on reasoning_effort.
153
+ // Absent, null, or empty object = disabled.
154
+ effortRouting?: Record<string, EffortRoutingRule> | null;
155
+ }
156
+
157
+ export interface EffortRoutingRule {
158
+ /** Effort key used when the request carries no recognizable effort. Defaults to "medium". */
159
+ defaultEffort?: string;
160
+ targets: Record<string, string>;
152
161
  }
153
162
 
154
163
  export const DEFAULT_QUOTA_POLL_INTERVAL_MS = 300_000;
@@ -164,6 +173,13 @@ const DEFAULT_MODEL_ALIASES: Record<string, string> = {
164
173
  "gpt-oss-120b": "gpt-oss-120b-medium",
165
174
  };
166
175
  let modelAliasesOverride: Record<string, string> | null = null;
176
+ type StoredEffortRoutingRule = {
177
+ defaultEffort: string;
178
+ targets: Record<string, string>;
179
+ };
180
+ type EffortRoutingModelKind = "alias" | "target";
181
+
182
+ let effortRoutingOverride: Record<string, StoredEffortRoutingRule> | null = null;
167
183
 
168
184
  /**
169
185
  * Replace the bundled model-alias table with operator-provided overrides.
@@ -180,6 +196,65 @@ export function setModelAliasesOverride(
180
196
  aliases && Object.keys(aliases).length > 0 ? aliases : null;
181
197
  }
182
198
 
199
+ export function setEffortRoutingOverride(
200
+ rules: Record<string, EffortRoutingRule> | null | undefined,
201
+ ): void {
202
+ if (!rules || Object.keys(rules).length === 0) {
203
+ effortRoutingOverride = null;
204
+ return;
205
+ }
206
+ const normalized = Object.create(null) as Record<
207
+ string,
208
+ StoredEffortRoutingRule
209
+ >;
210
+ for (const [rawAlias, rule] of Object.entries(rules)) {
211
+ const alias = rawAlias.trim().toLowerCase();
212
+ const defaultEffort = rule.defaultEffort?.trim().toLowerCase() || "medium";
213
+ const targets = Object.create(null) as Record<string, string>;
214
+ for (const [effortKey, targetValue] of Object.entries(rule.targets ?? {})) {
215
+ targets[effortKey.trim().toLowerCase()] =
216
+ typeof targetValue === "string" ? targetValue.trim() : targetValue;
217
+ }
218
+ normalized[alias] = {
219
+ defaultEffort,
220
+ targets,
221
+ };
222
+ }
223
+ effortRoutingOverride = normalized;
224
+ }
225
+
226
+ export function getEffortRouting(): Record<string, StoredEffortRoutingRule> | null {
227
+ return effortRoutingOverride;
228
+ }
229
+
230
+ export function getEffortRoutingRule(
231
+ requestedModel: string,
232
+ ): StoredEffortRoutingRule | undefined {
233
+ const rules = effortRoutingOverride;
234
+ if (!rules) return undefined;
235
+ const alias = requestedModel.trim().toLowerCase();
236
+ return Object.hasOwn(rules, alias) ? rules[alias] : undefined;
237
+ }
238
+
239
+ export function classifyEffortRoutingModel(
240
+ model: string,
241
+ ): EffortRoutingModelKind | null {
242
+ const rules = effortRoutingOverride;
243
+ if (!rules) return null;
244
+ const normalizedModel = model.trim().toLowerCase();
245
+ if (Object.hasOwn(rules, normalizedModel)) return "alias";
246
+ for (const rule of Object.values(rules)) {
247
+ if (
248
+ Object.values(rule.targets).some(
249
+ (target) => target.toLowerCase() === normalizedModel,
250
+ )
251
+ ) {
252
+ return "target";
253
+ }
254
+ }
255
+ return null;
256
+ }
257
+
183
258
  function getActiveModelAliases(): Record<string, string> {
184
259
  return modelAliasesOverride ?? DEFAULT_MODEL_ALIASES;
185
260
  }
@@ -190,7 +265,7 @@ function getActiveModelAliases(): Record<string, string> {
190
265
  */
191
266
  export function applyModelAlias(model: string): string {
192
267
  const aliases = getActiveModelAliases();
193
- if (model in aliases) return aliases[model];
268
+ if (Object.hasOwn(aliases, model)) return aliases[model];
194
269
  const lower = model.toLowerCase();
195
270
  for (const [from, to] of Object.entries(aliases)) {
196
271
  if (from.toLowerCase() === lower) return to;
@@ -332,7 +407,17 @@ export function resolveQuotaModelKey(requestModel: string): string | null {
332
407
  * - gemini-3.1-pro-low vs gemini-3.1-pro-high (same quota pool, different display)
333
408
  * - claude-sonnet-4-6 vs claude-opus-4-6-thinking (different pricing)
334
409
  */
335
- export function resolveDisplayModelKey(requestModel: string): string {
410
+ export function resolveDisplayModelKey(
411
+ requestModel: string,
412
+ effectiveModel?: string,
413
+ ): string {
414
+ if (
415
+ effectiveModel &&
416
+ effectiveModel !== requestModel &&
417
+ getEffortRoutingRule(requestModel)
418
+ ) {
419
+ return resolveDisplayModelKey(effectiveModel);
420
+ }
336
421
  const lower = requestModel.toLowerCase();
337
422
  // Explicit agent and gpt-oss overrides
338
423
  if (lower.includes("gemini-3-flash-agent")) return "gemini-3-flash";
package/src/validators.ts CHANGED
@@ -1,10 +1,13 @@
1
1
  import {
2
2
  MAX_QUOTA_POLL_INTERVAL_MS,
3
3
  MIN_QUOTA_POLL_INTERVAL_MS,
4
+ MODEL_TIER_ACCESS,
4
5
  type AccountConfig,
5
6
  type Config,
6
7
  } from "./types.js";
7
8
  import { getProxyConfigurationError } from "./providers/proxy-dispatcher.js";
9
+ import { isCodexRequestModel } from "./providers/openai-codex/catalog.js";
10
+ import { isOpenCodeZenModel } from "./providers/opencode-zen/catalog.js";
8
11
 
9
12
  export interface ValidationResult<T> {
10
13
  ok: boolean;
@@ -40,6 +43,15 @@ function isNonNegativeInteger(value: unknown): value is number {
40
43
  return isNonNegativeNumber(value) && Number.isInteger(value);
41
44
  }
42
45
 
46
+ function isKnownNonGoogleModel(model: string): boolean {
47
+ const trimmed = model.trim();
48
+ if (!trimmed) return false;
49
+ const lower = trimmed.toLowerCase();
50
+ if (isCodexRequestModel(trimmed)) return true;
51
+ if (isOpenCodeZenModel(trimmed) || isOpenCodeZenModel(lower)) return true;
52
+ return Object.keys(MODEL_TIER_ACCESS).some((k) => k.toLowerCase() === lower);
53
+ }
54
+
43
55
  export function validateAccountConfig(value: unknown, path = "account"): ValidationResult<AccountConfig> {
44
56
  if (!isRecord(value)) return fail([`${path} must be an object`]);
45
57
  const errors: string[] = [];
@@ -200,6 +212,98 @@ export function validateConfig(value: unknown): ValidationResult<Config> {
200
212
  }
201
213
  }
202
214
  }
215
+ if (value.effortRouting !== undefined && value.effortRouting !== null) {
216
+ if (!isRecord(value.effortRouting)) {
217
+ errors.push("config.effortRouting must be an object or null when provided");
218
+ } else {
219
+ const seenAliasKeys = new Map<string, string>();
220
+ for (const rawAlias of Object.keys(value.effortRouting)) {
221
+ if (typeof rawAlias !== "string" || rawAlias.trim().length === 0) {
222
+ errors.push("config.effortRouting keys must be non-empty strings");
223
+ continue;
224
+ }
225
+ const lowerAlias = rawAlias.trim().toLowerCase();
226
+ const prev = seenAliasKeys.get(lowerAlias);
227
+ if (prev !== undefined) {
228
+ errors.push(`config.effortRouting keys collide case-insensitively: "${prev}" / "${rawAlias}"`);
229
+ } else {
230
+ seenAliasKeys.set(lowerAlias, rawAlias);
231
+ }
232
+ }
233
+
234
+ const modelAliasesRecord = isRecord(value.modelAliases) ? value.modelAliases : null;
235
+
236
+ for (const [rawAlias, rule] of Object.entries(value.effortRouting)) {
237
+ if (typeof rawAlias !== "string" || rawAlias.trim().length === 0) {
238
+ continue;
239
+ }
240
+ const lowerAlias = rawAlias.trim().toLowerCase();
241
+
242
+ if (isKnownNonGoogleModel(rawAlias)) {
243
+ errors.push(`config.effortRouting.${rawAlias} collides with non-Antigravity model "${rawAlias}"`);
244
+ }
245
+
246
+ if (modelAliasesRecord) {
247
+ for (const maKey of Object.keys(modelAliasesRecord)) {
248
+ if (maKey.trim().toLowerCase() === lowerAlias) {
249
+ errors.push(`config.effortRouting.${rawAlias} conflicts with config.modelAliases entry of the same name`);
250
+ break;
251
+ }
252
+ }
253
+ }
254
+
255
+ if (!isRecord(rule)) {
256
+ errors.push(`config.effortRouting.${rawAlias} must be an object`);
257
+ continue;
258
+ }
259
+
260
+ if (rule.defaultEffort !== undefined && typeof rule.defaultEffort !== "string") {
261
+ errors.push(`config.effortRouting.${rawAlias}.defaultEffort must be a string when provided`);
262
+ }
263
+
264
+ if (!("targets" in rule) || !isRecord(rule.targets)) {
265
+ errors.push(`config.effortRouting.${rawAlias}.targets must be an object`);
266
+ continue;
267
+ }
268
+
269
+ const seenEffortKeys = new Map<string, string>();
270
+ for (const [rawEffort, targetValue] of Object.entries(rule.targets)) {
271
+ if (typeof rawEffort !== "string" || rawEffort.trim().length === 0) {
272
+ errors.push(`config.effortRouting.${rawAlias}.targets keys must be non-empty strings`);
273
+ } else {
274
+ const lowerEffort = rawEffort.trim().toLowerCase();
275
+ const prevEffort = seenEffortKeys.get(lowerEffort);
276
+ if (prevEffort !== undefined) {
277
+ errors.push(`config.effortRouting.${rawAlias}.targets keys collide case-insensitively: "${prevEffort}" / "${rawEffort}"`);
278
+ } else {
279
+ seenEffortKeys.set(lowerEffort, rawEffort);
280
+ }
281
+ }
282
+
283
+ if (typeof targetValue !== "string" || targetValue.trim().length === 0) {
284
+ errors.push(`config.effortRouting.${rawAlias}.targets.${rawEffort} must be a non-empty string`);
285
+ } else {
286
+ if (seenAliasKeys.has(targetValue.trim().toLowerCase())) {
287
+ errors.push(`config.effortRouting.${rawAlias}.targets.${rawEffort} chains into effort-routing alias "${targetValue}" (not supported)`);
288
+ }
289
+ if (isKnownNonGoogleModel(targetValue)) {
290
+ errors.push(`config.effortRouting.${rawAlias} collides with non-Antigravity model "${targetValue}"`);
291
+ }
292
+ }
293
+ }
294
+
295
+ if (rule.defaultEffort === undefined || typeof rule.defaultEffort === "string") {
296
+ const effectiveDefault = rule.defaultEffort !== undefined ? rule.defaultEffort : "medium";
297
+ const hasEffectiveDefault = Object.keys(rule.targets).some(
298
+ (k) => k.trim().toLowerCase() === effectiveDefault.trim().toLowerCase(),
299
+ );
300
+ if (!hasEffectiveDefault) {
301
+ errors.push(`config.effortRouting.${rawAlias} default effort "${effectiveDefault}" has no matching target`);
302
+ }
303
+ }
304
+ }
305
+ }
306
+ }
203
307
 
204
308
  return errors.length > 0 ? fail(errors) : ok(value as unknown as Config);
205
309
  }