tuxevil-rotator 3.4.0 → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,11 +12,39 @@ import {
12
12
  QUOTA_MODEL_KEYS,
13
13
  } from "../../types.js";
14
14
  import { fetchWithRetry } from "../../fetch-with-retry.js";
15
+ import {
16
+ getAccountIdentity,
17
+ getCredentialGeneration,
18
+ } from "../../account-identity.js";
15
19
  import type { QuotaFetchContext } from "../adapter.js";
16
20
  import { DEFAULT_PROVIDER, getProviderProjectId } from "../credential-helpers.js";
17
21
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
18
22
  import { sortQuotaPools } from "../registry.js";
19
23
 
24
+ import {
25
+ dynamicCatalog,
26
+ DynamicModelRegistry,
27
+ parseGoogleQuotaResponse,
28
+ } from "./dynamic-catalog.js";
29
+
30
+ type GoogleModelInfo = GoogleQuotaResponse["models"][string];
31
+ type GoogleModelInfoWithQuota = GoogleModelInfo & {
32
+ quotaInfo: NonNullable<GoogleModelInfo["quotaInfo"]> & {
33
+ remainingFraction: number;
34
+ };
35
+ };
36
+
37
+ function hasUsableQuotaInfo(
38
+ info: GoogleModelInfo | undefined,
39
+ ): info is GoogleModelInfoWithQuota {
40
+ if (!info?.quotaInfo) return false;
41
+ const remaining = info.quotaInfo.remainingFraction;
42
+ return typeof remaining === "number" &&
43
+ Number.isFinite(remaining) &&
44
+ remaining >= 0 &&
45
+ remaining <= 1;
46
+ }
47
+
20
48
  /**
21
49
  * Extract per-model quotas from a Google quota response, preserving the
22
50
  * previously classified timer type when the reset time is unchanged.
@@ -29,17 +57,29 @@ export function extractQuotas(
29
57
  const now = Date.now();
30
58
 
31
59
  for (const [, config] of Object.entries(QUOTA_MODEL_KEYS)) {
32
- let modelInfo = data.models[config.key];
60
+ let modelInfo: GoogleModelInfoWithQuota | undefined;
61
+ for (const candidate of [config.key, ...config.altKeys]) {
62
+ const info = data.models[candidate];
63
+ if (hasUsableQuotaInfo(info)) {
64
+ modelInfo = info;
65
+ break;
66
+ }
67
+ }
33
68
 
34
69
  if (!modelInfo) {
35
- for (const altKey of config.altKeys) {
36
- modelInfo = data.models[altKey];
37
- if (modelInfo) break;
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
+ }
38
78
  }
39
79
  }
40
80
 
41
81
  if (modelInfo?.quotaInfo) {
42
- const remainingFraction = modelInfo.quotaInfo.remainingFraction ?? 0;
82
+ const remainingFraction = modelInfo.quotaInfo.remainingFraction;
43
83
  // Google can publish a nominal reset for an untouched pool; no usage means
44
84
  // there is no active quota window yet.
45
85
  const resetTime =
@@ -86,6 +126,24 @@ export async function fetchProviderQuota(
86
126
  ctx: QuotaFetchContext,
87
127
  ): Promise<void> {
88
128
  if (!account.accessToken) return;
129
+ const accountId = getAccountIdentity(account);
130
+ const credentialGeneration = getCredentialGeneration(
131
+ account,
132
+ DEFAULT_PROVIDER,
133
+ );
134
+ const accountEpoch = dynamicCatalog.captureAccountEpoch(
135
+ accountId,
136
+ credentialGeneration,
137
+ );
138
+ if (accountEpoch === null) return;
139
+ const isCurrentGeneration = (): boolean =>
140
+ accountId === getAccountIdentity(account) &&
141
+ credentialGeneration === getCredentialGeneration(account, DEFAULT_PROVIDER) &&
142
+ dynamicCatalog.isAccountGenerationActive(
143
+ accountId,
144
+ credentialGeneration,
145
+ accountEpoch,
146
+ );
89
147
 
90
148
  try {
91
149
  const response = await fetchWithRetry(QUOTA_API_URL, {
@@ -101,10 +159,12 @@ export async function fetchProviderQuota(
101
159
  timeoutMs: 8000,
102
160
  dispatcher: getAccountProxyDispatcher(account, "google-antigravity"),
103
161
  });
162
+ if (!isCurrentGeneration()) return;
104
163
 
105
164
  if (!response.ok) {
106
165
  if (response.status === 401 || response.status === 403) {
107
166
  const errorText = await response.text();
167
+ if (!isCurrentGeneration()) return;
108
168
  ctx.log(
109
169
  `${account.config.email}: quota API returned ${response.status}, flagging account`,
110
170
  );
@@ -118,9 +178,24 @@ export async function fetchProviderQuota(
118
178
  return;
119
179
  }
120
180
 
121
- const data = (await response.json()) as GoogleQuotaResponse;
181
+ const rawData = await response.json();
182
+ if (!isCurrentGeneration()) return;
183
+ const data = parseGoogleQuotaResponse(rawData);
184
+ if (!data) return;
122
185
  const oldQuota = account.quota || [];
123
186
  const fresh = extractQuotas(data, oldQuota);
187
+ if (fresh.length === 0) return;
188
+ const newModels = dynamicCatalog.updateFromEndpointResponse(
189
+ data,
190
+ accountId,
191
+ credentialGeneration,
192
+ accountEpoch,
193
+ );
194
+ if (newModels > 0) {
195
+ ctx.log(
196
+ `${account.config.email}: discovered ${newModels} Antigravity model(s) from quota response`,
197
+ );
198
+ }
124
199
  // Drop the previous Antigravity entries so the new ones fully replace
125
200
  // them; keep entries from OTHER providers (Ollama) so multi-provider
126
201
  // accounts accumulate quotas across credentials without overwriting
@@ -11,6 +11,7 @@ import {
11
11
  getModelSpec,
12
12
  isThinkingModel,
13
13
  } from "../../compat/model-specs.js";
14
+ import { dynamicCatalog } from "./dynamic-catalog.js";
14
15
  import {
15
16
  thoughtSignatureCache,
16
17
  getStoredResponse,
@@ -22,6 +23,32 @@ const compatLogger = logger.child("compat");
22
23
 
23
24
  const VALIDATION_LOG_MAX_CHARS = 200;
24
25
 
26
+ function normalizeFixedThinking(
27
+ modelSpec: ReturnType<typeof getModelSpec>,
28
+ requestedMaxOutputTokens: number | undefined,
29
+ ): { budget?: number; maxOutputTokens: number | undefined } {
30
+ const outputLimit = Math.max(1, Math.floor(modelSpec.maxOutputTokens));
31
+ const minimum = typeof modelSpec.minThinkingBudget === "number" &&
32
+ Number.isFinite(modelSpec.minThinkingBudget)
33
+ ? Math.max(0, Math.floor(modelSpec.minThinkingBudget))
34
+ : 0;
35
+ let budget = Math.max(
36
+ minimum,
37
+ Math.max(0, Math.floor(modelSpec.thinkingBudget)),
38
+ );
39
+ budget = Math.min(budget, outputLimit - 1);
40
+ if (budget < minimum) {
41
+ return { maxOutputTokens: requestedMaxOutputTokens };
42
+ }
43
+
44
+ let maxOutputTokens = requestedMaxOutputTokens;
45
+ if (!maxOutputTokens || maxOutputTokens <= budget) {
46
+ maxOutputTokens = Math.min(budget + 8192, outputLimit);
47
+ if (maxOutputTokens <= budget) maxOutputTokens = budget + 1;
48
+ }
49
+ return { budget, maxOutputTokens };
50
+ }
51
+
25
52
  export function logValidationFailure(scope: string, payload: unknown): void {
26
53
  const truncated = redactSensitive(JSON.stringify(payload));
27
54
  const clipped =
@@ -156,6 +183,7 @@ export interface CompatCompletion {
156
183
  toolCalls?: OpenAIToolCall[];
157
184
  rawResponse?: unknown;
158
185
  streamError?: string;
186
+ finishReason?: string;
159
187
  }
160
188
 
161
189
  export type AntigravityPart =
@@ -841,20 +869,34 @@ export function convertResponsesToChatRequest(
841
869
  * reasoning_effort. Matched case-insensitively against the exact ID only;
842
870
  * virtual siblings (e.g. `gemini-3.7-flash-tiered-high`) are excluded.
843
871
  */
872
+
844
873
  export const TIERED_EFFORT_MODEL_ID = "gemini-3.7-flash-tiered";
874
+ export const TIERED_EFFORT_MODEL_IDS = new Set([
875
+ "gemini-3.7-flash-tiered",
876
+ ]);
877
+
878
+ export function isTieredEffortModel(modelId: string): boolean {
879
+ const l = modelId.toLowerCase().trim();
880
+ if (l.includes("3.6")) return false;
881
+ if (TIERED_EFFORT_MODEL_IDS.has(l)) return true;
882
+ // Exclude virtual siblings like gemini-X-tiered-high
883
+ if (l.includes("-tiered-")) return false;
884
+ if (l.endsWith("-tiered")) return true;
885
+ return dynamicCatalog.isTiered(l);
886
+ }
845
887
 
846
888
  /**
847
889
  * 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.
890
+ * tiered models (`gemini-3.7-flash-tiered`) only.
891
+ * Accepts exactly low/medium/high (case-insensitive); anything else returns
892
+ * undefined so the caller falls back to the existing adaptive/fixed-budget
893
+ * semantics and never emits an invalid upstream enum.
852
894
  */
853
895
  export function mapTieredReasoningEffortToThinkingLevel(
854
896
  effort: string | undefined,
855
897
  modelId: string,
856
898
  ): "LOW" | "MEDIUM" | "HIGH" | undefined {
857
- if (modelId.toLowerCase() !== TIERED_EFFORT_MODEL_ID) return undefined;
899
+ if (!isTieredEffortModel(modelId)) return undefined;
858
900
  if (!isNonEmptyString(effort)) return undefined;
859
901
  switch (effort.toLowerCase()) {
860
902
  case "low":
@@ -1177,13 +1219,22 @@ export function openAIToAntigravityBody(
1177
1219
 
1178
1220
  let thinkingConfigObj: Record<string, unknown> | undefined;
1179
1221
  if (modelFamily === "claude" && isThinking && !forcesToolUse(input.tool_choice)) {
1180
- const tb = modelSpec.thinkingBudget;
1181
- thinkingConfigObj = { include_thoughts: true, thinking_budget: tb };
1182
- if (!maxOutputTokens || maxOutputTokens <= tb) {
1183
- maxOutputTokens = Math.min(tb + 8192, modelSpec.maxOutputTokens);
1184
- compatLogger.debug(
1185
- `Adjusted Claude maxOutputTokens → ${maxOutputTokens}`,
1186
- );
1222
+ if (modelSpec.thinkingBudget === -1) {
1223
+ thinkingConfigObj = { include_thoughts: true };
1224
+ } else {
1225
+ const normalized = normalizeFixedThinking(modelSpec, maxOutputTokens);
1226
+ if (normalized.budget !== undefined) {
1227
+ thinkingConfigObj = {
1228
+ include_thoughts: true,
1229
+ thinking_budget: normalized.budget,
1230
+ };
1231
+ }
1232
+ if (maxOutputTokens !== normalized.maxOutputTokens) {
1233
+ maxOutputTokens = normalized.maxOutputTokens;
1234
+ compatLogger.debug(
1235
+ `Adjusted Claude maxOutputTokens → ${maxOutputTokens}`,
1236
+ );
1237
+ }
1187
1238
  }
1188
1239
  } else if (isThinking && modelFamily !== "claude") {
1189
1240
  const tb = modelSpec.thinkingBudget;
@@ -1206,23 +1257,29 @@ export function openAIToAntigravityBody(
1206
1257
  };
1207
1258
  } else if (tb === -1) {
1208
1259
  thinkingConfigObj = { includeThoughts: true };
1260
+ if (maxOutputTokens !== undefined) {
1261
+ // Adaptive models spend from the output budget before emitting visible text.
1262
+ const targetTokens = Math.max(maxOutputTokens + 8192, 8192);
1263
+ maxOutputTokens = Math.min(targetTokens, modelSpec.maxOutputTokens);
1264
+ compatLogger.debug(
1265
+ `Adjusted adaptive Gemini maxOutputTokens → ${maxOutputTokens}`,
1266
+ );
1267
+ }
1209
1268
  } else {
1210
- thinkingConfigObj = { includeThoughts: true, thinkingBudget: tb };
1211
- }
1212
- if (tb !== -1 && (!maxOutputTokens || maxOutputTokens <= tb)) {
1213
- maxOutputTokens = Math.min(tb + 8192, modelSpec.maxOutputTokens);
1214
- compatLogger.debug(
1215
- `Adjusted Gemini maxOutputTokens → ${maxOutputTokens}`,
1216
- );
1269
+ const normalized = normalizeFixedThinking(modelSpec, maxOutputTokens);
1270
+ if (normalized.budget !== undefined) {
1271
+ thinkingConfigObj = {
1272
+ includeThoughts: true,
1273
+ thinkingBudget: normalized.budget,
1274
+ };
1275
+ }
1276
+ if (maxOutputTokens !== normalized.maxOutputTokens) {
1277
+ maxOutputTokens = normalized.maxOutputTokens;
1278
+ compatLogger.debug(
1279
+ `Adjusted Gemini maxOutputTokens → ${maxOutputTokens}`,
1280
+ );
1281
+ }
1217
1282
  }
1218
- } else if (input.reasoning_effort) {
1219
- const budgets: Record<string, number> = {
1220
- low: Math.round(modelSpec.thinkingBudget / 4),
1221
- medium: Math.round(modelSpec.thinkingBudget / 2),
1222
- high: modelSpec.thinkingBudget,
1223
- };
1224
- const b = budgets[input.reasoning_effort.toLowerCase()];
1225
- if (b) thinkingConfigObj = { includeThoughts: true, thinkingBudget: b };
1226
1283
  }
1227
1284
 
1228
1285
  const generationConfig: Record<string, unknown> = {
package/src/proxy.ts CHANGED
@@ -132,6 +132,13 @@ function routingModelKey(rotator: AccountRotator, model: string): string {
132
132
  }).resolveQuotaModelKeyForDisplay;
133
133
  return resolver?.call(rotator, model) ?? resolveQuotaModelKey(model) ?? model;
134
134
  }
135
+
136
+ function observedModelKey(rotator: AccountRotator, model: string): string {
137
+ const resolver = (rotator as unknown as {
138
+ resolveObservedModelKey?: (value: string) => string;
139
+ }).resolveObservedModelKey;
140
+ return resolver?.call(rotator, model) ?? resolveDisplayModelKey(model);
141
+ }
135
142
  import { startVersionChecker, performSelfUpdate } from "./version-check.js";
136
143
  import { startNotificationPoller } from "./notification-poller.js";
137
144
  import {
@@ -1173,7 +1180,7 @@ export async function withRotation<T>(
1173
1180
 
1174
1181
  const label = account.config.label || account.config.email;
1175
1182
  const modelKey = routingModelKey(rotator, model);
1176
- const displayModelKey = resolveDisplayModelKey(body.displayModel || model);
1183
+ const displayModelKey = observedModelKey(rotator, body.displayModel || model);
1177
1184
  const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
1178
1185
  const requestStartMs = Date.now();
1179
1186
  let accountReleased = false;
@@ -1280,7 +1287,22 @@ export async function withRotation<T>(
1280
1287
  // success
1281
1288
  const result = await onSuccess(response, context);
1282
1289
  const shouldRotate = rotator.recordRequest(account, model);
1283
- logRequestEnd(response.status, `endpoint=${endpoint}`);
1290
+ const inTokens =
1291
+ result && typeof result === "object" && "inputTokens" in result
1292
+ ? (result as Record<string, unknown>).inputTokens
1293
+ : 0;
1294
+ const outTokens =
1295
+ result && typeof result === "object" && "outputTokens" in result
1296
+ ? (result as Record<string, unknown>).outputTokens
1297
+ : 0;
1298
+ const ttfbMs =
1299
+ result && typeof result === "object" && "firstByteMs" in result
1300
+ ? (result as Record<string, unknown>).firstByteMs
1301
+ : undefined;
1302
+ const ttfbInfo = ttfbMs !== undefined ? ` ttfbMs=${ttfbMs}` : "";
1303
+ const tokensInfo =
1304
+ inTokens || outTokens ? ` inTokens=${inTokens} outTokens=${outTokens}` : "";
1305
+ logRequestEnd(response.status, `endpoint=${endpoint}${ttfbInfo}${tokensInfo}`);
1284
1306
  if (shouldRotate) {
1285
1307
  await rotator.rotateToNext(model, account);
1286
1308
  }
@@ -1594,7 +1616,7 @@ async function handleProxyRequest(
1594
1616
 
1595
1617
  const label = account.config.label || account.config.email;
1596
1618
  const modelKey = rotator.resolveQuotaModelKeyForDisplay(body.model) ?? body.model; // quota routing
1597
- const displayModelKey = resolveDisplayModelKey(body.model); // metrics/logs
1619
+ const displayModelKey = observedModelKey(rotator, body.model); // metrics/logs
1598
1620
  const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
1599
1621
  let accountReleased = false;
1600
1622
  const releaseCurrentAccount = (): void => {
@@ -1750,7 +1772,7 @@ async function handleProxyRequest(
1750
1772
  const ttfbMs = usage?.firstByteMs ?? totalMs;
1751
1773
  const outcomeStatus = usage?.streamError ? 502 : response.status;
1752
1774
  rotator.recordLatency(body.displayModel || body.model, ttfbMs, totalMs);
1753
- logRequestEnd(outcomeStatus, `ttfbMs=${ttfbMs} endpoint=${endpoint}`);
1775
+ logRequestEnd(outcomeStatus, `ttfbMs=${ttfbMs} inTokens=${usage?.inputTokens ?? 0} outTokens=${usage?.outputTokens ?? 0} endpoint=${endpoint}`);
1754
1776
  rotator.recordRequestLog({
1755
1777
  model: displayModelKey,
1756
1778
  account: label,